aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco
diff options
context:
space:
mode:
Diffstat (limited to 'src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco')
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/reco.pro7
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.cpp138
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.def4
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.h95
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.cpp1186
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.h194
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.cpp211
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.h161
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.cpp178
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.h139
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.cpp6257
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.h1203
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.cfg422
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.pro27
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoConfig.cpp538
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoResult.cpp223
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoUtil.cpp486
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecognizer.cpp250
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.cpp288
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.h142
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/common.pro13
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeature.h224
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.cpp64
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.h102
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.cpp222
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.h94
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/common.pro9
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/featureextractor.pro13
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.cpp673
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.h267
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp587
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.h112
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.cpp105
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.h94
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.pro22
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.cpp103
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.h92
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.cpp340
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.h253
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.cpp722
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.h97
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/npen.pro22
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.cpp106
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.h110
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.cpp517
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.h199
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.cpp394
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.h70
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/pointfloat.pro22
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.cpp115
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.h98
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.cpp675
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.h200
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.cpp1035
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.h139
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/substroke.pro22
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.cpp112
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.def4
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.h62
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.cpp4682
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.h1111
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.cfg407
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.pro21
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.cpp142
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.def4
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.h100
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.cpp370
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.h110
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.cpp5432
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.h1178
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.cfg362
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.pro23
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/LTKPreprocessor.cpp3353
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.cpp109
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.h82
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.pro20
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/shaperec.pro14
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.cpp1336
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.h231
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cfg13
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cpp129
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.def3
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.h90
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.pro20
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKRecognitionContext.cpp1065
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoConfig.cpp477
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoResult.cpp291
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/common.pro10
-rw-r--r--src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/wordrec.pro7
94 files changed, 41466 insertions, 0 deletions
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/reco.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/reco.pro
new file mode 100644
index 00000000..72efcc7f
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/reco.pro
@@ -0,0 +1,7 @@
+TEMPLATE = subdirs
+
+SUBDIRS += \
+ shaperec \
+ wordrec
+
+wordrec.depends = shaperec
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.cpp
new file mode 100644
index 00000000..bdbec8c2
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.cpp
@@ -0,0 +1,138 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2011-01-18 15:41:43 +0530 (Tue, 18 Jan 2011) $
+* $Revision: 829 $
+* $Author: mnab $
+*
+************************************************************************/
+/************************************************************************
+* FILE DESCR: Defines the entry for ActiveDTW dll application
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+w
+* DATE: 3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+* Balaji MNA 18th Jan 2010 Receiving LTKShapeRecognizer as single pointer
+* instead of double pointer in deleteShapeRecognizer
+************************************************************************/
+
+
+#include "ActiveDTW.h"
+#include "LTKShapeRecognizer.h"
+#include "ActiveDTWShapeRecognizer.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKOSUtil.h"
+
+#ifdef _WIN32
+#include <windows.h>
+
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+/** createShapeRecognizer **/
+
+int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** ptrObj )
+{
+ try
+ {
+ *ptrObj = new ActiveDTWShapeRecognizer(controlInfo);
+ return SUCCESS;
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+}
+
+
+/**deleteShapeRecognizer **/
+int deleteShapeRecognizer(LTKShapeRecognizer *obj)
+{
+ try
+ {
+ if (obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+
+ //unloadDLLs();
+ }
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+
+
+ return SUCCESS;
+}
+
+/** unloadDLLs **/
+/*
+void unloadDLLs()
+{
+// Unload feature extractor DLL
+if(m_libHandlerFE != NULL)
+{
+//Unload the DLL
+LTKUnloadDLL(m_libHandlerFE);
+m_libHandlerFE = NULL;
+}
+}*/
+
+/** getTraceGroups **/
+int getTraceGroups(LTKShapeRecognizer *obj, int shapeId,
+ int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ int errorCode = ((ActiveDTWShapeRecognizer*)obj)->getTraceGroups(shapeId,
+ numberOfTraceGroups, outTraceGroups);
+
+ if ( errorCode != SUCCESS )
+ {
+ LTKReturnError(errorCode);
+ }
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.def
new file mode 100644
index 00000000..0a4f75c9
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.def
@@ -0,0 +1,4 @@
+EXPORTS
+ createShapeRecognizer @1
+ deleteShapeRecognizer @2
+ getTraceGroups @3 \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.h
new file mode 100644
index 00000000..854dc6da
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTW.h
@@ -0,0 +1,95 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2011-01-18 15:41:43 +0530 (Tue, 18 Jan 2011) $
+* $Revision: 829 $
+* $Author: mnab $
+*
+************************************************************************/
+/************************************************************************
+* FILE DESCR: Declarations for ActiveDTW dll exporting functions.
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+w
+* DATE: 3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+* Balaji MNA 18th Jan 2010 Receiving LTKShapeRecognizer as single pointer
+* instead of double pointer in deleteShapeRecognizer
+************************************************************************/
+
+#ifndef __ACTIVEDTW_H__
+#define __ACTIVEDTW_H__
+
+#include "LTKInc.h"
+#include "LTKTypes.h"
+
+#ifdef _WIN32
+#ifdef ACTIVEDTW_EXPORTS
+#define ACTIVEDTW_API __declspec(dllexport)
+#else
+#define ACTIVEDTW_API __declspec(dllimport)
+#endif //#ifdef ACTIVEDTW_EXPORTS
+#else
+#define ACTIVEDTW_API
+#endif //#ifdef _WIN32
+
+class LTKTraceGroup;
+class LTKShapeRecognizer;
+
+
+/** @defgroup ActiveDTWShapeRecognizer ActiveDTWShapeRecognizer
+*@brief The ActiveDTWShapeRecognizer
+*/
+
+/**
+* @ingroup ActiveDTWShapeRecognizer
+* @file ActiveDTW.cpp
+*/
+
+/**
+* Crates instance of type ActiveDTWShapeRecognizer and returns of type
+* LTKShpeRecognizer. (Acts as a Factory Method).
+*
+* @param none
+*
+* @return LTKShapeRecognizer - an instance of type LTKShapeRecognizer.
+*/
+extern "C" ACTIVEDTW_API int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** pReco );
+ /**
+ * Destroy the instance by taking the address as its argument.
+ *
+ * @param obj - Address of LTKShapeRecognizer instance.
+ *
+ * @return 0 on Success
+*/
+extern "C" ACTIVEDTW_API int deleteShapeRecognizer(LTKShapeRecognizer *obj);
+
+extern "C" ACTIVEDTW_API int getTraceGroups(LTKShapeRecognizer *obj, int shapeID, int numberOfTraceGroups,vector<LTKTraceGroup> &outTraceGroups);
+
+void unloadDLLs();
+
+#endif //#ifndef __NN_H__
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.cpp
new file mode 100644
index 00000000..e0c36e6b
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.cpp
@@ -0,0 +1,1186 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2009-04-06 11:55:15 +0530 (Mon, 06 Apr 2009) $
+* $Revision: 758 $
+* $Author: royva $
+*
+************************************************************************/
+/*********************************************************************************************
+* FILE DESCR: Definitions for ActiveDTW Adaptation module
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+w
+* DATE:3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+***********************************************************************************************/
+
+#include "ActiveDTWShapeRecognizer.h"
+#include "ActiveDTWAdapt.h"
+#include "LTKLoggerUtil.h"
+#include "LTKConfigFileReader.h"
+#include "LTKErrors.h"
+#include "LTKErrorsList.h"
+#include "LTKPreprocDefaults.h"
+
+LTKAdapt* LTKAdapt::adaptInstance = NULL;
+int LTKAdapt::m_count = 0;
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : Constructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt::LTKAdapt(ActiveDTWShapeRecognizer* ptrActiveDTWShapeReco)
+{
+ m_activedtwShapeRecognizer = ptrActiveDTWShapeReco;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << "Exit LTKAdapt::LTKAdapt()"<<endl;
+
+ //Assign Default Values
+
+ m_maxClusterSize = ADAPT_DEF_MAX_NUMBER_SAMPLES_PER_CLASS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : Destructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt::~LTKAdapt()
+{
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : deleteInstance
+* DESCRIPTION : delete AdaptInstance
+* ARGUMENTS :
+* RETURNS : None
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void LTKAdapt::deleteInstance()
+{
+ m_count = 0;
+ if(adaptInstance)
+ {
+ delete adaptInstance;
+ adaptInstance = NULL;
+ }
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getInstance
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt* LTKAdapt::getInstance(ActiveDTWShapeRecognizer* ptrActiveDTWShapeReco)
+{
+ if(adaptInstance == NULL)
+ {
+ adaptInstance = new LTKAdapt(ptrActiveDTWShapeReco);
+ }
+
+ return adaptInstance;
+
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : Process
+* DESCRIPTION : Performs adaptation
+* ARGUMENTS :
+* RETURNS : Success : If completed successfully
+* Failure : Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int LTKAdapt::adapt(int shapeId)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << "Enter LTKAdapt::adapt()"<<endl;
+
+ int iErrorCode;
+
+ //read config file values when first adapt sample is encountered
+ if(m_count==0)
+ {
+ m_count = 1;
+
+ iErrorCode = readAdaptConfig();
+ if(iErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during LTKAdapt::readAdaptConfig()"<<endl;
+ LTKReturnError(FAILURE);
+ }
+ }
+
+
+ //Check if Cached variables are valid
+ if(m_activedtwShapeRecognizer->m_neighborInfoVec.size()==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"DistanceIndexPair is empty"<<endl;
+
+ LTKReturnError(ENEIGHBOR_INFO_VECTOR_EMPTY );
+ }
+
+ //check if test featureVector is empty
+ if(m_activedtwShapeRecognizer->m_cachedShapeFeature.size() <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Features of input TraceGroup is empty"<<endl;
+
+ LTKReturnError(ESHAPE_SAMPLE_FEATURES_EMPTY);
+ }
+
+ //find out whether the test sample is close to a singleton or cluster
+
+ //case of incorrect classification
+ if(m_activedtwShapeRecognizer->m_vecRecoResult.size() == 0 ||
+ m_activedtwShapeRecognizer->m_vecRecoResult.at(0).getShapeId() != shapeId)
+ {
+
+ int index = 0;
+ //iterating through neighborInfoVec to retrieve information about the true
+ //shape model of class
+ while(shapeId != m_activedtwShapeRecognizer->m_neighborInfoVec[index].classId )
+ index++;
+
+ if(m_activedtwShapeRecognizer->m_neighborInfoVec[index].typeId == CLUSTER)
+ {
+ int clusterId = m_activedtwShapeRecognizer->m_neighborInfoVec[index].sampleId;
+
+ //adapting the cluster
+ iErrorCode = adaptCluster(m_activedtwShapeRecognizer->m_cachedShapeFeature,clusterId,shapeId);
+
+ if(iErrorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<iErrorCode<<
+ " LTKAdapt::adapt" << endl;
+ LTKReturnError(iErrorCode);
+ }
+ }
+ else
+ {
+ //adapting the singleton set
+ iErrorCode = adaptSingleton(m_activedtwShapeRecognizer->m_cachedShapeFeature,shapeId);
+ if(iErrorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<iErrorCode<<
+ " LTKAdapt::adapt" << endl;
+ LTKReturnError(iErrorCode);
+ }
+ }
+ }
+ else
+ {
+ //case of correct classification
+ if(m_activedtwShapeRecognizer->m_neighborInfoVec[0].typeId == CLUSTER)
+ {
+ int clusterId = m_activedtwShapeRecognizer->m_neighborInfoVec[0].sampleId;
+ int iterator = 0;
+ while(m_activedtwShapeRecognizer->m_prototypeShapes[iterator].getShapeId() != shapeId)
+ iterator++;
+
+ ActiveDTWShapeModel shapeModelToAdapt = m_activedtwShapeRecognizer->m_prototypeShapes[iterator];
+
+ vector<ActiveDTWClusterModel> currentClusterModelVector = shapeModelToAdapt.getClusterModelVector();
+
+ //adapt the model only if number of samples seen by the model is less than the threshold m_maxClustersize
+ if(currentClusterModelVector[clusterId].getNumSamples() < m_maxClusterSize)
+ {
+ iErrorCode = adaptCluster(m_activedtwShapeRecognizer->m_cachedShapeFeature,clusterId,shapeId);
+
+ if(iErrorCode != SUCCESS)
+ {
+ currentClusterModelVector.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<iErrorCode<<
+ " LTKAdapt::adapt" << endl;
+ LTKReturnError(iErrorCode);
+ }
+ }
+ currentClusterModelVector.clear();
+ }
+ else
+ {
+ //adapt singleton set
+ iErrorCode = adaptSingleton(m_activedtwShapeRecognizer->m_cachedShapeFeature,shapeId);
+ if(iErrorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<iErrorCode<<
+ " LTKAdapt::adapt" << endl;
+ LTKReturnError(iErrorCode);
+ }
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << "Exit LTKAdapt::adapt()"<<endl;
+
+ return(SUCCESS);
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : readAdaptConfig
+* DESCRIPTION : Reads configuration info for adaptation
+* ARGUMENTS : NONE
+* RETURNS : NONE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int LTKAdapt::readAdaptConfig()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Enter Adapt::readAdaptConfig"
+ <<endl;
+
+
+ LTKConfigFileReader *adaptConfigReader = NULL;
+
+ adaptConfigReader = new LTKConfigFileReader(m_activedtwShapeRecognizer->m_activedtwCfgFilePath);
+
+
+ //Don't throw Error as ShapeRecognizer might not support ADAPT
+ string tempStringVar = "";
+ int tempIntegerVar;
+
+ int errorCode = adaptConfigReader->getConfigValue(MAXCLUSTERSIZE,tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if(LTKStringUtil::isInteger(tempStringVar))
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ if(tempIntegerVar > 1)
+ {
+ if(tempIntegerVar < m_activedtwShapeRecognizer->m_minClusterSize)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << m_maxClusterSize <<
+ " is out of permitted range MAXCUSTERSIZE < MINCLUSTERSIZE" <<
+ " LTKAdapt::readAdaptConfig"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ else
+ {
+ m_maxClusterSize = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ MAXCLUSTERSIZE << " = " <<m_maxClusterSize<<endl;
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << m_maxClusterSize <<
+ " is out of permitted range" <<
+ " LTKAdapt::readAdaptConfig"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << MAXCLUSTERSIZE <<
+ " is out of permitted range" <<
+ " LTKAdapt::readAdaptConfig"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MAXCLUSTERSIZE << " : " << m_maxClusterSize << endl;
+ }
+
+
+ if(adaptConfigReader)
+ delete adaptConfigReader;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exit LTKAdapt::readAdaptConfig"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : adaptCluster
+* DESCRIPTION : This method adapts the cluster with the new featureVector. Implementation of method described in paper:
+"Incremental eigenanalysis for classifiation, published in British Machine Vision Conference-2008"
+*
+* ARGUMENTS : INPUT
+featureVecToAdapt shapeFeature
+clusterId int
+shapeId int
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int LTKAdapt::adaptCluster(shapeFeature& featureVecToAdapt,int clusterId,int shapeId)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "LTKAdapt::adaptCluster()" << endl;
+
+ int errorCode;
+
+ //validating input arguments
+ if(m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.find(shapeId) == m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ //finding the prototypeShape
+ int index = 0;
+
+ int i = 0;
+ int j = 0;
+
+ while(m_activedtwShapeRecognizer->m_prototypeShapes[index].getShapeId() != shapeId)
+ index++;
+
+ ActiveDTWShapeModel shapeModelToAdapt = m_activedtwShapeRecognizer->m_prototypeShapes[index];
+
+ vector<ActiveDTWClusterModel> currentClusterModelVector = shapeModelToAdapt.getClusterModelVector();
+
+ if(clusterId < 0 || clusterId >= currentClusterModelVector.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_CLUSTER_ID << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+
+ LTKReturnError(EINVALID_CLUSTER_ID);
+ }
+
+
+ ActiveDTWClusterModel clusterToAdapt = currentClusterModelVector[clusterId];
+
+ //obtaining data of cluster
+ doubleVector oldEigenValues = clusterToAdapt.getEigenValues();
+
+ double2DVector oldEigenVectors = clusterToAdapt.getEigenVectors();
+
+ doubleVector oldClusterMean = clusterToAdapt.getClusterMean();
+
+ int numClusterSamples = clusterToAdapt.getNumSamples();
+
+ //convert the shapefeature to double vector
+ floatVector floatFeatureVector;
+
+ doubleVector doubleFeatureVector;
+
+ errorCode = m_activedtwShapeRecognizer->m_shapeRecUtil.shapeFeatureVectorToFloatVector(featureVecToAdapt,floatFeatureVector);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "LTKAdapt::adaptCluster" <<endl;
+ LTKReturnError(errorCode);
+ }
+
+ int featureSize = floatFeatureVector.size();
+
+ for(i = 0; i < featureSize; i++)
+ doubleFeatureVector.push_back(floatFeatureVector[i]);
+
+ floatFeatureVector.clear();
+
+ //the difference vector
+ //refers to y - x(mean)
+ doubleVector diffVector;
+
+ //refers to g in the paper (Eqn 2)
+ //g = unp*(y - x(mean))
+ doubleVector projectedTestSample;
+
+ //refers to h in the paper (Eqn 3)
+ //h = (y - x(mean)) - (unp * g)
+ doubleVector residueVector;
+
+ //refers to unp*g
+ doubleVector reverseProjection;
+
+ int numEigenVectors = oldEigenVectors.size();
+
+ //calculating diffVector
+ for(i = 0; i < featureSize; i++)
+ diffVector.push_back(doubleFeatureVector[i] - oldClusterMean[i]);
+
+ //constructing the projected test sample i.e g
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ double tempValue = 0;
+ for(j = 0; j < featureSize; j++)
+ {
+ tempValue += (oldEigenVectors[i][j] * diffVector[j]);
+ }
+ projectedTestSample.push_back(tempValue);
+ }
+
+ //constructing reverse projection
+ for(i = 0; i < featureSize; i++)
+ {
+ double tempValue = 0;
+ for(j = 0; j < numEigenVectors;j++)
+ {
+ tempValue += oldEigenVectors[j][i] * projectedTestSample[j];
+ }
+ reverseProjection.push_back(tempValue);
+ }
+
+ //construct residue vector
+ for(i = 0; i < featureSize; i++)
+ residueVector.push_back(diffVector[i] - reverseProjection[i]);
+
+ //magnitude of residue vector
+ double residueMagnitude = 0;
+
+ for(i = 0; i < featureSize; i++)
+ residueMagnitude = residueMagnitude + (residueVector[i] * residueVector[i]);
+
+ residueMagnitude = sqrt(residueMagnitude);
+
+ //determining the recomputed eigenValues and eigenVectors
+ //case 1 residueMagnitude is 0
+ if(residueMagnitude == 0)
+ {
+ //construct the matrix whose eigen values and eigen vectors are to be calculated
+ doubleVector tempVector;
+
+ //corresponds to matrix in eqn 10
+ double2DVector coeff1;
+
+ tempVector.assign(numEigenVectors,0.0);
+
+ coeff1.assign(numEigenVectors,tempVector);
+
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ {
+ if(i == j)
+ coeff1[i][j] = oldEigenValues[j];
+ }
+ }
+
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ coeff1[i][j] = (coeff1[i][j] * numClusterSamples)/(numClusterSamples + 1);
+ }
+
+ //refers to eqn 11 in paper
+ double2DVector coeff2;
+
+ coeff2.assign(numEigenVectors,tempVector);
+
+ //constructing g*g(transpose)
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ coeff2[i][j] = projectedTestSample[i] * projectedTestSample[j];
+ }
+
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ coeff2[i][j] = (coeff2[i][j] * numClusterSamples) / ((numClusterSamples + 1) * (numClusterSamples + 1));
+ }
+
+ //final matrix
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ coeff1[i][j] += coeff2[i][j];
+ }
+
+ //solving the intermediate eigen value problem
+ //refers to eigenValue problem in eqn 12
+ double2DVector intermediateEigenVectors;
+ doubleVector eigenValues;
+ int nrot = 0;
+
+ intermediateEigenVectors.assign(numEigenVectors,tempVector);
+
+ errorCode = m_activedtwShapeRecognizer->computeEigenVectors(coeff1,coeff1.size(),eigenValues,intermediateEigenVectors,nrot);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //the new eigen vectors
+ double2DVector eigenVectors;
+
+ eigenVectors.assign(featureSize,tempVector);
+
+ tempVector.clear();
+
+ //calculating the new eigen vectors from the intermediateEigenVectors and oldEigenVectors
+ //refers to eqn 8
+ for( i = 0; i < featureSize; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ {
+ for(int k = 0; k < numEigenVectors;k++)
+ {
+ eigenVectors[i][j] += (oldEigenVectors[k][i] * intermediateEigenVectors[k][j]);
+ }
+ }
+ }
+
+ //now converting the eigen vectors to row format
+ //this makes it easy to write the eigen vectors to the mdt file and read from it
+ double2DVector newEigenVectors;
+
+ tempVector.assign(featureSize,0.0);
+
+ newEigenVectors.assign(numEigenVectors,tempVector);
+
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < featureSize; j++)
+ newEigenVectors[i][j] = eigenVectors[j][i];
+ }
+
+ numEigenVectors = 0;
+ double eigenEnergy = 0;
+ for( i = 0; i < eigenValues.size(); i++)
+ {
+ eigenEnergy += eigenValues[i];
+ }
+
+ double tempEigenEnergy = 0;
+
+ while(tempEigenEnergy <= ((m_activedtwShapeRecognizer->m_percentEigenEnergy * eigenEnergy)/100))
+ tempEigenEnergy += eigenValues[numEigenVectors++];
+
+ doubleVector selectedEigenValues;
+ double2DVector selectedEigenVectors;
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ selectedEigenValues.push_back(eigenValues[i]);
+ selectedEigenVectors.push_back(newEigenVectors[i]);
+ }
+
+ doubleVector newClusterMean;
+
+ for( i = 0; i < featureSize; i++)
+ {
+ double tempValue = ((numClusterSamples * oldClusterMean[i]) + doubleFeatureVector[i])/(numClusterSamples + 1);
+ newClusterMean.push_back(tempValue);
+ }
+
+ //updating the cluster model
+ errorCode = clusterToAdapt.setNumSamples(numClusterSamples + 1);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ clusterToAdapt.setEigenValues(selectedEigenValues);
+ selectedEigenValues.clear();
+
+ clusterToAdapt.setEigenVectors(selectedEigenVectors);
+ selectedEigenVectors.clear();
+
+ clusterToAdapt.setClusterMean(newClusterMean);
+
+ currentClusterModelVector[clusterId] = clusterToAdapt;
+
+ shapeModelToAdapt.setClusterModelVector(currentClusterModelVector);
+
+ m_activedtwShapeRecognizer->m_prototypeShapes[index] = shapeModelToAdapt;
+
+ //clearing vectors
+ tempVector.clear();
+ coeff1.clear();
+ coeff2.clear();
+ eigenValues.clear();
+ newEigenVectors.clear();
+ intermediateEigenVectors.clear();
+ newClusterMean.clear();
+ eigenVectors.clear();
+ }
+ else
+ {
+ //case residueMagnitude is not 0;
+ doubleVector unitResidueVector;
+
+ for(i = 0; i < featureSize; i++)
+ unitResidueVector.push_back(residueVector[i]/residueMagnitude);
+
+ //construct the matrix whose eigen values and eigen vectors are to be calculated
+ doubleVector tempVector;
+
+ //refer to eqn 10
+ double2DVector coeff1;
+
+ tempVector.assign(numEigenVectors + 1,0.0);
+
+ coeff1.assign(numEigenVectors + 1,tempVector);
+
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ {
+ if(i == j)
+ {
+ coeff1[i][j] = oldEigenValues[j];
+ }
+ }
+ }
+
+ for( i = 0; i < (numEigenVectors + 1 ); i++)
+ {
+ for(j = 0; j < (numEigenVectors + 1); j++)
+ coeff1[i][j] = (coeff1[i][j] * numClusterSamples)/(numClusterSamples + 1);
+ }
+
+ //refers to unith(transpose)*diffVector
+ double gamma = 0;
+
+ for( i = 0; i < featureSize; i++)
+ gamma = gamma + (unitResidueVector[i] * diffVector[i]);
+
+ //refers to eqn 11
+ double2DVector coeff2;
+
+ coeff2.assign(numEigenVectors + 1,tempVector);
+
+ //constructing g*g(transpose)
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < numEigenVectors; j++)
+ coeff2[i][j] = projectedTestSample[i] * projectedTestSample[j];
+ }
+
+ //calculating gamma * projectedTestSample i.e gamma * g
+ doubleVector gammaProjTestSample;
+
+ for( i = 0; i < numEigenVectors; i++)
+ gammaProjTestSample.push_back(projectedTestSample[i]*gamma);
+
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ coeff2[i][numEigenVectors] = gammaProjTestSample[i];
+ coeff2[numEigenVectors][i] = gammaProjTestSample[i];
+ }
+
+ coeff2[numEigenVectors][numEigenVectors] = gamma * gamma;
+
+ for( i = 0; i < numEigenVectors + 1; i++)
+ {
+ for(j = 0; j < numEigenVectors + 1; j++)
+ coeff2[i][j] = (coeff2[i][j] * numClusterSamples) / ((numClusterSamples + 1) * (numClusterSamples + 1));
+ }
+
+ //final matrix
+ for( i = 0; i < numEigenVectors + 1; i++)
+ {
+ for(j = 0; j < numEigenVectors + 1; j++)
+ coeff1[i][j] = coeff1[i][j] + coeff2[i][j];
+ }
+
+ //solving the intermediate eigen value problem
+ //refers to eqn 12
+ double2DVector intermediateEigenVectors;
+ doubleVector eigenValues;
+ int nrot = 0;
+
+ intermediateEigenVectors.assign(numEigenVectors + 1,tempVector);
+
+ errorCode = m_activedtwShapeRecognizer->computeEigenVectors(coeff1,coeff1.size(),eigenValues,intermediateEigenVectors,nrot);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //the new eigen vectors
+ double2DVector eigenVectors;
+
+ //adding unith to the old set of eigen vectors
+ oldEigenVectors.push_back(unitResidueVector);
+
+ eigenVectors.assign(featureSize,tempVector);
+
+ tempVector.clear();
+
+ //calculating the new eigen vectors from the oldEigenVectors
+ //refers to eqn 8
+ for( i = 0; i < featureSize; i++)
+ {
+ for(j = 0; j < (numEigenVectors + 1); j++)
+ {
+ for(int k = 0; k < (numEigenVectors + 1);k++)
+ {
+ eigenVectors[i][j] = eigenVectors[i][j] + (oldEigenVectors[k][i] * intermediateEigenVectors[k][j]);
+ }
+ }
+ }
+
+ //now converting the eigen vectors to row format
+ //this makes it easy to write the eigen vectors to the mdt file and read from it
+ double2DVector newEigenVectors;
+
+ tempVector.assign(featureSize,0.0);
+
+ newEigenVectors.assign(numEigenVectors + 1,tempVector);
+
+ for( i = 0; i < numEigenVectors + 1; i++)
+ {
+ for(j = 0; j < featureSize; j++)
+ newEigenVectors[i][j] = eigenVectors[j][i];
+ }
+
+ doubleVector newClusterMean;
+
+ for( i = 0; i < featureSize; i++)
+ {
+ double tempValue = ((numClusterSamples * oldClusterMean[i]) + doubleFeatureVector[i])/(numClusterSamples + 1);
+ newClusterMean.push_back(tempValue);
+ }
+
+ numEigenVectors = 0;
+ double eigenEnergy = 0;
+ for( i = 0; i < eigenValues.size(); i++)
+ {
+ eigenEnergy += eigenValues[i];
+ }
+
+ double tempEigenEnergy = 0;
+
+ while(tempEigenEnergy <= ((m_activedtwShapeRecognizer->m_percentEigenEnergy * eigenEnergy)/100))
+ tempEigenEnergy += eigenValues[numEigenVectors++];
+
+
+ doubleVector selectedEigenValues;
+ double2DVector selectedEigenVectors;
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ selectedEigenValues.push_back(eigenValues[i]);
+ selectedEigenVectors.push_back(newEigenVectors[i]);
+ }
+
+ //updating the cluster model
+
+ errorCode = clusterToAdapt.setNumSamples(numClusterSamples + 1);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ clusterToAdapt.setEigenValues(selectedEigenValues);
+ selectedEigenValues.clear();
+ clusterToAdapt.setEigenVectors(selectedEigenVectors);
+ selectedEigenVectors.clear();
+
+ clusterToAdapt.setClusterMean(newClusterMean);
+
+ currentClusterModelVector[clusterId] = clusterToAdapt;
+
+ shapeModelToAdapt.setClusterModelVector(currentClusterModelVector);
+
+ m_activedtwShapeRecognizer->m_prototypeShapes[index] = shapeModelToAdapt;
+
+ //clearing vectors
+ tempVector.clear();
+ coeff1.clear();
+ coeff2.clear();
+ gammaProjTestSample.clear();
+ eigenValues.clear();
+ newEigenVectors.clear();
+ intermediateEigenVectors.clear();
+ newClusterMean.clear();
+ eigenVectors.clear();
+ unitResidueVector.clear();
+ }
+
+ //clearing vectors
+ oldEigenValues.clear();
+ oldEigenVectors.clear();
+ oldClusterMean.clear();
+ doubleFeatureVector.clear();
+ projectedTestSample.clear();
+ residueVector.clear();
+ reverseProjection.clear();
+ diffVector.clear();
+ currentClusterModelVector.clear();
+
+ errorCode = m_activedtwShapeRecognizer->writePrototypeShapesToMDTFile();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "LTKAdapt::adaptCluster()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : adaptSingleton
+* DESCRIPTION : This method adapts the singleton sey with the
+new featureVector and trains the singleton set if the
+number of singletons exceeds a certain number
+* ARGUMENTS : INPUT
+featureVecToAdapt shapeFeature
+shapeId int
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int LTKAdapt::adaptSingleton(shapeFeature& featureVecToAdapt,int shapeId)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "LTKAdapt::adaptSingleton()" << endl;
+
+ //validating input parameters
+ if(m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.find(shapeId) == m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ int errorCode;
+
+ int index = 0;
+
+ //iterating prototypeShapes to find the shapeModel To Adapt
+ while(m_activedtwShapeRecognizer->m_prototypeShapes[index].getShapeId() != shapeId)
+ index++;
+
+ shapeMatrix currentSingletonVectors = m_activedtwShapeRecognizer->m_prototypeShapes[index].getSingletonVector();
+
+ currentSingletonVectors.push_back(featureVecToAdapt);
+
+ m_activedtwShapeRecognizer->m_prototypeShapes[index].setSingletonVector(currentSingletonVectors);
+
+ int singletonSize = currentSingletonVectors.size();
+
+ //train the singletons only if their number is above some threshold
+ if(singletonSize > (TRAINSINGLETONFACTOR * m_activedtwShapeRecognizer->m_minClusterSize) )
+ {
+ errorCode = trainSingletons(currentSingletonVectors,shapeId,index);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptSingleton()" << endl;
+ LTKReturnError(errorCode);
+ }
+ }
+
+ currentSingletonVectors.clear();
+
+ //updating the mdt file
+ errorCode = m_activedtwShapeRecognizer->writePrototypeShapesToMDTFile();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "LTKAdapt::adaptSingleton()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : trainSingletons
+* DESCRIPTION : This method trains the featureVectors in the singleton set
+* ARGUMENTS : INPUT
+singletons shapeMatrix
+shapeId int
+index int
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int LTKAdapt::trainSingletons(const shapeMatrix &singletons,int shapeId,int index)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "LTKAdapt::trainSingletons()" << endl;
+
+ //validating input arguments
+ if(m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.find(shapeId) == m_activedtwShapeRecognizer->m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ " LTKAdapt::adaptCluster()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ if(index < 0 || index >= m_activedtwShapeRecognizer->m_prototypeShapes.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROTOYPESHAPE_INDEX_OUT_OF_BOUND << " " <<
+ " LTKAdapt::adaptSingleton()" << endl;
+
+ LTKReturnError(EPROTOYPESHAPE_INDEX_OUT_OF_BOUND);
+ }
+
+ int errorCode;
+
+ LTKShapeSample tempShape;
+
+ vector<LTKShapeSample> shapesToTrain;
+
+ int singletonSize = singletons.size();
+
+ int2DVector clusterOutput;
+
+ shapeMatrix newSingletons;
+
+ vector<ActiveDTWClusterModel> currentClusterModelVector = m_activedtwShapeRecognizer->m_prototypeShapes[index].getClusterModelVector();
+
+ int i = 0;
+
+ for(i = 0; i < singletonSize; i++)
+ {
+ tempShape.setFeatureVector(singletons[i]);
+ shapesToTrain.push_back(tempShape);
+ }
+
+ //perform clustering
+ errorCode = m_activedtwShapeRecognizer->performClustering(shapesToTrain,clusterOutput);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainSingletons()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ int2DVector::iterator iter = clusterOutput.begin();
+ int2DVector::iterator iEnd = clusterOutput.end();
+ intVector cluster;
+
+ /**ITERATING THROUGH THE VARIOUS CLUSTERS **/
+ for(;iter != iEnd; ++iter)
+ {
+ cluster = (*iter);
+
+ /** SINGLETON VECTORS **/
+ if(cluster.size() < m_activedtwShapeRecognizer->m_minClusterSize)
+ {
+ for(i = 0; i < cluster.size(); i++)
+ newSingletons.push_back(shapesToTrain[cluster[i]].getFeatureVector());
+ }
+
+ /** CLUSTER PROCESSING **/
+ else
+ {
+ //creating new clusters
+ doubleVector tempFeature;
+
+ double2DVector featureMatrix;
+
+ double2DVector covarianceMatrix;
+
+ doubleVector clusterMean;
+
+ double2DVector intermediateEigenVectors;
+
+ double2DVector eigenVectors;
+
+ doubleVector eigenValues;
+
+ ActiveDTWClusterModel clusterModel;
+
+ //gather all the shape samples pertaining to a particular cluster
+ int clusterSize = cluster.size();
+ for(i = 0; i < clusterSize; i++)
+ {
+ floatVector floatFeatureVector;
+
+ errorCode = m_activedtwShapeRecognizer->m_shapeRecUtil.shapeFeatureVectorToFloatVector(shapesToTrain[cluster[i]].getFeatureVector(),
+ floatFeatureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ int floatFeatureVectorSize = floatFeatureVector.size();
+ for(int i = 0; i < floatFeatureVectorSize; i++)
+ tempFeature.push_back(floatFeatureVector[i]);
+
+ featureMatrix.push_back(tempFeature);
+ tempFeature.clear();
+ floatFeatureVector.clear();
+ }
+
+ /** COMPUTING COVARIANCE MATRIX **/
+ errorCode = m_activedtwShapeRecognizer->computeCovarianceMatrix(featureMatrix,covarianceMatrix,clusterMean);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ clusterModel.setClusterMean(clusterMean);
+
+ errorCode = m_activedtwShapeRecognizer->computeEigenVectorsForLargeDimension(featureMatrix,covarianceMatrix,intermediateEigenVectors,eigenValues);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ doubleVector tempEigenVector;
+ int eigenVectorDimension = intermediateEigenVectors.size();
+ if(eigenVectorDimension <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EEMPTY_EIGENVECTORS << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(EEMPTY_EIGENVECTORS);
+ }
+
+ int numEigenVectors = intermediateEigenVectors[0].size();
+
+ if(numEigenVectors <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_NUM_OF_EIGENVECTORS << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_EIGENVECTORS);
+ }
+
+ for(i = 0; i < numEigenVectors; i++)
+ {
+ for(int j = 0; j < eigenVectorDimension; j++)
+ tempEigenVector.push_back(intermediateEigenVectors[j][i]);
+
+ eigenVectors.push_back(tempEigenVector);
+ tempEigenVector.clear();
+ }
+
+ /**CONSTRUCTING CLUSTER MODEL **/
+
+ errorCode = clusterModel.setNumSamples(cluster.size());
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " LTKAdapt::trainSingletons()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ clusterModel.setEigenValues(eigenValues);
+
+ clusterModel.setEigenVectors(eigenVectors);
+
+ currentClusterModelVector.push_back(clusterModel);
+
+ //clearing vectors
+ featureMatrix.clear();
+ covarianceMatrix.clear();
+ clusterMean.clear();
+ intermediateEigenVectors.clear();
+ eigenVectors.clear();
+ eigenValues.clear();
+
+ }
+ }
+
+ //updating the shape model
+ (m_activedtwShapeRecognizer->m_prototypeShapes[index]).setClusterModelVector(currentClusterModelVector);
+ m_activedtwShapeRecognizer->m_prototypeShapes[index].setSingletonVector(newSingletons);
+
+ //clearing vectors
+ currentClusterModelVector.clear();
+ clusterOutput.clear();
+ shapesToTrain.clear();
+ newSingletons.clear();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "LTKAdapt::trainSingletons()" << endl;
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.h
new file mode 100644
index 00000000..276eeb24
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWAdapt.h
@@ -0,0 +1,194 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2009-04-06 11:55:15 +0530 (Mon, 06 Apr 2009) $
+* $Revision: 758 $
+* $Author: royva $
+*
+************************************************************************/
+
+/************************************************************************
+* FILE DESCR: Implements ActiveDTWShapeRecognizer::Adapt
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+* DATE: 3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description
+************************************************************************/
+#pragma once
+
+#include "ActiveDTWShapeRecognizer.h"
+#include "LTKLoggerUtil.h"
+#include "LTKConfigFileReader.h"
+#include "LTKErrors.h"
+#include "LTKErrorsList.h"
+#include "LTKPreprocDefaults.h"
+
+#define TRAINSINGLETONFACTOR 2
+
+class ActiveDTWShapeRecognizer;
+
+class LTKAdapt
+{
+private:
+ /** @name Constructor */
+ LTKAdapt(ActiveDTWShapeRecognizer* ptrActiveDTWShapeReco);
+
+
+ static LTKAdapt* adaptInstance;
+
+ static int m_count;
+ /**< @brief
+ * <p>
+ * Initially m_count = 0, when adapt is called on first sample
+ * it checks if m_count = 0, if yes it calls readAdaptConfig and then increments m_count to 1
+ * Thus readAdaptConfig is called only once
+ * </p>
+ */
+
+public:
+ static LTKAdapt* getInstance(ActiveDTWShapeRecognizer* ptrActiveDTWShapeReco);
+
+ /**
+ * Adapts the shapeId
+ *
+ * Semantics
+ *
+ * - Reads the internal classifier config information incase of first sample to be adapted
+
+ - Checks if the sample to be adapted was correctly classified or incorrectly classified
+
+ - Incase of correct classification
+ --Check if the shape was closest to the cluster or singletons
+ --If sample to be adapted was closest to the clusters, and cluster size does not exceed
+ m_maxClusterSize, then call adaptCluster
+ --It sample to be adapted was closest to the singleton, call adaptSingleton
+
+ -Incase of incorrect classification
+ --If the sample to be adapted was closest to a cluster, call adaptCluster
+ --If the sample to be adapted was closest to a singleton, call adaptSingleton
+ *
+ * @param shapeId : shape to be adapted
+ * @return SUCCESS : if the shapeId was adapted successfully
+ * ErrorCode: if some error occurs
+ * @exception ENEIGHBOR_INFO_VECTOR_EMPTY : ActiveDTWShapeRecognizer::m_neighbofInfoVec is empty
+ * @exception ESHAPE_SAMPLE_FEATURES_EMPTY : ActiveDTWShapeRecognizer::m_cachedShapeFeature is empty
+ */
+ int adapt(int shapeId);
+
+ /** @name Destructor */
+ ~LTKAdapt();
+
+ void deleteInstance();
+
+private:
+
+/**< @brief Pointer to ActiveDTWShapeRecognizer
+* <p>
+*
+* </p>
+ */
+ ActiveDTWShapeRecognizer* m_activedtwShapeRecognizer;
+
+ //the maximum number of samples in a cluster
+ int m_maxClusterSize;
+ /**< @brief Maximum Cluster Size
+ * <p>
+ * Specifies the maximum number of samples that can be present in a cluster
+ * It must be >= the ActiveDTWShapeRecognizer::m_minClusterSize
+ * </p>
+ */
+
+
+ /**
+ * This method reads Config variables related to Adapt from CFG
+ *
+ * Semantics
+ *
+ *
+ * @param none
+ *
+ * @return SUCCESS:
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int readAdaptConfig();
+
+ /**
+ * Adapts the cluster with the new shapeFeature
+ *
+ * Semantics
+ *
+ * - Recomputes the eigen values, eigen vectors and cluster mean,
+ * using the old values and the new shape feature
+ *
+ * @param featureVecToAdapt : shapeFeature
+ * @param clusterId : cluster to be adapted
+ * @param shapeId : shape to be adapted
+ * @return SUCCESS : if the shapeId was adapted successfully
+ * ErrorCode: if some error occurs
+ * @exception EINVALID_SHAPEID
+ * @exception EINVALID_CLUSTER_ID
+ */
+ int adaptCluster(shapeFeature& featureVecToAdapt,int clusterId,int shapeId);
+
+ /**
+ * Adapts the set of singletons with the new shapeFeature
+ *
+ * Semantics
+ *
+ * - Adds the new shapeFeature to the current set of singletons
+ *
+ * - If the number of singletons exceeds a certain threshold train the singletons
+ *
+ * @param featureVecToAdapt : shapeFeature
+ * @param shapeId : shape to be adapted
+ * @return SUCCESS : if the shapeId was adapted successfully
+ * ErrorCode: if some error occurs
+ * @exception EINVALID_SHAPEID
+ */
+ int adaptSingleton(shapeFeature& featureVecToAdapt,int shapeId);
+
+ /**
+ * Performs training on the set of singletons
+ *
+ * Semantics
+ *
+ * - performs clustering on the singletons, resulting in new clusters and singleton set
+ *
+ * - cluster and singleton information are added to the shape model
+ *
+ * @param singletons : shapeMatrix
+ * @param shapeId : shape to be adapted
+ * @param index : index in ActiveDTWShapeRecognizer::m_prototypeShapes which holds the shapeModel information
+ * @return SUCCESS : if the shapeId was adapted successfully
+ * ErrorCode: if some error occurs
+ * @exception EINVALID_SHAPEID : shapeId specified is Invalid
+ * @exception EPROTOYPESHAPE_INDEX_OUT_OF_BOUND ; index value specified is Invalid
+ * @exception EEMPTY_EIGENVECTORS ; eigen vector dimension is < 0
+ * @exception EINVALID_NUM_OF_EIGENVECTORS : number of eigen vectors < 0
+ */
+ int trainSingletons(const shapeMatrix &singletons,int shapeId,int index);
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.cpp
new file mode 100644
index 00000000..34886d32
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.cpp
@@ -0,0 +1,211 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2009-04-06 11:55:15 +0530 (Mon, 06 Apr 2009) $
+* $Revision: 758 $
+* $Author: royva $
+*
+************************************************************************/
+/*********************************************************************************************
+* FILE DESCR: Implementation for ActiveDTW Cluster Model. Used to store cluster model information
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+w
+* DATE:3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+***********************************************************************************************/
+
+#include "ActiveDTWClusterModel.h"
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ActiveDTWClusterModel
+* DESCRIPTION : Default Constructor
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWClusterModel::ActiveDTWClusterModel()
+{
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setNumSamples
+* DESCRIPTION : sets the number of samples in the cluster
+* ARGUMENTS : INPUT: numSamples
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWClusterModel::setNumSamples(int numSamples)
+{
+ if(numSamples > 0)
+ {
+ m_numberOfSamples = numSamples;
+ }
+ else
+ {
+ LTKReturnError(EINVALID_NUM_SAMPLES);
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getNumSamples
+* DESCRIPTION : returns the number of samples in a cluster
+* ARGUMENTS : none
+* RETURNS : number of samples
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWClusterModel::getNumSamples() const
+{
+ return m_numberOfSamples;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setEigenValues
+* DESCRIPTION : sets the eigen values of the cluster
+* ARGUMENTS : INPUT: eigen values
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void ActiveDTWClusterModel::setEigenValues(const doubleVector& eigVal)
+{
+ m_eigenValues = eigVal;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setClusterMean
+* DESCRIPTION : sets the cluster mean of the cluster
+* ARGUMENTS : INPUT: clusterMean
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void ActiveDTWClusterModel::setClusterMean(const doubleVector& clusterMean)
+{
+ m_clusterMean = clusterMean;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getEigenValues
+* DESCRIPTION : returns the eigen values of the cluster
+* ARGUMENTS : none
+* RETURNS : eigen values
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+const doubleVector& ActiveDTWClusterModel::getEigenValues() const
+{
+ return m_eigenValues;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setEigenVectors
+* DESCRIPTION : sets the eigen vectors of the cluster
+* ARGUMENTS : eigen vectors
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void ActiveDTWClusterModel::setEigenVectors(const double2DVector& eigVec)
+{
+ m_eigenVectors = eigVec;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getEigenVectors
+* DESCRIPTION : returns the eigen vectors of the cluster
+* ARGUMENTS : none
+* RETURNS : eigen vectors
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+const double2DVector& ActiveDTWClusterModel::getEigenVectors() const
+{
+ return m_eigenVectors;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getClusterMean
+* DESCRIPTION : returns the cluster mean of the cluster
+* ARGUMENTS : none
+* RETURNS : cluster mean
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+const doubleVector& ActiveDTWClusterModel::getClusterMean() const
+{
+ return m_clusterMean;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ~ActiveDTWClusterModel
+* DESCRIPTION : Default Destructor
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWClusterModel::~ActiveDTWClusterModel()
+{
+
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.h
new file mode 100644
index 00000000..4d183487
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWClusterModel.h
@@ -0,0 +1,161 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2011-01-11 13:48:17 +0530 (Tue, 11 Jan 2011) $
+* $Revision: 827 $
+* $Author: mnab $
+*
+************************************************************************/
+/*********************************************************************************************
+* FILE DESCR: Definitions for ActiveDTWClusterModel Class
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+* DATE:3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+***********************************************************************************************/
+
+
+#ifndef ACTIVEDTWCLUSTERMODEL_H
+#define ACTIVEDTWCLUSTERMODEL_H
+
+#include <iostream>
+#include "LTKTypes.h"
+#include "LTKInc.h"
+#include "LTKMacros.h"
+#include "LTKErrors.h"
+#include "LTKErrorsList.h"
+
+using namespace std;
+
+typedef vector<double> doubleVector;
+typedef vector<doubleVector> double2DVector;
+
+/**
+* @ingroup ActiveDTWShapeModel.h
+* @brief The Header file for the ActiveDTWShapeModel
+* @class ActiveDTWShapeModel
+*<p> <p>
+*/
+class ActiveDTWClusterModel
+{
+private:
+ int m_numberOfSamples;
+ /** @brief Number of samples in the cluster
+ * <p>
+ * Specifies the number of samples in the cluster
+ * </p>
+ */
+
+ doubleVector m_eigenValues;
+ /** @brief Eigen Values
+ * <p>
+ * Eigen values of the cluster covariance matrix
+ * </p>
+ */
+
+ double2DVector m_eigenVectors;
+ /** @brief Eigen Vectors
+ * <p>
+ * Eigen vectors of the cluster covariance matrix
+ * </p>
+ */
+
+ doubleVector m_clusterMean;
+ /** @brief Cluster mean
+ * <p>
+ * Mean of all the samples forming the cluster
+ * </p>
+ */
+
+public:
+
+ /** @name Constructors and Destructor */
+ ActiveDTWClusterModel();
+
+ ~ActiveDTWClusterModel();
+
+ /**
+ * Sets the number of samples in the cluster
+ * @param numSamples
+ * @return SUCCESS : if the number of samples was set successfully
+ * @exception EINVALID_SHAPEID
+ */
+ int setNumSamples(int numSamples);
+
+ /**
+ * Sets the eigen values of the cluser
+ * @param eigVal
+ * @return SUCCESS : if the number of samples was set successfully
+ * @exception EINVALID_SHAPEID
+ */
+ void setEigenValues(const doubleVector& eigVal);
+
+ /**
+ * Sets the eigen vectors of the cluster
+ * @param eigVec
+ * @return SUCCESS : if the number of samples was set successfully
+ * @exception EINVALID_SHAPEID
+ */
+ void setEigenVectors(const double2DVector& eigVec);
+
+ /**
+ * Sets the mean of the cluster
+ * @param clusterMean
+ * @return SUCCESS : if the number of samples was set successfully
+ * @exception EINVALID_SHAPEID
+ */
+ void setClusterMean(const doubleVector& clusterMean);
+
+ /**
+ * Returns the number of samples in the cluster
+ * @return number of samples
+ * @exception EINVALID_SHAPEID
+ */
+ int getNumSamples() const;
+
+ /**
+ * Returns the eigen values of the cluster
+ * @return eigen values
+ * @exception EINVALID_SHAPEID
+ */
+ const doubleVector& getEigenValues() const;
+
+ /**
+ * Returns the eigen vectors of the cluster
+ * @return eigen vectors
+ * @exception EINVALID_SHAPEID
+ */
+ const double2DVector& getEigenVectors() const;
+
+ /**
+ * Returns the mean of the cluster
+ * @return cluster mean
+ * @exception EINVALID_SHAPEID
+ */
+ const doubleVector& getClusterMean() const;
+
+
+};
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.cpp
new file mode 100644
index 00000000..2514a626
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.cpp
@@ -0,0 +1,178 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2009-04-06 11:55:15 +0530 (Mon, 06 Apr 2009) $
+* $Revision: 758 $
+* $Author: royva $
+*
+************************************************************************/
+/*********************************************************************************************
+* FILE DESCR: Implementation for ActiveDTW Shape Model. Used to store shape model information
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+* DATE:3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+***********************************************************************************************/
+
+#include "ActiveDTWShapeModel.h"
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ActiveDTWShapeModel
+* DESCRIPTION : Default Constructor
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWShapeModel::ActiveDTWShapeModel()
+{
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setShapeId
+* DESCRIPTION : sets the shape id for the shape model
+* ARGUMENTS : INPUT: shapeId
+* RETURNS : SUCCESS - on successfully setting the shape id
+: ErrorCode - otherwise
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeModel::setShapeId(const int shapeId)
+{
+ if(shapeId >= 0)
+ {
+ m_shapeId = shapeId;
+ }
+ else
+ {
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setClusterModelVector
+* DESCRIPTION : sets the vector of clusters for the ActiveDTWShapeModel
+* ARGUMENTS : INPUT: clusterModelVector
+* RETURNS : NONE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void ActiveDTWShapeModel::setClusterModelVector(const vector<ActiveDTWClusterModel>& clusterModelVector)
+{
+ m_clusterModelVector = clusterModelVector;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setSingletonVector
+* DESCRIPTION : sets the vector of singletons for the shape model
+* ARGUMENTS : INPUT: shapeId
+* RETURNS : NONE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void ActiveDTWShapeModel::setSingletonVector(const shapeMatrix& singletonVector)
+{
+ m_singletonVector = singletonVector;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getShapeId
+* DESCRIPTION : returns the shapeId of the model
+* ARGUMENTS : INPUT: NULL
+* RETURNS : shapeId
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeModel::getShapeId() const
+{
+ return m_shapeId;
+}
+
+/*************************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getClusterModelVector
+* DESCRIPTION : returns the clusters model vector
+* ARGUMENTS : INPUT: NULL
+* RETURNS : clusterModelVector
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+const vector<ActiveDTWClusterModel>& ActiveDTWShapeModel::getClusterModelVector() const
+{
+ return m_clusterModelVector;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getSingletonVector
+* DESCRIPTION : returns the set of singleton vectors
+* ARGUMENTS : INPUT: NULL
+* RETURNS : shapeMatrix
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+const shapeMatrix& ActiveDTWShapeModel::getSingletonVector() const
+{
+ return m_singletonVector;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ~ActiveDTWShapeModel
+* DESCRIPTION : Destructor
+* ARGUMENTS : NONE
+* RETURNS : NONE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWShapeModel::~ActiveDTWShapeModel()
+{
+
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.h
new file mode 100644
index 00000000..f79182ea
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeModel.h
@@ -0,0 +1,139 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2009-04-06 11:55:15 +0530 (Mon, 06 Apr 2009) $
+* $Revision: 758 $
+* $Author: royva $
+*
+************************************************************************/
+/************************************************************************
+* FILE DESCR: Definitions for ActiveDTW Shape Recognition module
+*
+* CONTENTS:
+*
+* AUTHOR:
+*
+* DATE:
+* CHANGE HISTORY:
+* Author Date Description of change
+************************************************************************/
+#ifndef ACTIVEDTWSHAPEMODEL_H
+#define ACTIVEDTWSHAPEMODEL_H
+#include <iostream>
+#include "LTKTypes.h"
+#include "ActiveDTWClusterModel.h"
+#include "LTKShapeFeatureMacros.h"
+#include "LTKShapeFeature.h"
+#include "LTKInc.h"
+
+using namespace std;
+
+typedef vector<LTKShapeFeaturePtr> shapeFeature;
+typedef vector<shapeFeature> shapeMatrix;
+
+/**
+* @ingroup ActiveDTWShapeModel.h
+* @brief The Header file for the ActiveDTWShapeModel
+* @class ActiveDTWShapeModel
+*<p> <p>
+*/
+class ActiveDTWShapeModel
+{
+private:
+ int m_shapeId;
+ /** @brief shape id of the class
+ * <p>
+ * It specifies a specific shape id to each shape model
+ * </p>
+ */
+
+ vector<ActiveDTWClusterModel> m_clusterModelVector;
+ /**< @brief vector of cluster models
+ * <p>
+ * Contains the information of all the clusters of the class
+ * </p>
+ */
+
+ shapeMatrix m_singletonVector;
+ /**< @brief singletons /free samples of the class
+ * <p>
+ * Contains all the singleton vectors of the class
+ * </p>
+ */
+
+public:
+
+ /** @name Constructors and Destructor */
+ ActiveDTWShapeModel();
+
+ ~ActiveDTWShapeModel();
+
+ /**
+ * Sets the shapeId of the class
+ * @param shapeId
+ * @return SUCCESS : if the shapeId was set successfully
+ * @exception EINVALID_SHAPEID
+ */
+ int setShapeId(const int shapeId);
+
+ /**
+ * Sets the clusterModelVector of the class
+ * @param clusterModelVector : vector<ActiveDTWClusterModel>
+ * @return NULL
+ * @exception None
+ */
+ void setClusterModelVector(const vector<ActiveDTWClusterModel>& clusterModelVector);
+
+ /**
+ * Sets the singleton vector of the class
+ * @param singletonVector : shapeMatrix
+ * @return NULL
+ * @exception None
+ */
+ void setSingletonVector(const shapeMatrix& singletonVector);
+
+ /**
+ * Returns the shapeId of the class
+ * @param None
+ * @return shapeId
+ * @exception None
+ */
+ int getShapeId() const;
+
+ /**
+ * Returns the clusterModelVector of the class
+ * @param None
+ * @return vector<ActiveDTWClusterModel>
+ * @exception None
+ */
+ const vector<ActiveDTWClusterModel>& getClusterModelVector() const;
+
+ /**
+ * Returns the singletonVector of the class
+ * @param None
+ * @return shapeMatrix
+ * @exception None
+ */
+ const shapeMatrix& getSingletonVector() const ;
+};
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.cpp
new file mode 100644
index 00000000..247f5f98
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.cpp
@@ -0,0 +1,6257 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2011-02-08 16:57:52 +0530 (Tue, 08 Feb 2011) $
+* $Revision: 834 $
+* $Author: mnab $
+*
+************************************************************************/
+/************************************************************************
+* FILE DESCR: Implementation for ActiveDTW Shape Recognition module
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+w
+* DATE: 3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+************************************************************************/
+
+#include "LTKConfigFileReader.h"
+
+#include "ActiveDTWShapeRecognizer.h"
+
+#include "LTKPreprocDefaults.h"
+
+#include "LTKHierarchicalClustering.h"
+
+#include "LTKPreprocessorInterface.h"
+
+#include "LTKShapeFeatureExtractorFactory.h"
+
+#include "LTKShapeFeatureExtractor.h"
+
+#include "LTKShapeFeature.h"
+
+#include "LTKVersionCompatibilityCheck.h"
+
+#include "LTKInkFileWriter.h"
+#include "LTKOSUtil.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKClassifierDefaults.h"
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ActiveDTWShapeRecognizer
+* DESCRIPTION : Default Constructor that initializes all data members
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+
+void ActiveDTWShapeRecognizer::assignDefaultValues()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::assignDefaultValues()" << endl;
+
+ m_numShapes = 0;
+ m_activedtwCfgFilePath = "";
+ m_activedtwMDTFilePath = "";
+ m_ptrPreproc = NULL;
+ m_projectTypeDynamic=false;
+ m_prototypeSelection=NN_DEF_PROTOTYPESELECTION;
+ m_prototypeReductionFactor=NN_DEF_PROTOTYPEREDUCTIONFACTOR;
+ m_nearestNeighbors=NN_DEF_NEARESTNEIGHBORS;
+ m_dtwBanding=NN_DEF_BANDING;
+ m_dtwEuclideanFilter= ACTIVEDTW_DEF_DTWEUCLIDEANFILTER;
+ m_preProcSeqn=NN_DEF_PREPROC_SEQ;
+ m_ptrFeatureExtractor=NULL;
+ m_featureExtractorName=NN_DEF_FEATURE_EXTRACTOR;
+ m_numClusters=NN_NUM_CLUST_INITIAL;
+ m_MDTUpdateFreq=NN_DEF_MDT_UPDATE_FREQ;
+ m_prototypeSetModifyCount=0;
+ m_rejectThreshold=NN_DEF_REJECT_THRESHOLD;
+ m_adaptivekNN=false;
+ m_deleteLTKLipiPreProcessor=NULL;
+ m_minClusterSize = ADAPT_DEF_MIN_NUMBER_SAMPLES_PER_CLASS;
+ m_percentEigenEnergy = ACTIVEDTW_DEF_PERCENTEIGENENERGY;
+ m_eigenSpreadValue = ACTIVEDTW_DEF_EIGENSPREADVALUE;
+ m_useSingleton = ACTIVEDTW_DEF_USESINGLETON;
+ m_MDTFileOpenMode = NN_MDT_OPEN_MODE_ASCII;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::assignDefaultValues()" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : initialize
+* DESCRIPTION : This method initializes the ActiveDTW shape recognizer
+* ARGUMENTS : string Holds the Project Name
+* string Holds the Profile Name
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no erros
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer(const LTKControlInfo& controlInfo):
+m_OSUtilPtr(LTKOSUtilFactory::getInstance()),
+m_libHandler(NULL),
+m_libHandlerFE(NULL)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" << endl;
+
+ try
+ {
+ LTKControlInfo tmpControlInfo=controlInfo;
+
+ string strProjectName = "";
+ string strProfileName = "";
+
+
+ if( (tmpControlInfo.projectName).empty() )
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+ if( (tmpControlInfo.lipiRoot).empty() )
+ {
+ throw LTKException(ELIPI_ROOT_PATH_NOT_SET);
+ }
+
+ if( (tmpControlInfo.profileName).empty() )
+ {
+ strProfileName = DEFAULT_PROFILE;
+ tmpControlInfo.profileName = strProfileName;
+ }
+
+ if ( tmpControlInfo.toolkitVersion.empty() )
+ {
+ throw LTKException(ENO_TOOLKIT_VERSION);
+ }
+
+ assignDefaultValues();
+
+ m_lipiRootPath = tmpControlInfo.lipiRoot;
+ m_lipiLibPath = tmpControlInfo.lipiLib;
+ m_currentVersion = tmpControlInfo.toolkitVersion;
+ strProjectName = tmpControlInfo.projectName;
+ strProfileName = tmpControlInfo.profileName;
+
+
+ //Model Data file Header Information
+ m_headerInfo[PROJNAME] = strProjectName;
+
+ //Holds the value of Number of Shapes in string format
+ string strNumShapes = "";
+
+ string strProfileDirectory = m_lipiRootPath + PROJECTS_PATH_STRING +
+ strProjectName + PROFILE_PATH_STRING;
+
+ //Holds the path of the Preproc.dll
+
+ //Holds the path of the Project.cfg
+ string projectCFGPath = strProfileDirectory + PROJECT_CFG_STRING;
+
+ // Config file
+
+ m_activedtwCfgFilePath = m_lipiRootPath + PROJECTS_PATH_STRING +
+ (tmpControlInfo.projectName) + PROFILE_PATH_STRING +
+ (tmpControlInfo.profileName) + SEPARATOR +
+ ACTIVEDTW + CONFIGFILEEXT;
+
+
+ //Set the path for activedtw.mdt
+ m_activedtwMDTFilePath = strProfileDirectory + strProfileName + SEPARATOR + ACTIVEDTW + DATFILEEXT;
+
+
+ //To find whether the project was dynamic or not andto read read number of shapes from project.cfg
+ int errorCode = m_shapeRecUtil.isProjectDynamic(projectCFGPath,
+ m_numShapes, strNumShapes, m_projectTypeDynamic);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Set the NumShapes to the m_headerInfo
+ m_headerInfo[NUMSHAPES] = strNumShapes;
+
+ //Currently preproc cfg also present in ActiveDTW
+ tmpControlInfo.cfgFileName = ACTIVEDTW;
+ errorCode = initializePreprocessor(tmpControlInfo,&m_ptrPreproc);
+
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Reading ActiveDTW configuration file
+ errorCode = readClassifierConfig();
+
+
+ if( errorCode != SUCCESS)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Writing Feature extractor name and version into the header
+ m_headerInfo[FE_NAME] = m_featureExtractorName;
+ //FE version
+ m_headerInfo[FE_VER] = SUPPORTED_MIN_VERSION;
+
+ //Writing mdt file open mode to the mdt header
+ m_headerInfo[MDT_FOPEN_MODE] = m_MDTFileOpenMode;
+
+ errorCode = initializeFeatureExtractorInstance(tmpControlInfo);
+
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+ }
+ catch(LTKException e)
+ {
+ deletePreprocessor();
+ m_prototypeShapes.clear();
+
+ m_cachedShapeFeature.clear();
+
+ //Unloading the feature Extractor instance
+ deleteFeatureExtractorInstance();
+
+ delete m_OSUtilPtr;
+ throw e;
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::ActiveDTWShapeRecognizer()" << endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : readClassifierConfig
+* DESCRIPTION : Reads the ActiveDTW.cfg and initializes the data members of the class
+* ARGUMENTS : none
+* RETURNS : SUCCESS - If config file read successfully
+* errorCode - If failure
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::readClassifierConfig()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::readClassifierConfig()" << endl;
+ string tempStringVar = "";
+ int tempIntegerVar = 0;
+ float tempFloatVar = 0.0;
+ LTKConfigFileReader *shapeRecognizerProperties = NULL;
+ int errorCode = FAILURE;
+
+ try
+ {
+ shapeRecognizerProperties = new LTKConfigFileReader(m_activedtwCfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<< "Info: " <<
+ "Config file not found, using default values of the parameters" <<
+ "ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ return FAILURE;
+ }
+
+ //Pre-processing sequence
+ errorCode = shapeRecognizerProperties->getConfigValue(PREPROCSEQUENCE, m_preProcSeqn);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Info: " <<
+ "Using default value of prerocessing sequence: "<< m_preProcSeqn <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ m_preProcSeqn = NN_DEF_PREPROC_SEQ;
+ }
+ else
+ {
+ m_headerInfo[PREPROC_SEQ] = m_preProcSeqn;
+ }
+
+
+ if((errorCode = mapPreprocFunctions()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<" Error: " << errorCode << " " <<
+ "ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(errorCode);
+ }
+
+ //reading percent of eigen energy
+ tempStringVar = "";
+
+ errorCode = shapeRecognizerProperties->getConfigValue(RETAINPERCENTEIGENENERGY,
+ tempStringVar);
+ if(errorCode == SUCCESS )
+ {
+ if (LTKStringUtil::isFloat(tempStringVar))
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar >= MIN_PERCENT_EIGEN_ENERGY && tempFloatVar <= MAX_PERCENT_EIGEN_ENERGY)
+ {
+ m_percentEigenEnergy = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ RETAINPERCENTEIGENENERGY " = " << m_percentEigenEnergy<< endl;
+
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " " << RETAINPERCENTEIGENENERGY
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " " << RETAINPERCENTEIGENENERGY
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()" << endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Using default value for " << RETAINPERCENTEIGENENERGY << ": " <<
+ m_percentEigenEnergy << " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+
+ //reading method of prototype selection
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PROTOTYPESELECTION,
+ tempStringVar);
+
+ if (errorCode == SUCCESS)
+ {
+ if( (LTKSTRCMP(tempStringVar.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0))
+ {
+ m_prototypeSelection = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ PROTOTYPESELECTION << " = " << tempStringVar <<
+ "ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " " <<
+ PROTOTYPESELECTION << " : " << tempStringVar
+ << " method is not supported" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << PROTOTYPESELECTION << " : " << m_prototypeSelection <<
+ " ActiveDTwShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+
+ //reading prototype reduction factor
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PROTOREDFACTOR,
+ tempStringVar);
+
+ string tempStringVar1 = "";
+ int errorCode1 = shapeRecognizerProperties->getConfigValue(NUMCLUSTERS,
+ tempStringVar1);
+
+ //prototype reduction factor
+ if(errorCode1 == SUCCESS && errorCode == SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ << " Cannot use both config parameters " <<
+ PROTOREDFACTOR << " and " << NUMCLUSTERS << " at the same time "<<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ if(tempStringVar != "")
+ {
+ if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_AUTOMATIC)==0)
+ {
+ //DEFINE MACRO DEF_PROTO_RED_FACTOR
+ m_prototypeReductionFactor = -1;
+ }
+ else if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_NONE)==0)
+ {
+ m_prototypeReductionFactor = 0;
+ }
+ else if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_COMPLETE) == 0)
+ {
+ m_prototypeReductionFactor = 100;
+ }
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+ if(tempIntegerVar >= 0 && tempIntegerVar <=100)
+ {
+ m_prototypeReductionFactor = tempIntegerVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << PROTOREDFACTOR << " is =" << tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ PROTOREDFACTOR << " is out of permitted range " <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ PROTOREDFACTOR << " is out of permitted range"<<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ }
+ }
+ else if(tempStringVar1 != "")
+ {
+ if(LTKSTRCMP(tempStringVar1.c_str(), PROTO_RED_FACTOR_AUTOMATIC) == 0)
+ {
+ m_prototypeReductionFactor = -1;
+ }
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar1) )
+ {
+ tempIntegerVar = atoi((tempStringVar1).c_str());
+ if(tempIntegerVar > 0)
+ {
+ m_numClusters = tempIntegerVar;
+
+ // m_numClusters is used in this case
+ m_prototypeReductionFactor = NN_NUM_CLUST_INITIAL;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NUMCLUSTERS << " is = " << tempStringVar << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ NUMCLUSTERS << " is out of permitted range "<<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ " Error: " << ECONFIG_FILE_RANGE <<
+ NUMCLUSTERS << " is out of permitted range"<<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Assuming default value of " NUMCLUSTERS << " : " << m_numClusters << endl;
+ }
+
+ //reading adaptive kNN
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(ADAPTIVE_kNN, tempStringVar);
+ if(LTKSTRCMP(tempStringVar.c_str(), "true") ==0)
+ {
+ m_adaptivekNN = true;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Confidence computation method: " << ADAPTIVE_kNN << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << ADAPTIVE_kNN << " : " <<
+ m_adaptivekNN << endl;
+ }
+
+ //reading nearest neighbors
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEARESTNEIGHBORS,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ //Valid values of nearest neighbors: 1 or greater than MIN_NEARESTNEIGHBORS
+ if(tempIntegerVar > 0)
+ {
+ // If the value of NearestNeighbors = 1, ActiveDTW recognizer is used
+ if(tempIntegerVar == 1)
+ {
+ m_adaptivekNN = false;
+ }
+
+ // If AdaptivekNN is set to false, simply assign the value to m_nearestNeighbors
+ // If AdaptivekNN is set, NearestNeighbors should be greater than than the
+ // minimum no.of nearest neighbors allowed (MIN_NEARESTNEIGHBORS defined as macro)
+ if(!m_adaptivekNN || (m_adaptivekNN && tempIntegerVar >= MIN_NEARESTNEIGHBORS))
+ {
+ m_nearestNeighbors = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEARESTNEIGHBORS << " = " <<m_nearestNeighbors<<endl;
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEARESTNEIGHBORS <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEARESTNEIGHBORS <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Debug: " << "Using default value for " << NEARESTNEIGHBORS <<
+ " : " << m_nearestNeighbors << endl;
+ }
+
+ //reading reject threshold
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(REJECT_THRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar < 1)
+ {
+ m_rejectThreshold = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ REJECT_THRESHOLD << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << REJECT_THRESHOLD <<
+ " : " << m_rejectThreshold << endl;
+ }
+
+ //reading min cluster Size
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MINCLUSTERSIZE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if(LTKStringUtil::isInteger(tempStringVar))
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ if(tempIntegerVar > 1)
+ {
+ m_minClusterSize = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ MINCLUSTERSIZE << " = " <<m_minClusterSize<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << m_minClusterSize <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << MINCLUSTERSIZE <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MINCLUSTERSIZE << " : " << m_minClusterSize << endl;
+ }
+
+ //reading eigen spread value
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(EIGENSPREADVALUE,
+ tempStringVar);
+
+
+
+ if(errorCode == SUCCESS)
+ {
+ if(LTKStringUtil::isInteger(tempStringVar))
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ if(tempIntegerVar > 0)
+ {
+ m_eigenSpreadValue = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ EIGENSPREADVALUE << " = " <<m_eigenSpreadValue<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << EIGENSPREADVALUE <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << EIGENSPREADVALUE <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << EIGENSPREADVALUE << " : " << m_eigenSpreadValue << endl;
+ }
+
+ //reading use singleton
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(USESINGLETON, tempStringVar);
+ if(LTKSTRCMP(tempStringVar.c_str(), "false") ==0)
+ {
+ m_useSingleton = false;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Use Singleton: " << USESINGLETON << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << USESINGLETON << " : " <<
+ m_useSingleton << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DTWBANDING,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar <= 1)
+ {
+ m_dtwBanding = tempFloatVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ DTWBANDING << " = " <<m_dtwBanding<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << DTWBANDING <<
+ " is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE <<
+ " DTWBANDING is out of permitted range" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << DTWBANDING << " : " << m_dtwBanding << endl;
+ }
+
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DTWEUCLIDEANFILTER,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if(LTKSTRCMP(tempStringVar.c_str(), DTW_EU_FILTER_ALL) == 0)
+ {
+ m_dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ }
+
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ if(tempIntegerVar > 0 && tempIntegerVar <= 100)
+ {
+ if(tempIntegerVar == 100 )
+ m_dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ else
+ m_dtwEuclideanFilter = tempIntegerVar;
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ DTWEUCLIDEANFILTER << " is = "<<
+ m_dtwEuclideanFilter<<endl;
+ }
+ else
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ DTWEUCLIDEANFILTER << " is out of permitted range " <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << DTWEUCLIDEANFILTER <<
+ " is out of permitted range"<<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << DTWEUCLIDEANFILTER <<
+ " : " << m_dtwEuclideanFilter << endl;
+ }
+
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(FEATUREEXTRACTOR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_featureExtractorName = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ FEATUREEXTRACTOR << " = "<<tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << FEATUREEXTRACTOR << " : " <<
+ m_featureExtractorName << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MDTFILEUPDATEFREQ,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ m_MDTUpdateFreq = atoi(tempStringVar.c_str());
+ if(m_MDTUpdateFreq <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDTFILEUPDATEFREQ <<
+ " should be zero or a positive integer" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDTFILEUPDATEFREQ <<
+ " should be zero or a positive integer" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MDT_UPDATE_FREQUENCY <<
+ " : " << m_MDTUpdateFreq << endl;
+ }
+
+
+
+ //reading mdt file open mode
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MDT_FILE_OPEN_MODE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( tempStringVar == NN_MDT_OPEN_MODE_ASCII ||
+ tempStringVar == NN_MDT_OPEN_MODE_BINARY )
+ {
+ m_MDTFileOpenMode = tempStringVar;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDT_FILE_OPEN_MODE <<
+ " should be ascii or binary" <<
+ " ActiveDTWShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MDT_FILE_OPEN_MODE <<
+ " : " << m_MDTFileOpenMode << endl;
+ }
+
+
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_SIZE_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(ASPECTRATIOTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[ASP_RATIO_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DOTTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVERELATIVEYPOSITION,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_REL_Y_POS] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVEASPECTRATIO,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_ASP_RATIO] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[NORM_LN_WID_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(RESAMPLINGMETHOD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[RESAMP_POINT_ALLOC] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SMOOTHFILTERLENGTH,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[SMOOTH_WIND_SIZE] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ LTKStringUtil::convertIntegerToString(m_ptrPreproc->getTraceDimension(),
+ tempStringVar);
+
+
+ m_headerInfo[TRACE_DIM] = tempStringVar;
+
+ delete shapeRecognizerProperties;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::readClassifierConfig()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : mapPreprocFunctions
+* DESCRIPTION : Maps the module name and its function names in the preprocessing
+sequence.
+* ARGUMENTS : none
+* RETURNS : SUCCESS on successful,
+* errorNumbers on Failure.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::mapPreprocFunctions()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ stringStringMap preProcSequence;
+
+ stringStringPair tmpPair;
+
+ stringVector moduleFuncNames;
+ stringVector modFuncs;
+ stringVector funcNameTokens;
+
+ string module = "", funName = "", sequence = "";
+ string::size_type indx;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ LTKStringUtil::tokenizeString(m_preProcSeqn, DELEMITER_SEQUENCE, funcNameTokens);
+
+ int numFunctions = funcNameTokens.size();
+
+ if(numFunctions == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Wrong preprocessor sequence in cfg file : " + m_preProcSeqn <<
+ " ActiveDTWShapeRecognizer::mapPreprocFunctions()"<<endl;
+
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+
+ for (indx = 0; indx < numFunctions ; indx++)
+ {
+ moduleFuncNames.push_back(funcNameTokens[indx]);
+ }
+
+ int numModuleFunctions = moduleFuncNames.size();
+
+ for(indx=0; indx < numModuleFunctions ; indx++)
+ {
+ sequence = moduleFuncNames[indx];
+
+ LTKStringUtil::tokenizeString(sequence, DELEMITER_FUNC, modFuncs);
+
+ if(modFuncs.size() >= 2)
+ {
+ module = modFuncs.at(0);
+
+ funName = modFuncs.at(1);
+
+ if(!module.compare("CommonPreProc"))
+ {
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+ if(pPreprocFunc!= NULL)
+ {
+ tmpPair.first = module;
+ tmpPair.second = funName;
+ m_preprocSequence.push_back(tmpPair);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " <<funName<<
+ " ActiveDTWShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " << module<<
+ " ActiveDTWShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : "<<module<<
+ " ActiveDTWShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : ~ActiveDTWShapeRecognizer
+* DESCRIPTION : destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ if(LTKAdapt::getInstance(this))
+ deleteAdaptInstance();
+
+ if(m_prototypeSetModifyCount >0)
+ {
+ m_prototypeSetModifyCount = m_MDTUpdateFreq-1;
+
+ returnStatus = writePrototypeShapesToMDTFile();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+ }
+
+ m_neighborInfoVec.clear();
+
+ returnStatus = deletePreprocessor();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ m_prototypeShapes.clear();
+ m_cachedShapeFeature.clear();
+
+ //Unloading the feature Extractor instance
+ returnStatus = deleteFeatureExtractorInstance();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ delete m_OSUtilPtr;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::~ActiveDTWShapeRecognizer()" << endl;
+}
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : train
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::train()" << endl;
+
+
+
+ int returnStatus = SUCCESS;
+
+
+ if(comment.empty() != true)
+ {
+ m_headerInfo[COMMENT] = comment;
+ }
+
+ if(dataset.empty() != true)
+ {
+ m_headerInfo[DATASET] = dataset;
+ }
+
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0)
+ {
+ returnStatus = trainClustering(trainingInputFilePath,
+ mdtHeaderFilePath,
+ trainFileType);
+
+ if(returnStatus != SUCCESS)
+ {
+ LTKReturnError(returnStatus);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::train()" << endl;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : trainClustering
+* DESCRIPTION : This function is the train method using Clustering prototype
+* selection technique.
+* ARGUMENTS :
+* RETURNS : SUCCESS : if training done successfully
+* errorCode : if traininhas some errors
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::trainClustering(const string& trainingInputFilePath,
+ const string &mdtHeaderFilePath,
+ const string& inFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::trainClustering()" << endl;
+
+
+ //Time at the beginning of Train Clustering
+ m_OSUtilPtr->recordStartTime();
+
+ int returnStatus = SUCCESS;
+
+ if(LTKSTRCMP(inFileType.c_str(), INK_FILE) == 0)
+ {
+ //If the Input file is UNIPEN Ink file
+ returnStatus = trainFromListFile(trainingInputFilePath);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " ActiveDTWShapeRecognizer::trainClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+ }
+
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ LTKCheckSumGenerate cheSumGen;
+
+ returnStatus = cheSumGen.addHeaderInfo(mdtHeaderFilePath,
+ m_activedtwMDTFilePath,
+ m_headerInfo);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " ActiveDTWShapeRecognizer::trainClustering()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ //Time at the end of Train Clustering
+ m_OSUtilPtr->recordEndTime();
+
+ string timeTaken = "";
+ m_OSUtilPtr->diffTime(timeTaken);
+
+ cout << "Time Taken = " << timeTaken << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::trainClustering()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : appendShapeModelToMDTFile
+* DESCRIPTION : This method is called after performing clustering on each class
+It writes the class information to the activedtw.mdt file
+* ARGUMENTS : INPUT
+shapeModel struct ActiveDTWShapeModel (class training data)
+mdtFileHandle ofstream (mdt File handle)
+
+ * RETURNS : integer Holds error value if occurs
+ * Holds SUCCESS if no erros
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::appendShapeModelToMDTFile(const ActiveDTWShapeModel& shapeModel,ofstream& mdtFileHandle)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::appendShapeModelToMDTFile()" << endl;
+
+
+ //used to temporarily store the size of a vector
+ int vecSize;
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_FILE_HANDLE << " " <<
+ "Invalid file handle for MDT file"<<
+ " ActiveDTWShapeRecognizer::appendShapeModelToMDTFile()" << endl;
+ LTKReturnError(EINVALID_FILE_HANDLE);
+ }
+
+ string strFeature;
+
+ vector<ActiveDTWClusterModel> clusterModelVector = shapeModel.getClusterModelVector();
+ vector<ActiveDTWClusterModel>::iterator iStart = clusterModelVector.begin();
+ vector<ActiveDTWClusterModel>::iterator iEnd = clusterModelVector.end();
+ double2DVector eigenVectors;
+ doubleVector eigenValues;
+ doubleVector clusterMean;
+ shapeMatrix singletonVector = shapeModel.getSingletonVector();
+ ActiveDTWClusterModel clusterModel;
+
+ /**APPENDING CLASS INFORMATION**/
+ //APPENDING CLASSID NUMCLUSTERS NUMSINGLETONS
+ if(m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII)
+ {
+ mdtFileHandle<<shapeModel.getShapeId()<<" "<<clusterModelVector.size()<<" "<<singletonVector.size()<<endl;
+ }
+ else
+ {
+ int clusterSize = clusterModelVector.size();
+ int singletonSize = singletonVector.size();
+ int shapeId = shapeModel.getShapeId();
+ int numFeatures;
+ int featureDimension;
+ int clusterMeanDimension;
+ mdtFileHandle.write((char*) &shapeId,sizeof(int));
+ mdtFileHandle.write((char*) &clusterSize,sizeof(int));
+ mdtFileHandle.write((char*) &singletonSize,sizeof(int));
+
+ if(clusterSize != 0)
+ {
+ clusterMean = clusterModelVector[0].getClusterMean();
+ clusterMeanDimension = clusterMean.size();
+ mdtFileHandle.write((char*) &clusterMeanDimension,sizeof(int));
+ }
+ else
+ {
+ clusterMeanDimension = 0;
+ mdtFileHandle.write((char*) &clusterMeanDimension,sizeof(int));
+ }
+
+ //writing number of features and feature dimension
+ if(singletonSize != 0)
+ {
+ numFeatures = singletonVector[0].size();
+ mdtFileHandle.write((char*) &numFeatures,sizeof(int));
+ featureDimension = singletonVector[0][0]->getFeatureDimension();
+ mdtFileHandle.write((char*) &featureDimension,sizeof(int));
+ }
+ else
+ {
+ numFeatures = 0;
+ mdtFileHandle.write((char*) &numFeatures,sizeof(int));
+ featureDimension = 0;
+ mdtFileHandle.write((char*) &featureDimension,sizeof(int));
+ }
+
+ }
+
+ /**APPENDING CLUSTER DATA**/
+ //iterating through the cluster models
+
+ for(;iStart != iEnd; ++iStart)
+ {
+
+ clusterModel = *iStart;
+
+
+ //appending number of clusters in each sample
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle<<clusterModel.getNumSamples()<<" ";
+ }
+ else
+ {
+ int numSamples = clusterModel.getNumSamples();
+ mdtFileHandle.write((char*) &numSamples,sizeof(int));
+ }
+
+
+ eigenValues = clusterModel.getEigenValues();
+ vecSize = eigenValues.size();
+
+ /**WRITING EIGEN VALUES**/
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ for(int i = 0; i < vecSize; i++)
+ {
+ mdtFileHandle<<eigenValues[i];
+ if(i != (vecSize - 1))
+ {
+ mdtFileHandle<<",";
+ }
+ }
+ mdtFileHandle<<FEATURE_EXTRACTOR_DELIMITER;
+ }
+ else
+ {
+ //writing number of eigen values
+ mdtFileHandle.write((char*) &vecSize,sizeof(int));
+
+ //writing eigenValues
+ for(int i = 0; i < vecSize; i++)
+ {
+ mdtFileHandle.write((char*) &(eigenValues[i]),sizeof(double));
+ }
+ }
+
+ /**WRITING EIGEN VECTORS**/
+
+ eigenVectors = clusterModel.getEigenVectors();
+ vecSize = eigenVectors[0].size();
+ int eigVecSize = eigenVectors.size();
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ for(int i = 0; i < eigVecSize; i++)
+ {
+ for(int j = 0; j < vecSize; j++)
+ {
+ mdtFileHandle<<eigenVectors[i][j];
+ if(j != (vecSize - 1))
+ {
+ mdtFileHandle<<",";
+ }
+ }
+ mdtFileHandle<<FEATURE_EXTRACTOR_DELIMITER;
+ }
+ }
+ else
+ {
+ for(int i = 0; i < eigVecSize; i++)
+ {
+ for(int j = 0; j < vecSize; j++)
+ {
+ mdtFileHandle.write((char*) &(eigenVectors[i][j]),sizeof(double));
+ }
+ }
+ }
+
+ /**APPENDING CLUSTER MEAN**/
+
+ clusterMean = clusterModel.getClusterMean();
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ for(int i = 0; i < vecSize; i++)
+ {
+ mdtFileHandle<<clusterMean[i];
+ if(i != (vecSize - 1))
+ {
+ mdtFileHandle<<",";
+ }
+
+ }
+ mdtFileHandle<<FEATURE_EXTRACTOR_DELIMITER<<endl;
+ }
+ else
+ {
+ for(int i = 0; i < vecSize; i++)
+ {
+ mdtFileHandle.write((char*) &(clusterMean[i]),sizeof(double));
+ }
+ }
+
+ eigenVectors.clear();
+ eigenValues.clear();
+ clusterMean.clear();
+
+ }
+ clusterModelVector.clear();
+
+ /**WRITING SINGLETON VECTORS**/
+ shapeMatrix::iterator iterStart = singletonVector.begin();
+ shapeMatrix::iterator iterEnd = singletonVector.end();
+ shapeFeature singleton;
+
+ for(; iterStart != iterEnd; ++iterStart )
+ {
+
+ singleton = *iterStart;
+
+ vecSize = singleton.size();
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = singleton.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = singleton.end();
+
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+ (*shapeFeatureIter)->toString(strFeature);
+ mdtFileHandle << strFeature << FEATURE_EXTRACTOR_DELIMITER;
+ }
+ mdtFileHandle<<endl;
+
+ }
+ else
+ {
+
+ //converting the singleton vector to float and writing it
+ floatVector floatFeatureVector;
+ int errorCode = m_shapeRecUtil.shapeFeatureVectorToFloatVector(singleton,
+ floatFeatureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<errorCode<<
+ " ActiveDTWShapeRecognizer::appendShapeModelToMDTFile" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ vecSize = floatFeatureVector.size();
+
+
+ for (int i=0; i< vecSize; i++)
+ {
+ float floatValue = floatFeatureVector[i];
+ mdtFileHandle.write((char *)(&floatValue), sizeof(float));
+ }
+ }
+ }
+
+ singletonVector.clear();
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::appendShapeModelToMDTFile()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : preprocess
+* DESCRIPTION : calls the required pre-processing functions from the LTKPreprocessor library
+* ARGUMENTS : inTraceGroup - reference to the input trace group
+* outPreprocessedTraceGroup - pre-processed inTraceGroup
+* RETURNS : SUCCESS on successful pre-processing operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::preprocess (const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outPreprocessedTraceGroup)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::preprocess()" << endl;
+
+ int indx = 0;
+ int errorCode = -1;
+
+ string module = "";
+ string funName = "" ;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ local_inTraceGroup = inTraceGroup;
+
+ if(m_preprocSequence.size() != 0)
+ {
+ while(indx < m_preprocSequence.size())
+ {
+ module = m_preprocSequence.at(indx).first;
+ funName = m_preprocSequence.at(indx).second;
+
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+
+ if(pPreprocFunc!= NULL)
+ {
+ outPreprocessedTraceGroup.emptyAllTraces();
+
+
+ if((errorCode = (m_ptrPreproc->*(pPreprocFunc))
+ (local_inTraceGroup,outPreprocessedTraceGroup)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::preprocess()" << endl;
+ LTKReturnError(errorCode);
+ }
+ local_inTraceGroup = outPreprocessedTraceGroup;
+ }
+ indx++;
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting ActiveDTWShapeRecognizer::preprocess()"<<endl;
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computerDTWDistanceClusteringWrapper
+* DESCRIPTION : Wrapper function to the function whichcomputes DTW distance between
+two characters
+* ARGUMENTS : train character, test character
+* RETURNS : DTWDistance
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::computeDTWDistance(
+ const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outDTWDistance)
+
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+
+ const vector<LTKShapeFeaturePtr>& firstFeatureVec = inFirstShapeSampleFeatures.getFeatureVector();
+ const vector<LTKShapeFeaturePtr>& secondFeatureVec = inSecondShapeSampleFeatures.getFeatureVector();
+
+ int errorCode = m_dtwObj.computeDTW(firstFeatureVec, secondFeatureVec, getDistance,outDTWDistance,
+ m_dtwBanding, FLT_MAX, FLT_MAX);
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "DTWDistance: " <<
+ outDTWDistance << endl;
+
+ if (errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: "<<
+ getErrorMessage(errorCode) <<
+ " ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computeDTWDistance
+* DESCRIPTION : This method computes the dtw distance between two shape features
+* ARGUMENTS : INPUT
+inFirstFeatureVector vector<LTKShapeFeaturePtr>
+inSecondFeatureVector vector<LTKShapeFeaturePtr>
+: OUTPUT
+outDTWDistance float
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::computeDTWDistance(
+ const vector<LTKShapeFeaturePtr>& inFirstFeatureVector,
+ const vector<LTKShapeFeaturePtr>& inSecondFeatureVector,
+ float& outDTWDistance)
+
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+
+ int errorCode = m_dtwObj.computeDTW(inFirstFeatureVector, inSecondFeatureVector, getDistance,outDTWDistance,
+ m_dtwBanding, FLT_MAX, FLT_MAX);
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "DTWDistance: " <<
+ outDTWDistance << endl;
+
+ if (errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: "<<
+ getErrorMessage(errorCode) <<
+ " ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeDTWDistance()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computeEuclideanDistance
+* DESCRIPTION : This computes the euclideanDistance between two shapeFeatures
+* ARGUMENTS : INPUT
+inFirstFeature shapeFeature
+inSecondFeature shapeFeature
+:OUTPUT
+outEuclideanDistance floats
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::computeEuclideanDistance(
+ const shapeFeature& inFirstFeature,
+ const shapeFeature& inSecondFeature,
+ float& outEuclideanDistance)
+{
+ int firstFeatureVectorSize = inFirstFeature.size();
+ int secondFeatureVectorSize = inSecondFeature.size();
+
+ if(firstFeatureVectorSize != secondFeatureVectorSize)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EUNEQUAL_LENGTH_VECTORS << " " <<
+ getErrorMessage(EUNEQUAL_LENGTH_VECTORS) <<
+ " ActiveDTWShapeRecognizer::computeEuclideanDistance()" << endl;
+
+ LTKReturnError(EUNEQUAL_LENGTH_VECTORS);
+ }
+
+ for(int i = 0; i < firstFeatureVectorSize; ++i)
+ {
+ float tempDistance = 0.0;
+ getDistance(inFirstFeature[i],
+ inSecondFeature[i],
+ tempDistance);
+
+ outEuclideanDistance += tempDistance;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeEuclideanDistance()" << endl;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : loadModelData
+* DESCRIPTION : loads the reference model file into memory
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful loading of the reference model file
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::loadModelData()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::loadModelData()" << endl;
+
+ int errorCode = -1;
+
+ int numofShapes = 0;
+
+ // variable for shape Id
+ int classId = -1;
+ int i = 0;
+
+ //Algorithm version
+ string algoVersionReadFromMDT = "";
+
+ stringStringMap headerSequence;
+ LTKCheckSumGenerate cheSumGen;
+
+ if(errorCode = cheSumGen.readMDTHeader(m_activedtwMDTFilePath,headerSequence))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // printing the headerseqn
+ stringStringMap::const_iterator iter = headerSequence.begin();
+ stringStringMap::const_iterator endIter = headerSequence.end();
+
+ for(; iter != endIter; iter++)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Debug: header seqn"<<
+ iter->first << " : " <<
+ iter->second << endl;
+ }
+
+ string featureExtractor = headerSequence[FE_NAME];
+
+ if(LTKSTRCMP(m_featureExtractorName.c_str(), featureExtractor.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of FeatureExtractor parameter in config file ("<<
+ m_featureExtractorName<<") does not match with the value in MDT file ("<<
+ featureExtractor<<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ string feVersion = headerSequence[FE_VER];
+
+ // comparing the mdt open mode read from cfg file with value in the mdt header
+ string mdtOpenMode = headerSequence[MDT_FOPEN_MODE];
+
+ if (LTKSTRCMP(m_MDTFileOpenMode.c_str(), mdtOpenMode.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of ActiveDTWMDTFileOpenMode parameter in config file ("<<
+ m_MDTFileOpenMode <<") does not match with the value in MDT file ("<<
+ mdtOpenMode<<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // validating preproc parameters
+ int iErrorCode = validatePreprocParameters(headerSequence);
+ if (iErrorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Values of ActiveMDTMDTFileOpenMode parameter in config file does not match with "
+ <<"the values in MDT file " << "ActiveDTWShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // Version comparison START
+ algoVersionReadFromMDT = headerSequence[RECVERSION].c_str();
+
+ LTKVersionCompatibilityCheck verTempObj;
+ string supportedMinVersion(SUPPORTED_MIN_VERSION);
+ string currentVersionStr(m_currentVersion);
+
+ bool compatibilityResults = verTempObj.checkCompatibility(supportedMinVersion,
+ currentVersionStr,
+ algoVersionReadFromMDT);
+
+ if(compatibilityResults == false)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINCOMPATIBLE_VERSION << " " <<
+ " Incompatible version"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EINCOMPATIBLE_VERSION);
+ }
+
+ // Version comparison END
+
+ //Input Stream for Model Data file
+ ifstream mdtFileHandle;
+
+ if (m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(), ios::in);
+ }
+ else
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(), ios::in | ios::binary);
+ }
+
+ //If error while opening, return an error
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ " Unable to open model data file : " <<m_activedtwMDTFilePath<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ mdtFileHandle.seekg(atoi(headerSequence[HEADERLEN].c_str()),ios::beg);
+
+ //Read the number of shapes
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> numofShapes;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &numofShapes,
+ atoi(headerSequence[SIZEOFSHORTINT].c_str()));
+ }
+
+ if(!m_projectTypeDynamic && m_numShapes != numofShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of NumShapes parameter in config file ("<<m_numShapes<<
+ ") does not match with the value in MDT file ("<<numofShapes<<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ if(m_projectTypeDynamic)
+ {
+ m_numShapes = numofShapes;
+ }
+
+ stringVector tokens;
+
+ stringVector subTokens;
+
+ string strFeatureVector = "";
+
+ //number of samples in each cluster
+ int numSamples;
+
+ //keeps count of number of clusters
+ // and singletons while reading from
+ //mdt file
+ int tempCount;
+
+ //number of clusters in a class
+ int numClusters;
+
+ //number of singletons in a class
+ int numSingletons;
+
+ //dimension of cluster mean
+ int clusterMeanDimension;
+
+ //number of features in a feature vector
+ int numFeatures;
+
+ //dimension of the featureVector
+ int featureDimension;
+
+
+ shapeMatrix singletonVector;
+ shapeFeature singleton;
+ doubleVector eigenValues;
+ double2DVector eigenVectors;
+ doubleVector clusterMean;
+ ActiveDTWClusterModel clusterModel;
+ ActiveDTWShapeModel shapeModel;
+ vector<ActiveDTWClusterModel> clusterModelVector;
+ doubleVector tempVector;
+
+ int floatSize = atoi(headerSequence[SIZEOFFLOAT].c_str());
+
+ int intSize = atoi(headerSequence[SIZEOFINT].c_str());
+
+ int doubleSize = sizeof(double);
+
+ //Each pass over the loop reads data corresponding to one class
+ //includes reading all the cluster data
+ //all singleton vectors
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> classId;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &classId, intSize);
+
+ }
+
+ while(!mdtFileHandle.eof())
+ {
+
+ /**READING CLASS INFORMATION**/
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> numClusters;
+
+ mdtFileHandle >> numSingletons;
+ }
+ else
+ {
+ //reading number of clusters, singletons, clusterMeanDimension,
+ //number of Features, and featureDimension
+ mdtFileHandle.read((char*) &numClusters,intSize);
+
+ mdtFileHandle.read((char*) &numSingletons,intSize);
+
+ mdtFileHandle.read((char*) &clusterMeanDimension,intSize);
+
+ mdtFileHandle.read((char*) &numFeatures,intSize);
+
+
+ mdtFileHandle.read((char*) &featureDimension,intSize);
+
+
+
+ }
+
+ tempCount = 0;
+
+ /**READING CLUSTER DATA**/
+
+ for(int clustersCount = 0 ; clustersCount < numClusters; clustersCount++)
+ {
+ //reading number of samples in a cluster
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> numSamples;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &numSamples,intSize);
+ }
+
+ iErrorCode = clusterModel.setNumSamples(numSamples);
+ if(iErrorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< iErrorCode << " " <<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(iErrorCode);
+ }
+
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ strFeatureVector = "";
+ mdtFileHandle >> strFeatureVector;
+
+ LTKStringUtil::tokenizeString(strFeatureVector,FEATURE_EXTRACTOR_DELIMITER,tokens);
+
+
+ //first token contains eigen values
+ LTKStringUtil::tokenizeString(tokens[0],",",subTokens);
+
+ //extracting eigen values
+ int i = 0;
+ for(i = 0; i < subTokens.size(); i++)
+ {
+
+ eigenValues.push_back(LTKStringUtil::convertStringToFloat(subTokens[i]));
+
+ }
+
+ clusterModel.setEigenValues(eigenValues);
+
+ subTokens.clear();
+
+ //extracting eigen vectors
+
+ for( i = 1; i < (eigenValues.size() + 1); i++)
+ {
+ LTKStringUtil::tokenizeString(tokens[i],",",subTokens);
+
+ for(int j = 0; j < subTokens.size(); j++)
+ {
+ tempVector.push_back(LTKStringUtil::convertStringToFloat(subTokens[j]));
+ }
+
+
+ eigenVectors.push_back(tempVector);
+ tempVector.clear();
+ subTokens.clear();
+ }
+
+ clusterModel.setEigenVectors(eigenVectors);
+
+
+ //extracting cluster mean
+
+ LTKStringUtil::tokenizeString(tokens[(eigenValues.size() + 1)],",",subTokens);
+
+ for( i = 0; i < subTokens.size(); i++)
+ {
+
+ clusterMean.push_back(LTKStringUtil::convertStringToFloat(subTokens[i]));
+ }
+
+ clusterModel.setClusterMean(clusterMean);
+
+ subTokens.clear();
+
+ clusterModelVector.push_back(clusterModel);
+ }
+ else
+ {
+ //reading number of eigenValues
+ int numEigenValues;
+ mdtFileHandle.read((char*) &numEigenValues,intSize);
+
+ //reading eigen values
+ int i = 0;
+ for(i = 0; i < numEigenValues; i++)
+ {
+ double eigenValue;
+ mdtFileHandle.read((char*) &eigenValue,doubleSize );
+
+ eigenValues.push_back(eigenValue);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ clusterModel.setEigenValues(eigenValues);
+
+
+ //reading eigenVectors
+ for( i = 0; i < numEigenValues; i++)
+ {
+ for(int j = 0; j < clusterMeanDimension; j++)
+ {
+ double eigenVectorValue;
+ mdtFileHandle.read((char*) &eigenVectorValue,doubleSize);
+ tempVector.push_back(eigenVectorValue);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ eigenVectors.push_back(tempVector);
+ tempVector.clear();
+ }
+
+ clusterModel.setEigenVectors(eigenVectors);
+
+
+ //reading cluster mean
+ for( i = 0; i < clusterMeanDimension; i++)
+ {
+ double clusterMeanValue;
+ mdtFileHandle.read((char*) &clusterMeanValue,doubleSize);
+
+ clusterMean.push_back(clusterMeanValue);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ clusterModel.setClusterMean(clusterMean);
+
+
+ clusterModelVector.push_back(clusterModel);
+ }
+
+ //clearing vectors
+
+ eigenValues.clear();
+
+ eigenVectors.clear();
+
+ clusterMean.clear();
+
+ tempVector.clear();
+ tokens.clear();
+
+ }
+
+ /**READING SINGLETON VECTORS**/
+ tempCount = 0;
+
+ for(int singletonCount = 0; singletonCount < numSingletons; singletonCount++)
+ {
+ LTKShapeFeaturePtr feature;
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ strFeatureVector = "";
+ mdtFileHandle >> strFeatureVector;
+
+ //parsing the singleton vector
+ LTKStringUtil::tokenizeString(strFeatureVector, FEATURE_EXTRACTOR_DELIMITER, tokens);
+
+ for(int i = 0; i < tokens.size(); ++i)
+ {
+ feature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+
+ if (feature->initialize(tokens[i]) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+
+ singleton.push_back(feature);
+ }
+
+ singletonVector.push_back(singleton);
+
+ singleton.clear();
+ tokens.clear();
+ }
+ else
+ {
+ int featureIndex = 0;
+
+ for ( ; featureIndex < numFeatures ; featureIndex++)
+ {
+ floatVector floatFeatureVector;
+ int featureValueIndex = 0;
+
+ feature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+
+ for(; featureValueIndex < featureDimension ; featureValueIndex++)
+ {
+ float featureValue = 0.0f;
+
+ mdtFileHandle.read((char*) &featureValue, floatSize);
+
+ floatFeatureVector.push_back(featureValue);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ if (feature->initialize(floatFeatureVector) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+
+
+ singleton.push_back(feature);
+
+ }
+
+ singletonVector.push_back(singleton);
+
+ singleton.clear();
+ }
+ }
+
+ /**CONSTRUCTING SHAPE MODEL**/
+
+
+ iErrorCode = shapeModel.setShapeId(classId);
+ if(iErrorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< iErrorCode << " "<< endl;
+ LTKReturnError(iErrorCode);
+ }
+
+ shapeModel.setClusterModelVector(clusterModelVector);
+
+ shapeModel.setSingletonVector(singletonVector);
+
+
+
+
+ /**APPENDING THE SHAPE MODEL TO PROTOTYPE VECTOR**/
+
+ m_prototypeShapes.push_back(shapeModel);
+
+
+ m_shapeIDNumPrototypesMap[classId] = clusterModelVector.size();
+
+
+ if(m_useSingleton == true || clusterModelVector.size() == 0)
+ m_shapeIDNumPrototypesMap[classId] += singletonVector.size();
+
+
+
+
+
+ clusterModelVector.clear();
+
+ singletonVector.clear();
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> classId;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &classId, intSize);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+
+ }
+
+
+
+ mdtFileHandle.close();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::loadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : recognize
+* DESCRIsPTION : recognizes the incoming tracegroup
+* ARGUMENTS : inTraceGroup - trace group to be recognized
+* screenContext - screen context
+* subSetOfClasses - subset of classes whose samples will be compared with traceGroup
+* confThreshold - classes with confidence below this threshold are not returned, valid range of confThreshold: (0,1)
+* numChoices - maximum number of choices to be returned
+* outResultVector - result of recognition
+* RETURNS : SUCCESS on successful running of the code
+* NOTES :
+* CHANGE HISTROY
+* Author : Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::recognize()" << endl;
+
+
+ //Check for empty traces in traceGroup
+
+ if(traceGroup.containsAnyEmptyTrace())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<EEMPTY_TRACE << " " <<
+ " Input trace is empty"<<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+
+ //Contains TraceGroup after Preprocessing is done
+ LTKTraceGroup preprocessedTraceGroup;
+
+
+ //Preprocess the traceGroup
+ int errorCode = preprocess(traceGroup, preprocessedTraceGroup);
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Extract the shapeSample from preprocessedTraceGroup
+ if(!m_ptrFeatureExtractor)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ENULL_POINTER << " " <<
+ " m_ptrFeatureExtractor is NULL"<<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(ENULL_POINTER);
+ }
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVec;
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ // call recognize with featureVector
+
+ if(recognize( shapeFeatureVec, subSetOfClasses, confThreshold,
+ numChoices, outResultVector) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : recognize
+* DESCRIsPTION : recognizes the incoming tracegroup
+* ARGUMENTS : shapeFeatureVec - feature vector to be recognized
+* screenContext - screen context
+* subSetOfClasses - subset of classes whose samples will be compared with traceGroup
+* confThreshold - classes with confidence below this threshold are not returned, valid range of confThreshold: (0,1)
+* numChoices - maximum number of choices to be returned
+* outResultVector - result of recognition
+* RETURNS : SUCCESS on successful running of the code
+* NOTES :
+* CHANGE HISTROY
+* Author : Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVec,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ m_cachedShapeFeature = shapeFeatureVec;
+
+ //Creating a local copy of input inSubSetOfClasses, as it is const, STL's unique function modifies it
+ vector<int> subSetOfClasses = inSubSetOfClasses;
+
+ int numPrototypeShapes = m_prototypeShapes.size();
+
+ /*********Validation for m_prototypeShapes ***************************/
+ if ( numPrototypeShapes == 0 )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROTOTYPE_SET_EMPTY << " " <<
+ " getErrorMessage(EPROTOTYPE_SET_EMPTY) "<<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(EPROTOTYPE_SET_EMPTY);
+ }
+
+ /******************************************************************/
+ /*******************VALIDATING INPUT ARGUMENTS*********************/
+ /******************************************************************/
+
+ // Validating numChoices: valid values: {-1, (0,m_numShapes]}
+ if(numChoices <= 0 && numChoices != NUM_CHOICES_FILTER_OFF)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<")<=0, setting it to off (-1)"<<endl;
+ numChoices = -1;
+ }
+
+ if(!m_projectTypeDynamic && numChoices > m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<") > numShapes ("<<
+ m_numShapes<<"), using numShapes "<<m_numShapes<<" instead"<<endl;
+ numChoices = m_numShapes;
+ }
+
+
+ //Validating confThreshold: valid values: [0,1]
+ if(confThreshold > 1 || confThreshold < 0)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "Invalid value of confThreshold, valid values are: [0,1]"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ // Clearing cached Variables
+ m_vecRecoResult.clear();
+ m_neighborInfoVec.clear();
+
+ //Temporary variable to be used to populate distIndexPairVector
+ struct NeighborInfo tempPair;
+
+ struct NeighborInfo tempDist;
+
+ int i = 0;
+ int j = 0;
+
+ //Variable to store the DTW distance.
+ float dtwDistance = 0.0f;
+
+ //Variable to store the Euclidean distance.
+ float euclideanDistance = 0.0f;
+
+
+ /***************End of declarations and initializations of variables**************/
+
+
+
+ /**CONVERTING THE FEATURE VECTOR TO DOUBLE***/
+
+ doubleVector featureVector;
+ floatVector floatFeatureVector;
+ int errorCode = m_shapeRecUtil.shapeFeatureVectorToFloatVector(shapeFeatureVec,floatFeatureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ int floatFeatureVectorSize = floatFeatureVector.size();
+
+
+ for(i = 0; i < floatFeatureVectorSize; i++)
+ featureVector.push_back(floatFeatureVector[i]);
+ floatFeatureVector.clear();
+
+
+
+
+ ActiveDTWShapeModel evalShapeModel;
+ //current shape model evaluated against test Sample
+
+
+ ActiveDTWClusterModel evalClusterModel;
+ //currently evaluated cluster model
+
+
+ vector<ActiveDTWClusterModel> clusterVector;
+ //vector of cluster models of current shape model
+
+
+ shapeMatrix evalSingletonVector;
+ //vector of all singletonVectors of current shape model
+
+ doubleVector eigenValues;
+ //eigen values of cluster model
+
+ double2DVector eigenVector;
+ //eigen vectors of cluster model
+
+ doubleVector clusterMean;
+ //cluster mean of cluster model
+
+ doubleVector deformationParameters;
+ //paramters required to construct optimal Deformation
+
+ doubleVector reconstructedSample;
+ //double vector form of optima lDeformation
+
+ shapeMatrix optimalDeformations;
+ //vector of all optimalDeformations of a class
+
+ vector<bool> clusterFilter;
+ //indicates which cluster are to be considered for computing DTW DISTANCE
+
+ vector<bool> singletonFilter;
+ //indicates which singletons are to be considered for computing DTW DISTANCE
+
+ vector<struct NeighborInfo> distInfo;
+ //used in dtwEuclidean filter
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVector;
+
+
+ /*****************COMPUTING DISTANCE******************************/
+ if(subSetOfClasses.size() == 0)
+ {
+ for(i = 0; i < m_prototypeShapes.size(); i++)
+ {
+ evalShapeModel = m_prototypeShapes[i];
+ clusterVector = evalShapeModel.getClusterModelVector();
+
+
+ evalSingletonVector = evalShapeModel.getSingletonVector();
+
+
+ int singletonSize = evalSingletonVector.size();
+ int clusterVectorSize = clusterVector.size();
+
+
+
+ //computing the optimalDeformations
+ for(j = 0; j < clusterVectorSize; j++)
+ {
+ evalClusterModel = clusterVector[j];
+
+ eigenVector = evalClusterModel.getEigenVectors();
+
+ eigenValues = evalClusterModel.getEigenValues();
+
+ clusterMean = evalClusterModel.getClusterMean();
+
+ deformationParameters.assign(eigenVector.size(),0.0);
+
+
+ int errorCode = findOptimalDeformation(deformationParameters,eigenValues,eigenVector,
+ clusterMean,featureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //reconstruct the sample
+ double tempCoordinate = 0.0;
+ int clusterMeanSize = clusterMean.size();
+ int deformationParametersSize = deformationParameters.size();
+
+ for(int k = 0; k < clusterMeanSize; k++)
+ {
+ tempCoordinate = clusterMean[k];
+
+ for(int l = 0; l < deformationParametersSize; l++)
+ tempCoordinate += deformationParameters[l]*eigenVector[l][k];
+
+ reconstructedSample.push_back(tempCoordinate);
+ }
+
+ //converting the reconstructed Sample to a featureVector
+ errorCode = convertDoubleToFeatureVector(shapeFeatureVector,reconstructedSample);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ optimalDeformations.push_back(shapeFeatureVector);
+
+ //clearing vectors
+ eigenValues.clear();
+ eigenVector.clear();
+ clusterMean.clear();
+ reconstructedSample.clear();
+ shapeFeatureVector.clear();
+ deformationParameters.clear();
+ }
+
+
+ //setting up dtweuclidean filter for the class
+ if(m_dtwEuclideanFilter != EUCLIDEAN_FILTER_OFF)
+ {
+ //calculating euclidean distance to clusters
+ for( j = 0; j < clusterVectorSize; j++)
+ {
+
+ euclideanDistance = 0.0;
+
+ errorCode = computeEuclideanDistance(shapeFeatureVec,optimalDeformations[j],euclideanDistance);
+
+
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempDist.typeId = CLUSTER;
+ tempDist.sampleId = j;
+ tempDist.distance = euclideanDistance;
+
+ distInfo.push_back(tempDist);
+ }
+
+ //calcualting euclidean distances to singletons
+ if(m_useSingleton == true || clusterVectorSize == 0)
+ {
+
+ for(j = 0; j < singletonSize; j++)
+ {
+
+ euclideanDistance = 0.0;
+ //computing euclidean distance between test sample
+ //and singleton vectors
+
+ errorCode = computeEuclideanDistance(shapeFeatureVec,evalSingletonVector[j],
+ euclideanDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempDist.typeId = SINGLETON;
+ tempDist.sampleId = j;
+ tempDist.distance = euclideanDistance;
+
+ distInfo.push_back(tempDist);
+
+
+ }
+ }
+
+
+ //sorting the euclidean distances in ascending order
+ sort(distInfo.begin(), distInfo.end(), sortDist);
+
+
+ //choose the top n
+ int numTopChoices = (int)(distInfo.size() * m_dtwEuclideanFilter)/100;
+ if(numTopChoices == 0)
+ {
+ numTopChoices = distInfo.size();
+ }
+
+ //setting the filter
+ clusterFilter.assign(clusterVectorSize,false);
+
+ if(m_useSingleton == true || clusterVectorSize == 0)
+ singletonFilter.assign(singletonSize,false);
+
+
+ for( j = 0; j < numTopChoices; j++)
+ {
+ if(distInfo[j].typeId == 0)
+ clusterFilter[distInfo[j].sampleId] = true;
+
+ if(distInfo[j].typeId == 1)
+ singletonFilter[distInfo[j].sampleId] = true;
+ }
+
+ //clearing distInfo
+ distInfo.clear();
+ }
+ else
+ {
+ clusterFilter.assign(clusterVectorSize,true);
+
+ if(m_useSingleton == true || clusterVectorSize == 0)
+ singletonFilter.assign(singletonSize,true);
+ }
+
+
+ /*****DETERMINING THE MINIMUM CLUSTER DISTANCE***************/
+ float minDistance = FLT_MAX;
+ float minClusterDistance;
+ float minSingletonDistance;
+
+ int clusterId;
+ int singletonId;
+
+ for( j = 0; j < clusterVectorSize; j++)
+ {
+
+ if(clusterFilter[j])
+ {
+ float tempDistance = 0.0;
+ errorCode = computeDTWDistance(shapeFeatureVec,optimalDeformations[j],tempDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(tempDistance < minDistance)
+ {
+ minDistance = tempDistance;
+ clusterId = j;
+ }
+
+
+
+ }
+
+ }
+
+ clusterVector.clear();
+ clusterFilter.clear();
+ optimalDeformations.clear();
+
+ minClusterDistance = minDistance;
+
+ /***DETERMINE THE MINIMUM DISTANCE FROM CLUSTERS ONLY IF THE
+ USE SINGLETON SWITCH IS TURNED ON. IF THE NUMBER OF CLUSTERS
+ IN A CLASS IS 0 THEN AUTOMATICALLY TURN ON THE SINGLETON SWITCH
+ FOR THAT CLASS ALONE ***/
+
+ if(m_useSingleton == false && clusterVectorSize == 0)
+ m_useSingleton = true;
+
+ /***************DETERMINING MINIMUM DISTANCE FROM SINGLETON VECTORS*********/
+ if(m_useSingleton == true)
+ {
+ evalSingletonVector = evalShapeModel.getSingletonVector();
+
+ int evalSingletonVectorSize = evalSingletonVector.size();
+
+ for(int j = 0; j < evalSingletonVectorSize; j++)
+ {
+ if(singletonFilter[j])
+ {
+
+ //calculate the dtw distance between testsamples and every singleton vector
+ float tempDistance = 0.0;
+
+ errorCode = computeDTWDistance(shapeFeatureVec,evalSingletonVector[j],tempDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(tempDistance < minDistance)
+ {
+ minDistance = tempDistance;
+ singletonId = j;
+ }
+
+ }
+ }
+ singletonFilter.clear();
+ }
+
+ //clearing vectors
+ evalSingletonVector.clear();
+
+ minSingletonDistance = minDistance;
+
+ //choosing the minimum distance
+ if(m_useSingleton == false)
+ {
+ tempPair.distance = minClusterDistance;
+ tempPair.typeId = CLUSTER;
+ tempPair.sampleId = clusterId;
+ }
+ else
+ {
+ if(clusterVectorSize == 0)
+ {
+ tempPair.distance = minSingletonDistance;
+ tempPair.typeId = SINGLETON;
+ tempPair.sampleId = singletonId;
+ }
+ else
+ {
+ if(minClusterDistance < minSingletonDistance)
+ {
+ tempPair.distance = minClusterDistance;
+ tempPair.typeId = CLUSTER;
+ tempPair.sampleId = clusterId;
+ }
+ else
+ {
+ tempPair.distance = minSingletonDistance;
+ tempPair.typeId = SINGLETON;
+ tempPair.sampleId = singletonId;
+ }
+ }
+ }
+
+ //turning off the singleton switch in case it was turned on automatically
+ if(m_useSingleton == true && clusterVectorSize == 0)
+ m_useSingleton = false;
+
+
+ tempPair.classId = evalShapeModel.getShapeId();
+ m_neighborInfoVec.push_back(tempPair);
+ }
+ }
+ else
+ {
+ /*****EVALUATE TEST SAMPLES ONLY AGAINST CLASSES SPECIFIED BY SUBSETOFCLASSES***/
+ intVector::iterator subSetStart = subSetOfClasses.begin();
+ intVector::iterator subSetEnd = subSetOfClasses.end();
+
+ for(;subSetStart != subSetEnd; ++subSetStart)
+ {
+ evalShapeModel = m_prototypeShapes[(*subSetStart)];
+
+ clusterVector = evalShapeModel.getClusterModelVector();
+
+ evalSingletonVector = evalShapeModel.getSingletonVector();
+
+ int clusterVectorSize = clusterVector.size();
+ int singletonSize = evalSingletonVector.size();
+
+ //computing the optimalDeformations
+ for( j = 0; j < clusterVectorSize; j++)
+ {
+ evalClusterModel = clusterVector[j];
+
+ eigenVector = evalClusterModel.getEigenVectors();
+
+ eigenValues = evalClusterModel.getEigenValues();
+
+ clusterMean = evalClusterModel.getClusterMean();
+
+ deformationParameters.assign(eigenVector.size(),0.0);
+
+ int errorCode = findOptimalDeformation(deformationParameters,eigenValues,eigenVector,
+ clusterMean,featureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //reconstruct the sample
+ double tempCoordinate = 0.0;
+ int clusterMeanSize = clusterMean.size();
+ int deformationParametersSize = deformationParameters.size();
+
+ for(int k = 0; k < clusterMeanSize; k++)
+ {
+ tempCoordinate = clusterMean[k];
+
+ for(int l = 0; l < deformationParametersSize; l++)
+ tempCoordinate += deformationParameters[l]*eigenVector[l][k];
+
+ reconstructedSample.push_back(tempCoordinate);
+ }
+
+ //converting the reconstructed Sample to a featureVector
+ errorCode = convertDoubleToFeatureVector(shapeFeatureVector,reconstructedSample);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ optimalDeformations.push_back(shapeFeatureVector);
+
+ //clearing vectors
+ eigenValues.clear();
+ eigenVector.clear();
+ clusterMean.clear();
+ reconstructedSample.clear();
+ shapeFeatureVector.clear();
+ deformationParameters.clear();
+ }
+
+ //setting up dtweuclidean filter for the class
+ if(m_dtwEuclideanFilter != EUCLIDEAN_FILTER_OFF)
+ {
+ //calculating euclidean distance to clusters
+ for(j = 0; j < clusterVectorSize; j++)
+ {
+ euclideanDistance = 0.0;
+
+ errorCode = computeEuclideanDistance(shapeFeatureVec,optimalDeformations[j],euclideanDistance);
+
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempDist.typeId = CLUSTER;
+ tempDist.sampleId = j;
+ tempDist.distance = euclideanDistance;
+
+ distInfo.push_back(tempDist);
+ }
+
+ //calcualting euclidean distances to singletons
+ if(m_useSingleton == true || clusterVectorSize == 0)
+ {
+ for(j = 0; j < singletonSize; j++)
+ {
+ euclideanDistance = 0.0;
+ //computing euclidean distance between test sample
+ //and singleton vectors
+
+ errorCode = computeEuclideanDistance(shapeFeatureVec,evalSingletonVector[j],
+ euclideanDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempDist.typeId = SINGLETON;
+ tempDist.sampleId = j;
+ tempDist.distance = euclideanDistance;
+
+ distInfo.push_back(tempDist);
+ }
+ }
+
+ //sorting the euclidean distances in ascending order
+
+ sort(distInfo.begin(), distInfo.end(), sortDist);
+
+
+ //choose the top n
+ int numTopChoices = (int)(distInfo.size() * m_dtwEuclideanFilter)/100;
+
+ if(numTopChoices == 0)
+ {
+ numTopChoices = distInfo.size();
+ }
+
+ //setting the filter
+ clusterFilter.assign(clusterVectorSize,false);
+
+ if(m_useSingleton == true || clusterVectorSize == 0)
+ singletonFilter.assign(singletonSize,false);
+
+ for( j = 0; j < numTopChoices; j++)
+ {
+ if(distInfo[j].typeId == 0)
+ clusterFilter[distInfo[j].sampleId] = true;
+
+ if(distInfo[j].typeId == 1)
+ singletonFilter[distInfo[j].sampleId] = true;
+ }
+
+ //clearing distInfo
+ distInfo.clear();
+ }
+
+ /*****DETERMINING THE MINIMUM CLUSTER DISTANCE***************/
+ float minDistance = FLT_MAX;
+ float minClusterDistance;
+ float minSingletonDistance;
+
+ int clusterId;
+ int singletonId;
+
+ for( j = 0; j < clusterVectorSize; j++)
+ {
+ if(clusterFilter[j])
+ {
+ float tempDistance = 0.0;
+ errorCode = computeDTWDistance(shapeFeatureVec,optimalDeformations[j],tempDistance);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(tempDistance < minDistance)
+ {
+ minDistance = tempDistance;
+ clusterId = j;
+ }
+ }
+ }
+
+ clusterVector.clear();
+ clusterFilter.clear();
+ optimalDeformations.clear();
+
+ minClusterDistance = minDistance;
+
+ /***DETERMINE THE MINIMUM DISTANCE FROM CLUSTERS ONLY IF THE
+ USE SINGLETON SWITCH IS TURNED ON. IF THE NUMBER OF CLUSTERS
+ IN A CLASS IS 0 THEN AUTOMATICALLY TURN ON THE SINGLETON SWITCH
+ FOR THAT CLASS ALONE ***/
+
+ if(m_useSingleton == false && clusterVectorSize == 0)
+ m_useSingleton = true;
+
+ /***************DETERMINING MINIMUM DISTANCE FROM SINGLETON VECTORS*********/
+ if(m_useSingleton == true)
+ {
+
+ evalSingletonVector = evalShapeModel.getSingletonVector();
+ int evalSingletonVectorSize = evalSingletonVector.size();
+
+ for(j = 0; j < evalSingletonVectorSize; j++)
+ {
+ if(singletonFilter[j])
+ {
+ //calculate the dtw distance between testsamples and every singleton vector
+ float tempDistance = 0.0;
+
+ errorCode = computeDTWDistance(shapeFeatureVec,evalSingletonVector[j],tempDistance);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ if(tempDistance < minDistance)
+ {
+ minDistance = tempDistance;
+ singletonId = j;
+ }
+
+
+ }
+ }
+
+ singletonFilter.clear();
+ }
+
+ //clearing vectors
+ evalSingletonVector.clear();
+
+ minSingletonDistance = minDistance;
+
+ //choosing the minimum distance
+ if(m_useSingleton == false)
+ {
+ tempPair.distance = minClusterDistance;
+ tempPair.typeId = CLUSTER;
+ tempPair.sampleId = clusterId;
+ }
+ else
+ {
+ if(clusterVectorSize == 0)
+ {
+ tempPair.distance = minSingletonDistance;
+ tempPair.typeId = SINGLETON;
+ tempPair.sampleId = singletonId;
+ }
+ else
+ {
+ if(minClusterDistance < minSingletonDistance)
+ {
+ tempPair.distance = minClusterDistance;
+ tempPair.typeId = CLUSTER;
+ tempPair.sampleId = clusterId;
+ }
+ else
+ {
+ tempPair.distance = minSingletonDistance;
+ tempPair.typeId = SINGLETON;
+ tempPair.sampleId = singletonId;
+ }
+ }
+ }
+
+ //turning off the singleton switch in case it was turned on automatically
+ if(m_useSingleton == true && clusterVectorSize == 0)
+ m_useSingleton = false;
+
+
+ tempPair.classId = evalShapeModel.getShapeId();
+
+
+ m_neighborInfoVec.push_back(tempPair);
+ }
+ }
+
+ featureVector.clear();
+
+
+ //Sort the distIndexPairVector based on distances, in ascending order.
+ sort(m_neighborInfoVec.begin(), m_neighborInfoVec.end(), sortDist);
+
+ //Reject the sample if the similarity of the nearest sample is lower than m_rejectThreshold specified by the user.
+ if(SIMILARITY(m_neighborInfoVec[0].distance) <= m_rejectThreshold)
+ {
+ m_vecRecoResult.clear();
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<"Test sample too distinct, rejecting the sample"<<endl;
+ return SUCCESS;
+ }
+
+ //compute confidence
+ if((errorCode = computeConfidence()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // Temporary result vector to store the results based on confThreshold and numChoices specified by the user.
+ vector<LTKShapeRecoResult> tempResultVector;
+
+ //If confThreshold is specified, get the entries from resultVector with confidence >= confThreshold
+ if(confThreshold != CONF_THRESHOLD_FILTER_OFF)
+ {
+ for(i = 0 ; i < m_vecRecoResult.size() ; i++)
+ {
+ if( m_vecRecoResult[i].getConfidence() >= confThreshold)
+ {
+ tempResultVector.push_back(m_vecRecoResult[i]);
+ }
+ }
+ m_vecRecoResult.clear();
+ m_vecRecoResult = tempResultVector;
+ tempResultVector.clear();
+ }
+ //Check if outResultVector is empty, if so, log
+ if(m_vecRecoResult.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) <<
+ "Size of the result vector is empty, could not satisfy confThreshold criteria"<<endl;
+ }
+
+ //If numChoices is specified, get the top numChoices entries from outResultVector
+ if(numChoices != NUM_CHOICES_FILTER_OFF)
+ {
+ //Get the entries from outResultVector only if size of resultVector > numChoices
+ if(m_vecRecoResult.size() > numChoices)
+ {
+ for( i = 0 ; i < numChoices ; ++i)
+ tempResultVector.push_back(m_vecRecoResult[i]);
+ m_vecRecoResult.clear();
+ m_vecRecoResult = tempResultVector;
+ tempResultVector.clear();
+ }
+
+ }
+
+ outResultVector = m_vecRecoResult;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : sortDist
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+bool ActiveDTWShapeRecognizer::sortDist(const NeighborInfo& x, const NeighborInfo& y)
+{
+ return (x.distance) < (y.distance);
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computeConfidence
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int ActiveDTWShapeRecognizer::computeConfidence()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeConfidence()" << endl;
+
+ /******************************************************************/
+ /*******************VALIDATING INPUT ARGUMENTS*********************/
+ /******************************************************************/
+ if(m_neighborInfoVec.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENEIGHBOR_INFO_VECTOR_EMPTY << " " <<
+ getErrorMessage(ENEIGHBOR_INFO_VECTOR_EMPTY) <<
+ " ActiveDTWShapeRecognizer::computeConfidence()" << endl;
+
+ LTKReturnError(ENEIGHBOR_INFO_VECTOR_EMPTY);
+ }
+ // Temporary vector to store the recognition results
+ LTKShapeRecoResult outResult;
+ vector<pair<int,float> > classIdSimilarityPairVec;
+ pair<int, float> classIdSimilarityPair;
+
+ // Temporary vector to store the distinct classes appearing in distIndexPairVector
+ intVector distinctClassVector;
+ intVector::iterator distinctClassVectorIter;
+
+ vector <LTKShapeRecoResult>::iterator resultVectorIter = m_vecRecoResult.begin();
+ vector <LTKShapeRecoResult>::iterator resultVectorIterEnd = m_vecRecoResult.end();
+
+ // Variable to store sum of distances to all the prototypes in distIndexPairVector
+ float similaritySum = 0.0f;
+ // Temporary variable to store the confidence value.
+ float confidence = 0.0f;
+
+
+
+ // Confidence computation for the ActiveDTW (1-NN) Classifier
+ if(m_nearestNeighbors == 1)
+ {
+ vector <struct NeighborInfo>::iterator distIndexPairIter = m_neighborInfoVec.begin();
+ vector <struct NeighborInfo>::iterator distIndexPairIterEnd = m_neighborInfoVec.end();
+
+
+
+ for(; distIndexPairIter != distIndexPairIterEnd; ++distIndexPairIter)
+ {
+ //Check if the class is already present in distinctClassVector
+ //The complexity of STL's find() is linear, with atmost last-first comparisons for equality
+ distinctClassVectorIter = find(distinctClassVector.begin(), distinctClassVector.end(), (*distIndexPairIter).classId);
+
+ //The distinctClassVectorIter will point to distinctClassVector.end() if the class is not present in distinctClassVector
+ if(distinctClassVectorIter == distinctClassVector.end())
+ {
+ classIdSimilarityPair.first = (*distIndexPairIter).classId ;
+ float similarityValue = SIMILARITY((*distIndexPairIter).distance);
+
+ classIdSimilarityPair.second = similarityValue;
+ similaritySum += similarityValue;
+
+ classIdSimilarityPairVec.push_back(classIdSimilarityPair);
+ distinctClassVector.push_back((*distIndexPairIter).classId);
+ }
+ }
+
+ /************COMPUTING CONFIDENCE VALUES FOR EACH CLASS************/
+ int classIdSimilarityPairVecSize = classIdSimilarityPairVec.size();
+ for( int i = 0 ; i < classIdSimilarityPairVecSize ; ++i)
+ {
+ int classID = classIdSimilarityPairVec[i].first;
+ confidence = classIdSimilarityPairVec[i].second;
+ confidence /= similaritySum;
+ outResult.setConfidence(confidence);
+ outResult.setShapeId(classID);
+
+ if(confidence > 0)
+ m_vecRecoResult.push_back(outResult);
+ }
+ classIdSimilarityPairVec.clear();
+ }
+ // Computing confidence for k-NN classifier, implementation of the confidence measure described in paper (cite)
+ else
+ {
+ if(m_nearestNeighbors >= m_neighborInfoVec.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_nearestNeighbors >= m_prototypeSet.size(), using distIndexPairVector.size() for m_nearestNeighbors instead" << endl;
+ m_nearestNeighbors = m_neighborInfoVec.size();
+ }
+
+ // Variable to store the maximum of the number of samples per class.
+ int maxClassSize = (max_element(m_shapeIDNumPrototypesMap.begin(), m_shapeIDNumPrototypesMap.end(), &compareMap))->second;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "maxClassSize: " <<maxClassSize<< endl;
+
+ // Vector to store the cumulative similarity values
+ vector<float> cumulativeSimilaritySum;
+
+ // Populate the values in cumulativeSimilaritySum vector for the top m_nearestNeighbors prototypes
+ // Assumption is m_nearestNeighbors >= MIN_NEARESTNEIGHBORS and m_nearestNeighbors < m_dtwEuclideanFilter, validation done in readClassifierConfig()
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Displaying cumulativeSimilaritySum..." << endl;
+ int i = 0;
+ for( i = 0 ; i < m_nearestNeighbors ; ++i)
+ {
+
+ classIdSimilarityPair.first = m_neighborInfoVec[i].classId;
+ float similarityValue = SIMILARITY((m_neighborInfoVec[i]).distance);
+
+ classIdSimilarityPair.second = similarityValue;
+
+ classIdSimilarityPairVec.push_back(classIdSimilarityPair);
+ similaritySum += similarityValue;
+ cumulativeSimilaritySum.push_back(similaritySum);
+
+ // Logging the cumulative similarity values for debugging
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "classID:" <<
+ m_neighborInfoVec[i].classId << " confidence:" <<
+ similarityValue << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << i << ": " << similaritySum << endl;
+ }
+
+
+ for(i = 0 ; i < classIdSimilarityPairVec.size() ; ++i)
+ {
+
+ int classID = classIdSimilarityPairVec[i].first;
+
+ int finalNearestNeighbors = 0;
+
+ //Check if the class is already present in distinctClassVector
+ distinctClassVectorIter = find(distinctClassVector.begin(), distinctClassVector.end(), classID);
+
+ //The distinctClassVectorIter will point to distinctClassVector.end() if the class is not present in distinctClassVector
+ if(distinctClassVectorIter == distinctClassVector.end())
+ {
+ distinctClassVector.push_back(classID);
+ confidence = 0.0f;
+
+ //If the confidence is based on Adaptive k-NN scheme,
+ //Computing number of nearest neighbours for the class to be used for computation of confidence
+ if(m_adaptivekNN == true )
+ {
+
+ int sizeProportion = (int)ceil(1.0*m_nearestNeighbors*m_shapeIDNumPrototypesMap[classID]/maxClassSize);
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"sizeProportion of class " <<classID<<" is "<<sizeProportion<<endl;
+
+ // Computing min(sizeProportion, m_shapeIDNumPrototypesMap[classID])
+ int upperBound = (sizeProportion < m_shapeIDNumPrototypesMap[classID]) ? sizeProportion:m_shapeIDNumPrototypesMap[classID];
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"upperBound: " <<upperBound<<endl;
+
+ // Computing max(upperBound, MIN_NEARESTNEIGHBORS)
+ finalNearestNeighbors = (MIN_NEARESTNEIGHBORS > upperBound) ? MIN_NEARESTNEIGHBORS:upperBound;
+ }
+ //Else, compute kNN based confidence
+ else if(m_adaptivekNN == false)
+ {
+ finalNearestNeighbors = m_nearestNeighbors;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: " << ECONFIG_FILE_RANGE << " " <<
+ "m_adaptivekNN should be true or false" <<
+ " ActiveDTWShapeRecognizer::computeConfidence()" << endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"finalNearestNeighbors: " <<finalNearestNeighbors<<endl;
+
+ for( int j = 0 ; j < finalNearestNeighbors ; ++j)
+ {
+ if(classID == classIdSimilarityPairVec[j].first)
+ {
+ confidence += classIdSimilarityPairVec[j].second;
+ }
+ }
+ confidence /= cumulativeSimilaritySum[finalNearestNeighbors-1];
+
+ outResult.setShapeId(classID);
+ outResult.setConfidence(confidence);
+
+ if(confidence > 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"classId: " <<classID<<" confidence: "<<confidence<<endl;
+
+ m_vecRecoResult.push_back(outResult);
+ }
+ }
+ }
+ classIdSimilarityPairVec.clear();
+ }
+
+ //Sort the result vector in descending order of confidence
+ sort(m_vecRecoResult.begin(), m_vecRecoResult.end(), sortResultByConfidence);
+
+ distinctClassVector.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeConfidence()" << endl;
+
+ return SUCCESS;
+
+}
+
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : sortResultByConfidence
+* DESCRIPTION : Sort the LTKShapeRecoResult vector based on the Confidence value
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+bool ActiveDTWShapeRecognizer::sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y)
+{
+ return (x.getConfidence()) > (y.getConfidence());
+}
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : compareMap
+* DESCRIPTION : Sort the STL's map based on the 'value'(second) field
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+
+bool ActiveDTWShapeRecognizer::compareMap( const map<int, int>::value_type& lhs, const map<int, int>::value_type& rhs )
+{
+ return lhs.second < rhs.second;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : unloadModelData
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS : SUCCESS
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::unloadModelData()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::unloadModelData()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ //Update MDT file with any modification, if available in memory
+ if(m_prototypeSetModifyCount >0)
+ {
+ m_prototypeSetModifyCount = m_MDTUpdateFreq-1;
+
+ returnStatus = writePrototypeShapesToMDTFile();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::unloadModelData()" << endl;
+ }
+ m_prototypeSetModifyCount = 0;
+ }
+
+ //Clearing the prototypSet
+ m_prototypeShapes.clear();
+ m_shapeIDNumPrototypesMap.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::unloadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : setDeviceContext
+* DESCRIPTION : New Function - Not yet added
+* ARGUMENTS :
+* RETURNS : SUCCESS
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::setDeviceContext(const LTKCaptureDevice& deviceInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::setDeviceContext()" << endl;
+
+ m_captureDevice = deviceInfo;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::setDeviceContext()" << endl;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : performClustering
+* DESCRIPTION : This method performs clustering on each class data
+and returns a vector specifying which samples
+belong to which cluster
+* ARGUMENTS : INPUT
+shapeSamplesVec vector<LTKShapeSample> Class Data to be clustered
+: OUTPUT
+outputVector int2DVector
+(Here each row of the outputVector denotes a cluster
+in turn each row holds the indices of the samples
+belonging to that cluster)
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::performClustering(const vector<LTKShapeSample>& shapeSamplesVec,
+ int2DVector& outputVector)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::performClustering()" << endl;
+
+ intVector tempVec;
+
+ float2DVector distanceMatrix;
+ int sampleCount=shapeSamplesVec.size();
+ int returnStatus = SUCCESS;
+
+
+
+ if(m_prototypeReductionFactor == -1)
+ {
+ //find number of clusters automatically
+ //this is done when either of NumClusters or PrototypeReducrion factor is set
+ //to automatic
+ LTKHierarchicalClustering<LTKShapeSample,ActiveDTWShapeRecognizer> hc(shapeSamplesVec,AVERAGE_LINKAGE,AVG_SIL);
+
+ returnStatus = hc.cluster(this,&ActiveDTWShapeRecognizer::computeDTWDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ //Cluster results are populated in an outputVector
+ hc.getClusterResult(outputVector);
+
+ }
+ else if(m_prototypeReductionFactor == 0|| m_numClusters >= sampleCount)
+ {
+ intVector clusterIndices;
+ //case where clustering is not required every sample is a cluster by itself
+ for(int i = 0; i < sampleCount; i++)
+ clusterIndices.push_back(i);
+
+ outputVector.push_back(clusterIndices);
+ clusterIndices.clear();
+
+ }
+ else
+ {
+ //clustering has to be performed
+
+ int numClusters;
+ if(m_numClusters == NN_NUM_CLUST_INITIAL)
+ {
+ numClusters = (100-m_prototypeReductionFactor)*sampleCount/100;
+ if(numClusters == 0)
+ {
+ numClusters = 1;
+ }
+ }
+
+ else if(m_prototypeReductionFactor == NN_NUM_CLUST_INITIAL)
+ {
+ numClusters = m_numClusters;
+ }
+
+ try
+ {
+
+ LTKHierarchicalClustering<LTKShapeSample,ActiveDTWShapeRecognizer>
+ hc(shapeSamplesVec,numClusters, AVERAGE_LINKAGE);
+
+ if(numClusters == 1)
+ {
+ int tempVar;
+ hc.computeProximityMatrix(this, &ActiveDTWShapeRecognizer::computeDTWDistance);
+
+
+ for(tempVar=0;tempVar<shapeSamplesVec.size();tempVar++)
+ {
+ tempVec.push_back(tempVar);
+ }
+
+ outputVector.push_back(tempVec);
+ tempVec.clear();
+ }
+ else
+ {
+ returnStatus = hc.cluster(this,&ActiveDTWShapeRecognizer::computeDTWDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " ActiveDTWShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ //Cluster results are populated in an outputVector
+ hc.getClusterResult(outputVector);
+ }
+
+ }
+ catch(LTKException e)
+ {
+ int errorCode = e.getErrorCode();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " ActiveDTWShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(errorCode);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::performClustering()" << endl;
+
+
+
+ return SUCCESS;
+
+}
+
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getShapeSampleFromInkFile
+* DESCRIPTION : This method will get the ShapeSample by giving the ink
+* file path as input
+* ARGUMENTS :
+* RETURNS : SUCCESS
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ if ( inkFilePath.empty() )
+ return FAILURE;
+
+ LTKCaptureDevice captureDevice;
+ LTKScreenContext screenContext;
+
+
+ LTKTraceGroup inTraceGroup, preprocessedTraceGroup;
+
+
+ inTraceGroup.emptyAllTraces();
+
+ int returnVal = m_shapeRecUtil.readInkFromFile(inkFilePath,
+ m_lipiRootPath, inTraceGroup,
+ captureDevice, screenContext);
+
+ if (returnVal!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<returnVal<<
+ " ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(returnVal);
+ }
+
+ m_ptrPreproc->setCaptureDevice(captureDevice);
+ m_ptrPreproc->setScreenContext(screenContext);
+
+ preprocessedTraceGroup.emptyAllTraces();
+
+ //Preprocessing to be done for the trace group that was read
+ int errorCode = preprocess(inTraceGroup, preprocessedTraceGroup);
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : trainFromListFile
+* DESCRIPTION : This method will do the training by giving the Train List
+* file as input
+* ARGUMENTS :
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int ActiveDTWShapeRecognizer::trainFromListFile(const string& listFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+
+ //Count for the no. of samples read for a shape
+ int sampleCount = 0;
+
+ //Count of the no. of shapes read so far
+ int shapeCount = 0;
+
+ //Flag to skip reading a newline in the list file, when a new class starts
+ bool lastshapeIdFlag = false;
+
+ //Ink File Path
+ string path = "";
+
+ //Line from the list file
+ string line = "";
+
+ //Line is split into tokens
+ stringVector tokens;
+
+ //Flag is set when EOF is reached
+ bool eofFlag = false;
+
+ //ID for each shapes
+ int shapeId = -1;
+
+ //classId of the character
+ int prevClassId = -1;
+
+ //Indicates the first class
+ bool initClassFlag = false;
+
+ /**vectors for cluster indices
+ *each vector corresponds to a cluster in a class
+ *each vector has the indices of the shapesamples belonging to the cluster
+ **/
+ int2DVector clusterIndices;
+
+ /**
+ * this will hold a vector of indices pertaining to a certain cluster
+ **/
+ intVector cluster;
+
+ /**
+ * this will hold a temporary float feature vector
+ **/
+ doubleVector tempFeature;
+
+ /**
+ * Feature Matrix
+ **/
+ double2DVector featureMatrix;
+
+ /**
+ * Covariance Matrix
+ **/
+ double2DVector covarianceMatrix;
+
+ /**
+ * Eigen Vector Matrix
+ **/
+ double2DVector eigenVectors;
+
+ /**
+ * Eigen Values
+ **/
+ doubleVector eigenValues;
+
+ /**
+ * nrot --> number of iterations for eigen vector computation
+ **/
+ int nrot = 0;
+
+ /**
+ * clusterModel
+ **/
+
+ ActiveDTWClusterModel clusterModel;
+
+
+
+ /**
+ * vector of cluster models
+ **/
+ vector<ActiveDTWClusterModel> clusterModelVector;
+
+
+ /**
+ * shape Model
+ **/
+
+ ActiveDTWShapeModel shapeModel;
+
+ /**
+ * vector of singleton clusters
+ **/
+
+ shapeMatrix singletonVector;
+
+ /**
+ * selected eigen vectors
+ **/
+ double2DVector selectedEigenVectors;
+
+ /**
+ * cluster mean
+ **/
+ doubleVector clusterMean;
+
+
+
+ LTKShapeSample shapeSampleFeatures;
+
+
+ vector<LTKShapeSample> shapeSamplesVec;
+
+ vector<LTKShapeSample> clusteredShapeSampleVec;
+
+ ofstream mdtFileHandle;
+ ifstream listFileHandle;
+
+ vector<LTKShapeFeaturePtr> shapeFeature;
+
+ //Opening the train list file for reading mode
+ listFileHandle.open(listFilePath.c_str(), ios::in);
+
+ //Return error if unable to open the training list file
+ if(!listFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ETRAINLIST_FILE_OPEN << " " <<
+ getErrorMessage(ETRAINLIST_FILE_OPEN)<<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(ETRAINLIST_FILE_OPEN);
+ }
+
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(),ios::out|ios::binary);
+ }
+
+ //Return error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ listFileHandle.close();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN)<<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ //Write the number of Shapes
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle << m_numShapes << endl;
+ }
+ else
+ {
+ mdtFileHandle.write((char*) &m_numShapes, sizeof(unsigned short));
+ }
+
+ int errorCode = SUCCESS;
+ while(!listFileHandle.eof())
+ {
+ // Not a sample of a new class
+ if( lastshapeIdFlag == false )
+ {
+ //Get the line from the list file
+ getline(listFileHandle, line, NEW_LINE_DELIMITER);
+
+ path = "";
+
+ //Check if EOF is reached
+ if( listFileHandle.eof() )
+ {
+ eofFlag = true;
+ }
+
+ //Skip commented line
+ if ( line[0] == COMMENTCHAR )
+ {
+ continue;
+ }
+
+ if (eofFlag == false)
+ {
+ //Tokenize the string
+ errorCode = LTKStringUtil::tokenizeString(line, LIST_FILE_DELIMITER, tokens);
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ listFileHandle.close();
+ mdtFileHandle.close();
+ LTKReturnError(errorCode);
+ }
+
+
+ //Tokens must be of size 2, one is pathname and other is shapeId
+ //If the end of file not reached then continue the looping
+ if( tokens.size() != 2 && eofFlag == false )
+ continue;
+
+ //Tokens[0] indicates the path name
+ path = tokens[0];
+
+ //Tokens[1] indicates the shapeId
+ shapeId = atoi( tokens[1].c_str() );
+
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "The ActiveDTWShapeRecognizer requires training file class Ids to be positive integers and listed in the increasing order"<<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_SHAPEID;
+ break;
+ }
+ else if(shapeId < prevClassId)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "Shape IDs in the train list file should be in the increasing order. Please use scripts/validateListFile.pl to generate list files." <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_ORDER_LISTFILE;
+ break;
+ }
+
+
+ //This condition is used to check the first shape must be start from 0
+ if( initClassFlag == false )
+ {
+ initClassFlag = true;
+ prevClassId=shapeId;
+ }
+ }
+ }
+ else //Sample of a new class; do not read the next line during this iteration
+ {
+ //flag unset to read next line during the next iteration
+ lastshapeIdFlag = false;
+ }
+
+ // Sample from the same class, extract features, and push the extracted features to shapeSamplesVec
+ if( shapeId == prevClassId && ! path.empty())
+ {
+ if( getShapeFeatureFromInkFile(path, shapeFeature) != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Error extracting features from the ink file: " <<
+ path << ", extracting features from the next sample."<<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ continue;
+ }
+
+ shapeSampleFeatures.setFeatureVector(shapeFeature);
+ shapeSampleFeatures.setClassID(shapeId);
+
+ ++sampleCount;
+ shapeSamplesVec.push_back(shapeSampleFeatures);
+
+ shapeFeature.clear();
+
+ }
+
+ // Sample of new class seen, or end of list file reached; train all the samples of previous class ID
+ if( shapeId != prevClassId || eofFlag == true )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Training for class : " << prevClassId << endl;
+
+ //Increase shape count only if there are atleast one sample per class
+ if( sampleCount > 0 )
+ shapeCount++;
+
+ //check that shapecount must not be greater than specified number
+ //of shapes, if projecttype was not dynamic
+ if( !m_projectTypeDynamic && shapeCount > m_numShapes )
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+ break;
+ }
+
+ if( shapeCount > 0 && sampleCount > 0 )
+ {
+
+ /** PERFORM CLUSTERING **/
+
+
+
+ errorCode = performClustering(shapeSamplesVec,clusterIndices);
+
+
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+ mdtFileHandle.close();
+ LTKReturnError(errorCode);
+ }
+
+
+
+
+ int2DVector::iterator iter = clusterIndices.begin();
+ int2DVector::iterator iEnd = clusterIndices.end();
+
+
+
+ /**ITERATING THROUGH THE VARIOUS CLUSTERS **/
+ for(;iter != iEnd; ++iter)
+ {
+ cluster = (*iter);
+
+
+
+ /** SINGLETON VECTORS **/
+ if(cluster.size() < m_minClusterSize)
+ {
+ /**CONSTRUCTING THE SINGLETON VECTOR**/
+ for(int i = 0; i < cluster.size(); i++)
+ singletonVector.push_back(shapeSamplesVec[cluster[i]].getFeatureVector());
+ }
+
+ /** CLUSTER PROCESSING **/
+ else
+ {
+ //gather all the shape samples pertaining to a particular cluster
+ int clusterSize = cluster.size();
+ int i = 0;
+ for( i = 0; i < clusterSize; i++)
+ {
+ //CONVERT ALL THE SHAPE SAMPLES TO FLOAT FEATURE VECTORS
+ floatVector floatFeatureVector;
+ errorCode = m_shapeRecUtil.shapeFeatureVectorToFloatVector(shapeSamplesVec[cluster[i]].getFeatureVector(),
+ floatFeatureVector);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ int floatFeatureVectorSize = floatFeatureVector.size();
+ for(int i = 0; i < floatFeatureVectorSize; i++)
+ tempFeature.push_back(floatFeatureVector[i]);
+
+ featureMatrix.push_back(tempFeature);
+ tempFeature.clear();
+ floatFeatureVector.clear();
+
+ }
+
+
+ /** COMPUTING COVARIANCE MATRIX **/
+ errorCode = computeCovarianceMatrix(featureMatrix,covarianceMatrix,clusterMean);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //setting cluster mean for cluster model
+
+ clusterModel.setClusterMean(clusterMean);
+
+
+ /** COMPUTING EIGEN VECTORS **/
+ //computes the eigen vector for the larger covarianceMatrix
+ //from the smaller covarianceMatrix
+ errorCode = computeEigenVectorsForLargeDimension(featureMatrix,covarianceMatrix,eigenVectors,eigenValues);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ doubleVector tempEigenVector;
+ int eigenVectorDimension = eigenVectors.size();
+
+ if(eigenVectorDimension <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EEMPTY_EIGENVECTORS << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(EEMPTY_EIGENVECTORS);
+ }
+
+ int numEigenVectors = eigenVectors[0].size();
+
+ if(numEigenVectors <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_NUM_OF_EIGENVECTORS << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_EIGENVECTORS );
+ }
+
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ for(int j = 0; j < eigenVectorDimension; j++)
+ tempEigenVector.push_back(eigenVectors[j][i]);
+
+ selectedEigenVectors.push_back(tempEigenVector);
+ tempEigenVector.clear();
+ }
+
+
+
+ /**CONSTRUCTING CLUSTER MODEL **/
+ errorCode = clusterModel.setNumSamples(cluster.size());
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ clusterModel.setEigenValues(eigenValues);
+
+ clusterModel.setEigenVectors(selectedEigenVectors);
+
+
+ /**APPENDING THE CLUSTER MODEL VECTOR**/
+ clusterModelVector.push_back(clusterModel);
+
+ featureMatrix.clear();
+ covarianceMatrix.clear();
+ selectedEigenVectors.clear();
+ clusterMean.clear();
+ eigenValues.clear();
+ eigenVectors.clear();
+ }
+ }
+
+
+ clusterIndices.clear();
+
+
+
+ /**CONSTRUCTING SHAPE MODEL**/
+
+ errorCode = shapeModel.setShapeId(shapeCount - 1);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " "<< endl;
+ LTKReturnError(errorCode);
+ }
+
+ shapeModel.setClusterModelVector(clusterModelVector);
+
+ shapeModel.setSingletonVector(singletonVector);
+
+
+ clusterModelVector.clear();
+ singletonVector.clear();
+
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0)
+ {
+
+ //Writing results to the MDT file
+
+ errorCode = appendShapeModelToMDTFile(shapeModel, mdtFileHandle);
+
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+
+ listFileHandle.close();
+ mdtFileHandle.close();
+ LTKReturnError(errorCode);
+ }
+
+
+ }
+
+ //Clearing the shapeSampleVector and clusteredShapeSampleVector
+
+
+ shapeSamplesVec.clear();
+
+ //Resetting sampleCount for the next class
+ sampleCount = 0;
+
+ //Set the flag so that the already read line of next class in the list file is not lost
+ lastshapeIdFlag = true;
+
+ prevClassId = shapeId;
+
+ }
+ }
+ }//End of while
+
+ //Closing the Train List file and Model Data file
+ listFileHandle.close();
+ mdtFileHandle.close();
+
+ if(!m_projectTypeDynamic && shapeCount != m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_SHAPES << " " <<
+ getErrorMessage(EINVALID_NUM_OF_SHAPES)<<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+
+ return SUCCESS;
+
+}
+
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computeCovarianceMatrix
+* DESCRIPTION : This method computes the covariance matrix and mean of
+a feature matrix
+* ARGUMENTS : INPUT
+featureMatrix double2DVector Feature matrix whose covarianceMatrix
+is to be computed
+;OUTPUT
+covarianceMatrix double2DVector covarianceMatrix of feature matrix
+meanFeature doubleVector mean of feature matrix
+
+ * RETURNS : integer Holds error value if occurs
+ * Holds SUCCESS if no errors
+ *************************************************************************************/
+ int ActiveDTWShapeRecognizer::computeCovarianceMatrix(double2DVector& featureMatrix,
+ double2DVector& covarianceMatrix,doubleVector& meanFeature)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeCovarianceMatrix()" << endl;
+
+ if(featureMatrix.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_FEATUREMATRIX << " " <<
+ getErrorMessage(EEMPTY_FEATUREMATRIX) <<
+ " ActiveDTWShapeRecognizer::computeCovarianceMatrix()" << endl;
+
+ LTKReturnError(EEMPTY_FEATUREMATRIX);
+ }
+
+
+ doubleVector tempVector;
+ double mean;
+
+ int numberOfRows;
+ int numberOfColumns;
+
+ //rows
+ numberOfRows = featureMatrix.size();
+ //cols
+ numberOfColumns = featureMatrix[0].size();
+
+
+ int i = 0;
+ int j = 0;
+ /***********CALCULATING MEAN*********/
+ for(i = 0; i < numberOfColumns;i++)
+ {
+ mean = 0.0;
+ for(j = 0;j < numberOfRows;j++)
+ {
+ mean = mean + featureMatrix[j][i];
+ }
+ mean = mean /numberOfRows;
+ meanFeature.push_back(mean);
+ }
+
+ /**********MEAN CORRECTED DATA************/
+ for( i = 0; i < numberOfRows; i++)
+ {
+ for(j = 0; j < numberOfColumns; j++)
+ {
+ featureMatrix[i][j] = featureMatrix[i][j] - meanFeature[j];
+ }
+ }
+
+ /** COMPUTING COVARIANCE MATRIX**/
+ tempVector.assign(numberOfColumns,0.0);
+ covarianceMatrix.assign(numberOfColumns,tempVector);
+ tempVector.clear();
+
+ bool bcovarianceMatrixFlag = false;
+ for( i = 0; i < numberOfColumns; i++)
+ {
+ for(j = 0;j < numberOfColumns; j++)
+ {
+ if(i <= j)
+ {
+ for(int k = 0; k < numberOfRows; k++)
+ {
+
+ covarianceMatrix[i][j] += featureMatrix[k][i]*featureMatrix[k][j];
+
+ }
+ covarianceMatrix[i][j] = covarianceMatrix[i][j] /(numberOfRows - 1);
+ }
+ else
+ {
+ covarianceMatrix[i][j] = covarianceMatrix[j][i];
+ }
+ if(covarianceMatrix[i][j] != 0.0)
+ bcovarianceMatrixFlag = true;
+ }
+ }
+
+ if(!bcovarianceMatrixFlag)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_COVARIANCEMATRIX << " " <<
+ getErrorMessage(EEMPTY_COVARIANCEMATRIX) <<
+ " ActiveDTWShapeRecognizer::computeCovarianceMatrix()" << endl;
+
+ LTKReturnError(EEMPTY_COVARIANCEMATRIX);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeCovarianceMatrix()" << endl;
+
+ return SUCCESS;
+ }
+
+
+ /**********************************************************************************
+ * AUTHOR : S Anand
+ * DATE : 3-MAR-2009
+ * NAME : computeEigenVectors
+ * DESCRIPTION : This method computes the eigenValues and eigenVectors of
+ a covarianceMatrix
+ * ARGUMENTS : INPUT
+ covarianceMatrix double2DVector (matrix whose eigenValues and eigenVectors are to be computed)
+ rank int (rank of covarianceMatrix)
+ nrot int (number of rotations) This a parameter used by the algorithm
+ OUTPUT
+ eigenValueVec doubleVector Eigen values of covarianceMatrix
+ eigenVectorMatrix double2DVector Eigen vectors of covarianceMatrix
+
+ * RETURNS : integer Holds error value if occurs
+ * Holds SUCCESS if no erros
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+ int ActiveDTWShapeRecognizer::computeEigenVectors(double2DVector &covarianceMatrix,const int rank,
+ doubleVector &eigenValueVec, double2DVector &eigenVectorMatrix, int& nrot)
+ {
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeEigenVectors()" << endl;
+
+ if(covarianceMatrix.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_COVARIANCEMATRIX << " " <<
+ getErrorMessage(EEMPTY_COVARIANCEMATRIX) <<
+ " ActiveDTWShapeRecognizer::computeEigenVectors()" << endl;
+
+ LTKReturnError(EEMPTY_COVARIANCEMATRIX);
+ }
+
+ if(rank <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_RANK << " " <<
+ getErrorMessage(EINVALID_RANK) <<
+ " ActiveDTWShapeRecognizer::computeEigenVectors()" << endl;
+
+ LTKReturnError(EINVALID_RANK);
+ }
+
+ int MAX_ITER = 1000;
+
+ int ip,count,p,q,r;
+
+ double theta, tau, t,sm,s,h,g,c;
+
+ double app,aqq,apq,vpp,vqq,vpq;
+
+ double2DVector::iterator itrRow,itrRowEnd;
+
+ doubleVector::iterator itrCol,itrColEnd;
+
+ itrRowEnd = eigenVectorMatrix.end();
+
+ for(ip = 0,itrRow = eigenVectorMatrix.begin(); itrRow <itrRowEnd;++ip, ++itrRow)
+ {
+ itrColEnd = (*itrRow).end();
+
+ for(itrCol = (*itrRow).begin(); itrCol < itrColEnd; ++itrCol)
+ {
+ *itrCol = 0;
+ }
+
+ *((*itrRow).begin() + ip) = 1;
+
+ eigenValueVec.push_back(0.0);
+ }
+
+ nrot = 0;
+
+ for(count = 0; count < MAX_ITER; count++)
+ {
+ nrot++;
+
+ sm = 0.0;
+
+ itrRowEnd = covarianceMatrix.end();
+
+ for(p = 0,itrRow = covarianceMatrix.begin(); itrRow <itrRowEnd;++p, ++itrRow)
+ {
+ itrColEnd = (*itrRow).end();
+
+ for(itrCol = (*itrRow).begin()+p+1; itrCol < itrColEnd; ++itrCol)
+ {
+ sm += fabs(*itrCol);
+ }
+ }
+
+ if(sm < EPS)
+ {
+ for(r=0;r<rank;r++)
+ {
+ eigenValueVec[r] = covarianceMatrix[r][r];
+ }
+
+ }
+
+ for(p=0; p<(rank-1) ; p++)
+ {
+ for(q=(p+1); q<rank; q++)
+ {
+ if(fabs(covarianceMatrix[p][q])>EPS1)
+ {
+ theta = (covarianceMatrix[q][q] - covarianceMatrix[p][p])/
+ (2*covarianceMatrix[p][q]);
+
+ t = sqrt(1+theta * theta) - theta;
+
+ c = 1/(sqrt(1+t*t));
+
+ s = t*c;
+
+ tau = s/(1+c);
+
+ apq = covarianceMatrix[p][q];
+
+ app = covarianceMatrix[p][p];
+
+ aqq = covarianceMatrix[q][q];
+
+ vpp = eigenVectorMatrix[p][p];
+
+ vpq = eigenVectorMatrix[p][q];
+
+ vqq = eigenVectorMatrix[q][q];
+
+ for(r=0;r<p;r++)
+ {
+ h = covarianceMatrix[r][p];
+
+ g = covarianceMatrix[r][q];
+
+ covarianceMatrix[r][p] = (double)(c*h - s*g);
+
+ covarianceMatrix[r][q] = (double)(c*g + s*h);
+ }
+ covarianceMatrix[p][p] -= (double)(t*apq);
+
+ covarianceMatrix[p][q] = (double)(0.0);
+
+ for(r=p+1; r<q; r++)
+ {
+ h = covarianceMatrix[p][r];
+
+ g = covarianceMatrix[r][q];
+
+ covarianceMatrix[p][r] = (double)(c*h - s*g);
+
+ covarianceMatrix[r][q] = (double)(c*g + s*h);
+ }
+
+ covarianceMatrix[q][q] += (double)(t*apq);
+
+ for(r = q+1; r<rank; r++)
+ {
+ h = covarianceMatrix[p][r];
+
+ g = covarianceMatrix[q][r];
+
+ covarianceMatrix[p][r] = (double)(c*h - s*g);
+
+ covarianceMatrix[q][r] = (double)(c*g + s*h);
+ }
+
+ for(r = 0; r<rank ; r++)
+ {
+ h = eigenVectorMatrix[r][p];
+
+ g = eigenVectorMatrix[r][q];
+
+ eigenVectorMatrix[r][p] = (double)(c*h - s*g);
+
+ eigenVectorMatrix[r][q] = (double)(c*g + s*h);
+ }
+ }
+ else
+ {
+ covarianceMatrix[p][q] = 0;
+ }
+ }
+ }
+
+ }
+
+
+
+ for(r=0;r<rank;r++)
+ {
+ eigenValueVec[r] = covarianceMatrix[r][r];
+ }
+
+ double temp;
+
+ for(p = 0; p<rank-1; p++)
+ {
+ for(q = p+1; q<rank; q++)
+ {
+ if(fabs(eigenValueVec[p]) < fabs(eigenValueVec[q]))
+ {
+ for(r = 0; r<rank; r++)
+ {
+ temp = eigenVectorMatrix[r][p];
+
+ eigenVectorMatrix[r][p] = eigenVectorMatrix[r][q];
+
+ eigenVectorMatrix[r][q] = temp;
+
+ }
+
+ temp = eigenValueVec[p];
+
+ eigenValueVec[p] = eigenValueVec[q];
+
+ eigenValueVec[q] = temp;
+
+ }
+ }
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::computeEigenVectors()" << endl;
+
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : initializeFeatureExtractorInstance
+* DESCRIPTION : This method get the Instance of the Feature Extractor
+* from LTKShapeFeatureExtractorFactory
+* ARGUMENTS :
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int ActiveDTWShapeRecognizer::initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+
+ LTKShapeFeatureExtractorFactory factory;
+ int errorCode = factory.createFeatureExtractor(m_featureExtractorName,
+ m_lipiRootPath,
+ m_lipiLibPath,
+ &m_libHandlerFE,
+ controlInfo,
+ &m_ptrFeatureExtractor);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EFTR_EXTR_NOT_EXIST << " " <<
+ " ActiveDTWShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+ LTKReturnError(errorCode);
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : deleteFeatureExtractorInstance
+* DESCRIPTION : This method unloads the Feature extractor instance
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int ActiveDTWShapeRecognizer::deleteFeatureExtractorInstance()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ if (m_ptrFeatureExtractor != NULL)
+ {
+ typedef int (*FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)(LTKShapeFeatureExtractor *obj);
+ FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR deleteFeatureExtractor;
+ void * functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ int returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandlerFE,
+ DELETE_SHAPE_FEATURE_EXTRACTOR,
+ &functionHandle);
+
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: "<< EDLL_FUNC_ADDRESS_DELETE_FEATEXT << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_DELETE_FEATEXT) <<
+ " ActiveDTWShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_DELETE_FEATEXT);
+ }
+
+ deleteFeatureExtractor = (FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)functionHandle;
+
+ deleteFeatureExtractor(m_ptrFeatureExtractor);
+
+ m_ptrFeatureExtractor = NULL;
+
+ // unload feature extractor dll
+ if(m_libHandlerFE != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandlerFE);
+ m_libHandlerFE = NULL;
+
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : updateHeaderWithAlgoInfo
+* DESCRIPTION : This method will Update the Header information for the MDT file
+* ARGUMENTS :
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+void ActiveDTWShapeRecognizer::updateHeaderWithAlgoInfo()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+ m_headerInfo[RECVERSION] = m_currentVersion;
+ string algoName = ACTIVEDTW;
+ m_headerInfo[RECNAME] = algoName;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+}
+
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getDistance
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+void ActiveDTWShapeRecognizer::getDistance(const LTKShapeFeaturePtr& f1,
+ const LTKShapeFeaturePtr& f2,
+ float& distance)
+{
+ f1->getDistance(f2, distance);
+}
+
+
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getFeaturesFromTraceGroup
+* DESCRIPTION : 1. PreProcess 2. Extract Features 3.Add to PrototypeSet
+* 4. Add to MDT
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+
+int ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& featureVec)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+
+ //TraceGroup after Preprocessing
+ LTKTraceGroup preprocessedTraceGroup;
+
+ //Check for empty traces in inTraceGroup
+ if(inTraceGroup.containsAnyEmptyTrace())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_TRACE << " " <<
+ getErrorMessage(EEMPTY_TRACE) <<
+ " ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ //Preprocess the inTraceGroup
+ int errorCode = preprocess(inTraceGroup, preprocessedTraceGroup);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ featureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting ActiveDTWShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : getTraceGroup
+* DESCRIPTION : Returns the tracegroups of the shape
+* For singletons it returns the tracegroups from the feature vector
+* For clusters it returns the tracegroup of the cluster mean
+* ARGUMENTS : INPUT:
+shapeID - class whose trace groups are to be returned
+numberOfTraceGroups - maximum number of trace groups to be returned
+: OUTPUT
+outTraceGroups - tracegroups of the class
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+
+int ActiveDTWShapeRecognizer::getTraceGroups(int shapeID, int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering ActiveDTWShapeRecognizer::getTraceGroups"
+ <<endl;
+
+ if(m_shapeIDNumPrototypesMap.find(shapeID) == m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_SHAPEID << " " <<
+ getErrorMessage(EINVALID_SHAPEID) <<
+ " ActiveDTWShapeRecognizer::getTraceGroups()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ if(m_shapeIDNumPrototypesMap[shapeID] < numberOfTraceGroups)
+ {
+ numberOfTraceGroups = m_shapeIDNumPrototypesMap[shapeID];
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Number of TraceGroup in PrototypeShapes is less than specified."
+ << "Returning all TraceGroups :"
+ << numberOfTraceGroups <<endl;
+ }
+
+ vector<ActiveDTWShapeModel>::iterator prototypeShapesIter = m_prototypeShapes.begin();
+ int counter =0;
+ vector<ActiveDTWClusterModel> clusterModelVector;
+ shapeMatrix singletonVector;
+
+ for(;prototypeShapesIter!=m_prototypeShapes.end();)
+ {
+ int currentShapeId = (*prototypeShapesIter).getShapeId();
+
+ if(currentShapeId == shapeID)
+ {
+ LTKTraceGroup traceGroup;
+
+ clusterModelVector = (*prototypeShapesIter).getClusterModelVector();
+ singletonVector = (*prototypeShapesIter).getSingletonVector();
+
+ int clusterModelVectorSize = clusterModelVector.size();
+ int singletonVectorSize = singletonVector.size();
+
+ if(singletonVectorSize > 0)
+ {
+ //convert singletons into tracegroups
+ for(int i = 0; i < singletonVectorSize; i++)
+ {
+ //converting the featureVector to traceGroup
+ int errorCode = m_ptrFeatureExtractor->convertFeatVecToTraceGroup(
+ singletonVector[i],traceGroup);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::getTraceGroups()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ outTraceGroups.push_back(traceGroup);
+ counter++;
+ if(counter==numberOfTraceGroups)
+ break;
+ }
+ }
+
+
+ if(clusterModelVectorSize > 0)
+ {
+ //converting all the cluster means into traceGroups
+ for(int i = 0; i < clusterModelVectorSize; i++)
+ {
+ doubleVector clusterMean = clusterModelVector[i].getClusterMean();
+
+ //converting the doubleVector to featureVector
+ vector<LTKShapeFeaturePtr> shapeFeatureVec;
+
+ int errorCode = convertDoubleToFeatureVector(shapeFeatureVec,clusterMean);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::getTraceGroups()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //converting the featureVector to traceGroup
+ errorCode = m_ptrFeatureExtractor->convertFeatVecToTraceGroup(
+ shapeFeatureVec,traceGroup);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::getTraceGroups()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ outTraceGroups.push_back(traceGroup);
+ clusterMean.clear();
+ counter++;
+ if(counter==numberOfTraceGroups)
+ break;
+ }
+ }
+ }
+ prototypeShapesIter++;
+ }
+
+ //clearing vectors
+ clusterModelVector.clear();
+ singletonVector.clear();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting ActiveDTWShapeRecognizer::getTraceGroups"
+ <<endl;
+ return SUCCESS;
+}
+
+/***********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : initializePreprocessor
+* DESCRIPTION : This method is used to initialize the PreProcessor
+* ARGUMENTS : preprocDLLPath : string : Holds the Path of the Preprocessor DLL,
+* returnStatus : int : Holds SUCCESS or Error Values, if occurs
+* RETURNS : preprocessor instance
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+
+ FN_PTR_CREATELTKLIPIPREPROCESSOR createLTKLipiPreProcessor = NULL;
+
+ int errorCode;
+
+ // Load the DLL with path=preprocDLLPath
+ void* functionHandle = NULL;
+
+ int returnVal = m_OSUtilPtr->loadSharedLib(controlInfo.lipiLib, PREPROC, &m_libHandler);
+
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ELOAD_PREPROC_DLL << " " <<
+ getErrorMessage(ELOAD_PREPROC_DLL) <<
+ " ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ELOAD_PREPROC_DLL);
+ }
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ CREATEPREPROCINST,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ createLTKLipiPreProcessor = (FN_PTR_CREATELTKLIPIPREPROCESSOR)functionHandle;
+
+ functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ DESTROYPREPROCINST,
+ &functionHandle);
+
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ m_deleteLTKLipiPreProcessor = (FN_PTR_DELETELTKLIPIPREPROCESSOR)functionHandle;
+
+ // Create preprocessor instance
+ errorCode = createLTKLipiPreProcessor(controlInfo, preprocInstance);
+
+ if(errorCode!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // Could not create a LTKLipiPreProcessor
+ if(*preprocInstance == NULL)
+ {
+ // Unload the DLL
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ECREATE_PREPROC << " " <<
+ getErrorMessage(ECREATE_PREPROC) <<
+ " ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ECREATE_PREPROC);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::initializePreprocessor()" << endl;
+
+ return SUCCESS;
+
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : deletePreprocessor
+* DESCRIPTION : This method is used to deletes the PreProcessor instance
+* ARGUMENTS : ptrPreprocInstance : Holds the pointer to the LTKPreprocessorInterface
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+
+//int ActiveDTWShapeRecognizer::deletePreprocessor(LTKPreprocessorInterface *ptrPreprocInstance)
+int ActiveDTWShapeRecognizer::deletePreprocessor()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::deletePreprocessor()" << endl;
+
+ //deleting the preprocessor instance
+ if(m_ptrPreproc != NULL)
+ {
+ m_deleteLTKLipiPreProcessor(m_ptrPreproc);
+ m_ptrPreproc = NULL;
+ }
+
+ //Unload the dll
+ int returnStatus = unloadPreprocessorDLL();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " ActiveDTWShapeRecognizer::deletePreprocessor()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::deletePreprocessor()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : unloadPreprocessorDLL
+* DESCRIPTION : This method is used to Unloads the preprocessor DLL.
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::unloadPreprocessorDLL()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+ //Check the preprocessor DLL was loaded already
+ if(m_libHandler != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandler);
+ m_libHandler = NULL;
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : findOptimalDeformation
+* DESCRIPTION : This method computes the parameters required to construct the optimal
+deformation of each cluster that is closest to the test sample
+* ARGUMENTS : INPUT
+eigenValues doubleVector (eigenValues of cluster)
+eigenVector double2DVector (eigenVectors of cluster)
+clusterMean doubleVector (mean of cluster)
+testSample doubleVector (test sample)
+:OUTPUT
+deformationParameters doubleVector (deformation parameters)
+*
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::findOptimalDeformation(doubleVector& deformationParameters,doubleVector& eigenValues, double2DVector& eigenVector,
+ doubleVector& clusterMean, doubleVector& testSample)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+
+ if(eigenValues.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_EIGENVALUES << " " <<
+ getErrorMessage(EEMPTY_EIGENVALUES) <<
+ " ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+
+ LTKReturnError(EEMPTY_EIGENVALUES);
+ }
+
+ if(eigenVector.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_EIGENVECTORS << " " <<
+ getErrorMessage(EEMPTY_EIGENVECTORS) <<
+ " ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+
+ LTKReturnError(EEMPTY_EIGENVECTORS);
+ }
+
+ if(clusterMean.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_CLUSTERMEAN << " " <<
+ getErrorMessage(EEMPTY_CLUSTERMEAN) <<
+ " ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+
+ LTKReturnError(EEMPTY_CLUSTERMEAN);
+ }
+
+ if(eigenValues.size() != eigenVector.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENUM_EIGVALUES_NOTEQUALTO_NUM_EIGVECTORS << " " <<
+ getErrorMessage(ENUM_EIGVALUES_NOTEQUALTO_NUM_EIGVECTORS) <<
+ " ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+
+ LTKReturnError(ENUM_EIGVALUES_NOTEQUALTO_NUM_EIGVECTORS);
+ }
+
+
+ doubleVector diffVec;
+ doubleVector linearConstant;
+ doubleVector tempDoubleVec;
+ doubleVector lowerBounds;
+ doubleVector upperBounds;
+ double tempSum;
+
+ int n ;
+
+ int i = 0;
+
+
+
+ /***************CALCULATING PARAMETERS***********************/
+ /**CALCULATING THE DIFFERENCE VECTOR**/
+ diffVec.assign(clusterMean.size(),0.0);
+
+ for(i = 0; i < diffVec.size(); i++)
+ diffVec[i] = testSample[i] - clusterMean[i];
+
+
+ /**CALCULATING THE LINEAR CONSTANT TERM**/
+ //linearConstant is calculated as:
+ //linearConstant = eigVec*diffVec
+ double2DVector::iterator iStart = eigenVector.begin();
+ double2DVector::iterator iEnd = eigenVector.end();
+
+ for(;iStart != iEnd;++iStart)
+ {
+ tempDoubleVec = (*iStart);
+
+ tempSum = 0.0;
+ for(i = 0; i < tempDoubleVec.size(); i++ )
+ {
+
+ tempSum += (tempDoubleVec[i] * diffVec[i]);
+ }
+
+ linearConstant.push_back(tempSum);
+ }
+
+ //problem dimension
+ n = eigenVector.size();
+
+
+
+ double tempBounds;
+
+ for( i = 0; i < n; i++)
+ {
+
+ tempBounds = sqrt(eigenValues[i] * m_eigenSpreadValue);
+ lowerBounds.push_back((-1) * tempBounds);
+ upperBounds.push_back(tempBounds);
+ }
+
+ /**OPTIMIZATION PROCEDURE**/
+ for( i = 0; i < n; i++)
+ {
+ if(linearConstant[i] >= lowerBounds[i] && linearConstant[i] <= upperBounds[i])
+ deformationParameters[i] = linearConstant[i];
+ else
+ {
+ if(linearConstant[i] < lowerBounds[i])
+ deformationParameters[i] = lowerBounds[i];
+ else
+ deformationParameters[i] = upperBounds[i];
+ }
+ }
+
+ //clearing vectors
+ linearConstant.clear();
+ lowerBounds.clear();
+ upperBounds.clear();
+ diffVec.clear();
+ tempDoubleVec.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::findOptimalDeformation()" << endl;
+ return SUCCESS;
+};
+
+/**************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : validatePreprocParameters
+* DESCRIPTION : This method is used to validate the preproc parameters with
+* mdt header values
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+****************************************************************************/
+int ActiveDTWShapeRecognizer::validatePreprocParameters(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::validatePreprocParameters()" << endl;
+
+
+ string tempStrVar = "";
+ string headerValue = "";
+ int headerValueInt = 0;
+ float headerValueFloat = 0.0f;
+ int tempIntegerValue = 0;
+ float tempFloatValue = 0.0f;
+
+ //preproc sequence
+ string mdtPreprocSeqn = headerSequence[PREPROC_SEQ];
+ if(LTKSTRCMP(m_preProcSeqn.c_str(), mdtPreprocSeqn.c_str()) != 0 &&
+ LTKSTRCMP("NA", mdtPreprocSeqn.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preprocSeqn in config file ("<<
+ m_preProcSeqn <<") does not match with the value in MDT file ("<<
+ mdtPreprocSeqn <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+
+ //ResampTraceDimension
+ headerValue = "";
+ if(LTKSTRCMP("NA", headerSequence[TRACE_DIM].c_str()) != 0)
+ {
+ headerValueInt = atoi(headerSequence[TRACE_DIM].c_str());
+ tempIntegerValue = m_ptrPreproc->getTraceDimension();
+
+ if(headerValueInt != tempIntegerValue )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of TraceDimension in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+
+ // preserve aspect ratio
+ bool preProcPreserveAspectRatio = m_ptrPreproc->getPreserveAspectRatio();
+ tempStrVar = "false";
+ if (preProcPreserveAspectRatio == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatio in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_ASP_RATIO] <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ //NormPreserveRelativeYPosition
+ bool preProcNormPreserveRelativeYPosition = m_ptrPreproc->getPreserveRealtiveYPosition();
+ tempStrVar = "false";
+ if (preProcNormPreserveRelativeYPosition == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormPreserveRelativeYPosition in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_REL_Y_POS] <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+
+ // NormPreserveAspectRatioThreshold
+ tempFloatValue = m_ptrPreproc->getAspectRatioThreshold();
+ if(LTKSTRCMP((headerSequence[ASP_RATIO_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[ASP_RATIO_THRES]);
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatioThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+
+
+ // NormLineWidthThreshold
+ if(LTKSTRCMP((headerSequence[DOT_SIZE_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_SIZE_THRES]);
+ tempFloatValue = m_ptrPreproc->getSizeThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormLineWidthThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+
+ // NormDotSizeThreshold
+ if(LTKSTRCMP((headerSequence[DOT_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_THRES]);
+ tempFloatValue = m_ptrPreproc->getDotThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormDotSizeThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+
+
+ //ResampPointAllocation
+ tempStrVar = "";
+ tempStrVar = m_ptrPreproc->getResamplingMethod();
+ if(LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcResampPointAllocation in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[RESAMP_POINT_ALLOC] <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ //SmoothWindowSize
+ if(LTKSTRCMP((headerSequence[SMOOTH_WIND_SIZE]).c_str(), "NA") != 0)
+ {
+ headerValueInt = atoi(headerSequence[SMOOTH_WIND_SIZE].c_str());
+ tempIntegerValue = m_ptrPreproc->getFilterLength();
+
+ if(headerValueInt != tempIntegerValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcSmoothWindowSize in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " ActiveDTWShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::validatePreprocParameters()" << endl;
+ return SUCCESS;
+
+}
+
+
+/*********************************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : computeEigenVectorsForLargeDimension
+* DESCRIPTION : This method computes the eigen values and eigen vectors for larger
+covariance matrices of large dimension using the eigen value and
+eigen vectors of the smaller covariance matrix
+* ARGUMENTS :INPUT
+meanCorrectedData double2DVector
+-- used for constructing the smaller covariance matrix
+covarianceMatrix double2DVector
+-- this is the larger covariance matrix whose eigen values and
+eigen vectors are to be computed
+:OUTPUT
+eigenValues doubleVector
+-- eigenValues of the larger covarianceMatrix
+eigenVectors double2DVector
+-- eigenVectors of the larger covarianceMatrix
+*
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+* NOTES : This based on a paper implementation
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::computeEigenVectorsForLargeDimension(double2DVector& meanCorrectedData,double2DVector& covarianceMatrix,
+ double2DVector& eigenVector,doubleVector& eigenValues)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::computeEigenVectorsForLargeDimension()" << endl;
+
+ if(meanCorrectedData.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_MEANCORRECTEDDATA << " " <<
+ getErrorMessage(EEMPTY_MEANCORRECTEDDATA) <<
+ " ActiveDTWShapeRecognizer::computeEigenVectorsForLargeDimension()" << endl;
+
+ LTKReturnError(EEMPTY_MEANCORRECTEDDATA);
+ }
+
+ if(covarianceMatrix.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_COVARIANCEMATRIX << " " <<
+ getErrorMessage(EEMPTY_COVARIANCEMATRIX) <<
+ " ActiveDTWShapeRecognizer::computeEigenVectorsForLargeDimension()" << endl;
+
+ LTKReturnError(EEMPTY_COVARIANCEMATRIX);
+ }
+
+
+ //covarianceSmall = A(transpose) * A
+ double2DVector covarianceSmall;
+
+ doubleVector tempVector;
+
+ //eigen values and eigen vectors of A(transpose) * A
+ double2DVector eigVecMat;
+ doubleVector eigValVec;
+
+ //number of iterations for computing eigen vectors
+ int nrot = 0;
+
+ int meanCorrectedDataSize = meanCorrectedData.size();
+ int rowSize = meanCorrectedData[0].size();
+
+ tempVector.assign(meanCorrectedDataSize,0.0);
+ covarianceSmall.assign(meanCorrectedDataSize,tempVector);
+ tempVector.clear();
+
+ int i = 0;
+ int j = 0;
+
+ //calculating A(transpose)* A
+ for(i = 0; i < meanCorrectedDataSize; i++)
+ {
+ for(j = 0;j < meanCorrectedDataSize; j++)
+ {
+ if(i <= j)
+ {
+ for(int k = 0; k < rowSize; k++)
+ {
+ covarianceSmall[i][j] += meanCorrectedData[i][k]*meanCorrectedData[j][k];
+ }
+ covarianceSmall[i][j] = covarianceSmall[i][j] /(meanCorrectedDataSize -1);
+ }
+ else
+ {
+ covarianceSmall[i][j] = covarianceSmall[j][i];
+ }
+ }
+ }
+
+
+ //allocating memory for eigVecMat
+ tempVector.assign(meanCorrectedDataSize,0.0);
+ eigVecMat.assign(meanCorrectedDataSize,tempVector);
+ tempVector.clear();
+
+
+ //computing the eigen vectors of A(transpose)*A
+
+
+ int errorCode = computeEigenVectors(covarianceSmall,covarianceSmall.size(),
+ eigValVec,eigVecMat,nrot);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+
+
+
+ /**CALCULATING EIGEN ENERGY **/
+ double totalEigenEnergy = 0.0;
+ double currentEigenEnergy = 0.0;
+ int numEigenVectors = 0;
+
+ int eigenValSize = eigValVec.size();
+ for( i = 0; i < eigenValSize; i++)
+ totalEigenEnergy += eigValVec[i];
+
+ /**DETERMINING NUMBER OF EIGEN VECTORS**/
+ while(currentEigenEnergy <= ((m_percentEigenEnergy*totalEigenEnergy)/100) && numEigenVectors < eigenValSize)
+ currentEigenEnergy += eigValVec[numEigenVectors++];
+
+ /**COMPUTING THE EIGEN VECTORS OF THE LARGER COVARIANCE MATRIX AS (A * EIGENVECTOR) **/
+
+ tempVector.assign(numEigenVectors,0.0);
+ eigenVector.assign(rowSize,tempVector);
+ tempVector.clear();
+
+ for( i = 0; i < rowSize; i++)
+ {
+ for(int j = 0; j < numEigenVectors; j++)
+ {
+ for(int k = 0; k < meanCorrectedDataSize; k++)
+ {
+ eigenVector[i][j] += meanCorrectedData[k][i] * eigVecMat[k][j];
+ }
+ }
+ }
+
+ //calculating the magnitude of each eigenVectors
+ doubleVector magnitudeVector;
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ double tempMagnitude = 0;
+ for(j = 0; j < rowSize; j++)
+ tempMagnitude += (eigenVector[j][i] * eigenVector[j][i]);
+ double sqrtMagnitude = sqrt(tempMagnitude);
+ magnitudeVector.push_back(sqrtMagnitude);
+ }
+
+
+ //normalizing eigenVectors
+ for( i = 0; i < numEigenVectors; i++)
+ {
+ for(j = 0; j < rowSize; j++)
+ eigenVector[j][i] = (eigenVector[j][i]/magnitudeVector[i]);
+ }
+ magnitudeVector.clear();
+
+ //selecting the corresponding eigen values
+ for( i = 0; i < numEigenVectors; i++)
+ eigenValues.push_back(eigValVec[i]);
+
+ eigVecMat.clear();
+ eigValVec.clear();
+ covarianceSmall.clear();
+
+
+ return SUCCESS;
+
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : convertDoubleToFeatureVector
+* DESCRIPTION : This method converts the double Vector (flatenned version of the feature vector)
+to the vector<LTKShapeFeaturePtr> form
+* ARGUMENTS : INPUT
+* featureVec doubleVector
+:OUTPUT
+shapeFeatureVec vector<LTKShapeFeaturePtr>
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no erros
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::convertDoubleToFeatureVector(vector<LTKShapeFeaturePtr>& shapeFeatureVec,doubleVector& featureVec)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::convertDoubleToFeatureVector" << endl;
+
+ LTKShapeFeaturePtr shapeFeature;
+ int featureVectorSize = featureVec.size();
+ int featureDimension;
+ floatVector tempFeature;
+
+ for(int i = 0; i < featureVectorSize;)
+ {
+ shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+ featureDimension = shapeFeature->getFeatureDimension();
+
+
+ for(int j = 0; j < featureDimension; j++)
+ {
+ tempFeature.push_back((float)featureVec[i]);
+ i++;
+ }
+
+
+ if (shapeFeature->initialize(tempFeature) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct"<<
+ " ActiveDTWShapeRecognizer::convertDoubleToFeatureVector" << endl;
+
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+ shapeFeatureVec.push_back(shapeFeature);
+
+ tempFeature.clear();
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::convertDoubleToFeatureVector" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : adapt
+* DESCRIPTION : adapt recent recognized sample
+* ARGUMENTS : shapeID : True shapeID of sample
+* RETURNS : Success : If sample was adapted successfully
+* Failure : Returns Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::adapt(int shapeId)
+{
+ try{
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Enter ActiveDTWShapeRecognizer::adapt()"<<endl;
+
+ //check if shapeId has already seen by classifier else add shapeId
+ if(m_shapeIDNumPrototypesMap.find(shapeId) == m_shapeIDNumPrototypesMap.end())
+ {
+
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ //Adaptation Code
+ LTKAdapt* adaptObj = LTKAdapt::getInstance(this);
+
+ int nErrorCode;
+ nErrorCode = adaptObj->adapt(shapeId);
+ if(nErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during ActiveDTWShapeRecognizer::adapt()"<<endl;
+ LTKReturnError(nErrorCode);
+ }
+
+ //Clear Variables cached
+ m_neighborInfoVec.clear();
+ m_vecRecoResult.clear();
+
+ }
+ catch(...)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during ActiveDTWShapeRecognizer::adapt()"<<endl;
+ return FAILURE;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Exit ActiveDTWShapeRecognizer::adapt()"<<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : adapt
+* DESCRIPTION : adapt sample passed as argument
+* ARGUMENTS : sampleTraceGroup : TraceGroup of sample to be adapted
+* shapeID : True shapeID of sample
+* RETURNS : Success : If sample was adapted successfully
+* Failure : Returns Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::adapt(const LTKTraceGroup& sampleTraceGroup, int shapeId )
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Enter ActiveDTWShapeRecognizer::Adapt()"<<endl;
+
+ int errorCode;
+
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "ActiveDTWShapeRecognizer::Adapt(): Invalid shapeId"<< endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ //check if shapeId has already seen by classifier else add shapeId
+ if(m_shapeIDNumPrototypesMap.find(shapeId) == m_shapeIDNumPrototypesMap.end())
+ {
+ //add class
+ errorCode = addClass(sampleTraceGroup, shapeId);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during call to recognize in ActiveDTWShapeRecognizer::Adapt()"<<endl;
+ LTKReturnError(errorCode);
+ }
+ }
+ else
+ {
+ //recognize and adapt
+ vector<int> vecSubSet;
+ vector<LTKShapeRecoResult> vecRecoResult;
+ LTKScreenContext objScreenContext;
+
+ errorCode = recognize(sampleTraceGroup,objScreenContext,
+ vecSubSet,CONF_THRESHOLD_FILTER_OFF,
+ NN_DEF_RECO_NUM_CHOICES,vecRecoResult);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during call to recognize in ActiveDTWShapeRecognizer::Adapt()"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = adapt(shapeId);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during call to recognize in ActiveDTWShapeRecognizer::Adapt()"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Exit ActiveDTWShapeRecognizer::Adapt()"<<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : deleteAdaptInstance
+* DESCRIPTION : delete AdaptInstance
+* ARGUMENTS :
+* RETURNS : None
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::deleteAdaptInstance()
+{
+ //Implemented as deleteAdaptInstance is called by ~NNShapeRecognizer
+ //and adaptObj object is not available in NN.cpp
+
+ LTKAdapt *adaptInstance = LTKAdapt::getInstance(this);
+ if(adaptInstance)
+ {
+ adaptInstance->deleteInstance();
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR ; S Anand
+* DATE : 3-MAR-2009
+* NAME : writePrototypeShapesToMDTFile
+* DESCRIPTION : Flushes the prototype shapes data to activedtw.mdt file
+* ARGUMENTS :
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+
+int ActiveDTWShapeRecognizer::writePrototypeShapesToMDTFile()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::writePrototypeShapesToMDTFile()" << endl;
+
+ int errorCode = SUCCESS;
+
+ //Flush to MDT only after m_MDTUpdateFreq modifications
+ m_prototypeSetModifyCount++;
+
+ if(m_prototypeSetModifyCount == m_MDTUpdateFreq)
+ {
+ m_prototypeSetModifyCount = 0;
+
+ ofstream mdtFileHandle;
+
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_activedtwMDTFilePath.c_str(),ios::out|ios::binary);
+ }
+
+ //Return error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN) <<
+ " ActiveDTWShapeRecognizer::writePrototypeShapesToMDTFile()" << endl;
+
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ //write the number of shapes to MDT file
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ // 0 represents dynamic
+ mdtFileHandle << 0 << endl;
+ }
+ else
+ {
+ int numShapes = 0;
+ mdtFileHandle.write((char*) &numShapes, sizeof(unsigned short));
+ }
+
+ int prototypeShapesSize = m_prototypeShapes.size();
+
+ for(int i = 0; i < prototypeShapesSize; i++)
+ {
+ errorCode = appendShapeModelToMDTFile(m_prototypeShapes[i],mdtFileHandle);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::writePrototypeShapesToMDTFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+ }
+
+ mdtFileHandle.close();
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ string strModelDataHeaderInfoFile = "";
+ LTKCheckSumGenerate cheSumGen;
+
+ errorCode = cheSumGen.addHeaderInfo(
+ strModelDataHeaderInfoFile,
+ m_activedtwMDTFilePath,
+ m_headerInfo);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::writePrototypeSetToMDTFile()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::writePrototypeShapesToMDTFile()" << endl;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : addClass
+* DESCRIPTION : Adds a new trace group as a class
+* ARGUMENTS : INPUT
+sampleTraceGroup LTKTraceGroup
+shapeID int
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::addClass()" << endl;
+
+ int errorCode;
+
+ //unless projecttype is dynamic we cannot add classes
+ if(!m_projectTypeDynamic)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROJ_NOT_DYNAMIC << " " <<
+ "Not allowed to ADD shapes to a project with fixed number of shapes"<<
+ " ActiveDTWShapeRecognizer::addClass()" << endl;
+
+ LTKReturnError(EPROJ_NOT_DYNAMIC);
+ }
+
+
+ //if the sample does not have a shape id, we assign it NEW_SHAPEID = -2 in runshaperecInternal
+ //then in the following module we determine the new shape id based on the existing shape ids
+ if(shapeID = NEW_SHAPEID)
+ {
+ int tempShapeID;
+
+ if(m_shapeIDNumPrototypesMap.size() > 0)
+ {
+ map<int,int>::reverse_iterator m_shapeIDNumPrototypesMapIter;
+ m_shapeIDNumPrototypesMapIter = m_shapeIDNumPrototypesMap.rbegin();
+ tempShapeID = m_shapeIDNumPrototypesMapIter->first;
+ shapeID = tempShapeID+1;
+ }
+ else
+ {
+ shapeID = LTK_START_SHAPEID;
+ }
+
+ }
+
+ vector<LTKShapeFeaturePtr> tempFeatureVec;
+
+ errorCode = extractFeatVecFromTraceGroup(sampleTraceGroup,tempFeatureVec);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::addClass()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ shapeMatrix newShapeMatrix;
+
+ newShapeMatrix.push_back(tempFeatureVec);
+
+ //add the feature vector as a singleton Vector
+ ActiveDTWShapeModel newShapeModel;
+
+
+ errorCode = newShapeModel.setShapeId(shapeID);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " "<< endl;
+ LTKReturnError(errorCode);
+ }
+
+ newShapeModel.setSingletonVector(newShapeMatrix);
+
+ if(m_prototypeShapes.empty())
+ {
+ m_prototypeShapes.push_back(newShapeModel);
+ }
+ else
+ {
+ int prototypeShapesSize = m_prototypeShapes.size();
+ int maxClassId = m_prototypeShapes[prototypeShapesSize - 1].getShapeId();
+
+ if(shapeID > maxClassId)
+ m_prototypeShapes.push_back(newShapeModel);
+ else
+ {
+ vector<ActiveDTWShapeModel>::iterator prototypeShapesIter = m_prototypeShapes.begin();
+
+ while(prototypeShapesIter != m_prototypeShapes.end())
+ {
+ int currentShapeId = (*prototypeShapesIter).getShapeId();
+
+ if(currentShapeId > shapeID)
+ {
+ m_prototypeShapes.insert(prototypeShapesIter,newShapeModel);
+ break;
+ }
+ prototypeShapesIter++;
+ }
+ }
+ }
+
+ //Update m_shapeIDNumPrototypesMap
+ m_shapeIDNumPrototypesMap[shapeID]= 1;
+
+ //Update MDT File
+ errorCode = writePrototypeShapesToMDTFile();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " ActiveDTWShapeRecognizer::addClass()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //clearing vectors
+ tempFeatureVec.clear();
+ newShapeMatrix.clear();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::addClass()" << endl;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : S Anand
+* DATE : 3-MAR-2009
+* NAME : deleteClass
+* DESCRIPTION : Deletes the class with shapeID
+* ARGUMENTS : INPUT
+shapeID int
+* RETURNS : integer Holds error value if occurs
+* Holds SUCCESS if no errors
+*************************************************************************************/
+int ActiveDTWShapeRecognizer::deleteClass(int shapeID)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "ActiveDTWShapeRecognizer::deleteClass()" << endl;
+
+ if(!m_projectTypeDynamic)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROJ_NOT_DYNAMIC << " " <<
+ "Not allowed to delete shapes to a project with fixed number of Shapes"<<
+ " ActiveDTWShapeRecognizer::deleteClass()" << endl;
+
+ LTKReturnError(EPROJ_NOT_DYNAMIC);
+ }
+
+ //Validate Input Parameters - shapeID
+ if(m_shapeIDNumPrototypesMap.find(shapeID) ==m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ "shapeID is not valid"<<
+ " ActiveDTWShapeRecognizer::deleteClass()" << endl;
+
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ vector<ActiveDTWShapeModel>::iterator prototypeShapesIter;
+
+ int prototypeShapesSize = m_prototypeShapes.size();
+ int k = 0;
+
+ for(int i = 0; i < prototypeShapesSize; i++)
+ {
+ prototypeShapesIter = m_prototypeShapes.begin() + k;
+
+ int classId = (*prototypeShapesIter).getShapeId();
+
+ if(classId == shapeID)
+ {
+ vector<ActiveDTWClusterModel> currentClusterModelVector;
+ shapeMatrix currentSingletonVector;
+
+ //clearing cluster Model and singleton vectors
+ currentClusterModelVector = (*prototypeShapesIter).getClusterModelVector();
+ currentClusterModelVector.clear();
+ (*prototypeShapesIter).setClusterModelVector(currentClusterModelVector);
+
+ currentSingletonVector = (*prototypeShapesIter).getSingletonVector();
+ currentSingletonVector.clear();
+ (*prototypeShapesIter).setSingletonVector(currentSingletonVector);
+
+ m_prototypeShapes.erase(prototypeShapesIter);
+ continue;
+ }
+ k++;
+ prototypeShapesIter++;
+ }
+
+ //Update m_shapeIDNumPrototypesMap
+ m_shapeIDNumPrototypesMap.erase(shapeID);
+
+ //Update MDT File
+ int returnStatus = writePrototypeShapesToMDTFile();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " << returnStatus << " " <<
+ "Exiting ActiveDTWShapeRecognizer::deleteClass" <<endl;
+ LTKReturnError(returnStatus);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "ActiveDTWShapeRecognizer::deleteClass()" << endl;
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.h
new file mode 100644
index 00000000..9459d5c7
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/ActiveDTWShapeRecognizer.h
@@ -0,0 +1,1203 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies
+* or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+* SVN MACROS
+*
+* $LastChangedDate: 2011-08-23 13:28:15 +0530 (Tue, 23 Aug 2011) $
+* $Revision: 857 $
+* $Author: jitender $
+*
+************************************************************************/
+/*********************************************************************************************
+* FILE DESCR: Definitions for ActiveDTW Shape Recognition module
+*
+* CONTENTS:
+*
+* AUTHOR: S Anand
+*
+*
+* DATE:3-MAR-2009
+* CHANGE HISTORY:
+* Author Date Description of change
+***********************************************************************************************/
+
+
+#ifndef __ACTIVEDTWSHAPERECOGNIZER_H
+#define __ACTIVEDTWSHAPERECOGNIZER_H
+
+#include "LTKInc.h"
+#include "LTKTypes.h"
+#include "LTKMacros.h"
+#include "LTKShapeRecognizer.h"
+#include "LTKShapeRecoUtil.h"
+#include "LTKShapeSample.h"
+#include "LTKCheckSumGenerate.h"
+#include "LTKDynamicTimeWarping.h"
+#include "ActiveDTWShapeModel.h"
+#include "ActiveDTWAdapt.h"
+
+class LTKTraceGroup;
+class LTKPreprocessorInterface;
+class LTKShapeSample;
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+class LTKAdapt;
+
+#define SIMILARITY(distance) (1 / (distance + EPS ))
+#define SUPPORTED_MIN_VERSION "3.0.0"
+
+#define CLUSTER 0
+#define SINGLETON 1
+
+#define INVALID_SHAPEID -2
+#define NEW_SHAPEID -2
+
+//#ifdef _INTERNAL
+//#endif
+
+typedef int (*FN_PTR_LOCAL_DISTANCE)(LTKShapeFeaturePtr, LTKShapeFeaturePtr,float&);
+typedef int (*FN_PTR_CREATELTKLIPIPREPROCESSOR)(const LTKControlInfo& , LTKPreprocessorInterface** );
+typedef int (*FN_PTR_DELETELTKLIPIPREPROCESSOR)(LTKPreprocessorInterface* );
+
+typedef vector<LTKShapeFeaturePtr> shapeFeature;
+typedef vector<shapeFeature> shapeMatrix;
+
+
+/**
+* @ingroup ActiveDTWShapeRecognizer.h
+* @brief The Header file for the ActiveDTWShapeRecognizer
+* @class ActiveDTWShapeRecognizer
+*<p> <p>
+*/
+
+class ActiveDTWShapeRecognizer: public LTKShapeRecognizer
+{
+
+public:
+ //#ifdef _INTERNAL
+ friend class LTKAdapt;
+ int adapt(int shapeID );
+ int adapt(const LTKTraceGroup& sampleTraceGroup, int shapeID );
+
+ /**
+ * This function does the recognition function required for training phase (called from trainLVQ)
+ * The input parameter are the incharacter, which is compared with the existing
+ * set of prototypes and then the matched code vector and along with its index (and also the shape id) is returned
+ * @param incharacter is the character which we are trying to recognise.
+ * @param returnshapeID is the value of the matched character which is returned, codeCharacter is the matched prototype (code vector) vector, and codeVecIndex is the matched prototype (code vector) index
+ */
+ int trainRecognize(LTKShapeSample& inShapeSample, LTKShapeSample& bestShapeSample, int& codeVecIndex);
+
+ int writePrototypeShapesToMDTFile();
+
+ int addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID);
+
+ int deleteClass(int shapeID);
+
+ int readInternalClassifierConfig();
+
+private:
+
+ int deleteAdaptInstance();
+
+
+
+ // #endif
+
+
+private:
+
+ FN_PTR_DELETELTKLIPIPREPROCESSOR m_deleteLTKLipiPreProcessor;
+ //Function pointer for deleteLTKLipiPreProcessor
+
+ // preproc lib handle
+ void *m_libHandler;
+
+ // feature extractor lib handle
+ void *m_libHandlerFE;
+
+ unsigned short m_numShapes;
+ /**< @brief Number of shapes
+ * <p>
+ * It Defines the number of shapes to be recognized
+ *
+ * DEFAULT: 0
+ *
+ * Note: If the project is dynamic, then this numShapes was set to 0
+ * If the project is not dynamic, then the numShapes was read from project configuration file
+ * </p>
+ */
+
+
+ string m_prototypeSelection;
+ /**< @brief The Prototype Selection
+ * <p>
+ * if Prototype Selection = clustering, the training method used was clustering
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_PROTOTYPESELECTION
+ * Possible values are "clustering"
+ * </p>
+ */
+
+ int m_prototypeReductionFactor;
+ /**< @brief The prototype Reduction factor
+ * <p>
+ * if PrototypeReductionFactor = 0 every training sample is cluster on its own
+ * = 100 all training samples are represented by one prototype
+ * = 80 then all samples are represented by 20% of the training samples
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_PROTOTYPEREDUCTIONFACTOR
+ * RANGE: 0 TO 100
+ * </p>
+ */
+
+ int m_numClusters;
+ /**< @brief The number of clusters
+ * <p>
+ * if NumClusters = k, then k clusters are found from the training samples
+ *
+ *
+ *
+ * DEFAULT: There is no default as this and prototype reduction factor are dependent
+ * RANGE:
+ * </p>
+ */
+
+
+ float m_percentEigenEnergy;
+ /**< @brief The percent of Eigen Energy
+ * <p>
+ * if PercentEigenEnergy = 90 then those eigen values contributing to 90% of the Eigen Energy,
+ * and their corresponding eigen vectors are retained
+ *
+ *
+ * DEFAULT: LTKClassifierDefaults::ACTIVEDTW_DEF_PERCENTEIGENENERGY
+ * RANGE: 1-100
+ * </p>
+ */
+
+ int m_eigenSpreadValue;
+ /**< @brief The eigen values spread range
+ * <p>
+ * if EigenSpreadValue = 16 then deformation parameters for computing the optimal deformation,
+ * can lie in the range [-4*Eigen Value,4*Eigen Value]
+ *
+ *
+ * DEFAULT: LTKClassifierDefaults::ACTIVEDTW_DEF_EIGENSPREADVALUE
+ * RANGE: greater than 0
+ * </p>
+ */
+
+ int m_minClusterSize;
+ /**< @brief The minimum cluster size
+ * <p>
+ * It specifies the minimum number of samples required to form a cluster
+ *
+ *
+ * DEFAULT: LTKPreprocDefaults::ADAPT_DEF_MIN_NUMBER_SAMPLES_PER_CLASS
+ * RANGE: >= 2
+ * </p>
+ */
+
+ bool m_useSingleton;
+ /**< @brief Use Singletons
+ * <p>
+ * It specifies if singletons should be considered during the recognition process
+ * If Use Singleton is true, singletons will be considered during the recognition process,
+ * else they will be ignored
+ *
+ * DEFAULT: LTKClassifierDefaults::ACTIVEDTW_DEF_USESINGLETON
+ * RANGE: True or False
+ * </p>
+ */
+
+
+ int m_nearestNeighbors;
+ /**< @brief Nearest Neighbors
+ * <p>
+ *
+ * DEFAULT: LTKClassifierDefaults::NN_DEF_NEARESTNEIGHBORS
+ * </p>
+ */
+
+
+ float m_dtwBanding;
+ /**< @brief DTW Banding
+ * <p>
+ *
+ * DEFAULT: LTKClassifierDefaults::NN_DEF_BANDING
+ * </p>
+ */
+
+ int m_dtwEuclideanFilter;
+ /**< @brief DTW Euclidean Filter
+ * <p>
+ *
+ * DEFAULT: LTKClassifierDefaults::ACTIVEDTW_DEF_DTWEUCLIDEANFILTER
+ * </p>
+ */
+
+ string m_featureExtractorName;
+ /**< @brief The Feature Extractor
+ * <p>
+ *
+ * DEFAULT:
+ *
+ * </p>
+ */
+
+ bool m_projectTypeDynamic;
+ /**< @brief Project Dynamic
+ * <p>
+ * if projectTypeDynamic = true, then the project is dynamic ie, the numShapes can take any number of value
+ * = false, then the project is not dynamic ie, the numShape can take value specified in project.cfg file
+ *
+ * DEFAULT: false
+ * </p>
+ */
+
+ LTKPreprocessorInterface *m_ptrPreproc;
+ /**< @brief Pointer to preprocessor instance
+ * <p>
+ * Instance which is used to call the preprocessing methods before recognition
+ *
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_activedtwCfgFilePath;
+ /**< @brief Full path of ActiveDTW configuration file
+ * <p>
+ * Assigned value in the ActiveDTWShapeRecognizer::initialize function
+ * </p>
+ */
+
+ string m_activedtwMDTFilePath;
+ /**< @brief Full path of Model data file
+ * <p>
+ * Assigned value in the ActiveDTWShapeRecognizer::initialize function
+ * </p>
+ */
+
+ stringStringMap m_headerInfo;
+ /**< @brief Header Information
+ * <p>
+ * </p>
+ */
+
+ LTKShapeRecoUtil m_shapeRecUtil;
+ /**< @brief Pointer to LTKShapeRecoUtil class
+ * <p>
+ * Instance which used to call Shape Recognizer Utility functions
+ *
+ * DEFAULT: NULL
+ */
+
+ string m_lipiRootPath;
+ /**< @brief Path of the Lipi Root
+ * <p>
+ * DEFAULT: LipiEngine::getLipiPath()
+ * </p>
+ */
+
+ string m_lipiLibPath;
+ /**< @brief Path of the Lipi Libraries
+ * <p>
+ * DEFAULT: LipiEngine::getLipiLibPath()
+ * </p>
+ */
+
+ LTKShapeFeatureExtractor *m_ptrFeatureExtractor;
+ /**< @brief Pointer to LTKShapeFeatureExtractor class
+ * <p>
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_preProcSeqn;
+ /**< @brief Preprocessor Sequence
+ * <p>
+ * This string will holds what sequence the preprocessor methods to be executed
+ * </p>
+ */
+
+ LTKCaptureDevice m_captureDevice;
+
+ /** Structure to store information required for recognition and adaptation **/
+ struct NeighborInfo
+ {
+ int typeId;
+ int sampleId;
+ int classId;
+ double distance;
+ };
+ /**< @brief Structure to store information required for recognition and adaptation
+ * <p>
+ * TypeId: Specifies whether it is a singleton (defined by 1) or a cluster (defined by 0)
+ * SampleId: Specifies which singleton or cluster sample. The range of values depend on
+ * the number of clusters or singletons (>= 0)
+ * ClassId: Specifies the class id
+ * Distance: The distance between the test sample and singleton or
+ * the distance between the test sample and optimal deformation (cluster case)
+ * The range of values is >= 0
+ *
+ * DEFAULT: NULL
+ * Range: Depends on Individual fields
+ * </p>
+ */
+
+ /**Vector to store the distances from each class to test sample**/
+ vector <struct NeighborInfo> m_neighborInfoVec;
+ /**< @brief Neighbor Information Vector
+ * <p>
+ * This vector contains the distance information between the test samples and
+ * prototype data. It is a vector of structures NeighborInfo
+ * </p>
+ */
+
+ /** contains all the prototype data from load Model data **/
+ vector<ActiveDTWShapeModel> m_prototypeShapes;
+ /**< @brief Prototype Shapes
+ * <p>
+ * This is a vector of ActiveDTWShapeModels
+ * This populated via the loadModelData function
+ * </p>
+ */
+
+ /** Sorts dtw distances **/
+ static bool sortDist(const NeighborInfo& x, const NeighborInfo& y);
+ /**
+ * This method compares distances
+ *
+ * Semantics
+ *
+ * - Compare distances
+ *
+ * @param NeighborInfo(X)
+ * @param NeighborInfo(Y)
+ *
+ * @return TRUE: if X.distance lesser than Y.distance
+ * FALSE: if X.distance greater than Y.distance
+ * @exception none
+ */
+
+ vector<stringStringPair> m_preprocSequence;
+
+ intIntMap m_shapeIDNumPrototypesMap;
+ /**< @brief Map of shapeID and Number of Samples per shape
+ * <p>
+ *
+ * </p>
+ */
+
+ int m_prototypeSetModifyCount;
+ /**< @brief
+ * <p>
+ * Used to count number of modifications done to m_prototypeShapes.
+ * Write to MDT after m_prototypeModifyCntCFG such modifications or at Exit.
+ * </p>
+ */
+
+ int m_MDTUpdateFreq;
+ /**< @brief Update MDT after a specified number of modifications to m_prototypeSet
+ * <p>
+ * Specified in ActiveDTW.cfg
+ *
+ * </p>
+ */
+
+ shapeFeature m_cachedShapeFeature;
+ /**< @brief Store shapeFeature of the last inTraceGroup to Recognize
+ * Used during subsequent call to Adapt
+ * <p>
+ *
+ *
+ * </p>
+ */
+
+ float m_rejectThreshold;
+ /**< @brief Threshold on the confidence to reject a test sample
+ * <p>
+ *
+ * </p>
+ */
+
+ bool m_adaptivekNN;
+ /**< @brief Adaptive kNN method to compute confidence
+ * <p>
+ * If m_adaptivekNN = true, the adaptive kNN method is used for confidence computation
+ * false, NN or kNN method is used, based on the value of m_nearestNeighbors
+ * </p>
+ */
+
+ string m_currentVersion;
+
+ string m_MDTFileOpenMode;
+ /**< @brief File modes of the mdt file
+ * <p>
+ * If m_adaptivekNN = ascii, the mdt file is written in ascii mode
+ * binary, the mdt file will be written in binary mode
+ * Default: LTKPreprocDefaults::NN_MDT_OPEN_MODE_ASCII
+ * </p>
+ */
+
+ //dtw obj for computing the dtw distance between features
+ DynamicTimeWarping<LTKShapeFeaturePtr, float> m_dtwObj;
+ /**< @brief Dynamic Time Warping Object
+ * <p>
+ * This object aids in calculating the dtw distance between two LTKShapeFeaturePtrs
+ * and the distance is in float
+ * </p>
+ */
+
+ //store the recognitioresults
+ vector<LTKShapeRecoResult> m_vecRecoResult;
+ /**< @brief Vector of LTKShapeRecoResult
+ * <p>
+ * This vector is used to store the confidence values computed using computeConfidence
+ * </p>
+ */
+
+ //minimum numberOfSamples to form cluster
+
+
+ public:
+
+ /** @name Constructors and Destructor */
+
+ /**
+ * Constructor
+ */
+ ActiveDTWShapeRecognizer(const LTKControlInfo& controlInfo);
+
+ /**
+ * Destructor
+ */
+ ~ActiveDTWShapeRecognizer();
+
+ //@}
+
+ /**
+ * This method initializes the ActiveDTW shape recognizer
+ * <p>
+ * Semantics
+ * - Set the project name in ActiveDTWShapeRecognizer::headerInfo with the parameter passed.<br>
+ * m_headerInfo[PROJNAME] = strProjectName;
+ *
+ * - Initialize ActiveDTWShapeRecognizer::m_activedtwCfgFilePath <br>
+ * m_activedtwCfgFilePath = ActiveDTWShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::ActiveDTW + LTKInc::CONFIGFILEEXT;
+ *
+ * - Initializes ActiveDTWShapeRecognizer::m_activedtwMDTFilePath <br>
+ * m_activedtwMDTFilePath = ActiveDTWShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::ActiveDTW + LTKInc::DATFILEEXT;
+ *
+ * - Initializes ActiveDTWShapeRecognizer::m_projectTypeDynamic with the value returned from LTKShapeRecoUtil::isProjectDynamic
+ *
+ * - Initialize the preprocessor using LTKShapeRecoUtil::initializePreprocessor and assign
+ * default values for
+ * -# Normalised size
+ * -# Threshold size
+ * -# Aspect ratio
+ * -# Dot threshold
+ *
+ * - Initialize the recognizers instance variables with the values given in classifier config file.
+ *
+ * </p>
+ * @param strProjectName : string : Holds the name of the Project
+ * @param strProfileName : string : Holds the name of the Profile
+ *
+ * @return int : LTKInc::SUCCESS if initialization done successfully
+ * errorValues if initialization has some errors
+ *
+ * @exception LTKErrorList::ECONFIG_FILE_OPEN Could not open project.cfg
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES Negative value for number of shapes
+ * @exception LTKErrorList::ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+
+ /**
+ * This method calls the train method of the ActiveDTW classifier.
+ *
+ */
+ int train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType=INK_FILE) ;
+
+ /**
+ * This method loads the Training Data of the ActiveDTW classifier.
+ * @param
+ * @return LTKInc::SUCCESS : if the model data was loaded successfully
+ * @exception
+ */
+ int loadModelData();
+
+ /**
+ * This method unloads all the training data
+ * @param none
+ * @return LTKInc::SUCCESS : if the model data was unloaded successfully
+ * @exception none
+ */
+ int unloadModelData();
+
+ /**
+ * This method sets the device context for the recognition
+ *
+ * @param deviceInfo The parameter to be set
+ * @return
+ * @exception
+ */
+ int setDeviceContext(const LTKCaptureDevice& deviceInfo);
+
+ /**
+ * Populates a vector of LTKShapeRecoResult consisting of top classes with their confidences.
+ *
+ * Semantics
+ *
+ * - Validate the input arguments
+ * - Extract the features from traceGroup
+ * - Compute the optimal deformation vectors for each class
+ * - If the dtwEuclidean filter is on:
+ * --Then for Clusters
+ * -- Calculate the euclidean distances between the test samples and the optimal deformations
+ * Accordingly populate the distFilter vector
+ * --Then for singletons
+ * --Calculate the euclidean distances between the test samples and the singletonVectors
+ * Accordingly populate the distFilter vector
+ * - Compute the dtw distances between the test sample and the optimal deformations and singletonVectors
+ -- If the dtwEuclidean filter is on then calculate the dtw distances only
+ to those deformations and singletonVectors recommended by the dtw euclidean filter
+ * - Populate the distIndexPairVector with distances and shapeID
+ * - Sort the distIndexPairVector based on the distances in ascending order
+ * - Compute the confidences of the classes appearing in distIndexPairVector, call computeConfidence()
+ * - Check if the first element of resultVector has confidence less than m_rejectThreshold, if so,
+ empty the resultVector (reject the sample), log and return.
+ * - If the confThreshold value was specified by the user (not equal to -1),
+ delete the entries from resultVector with confidence values less than confThreshold.
+ * - If the numChoices value was specified by the user (not equal to -1),
+ update the resultVector with top numChoices entries, delete the other values.
+ *
+ * @param traceGroup The co-ordinates of the shape which is to be recognized
+ * @param screenContext Contains information about the input field like whether it is boxed input
+ * or continuous writing
+ * @param subSetOfClasses A subset of the entire class space which is to be used for
+ * recognizing the input shape.
+ * @param confThreshold Classes with confidence below this threshold are not returned,
+ * valid range of confThreshold: (0,1)
+ * @param numOfChoices Number of top choices to be returned in the result structure
+ * @param resultVector The result of recognition
+ *
+ * @return SUCCESS: resultVector populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector);
+
+ /* Overloaded the above function to take vector<LTKShapeFeaturePtr> as
+ * input
+ */
+ int recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVec,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector);
+
+ /**
+ * In case of:
+ * 1. Singleton Vectors: This method converts them to traceGroups
+ * 2. Clusters: This method converts the cluster means to traceGroup
+ * Semantics
+ *
+ * - Check if shapeID is valid, if not return error code
+ * - Check if project is Dynamic, if not return ErrorCode
+ * - Update PrototypeSet
+ * - Update MDTFile
+ *
+ * @param shapeID : int : Holds shapeID
+ * @param numberOfTraceGroups : int : Maximum number of Trace Groups to populate
+ * @param outTraceGroups : vector<LTKTraceGroup> : TraceGroup
+ *
+ * @return SUCCESS: TraceGroup is populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int getTraceGroups(int shapeID, int numberOfTraceGroups, vector<LTKTraceGroup> &outTraceGroups);
+
+
+
+ private:
+ /**
+ * This function is the train method using Clustering prototype selection technique.
+ *
+ *
+ * Semantics
+ *
+ * - Note the start time for time calculations.
+ *
+ * - Create an instance of the feature extractor using ActiveDTWShapeRecognizer::initializeFeatureExtractorInstance() method
+ *
+ * - Call train method depending on the inFileType
+ * - ActiveDTWShapeRecognizer::trainFromListFile() if inFileType = LTKMacros::INK_FILE
+ * - ActiveDTWShapeRecognizer::trainFromFeatureFile() if inFileType = LTKMacros ::FEATURE_FILE
+ *
+ * - Update the headerInfo with algorithm version and name using ActiveDTWShapeRecognizer::updateHeaderWithAlgoInfo() method
+ *
+ * - Calculate the checksum.
+ *
+ * - Note the finish time for time calculations.
+ *
+ *
+ * @param inputFilePath :string : Path of trainListFile / featureFile
+ * @param strModelDataHeaderInfoFile : string : Holds the Header information of Model Data File
+ * @param inFileType : string : Possible values ink / featureFile
+ *
+ * @return LTKInc::SUCCESS : if the training done successfully
+ * @return errorCode : if it contains some errors
+ */
+ int trainClustering(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string& trainFileType);
+
+
+ /**
+ * This method do the map between the module name and function names from the cfg file
+ *
+ * Semantics
+ *
+ * - Read the Preprocess Sequence from the nn.cfg
+ *
+ * - Split the sequence into tokens with delimiter LTKMacros::DELEMITER_SEQUENCE using LTKStringUtil::tokenizeString
+ *
+ * - Split each token with delimiter LTKMacrosDELEMITER_FUNC using LTKStringUtil::tokenizeString
+ * to get the Module name and Function name
+ *
+ * - Store the Module name and the Function name into a structure
+ *
+ *
+ * @param none
+ * @return LTKInc::SUCCESS : if functions are successfully mapped,
+ * @return errorCodes : if contains any errors
+ * @exception none
+ */
+ int mapPreprocFunctions();
+
+ /**
+ * This method will assign default values to the members
+ *
+ * Semantics
+ *
+ * - Assign Default values to all the data members
+ *
+ *
+ * @param none
+ *
+ * @return none
+ */
+ void assignDefaultValues();
+
+ /** Reads the ActiveDTW.cfg and initializes the instance variable of the classifier with the user defined
+ * values.
+ *
+ * Semantics
+ *
+ * - Open the activedtw.cfg using LTKConfigFileReader
+ *
+ * - Incase of file open failure (activedtw.cfg), default values of the classifier parameters are used.
+ *
+ * - The valid values of the classifier parameters are cached in to the class data members.
+ * LTKConfigFileReader::getConfigValue is used to get the value fora key defined in the config file
+ *
+ * - Exception is thrown if the user has specified an invalid valid for a parameter
+ *
+ *
+ * @param none
+ * @return SUCCESS : If the Config file read successfully
+ * @return errorCode : If it contains some errors
+ * @exception LTKErrorList::ECONFIG_FILE_RANGE The config file variable is not within the correct range
+ */
+ int readClassifierConfig();
+
+ /**
+ * This function serves as wrapper function to the Dtw distance computation function
+ * (for use by clustering prototype selection)
+ * @param train This is an input parameter and corresponds to the training character.
+ * @param test This is an input parameter and corresponds to the testing character.
+ */
+ int computeDTWDistance(const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outDTWDistance);
+
+ /**
+ * computes the dtw distance between two shape feature vectors
+ **/
+ int computeDTWDistance(const vector<LTKShapeFeaturePtr>& inFirstFeatureVector,
+ const vector<LTKShapeFeaturePtr>& inSecondFeatureVector,
+ float& outDTWDistance);
+ /**
+ * This function serves as wrapper function to the Dtw distance computation function
+ * (for use by recognize function)
+ * @param train This is an input parameter and corresponds to the training character.
+ * @param test This is an input parameter and corresponds to the testing character.
+ */
+
+
+ /**
+ * Computes the euclidean distance between two shape Features
+ **/
+ int computeEuclideanDistance(const shapeFeature& inFirstFeature,
+ const shapeFeature& inSecondFeature,
+ float& outEuclideanDistance);
+ /**
+ * This function is used to compute the Euclidean distance between two shape Features
+ * (for use by recognize when dtwEuclidean filter is on)
+ * @param train This is an input parameter and corresponds to the training character.
+ * @param test This is an input parameter and corresponds to the testing character.
+ */
+
+
+
+
+
+ /**
+ * This method creates a custom feature extractor instance and stores it's address in
+ * ActiveDTWShapeRecognizer::m_ltkFE. The local distance function pointer is also initialized.
+ *
+ * Semantics
+ *
+ *
+ * - Intialize the ActiveDTWShapeRecognizer::m_ptrFeatureExtractor with address of the feature extractor instance created
+ * using LTKShapeFeatureExtractorFactory::createFeatureExtractor
+ *
+ * - Cache the address of LTKShapeFeatureExtractor::getLocalDistance() in an instance variable
+ *
+ * @param none
+ *
+ * @return 0 on LTKInc::SUCCESS and 1 on LTKInc::FAILURE
+ *
+ * @exception none
+ */
+ int initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo);
+
+ /**
+ * This method trains the classifier from the train list file whose path is passed as paramater.
+ *
+ * Semantics
+ *
+ * - Open the trainListFile for reading.
+ *
+ * - Open the mdt file for writing.
+ *
+ * - Write header information to the mdt file
+ * - ActiveDTWShapeRecognizer::m_numShapes
+ * - ActiveDTWShapeRecognizer::m_traceDimension
+ * - ActiveDTWShapeRecognizer::m_flexibilityIndex
+ *
+ * - Get a valid line from the train list file
+ * - Skip commented lines
+ * - Skip lines where number_of_tokens != 2
+ * - Throw error LTKErrorList::EINITSHAPE_NONZERO, if the first shape in the list file is not zero
+ * - Throw error LTKErrorList::EINVALID_ORDER_LISTFILE if the shapes are not in sequential order
+ *
+ * - For every valid line get the ShapeSample from the ink file using ActiveDTWShapeRecognizer::getShapeSampleFromInkFile
+ * - Read ink from UNIPEN ink file
+ * - Skip if the trace group is empty
+ * - Pre process the trace group read from the ink file
+ * - Extract features
+ *
+ * - Push all the ShapeSamples corresponding to a shape into a vector of ShapeSample ShapeSamplesVec.
+ *
+ * - When all the ShapeSamples corresponding to a Shape have been collected, cluster them using ActiveDTWShapeRecognizer::performClustering
+ *
+ * - performClustering results in vector of clustered ShapeSamples.
+ *
+ * - computeCovarianceMatrix of clusters
+ *
+ * - computeEigenVectorsForLargeDimension for the covariance matrices of the clusters
+ *
+ * - construct shape models using cluster models and singletons
+ *
+ * - Append these clustered vector<ActiveDTWShapeModel> to the mdt file.
+ *
+ *
+ * @param listFilePath : string : Holds the path for train list file
+ * @param trainSet : ShapeSampleVector: Holds the ShapeSample for all shapes, used for LVQ only
+ *
+ * @return none
+ *
+ * @exception LTKErrorList::EFILE_OPEN_ERROR : Error in Opening a file (may be mdt file or list file)
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES : Invalid value for number of shapes
+ * @exception LTKErrorList::EINVALID_ORDER_LISTFILE: Invalid order of shapeId in List file
+ * @exception LTKErrorList::EINITSHAPE_NONZERO : Initial shapeId must not be zero
+ * @exception LTKErrorList::EEMPTY_EIGENVECTORS : Number of eigen vectors must be a positive number
+ * @exception LTKErrorList::EINVALID_NUM_OF_EIGENVECTORS : Number of eigen vector must be a positive number
+ */
+
+ int trainFromListFile(const string& listFilePath);
+
+ /**
+ * This method will get the ShapeSample by giving the ink file path as input
+ *
+ * Semantics
+ *
+ * - Call the LTKShapeRecoUtil::readInkFromFile() method (Utility Method) to read the ink file
+ * By reading this file, an inTraceGroup was generated
+ *
+ * - Preprocess the inTraceGroup and get the preprocessed trace group
+ * LTKTraceGroup preprocessedTraceGroup
+ *
+ * - Extract features from the preprocessed trace group to get the ShapeSamples.
+ *
+ *
+ * @param path : string : The path for Ink file
+ * @param ShapeSample : ShapeSample : The ShapeSample generated after feature extraction
+ *
+ * @return SUCCESS : If the ShapeSample was got successfully
+ * @return FAILURE : Empty traces group detected for current shape
+ *
+ * @exception LTKErrorList::EINKFILE_EMPTY : Ink file is empty
+ * @exception LTKErrorList::EINK_FILE_OPEN : Unable to open unipen ink file
+ * @exception LTKErrorList::EINKFILE_CORRUPTED : Incorrect or corrupted unipen ink file.
+ * @exception LTKErrorList::EEMPTY_TRACE : Number of points in the trace is zero
+ * @exception LTKErrorList::EEMPTY_TRACE_GROUP : Number of traces in the trace group is zero
+ */
+ int getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec);
+
+
+ /**
+ * This method will do Custering for the given ShapeSamples
+ *
+ * Semantics
+ *
+ * - If the ActiveDTWShapeRecognizer::m_prototypeReductionFactor is -1 means Automatic clustering could be done
+ *
+ * - If the ActiveDTWShapeRecognizer::m_prototypeReductionFactor is 0 means No clustering was needed
+ *
+ * - Otherwise clustering is needed based on the value of ActiveDTWShapeRecognizer::m_prototypeReductionFactor
+ *
+ *
+ *
+ * @param ShapeSamplesVec : ShapeSampleVector : Holds all the ShapeSample for a single class
+ * @param resultVector : int2DVector : Vector of indices of samples belonging to a cluster
+ *
+ * @return SUCCESS ; On successfully performing clustering
+ * @return ErrorCode ; On some error
+ * @exception none
+ */
+ int performClustering(const vector<LTKShapeSample>& shapeSamplesVec,
+ int2DVector& outputVector);
+
+ /**
+ * This method computes the covariance matrix and the mean for a given feature matrix
+ *
+ * Semantics
+ *
+ * - Computes the mean of the feature matrix
+ *
+ * - Computes the mean corrected data
+ *
+ * - Computes the covariance matrix
+ *
+ *
+ *
+ * @param featureMatrix : double2DVector : Holds all the features of a cluster
+ * @param covarianceMatrix : double2DVector : covariance matrix of the cluster
+ * @param meanFeature : doubleVector : mean feature of the cluster
+ *
+ * @return SUCCESS ; On successfully computing the covariance matrix
+ * @return ErrorCode ; On some error
+ * @exception LTKErrorList:: EEMPTY_FEATUREMATRIX, Feature matrix is empty
+ */
+ int computeCovarianceMatrix(double2DVector& featureMatrix,
+ double2DVector& covarianceMatrix,doubleVector& meanFeature);
+
+ /**
+ * compute the eigen vectors
+ * for a covariance Matrix
+ * @inparam covarianceMatrix,rank,nrot --> no of rotations
+ * @outparam eigenValueVec, eigenVectorMatrix
+ **/
+ int computeEigenVectors(double2DVector &covarianceMatrix,const int rank,
+ doubleVector &eigenValueVec, double2DVector &eigenVectorMatrix, int& nrot);
+
+
+ /**
+ * This method will Update the Header information for the MDT file
+ *
+ * Semantics
+ *
+ * - Copy the version number to a string
+ *
+ * - Update the version info and algoName to ActiveDTWShapeRecognizer::m_headerInfo, which specifies the
+ * header information for MDT file
+ *
+ *
+ * @param none
+ *
+ * @return none
+
+ * @exception none
+ */
+ void updateHeaderWithAlgoInfo();
+
+ int preprocess (const LTKTraceGroup& inTraceGroup, LTKTraceGroup& outPreprocessedTraceGroup);
+
+
+ /**
+ * This append the shape model data to the mdt file
+ *
+ * Semantics
+ *
+ * - Append cluster models
+ *
+ * - Append singleton vectors
+ *
+ *
+ *
+ * @param shapeModel : ActiveDTWShapeModel : Holds clusters and singletons of a shape
+ * @param mdtFileHandle : ofstream : file handle for the mdt file
+ *
+ * @return SUCCESS ; On successfully appending the data to mdt file
+ * @return ErrorCode:
+ * @exception LTKErrorList:: EINVALID_FILE_HANDLE, unable to open mdt file
+ */
+ int appendShapeModelToMDTFile(const ActiveDTWShapeModel& shapeModel,ofstream& mdtFileHandle);
+
+ /**
+ * find optimal deformation parameters using bound constrained optimization
+ * here any third part library can be called
+ * we will solve the equation
+ * Min f(x)
+ * Subject to: lb <= x <= ub
+ * where lb -- lower bound ub --- upper bound
+ **/
+
+ /**
+ * This solves the optimization problem and finds the deformation parameters
+ * It constructs the optimal deformation, the sample in the cluster closest to the test sample
+ * Semantics
+ *
+ * - Solve the optimization problem
+ * Min f(x)
+ * Subject to: lb <= x <= ub
+ * where lb -- lower bound ub --- upper bound
+ *
+ *
+ *
+ * @param eigenValues : doubleVector : eigen values of a cluster
+ * @param eigenVector : double2DVector : eigen vectorsof a cluster
+ * @param clusterMean : doubleVector : mean of the cluster
+ * @param testSample : doubleVector : test sample
+ * @param deformationParameters : doubleVector : parameters required to construct the optimal deformation
+ *
+ * @return SUCCESS ; On successfully appending the data to mdt file
+ * @return ErrorCode:
+ * @exception LTKErrorList:: EEMPTY_EIGENVALUES, eigen values are empty
+ * @exception LTKErrorList:: EEMPTY_EIGENVECTORS, eigen vectors are empty
+ * @exception LTKErrorList:: EEMPTY_CLUSTERMEAN, cluster mean is empty
+ * @exception LTKErrorList:: ENUM_EIGVALUES_NOTEQUALTO_NUM_EIGVECTORS, number of eigen value is not equal to the number of eigen vectors
+ * @exception LTKErrorList:: EEMPTY_EIGENVECTORS, eigen vectors are empty
+ */
+ int findOptimalDeformation(doubleVector& deformationParameters,doubleVector& eigenValues, double2DVector& eigenVector,
+ doubleVector& clusterMean, doubleVector& testSample);
+
+ static void getDistance(const LTKShapeFeaturePtr& f1,const LTKShapeFeaturePtr& f2, float& distance);
+
+
+ /**
+ * This method computes the confidences of test sample belonging to various classes
+ *
+ * Semantics
+ *
+ * - Compute the confidence based on the values of m_nearestNeighbors and m_adaptiveKNN
+ * - Populate the resultVector
+ * - Sort the resultVector
+ * -
+ *
+ * @param distIndexPairVector : vector<struct NeighborInfo>: Holds the samples, classIDs and distances to the test sample
+ * @param resultVector : vector<LTKShapeRecoResult> : Holds the classIDs and the respective confidences
+ *
+ * @return SUCCESS: resultVector populated
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int computeConfidence();
+
+ /**
+ * The comparison function object of STL's sort() method, overloaded for class LTKShapeRecoResult, used to sort the vector of LTKShapeRecoResult based on the member variable confidence
+ *
+ * Semantics
+ *
+ * - Check if the first object's confidence value is greater than the second object's confidence value
+ * - Return true or false
+ * -
+ *
+ * @param x : LTKShapeRecoResult : First object for comparison
+ * @param y : LTKShapeRecoResult : Second object for comparison
+ *
+ * @return true: If x.confidence > y.confidence
+ * false: If x.confidence <= y.confidence
+ * @exception none
+ */
+ static bool sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y);
+
+ static bool compareMap( const map<int, int>::value_type& lhs, const map<int, int>::value_type& rhs );
+
+ int mapFeatureExtractor();
+
+ int deleteFeatureExtractorInstance();
+ /**
+ * This method extracts shape features from given TraceGroup
+ *
+ * Semantics
+ *
+ * - PreProcess tracegroup
+ * - Extract Features
+ *
+ * @param inTraceGroup : LTKTraceGroup : Holds TraceGroup of sample
+ *
+ * @return SUCCESS: if shapeFeatures is populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int extractFeatVecFromTraceGroup(const LTKTraceGroup& traceGroup,
+ vector<LTKShapeFeaturePtr>& featureVec);
+
+
+ /** This method is used to initialize the PreProcessor
+ *
+ * Semantics
+ *
+ * - Load the preprocessor DLL using LTKLoadDLL().
+ *
+ * - Get the proc address for creating and deleting the preprocessor instance.
+ *
+ * - Create preprocessor instance.
+ *
+ * - Start the logging for the preprocessor module.
+ *
+ * @param preprocDLLPath : string : Holds the Path of the Preprocessor DLL,
+ * @param errorStatus : int : Holds SUCCESS or Error Values, if occurs
+ * @return preprocessor instance
+ *
+ * @exception ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+ int initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance);
+
+ /** This method is used to deletes the PreProcessor instance
+ *
+ * Semantics
+ *
+ * - Call deleteLTKPreprocInst from the preproc.dll.
+ *
+ * - Unload the preprocessor DLL.
+ *
+ * @param ptrPreprocInstance : Holds the pointer to the LTKPreprocessorInterface
+ * @return none
+ * @exception none
+ */
+
+ int deletePreprocessor();
+
+ /** This method is used to Unloads the preprocessor DLL.
+ *
+ * Semantics
+ *
+ * - If m_libHandler != NULL, unload the DLL
+ * LTKUnloadDLL(m_libHandler);
+ * m_libHandler = NULL;
+ *
+ * @param none
+ * @return none
+ * @exception none
+ */
+ int unloadPreprocessorDLL();
+
+ /**< @brief Pointer to LTKOSUtil interface
+ * <p>
+ *
+ * </p>
+ */
+ LTKOSUtil* m_OSUtilPtr;
+
+ int validatePreprocParameters(stringStringMap& headerSequence);
+
+ /**
+ * Computes the eigen values and eigen vectors of the larger covariance matrix using the
+ * a smaller covariance matrix
+ *
+ * Semantics
+ *
+ * - Compute the smaller covariance matrix, using meanCorrectedData(Transpose)*meanCorrectedData(Transpose)
+ *
+ * - Compute the eigen vectors of the smaller covariance matrix
+ *
+ * - Determine the number of eigen vectors, depending on the eigen energy to be retained
+ *
+ * - Compute the eigen vectors of the larger covariance matrix
+ *
+ * - Normalizing the eigen vectors
+ *
+ *
+ *
+ * @param meanCorrectedData : double2DVector : mean corrected data
+ * @param covarianceMatrix : double2DVector : covariance matrix of the corresponding mean corrected data
+ * @param eigenValues : doubleVector : output selected eigen values
+ * @param eigenVector : double2DVectorr : output selected eigen vectors
+ *
+ * @return SUCCESS ; On successfully computing eigen values and eigen vectors
+ * @return ErrorCode:
+ * @exception LTKErrorList:: EEMPTY_MEANCORRECTEDDATA, empty mean corrected data
+ * @exception LTKErrorList:: EEMPTY_COVARIANCEMATRIX, empty covariance matrix
+ */
+ int computeEigenVectorsForLargeDimension(double2DVector& meanCorrectedData,double2DVector& covarianceMatrix,
+ double2DVector& eigenVector,doubleVector& eigenValues);
+
+ /**
+ * This converts the double vector to a feature vector
+ * It constructs the optimal deformation, the sample in the cluster closest to the test sample
+ *
+ *
+ * @param featureVec : doubleVector : input double feature vector
+ * @param shapeFeatureVec : vector<LTkShapeFeaturePtr> : output feature vector
+ *
+ * @return SUCCESS ; On successfully conversion
+ * @return ErrorCode:
+ * @exception LTKErrorList:: EINVALID_INPUT_FORMAT
+ */
+ int convertDoubleToFeatureVector(vector<LTKShapeFeaturePtr>& shapeFeatureVec,doubleVector& featureVec);
+
+
+};
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.cfg b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.cfg
new file mode 100644
index 00000000..142470cf
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.cfg
@@ -0,0 +1,422 @@
+#------------------------------------------------------------------------------
+# activedtw.cfg
+#
+# Configuration file for Active-DTW Classification Method for
+# Lipi Toolkit 4.0.0
+#------------------------------------------------------------------------------
+
+#------------------------------------------------------------------------------
+# The standard format for the configuration entries is the name of the
+# configuration parameter seperated by an equal to sign and then the value of
+# the configuration parameter. For example:
+# ConfigurationEntryName = value
+#
+# Lines starting with a # are commnet lines
+#
+# A cfg entry is strictly a key value pair and leaving the key without the
+# value or specification of a value out of the range is not permitted
+#
+# If a cfg entry is not specified at all, then default values are used by the
+# recognizer
+#------------------------------------------------------------------------------
+
+#-------------------------------
+# PREPROCESSING
+#-------------------------------
+
+#-------------------------------------------------------------------------------
+# ResampTraceDimension
+#
+# Description: The number of target points for resampling. In other words,
+# each character will be resampled to this number of points. In case of
+# multistroke characters, this number of points will be distributed between
+# the strokes in proportion to their lengths in proportion to their initial
+# number of points.
+#
+# Valid values: Any integer > 0
+# Units: Points
+# Default value: 60
+# Typical value: Average number of points per character in the training data set.
+#-------------------------------------------------------------------------------
+ResampTraceDimension = 60
+
+
+
+#-------------------------------------------------------------------------------
+# ResampPointAllocation
+#
+# Description: Method to be used for point allocation among different strokes
+# during resampling. Two schemes have been implemented lengthbased and point
+# based. In lengthbased allocation scheme, the number of points allocated to
+# each stroke is proportional to the length of the stroke. Length of a stroke
+# is calculated as the sum of the distances between each point in the stroke.
+# In the pointbased allocation scheme, the target stroke point allocation is
+# proportional to the number of points in the initial stroke.
+#
+# Valid value: [lengthbased | pointbased]
+# Default value: lengthbased
+#-------------------------------------------------------------------------------
+ResampPointAllocation = lengthbased
+
+
+#-------------------------------------------------------------------------------
+# NormDotSizeThreshold
+#
+# Description: This threshold is used to determine whether a character is a dot.
+# It is expressed in real length terms (inches) and converted internally to
+# points using knowledge of the device�s spatial resolution. If the width
+# and height are both less than this threshold, then all the points are replaced
+# with the center of the of the normalized character, basically to represent it
+# as a dot
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormDotSizeThreshold = 0.01
+
+#-------------------------------------------------------------------------------
+# NormLineWidthThreshold
+#
+# Description: This threshold is used to detect whether the character is a
+# vertical or horizontal line. If only the height is less than this threshold
+# then the character is detected as a horizontal line and if only the width is
+# less than this threshold then the character is detected as a vertical line.
+# Assuming the height is along the y-dimension and width is along the x-
+# dimension, during normalization of a horizontal line only the x-coordinates
+# are scaled and the y-coordinates are translated to the center of the character,
+# with out scaling. Similarly for the vertical line only the y-coordinates are
+# normalized and the x-coordinates are translated to the center with out scaling
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormLineWidthThreshold = 0.01
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatio
+#
+# Description: This parameter is used to indicate whether the aspect ratio
+# has to be preserved during normalization. The aspect ratio is the calculated
+# as maximum of (height/width , width/height). The aspect ratio is preserved only
+# if the calculated aspect ratio is greater than the threshold value specified
+# through NormPreserveAspectRatioThreshold and this configuration variable is
+# set to true. If this configuration variable is set to false the aspect ratio
+# is not preserved during normalization.
+#
+# Valid value: [true | false]
+# Default value: true
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatio = true
+
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatioThreshold
+#
+# Description: Aspect ratio is preserved during normalization if the computed
+# aspect ratio (max(height/width, width/height)) is greater than this threshold
+# and the configuration value NormPreserveAspectRatio is set to true. During
+# aspect ratio preserving normalization, the larger of the two dimensions is
+# normalized to the standard size and the other dimension is normalized
+# proportional to the initial height and width ratio, so that the initial
+# aspect ratio is maintained.
+#
+# Valid values: Any real number >= 1
+# Default value: 3
+# Typical value: >= 1.5
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatioThreshold = 3
+
+#-------------------------------------------------------------------------------
+# NormPreserveRelativeYPosition
+#
+# Description: The relative Y position is the mean of the y-coordinates in the
+# input character. During normalization if this parameter is set to true, each
+# y-coordinate of the character point is translated by the initial y-mean value,
+# so that the mean of the y-coordinates remains the same before and after
+# normalization. This is typically used in the word recognition context where
+# each stroke of the character has to be normalized separately and the relative
+# position of the strokes should be maintained even after normalization.
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+NormPreserveRelativeYPosition = false
+
+#-------------------------------------------------------------------------------
+# SmoothWindowSize
+#
+# Description: The configuration value specifies the length of the moving
+# average filter (size of the window) for smoothing the character image.
+# If this value is set to N, then each point in the input character is replaced
+# by the average of value of this point, (N-1)/2 points on the right and (N-1)/2
+# on the left of this point.
+#
+# Valid value: Any integer > 0
+# Units: Points
+# Typical value: 5
+# Default value: 3
+#-------------------------------------------------------------------------------
+SmoothWindowSize = 3
+
+#-------------------------------------------------------------------------------
+# NNPreprocSequence
+#
+# Description: This variable is used to specify the sequence of preprocessing
+# operations to be carried out on the input character sample before extracting
+# the features. A valid preprocessing sequence can consist of combination of one
+# or more of the functions selected from the valid values set mentioned below.
+# The CommonPreProc prefix is used specify the default preprocessing module of
+# LipiTk. The user can add his own preprocessing functions in other modules and
+# specify them in the preprocessing sequence.
+#
+# Valid values: Any sequence formed from the following set
+# CommonPreProc::normalizeSize;
+# CommonPreProc::removeDuplicatePoints;
+# CommonPreProc::smoothenTraceGroup;
+# CommonPreProc::dehookTraces;
+# CommonPreProc::normalizeOrientation;
+# CommonPreProc::resampleTraceGroup;
+# Default value: {CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+#-------------------------------------------------------------------------------
+PreprocSequence={CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+
+#---------------------------------------
+# TRAINING
+#---------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNTrainPrototypeSelectionMethod
+#
+# Description: This is used to specify the prototype selection method to be used
+# while training the shape recognizer. When set to hier-clustering, the
+# prototypes are selected using hierarchical clustering method.
+#
+# Valid value: [hier-clustering]
+# Default value: hier-clustering
+#-------------------------------------------------------------------------------
+NNTrainPrototypeSelectionMethod=hier-clustering
+
+
+#-------------------------------------------------------------------------------
+# NNTrainPrototypeReductionFactorPerClass
+#
+# Description: This config parameter is used only when the prototype selection
+# is clustering. This config parameter is used to specify the amount of the
+# initial prototypes to be excluded during prototype selection.
+# Set it to automatic if the number of clusters is to be determined
+# automatically. Set it to none if no prototype selection is required. If the
+# value of this parameter is set to a number between 1-100, say 25, then 75%
+# (i.e 100-25) of the initial training data are retained as prototypes.
+# This parameter can be specified only if the NNTrainNumPrototypesPerClass
+# is not specified.
+#
+# Valid value: [automatic | none | any real number from 0-100]
+# Default value: automatic
+#-------------------------------------------------------------------------------
+NNTrainPrototypeReductionFactorPerClass = 25
+
+#-------------------------------------------------------------------------------
+# NNTrainNumPrototypesPerClass
+#
+# Description: This config parameter is used only when the prototype selection
+# is clustering. This is used to specify the number of prototypes to be selected
+# from the training data. This parameter can be specified only if
+# PrototypeReductionFactor is not specified. This config entry is commented as
+# only one of NNTrainPrototypeReductionFactorPerClass or
+# NNTrainNumPrototypesPerClass can be active in a valid cfg file.
+#
+# Valid value: [automatic | none | any integer from 1-N]
+# (N is the number of samples # per class)
+# Default value: automatic
+#-------------------------------------------------------------------------------
+#NNTrainNumPrototypesPerClass=100
+
+# Note: Only one of either PrototypeReductionFactor or NumClusters can be
+# enabled at any particular instance
+
+#-------------------------------------------------------------------------------
+# ActiveDTWRetainPercentEigenEnergy
+#
+# Description: This config parameter is used to specify the amount of Eigen
+# energy to be included to select the number of eigen vectors
+#
+# Valid value: [any integer from 0-100]
+#
+# Default value: 90
+#-------------------------------------------------------------------------------
+ActiveDTWRetainPercentEigenEnergy= 90
+
+#-------------------------------------------------------------------------------
+# ActiveDTWMinClusterSize
+#
+# Description: This config parameter is used to specify the minimum number
+# of samples required to form a cluster
+#
+# Valid value: [any postive integer > 1]
+#
+# Default value: 2
+#-------------------------------------------------------------------------------
+ActiveDTWMinClusterSize = 2
+
+#-----------------------------------------
+# FEATURE EXTRACTION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# FeatureExtractor
+#
+# Description: The configuration value is used to specify the feature extraction
+# module to be used for feature extraction. The point float feature extraction
+# module extracts the x,y,cosine and sine angle features at every point of the
+# character.
+#
+# Valid value: [PointFloatShapeFeatureExtractor]
+# Default value: PointFloatShapeFeatureExtractor
+#-------------------------------------------------------------------------------
+FeatureExtractor=PointFloatShapeFeatureExtractor
+
+#-----------------------------------------
+# RECOGNITION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNRecoDTWEuFilterOutputSize
+#
+# Description: This config parameter is used to set the proportion of nearest
+# cluster or singleton vectors from a class (filtered based on euclidean distance)
+# to be considered for calculating deformations or dtw distance. Set to 100 if
+# all clusters or singletons are to be considered for calculating dtw distance.
+# This is mainly used to increase the speed of recognition.
+#
+# Valid value: [all | any number from 1-100]
+# Default Value: all
+#-------------------------------------------------------------------------------
+NNRecoDTWEuFilterOutputSize = 30
+
+#-------------------------------------------------------------------------------
+# ActiveDTWEigenSpreadValue
+#
+# Description: This value is used to configure the range of values the
+# bound constraint optimization algorithm will take to calculate the
+# optimal deformation sample
+# Valid value: [greater than 0| default = 16]
+#-------------------------------------------------------------------------------
+ActiveDTWEigenSpreadValue = 16
+
+#-------------------------------------------------------------------------------
+# ActiveDTWUseSingleton
+#
+# Description: This value is used to configure whether singleton vectors
+# from classes will be taken into consideration during the recognition
+# process
+# Valid value: [true | false]
+# Default Value: true
+#-------------------------------------------------------------------------------
+ActiveDTWUseSingleton = true
+
+#-------------------------------------------------------------------------------
+# NNRecoRejectThreshold
+#
+# Description: Threshold to reject the test sample. If the confidence obtained
+# for the recognition of test sample is less than this threshold then the test
+# sample is rejected.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.001
+#-------------------------------------------------------------------------------
+NNRecoRejectThreshold = 0.001
+
+#-------------------------------------------------------------------------------
+# NNRecoNumNearestNeighbors
+#
+# Description: Number of nearest neighbors to be considered during recognition
+# and computation of confidence. If the value is set to 1, nearest neighbor
+# classifier is used, otherwise k-nearest neighbor or Adaptive k-nearest
+# neighbor classifiers are used. By default, nearest neighbor classifier is used.
+#
+# Valid value: Any integer >= 1
+# Default value: 1
+#-------------------------------------------------------------------------------
+NNRecoNumNearestNeighbors = 1
+
+#-------------------------------------------------------------------------------
+# NNRecoUseAdaptiveKNN
+#
+# Description: This parameter is used to specify whether Adaptive k-nearest
+# neighbor recognizer (A-kNN) is to be used. If set to true, A-kNN recognizer is
+# used, otherwise kNN recognizer is used. The A-kNN recognizer automatically
+# determines the number of nearest neighbors to be considered for recognition in
+# each class. If NNRecoNumNearestNeighbors is set to 1, this parameter is
+# automatically set to false and the manually set value will not be considered.
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+NNRecoUseAdaptiveKNN = false
+
+#--------------------------------------------
+# ADAPTATION
+#--------------------------------------------
+
+#-------------------------------------------------------------------------------
+# ActiveDTWMaxClusterSize
+#
+# Description: This config parameter is used to specify the maximum number
+# of samples a cluster is permitted to have
+#
+# Valid value: [any postive integer > 1 And Greater than ActiveDTWMinClusterSize]
+#
+# Default value: 2
+#-------------------------------------------------------------------------------
+ActiveDTWMaxClusterSize = 30
+
+#--------------------------------------------
+# COMMON FOR TRAINING AND RECOGNITION
+#--------------------------------------------
+
+
+#-------------------------------------------------------------------------------
+# NNDTWBandingRadius
+#
+# Description: This configuration parameter specifies the banding radius
+# to be used for DTW computation. This is used to speed up the computation
+# process. If this value is zero no banding is done. The value is specified as
+# fraction of ResampTraceDimension to be used while computing the DTW
+# distance.
+#
+# Valid values: Any real number > 0 and <= 1
+# Default Value: 0.33
+#-------------------------------------------------------------------------------
+NNDTWBandingRadius=0.33
+
+#-------------------------------------------------------------------------------
+#ActiveDTWMDTFileUpdateFreq
+#
+# Description: This configuration parameter specifies the number of iterations after
+# which MDT file is to be updated.
+# Every call to addClass or deleteClass will add/delete the given class. These
+# in-memory changes will be reflected in nn.mdt only after the specified
+# number of such iterations and on application exit.
+#
+# Valid values: Any integer > 0
+# Default value: 5
+# Typical value: 5
+#-------------------------------------------------------------------------------
+ActiveDTWMDTFileUpdateFreq = 100
+
+#-------------------------------------------------------------------------------
+# NNMDTFileOpenMode
+#
+# Description: This configuration parameter specifies the mode for
+# opening the mdt file.
+#
+# Valid values: ascii, binary
+# Default Value: ascii
+#-------------------------------------------------------------------------------
+
+NNMDTFileOpenMode=ascii
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.pro
new file mode 100644
index 00000000..255c5512
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/activedtw/activedtw.pro
@@ -0,0 +1,27 @@
+LIPILIBS = shaperecommon ltkcommon ltkutil featureextractorcommon
+include(../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../featureextractor/common \
+ ../common \
+
+HEADERS += \
+ ActiveDTW.h \
+ ActiveDTWAdapt.h \
+ ActiveDTWClusterModel.h \
+ ActiveDTWShapeModel.h \
+ ActiveDTWShapeRecognizer.h \
+
+SOURCES += \
+ ActiveDTW.cpp \
+ ActiveDTWShapeRecognizer.cpp\
+ ActiveDTWClusterModel.cpp \
+ ActiveDTWShapeModel.cpp \
+ ActiveDTWAdapt.cpp \
+
+win32 {
+ DEFINES += ACTIVEDTW_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = ActiveDTW.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoConfig.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoConfig.cpp
new file mode 100644
index 00000000..8ff31c80
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoConfig.cpp
@@ -0,0 +1,538 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-02-08 11:00:11 +0530 (Tue, 08 Feb 2011) $
+ * $Revision: 832 $
+ * $Author: dineshm $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKShapeRecoConfig which holds the configuration information read
+ * from the configuration files
+ *
+ * CONTENTS:
+ * readConfigInfo
+ * getLipiRoot
+ * getShapeSet
+ * getProfile
+ * getShapeRecognizerName
+ * getNumberOfShapes
+ * setLipiRoot
+ * setShapeSet
+ * setProfile
+ * setShapeRecognizerName
+ * setNumShapes
+ *
+ * AUTHOR: Balaji R.
+ *
+ * DATE: December 23, 2004
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKShapeRecoConfig.h"
+#include "LTKErrorsList.h"
+#include "LTKLoggerUtil.h"
+#include "LTKErrors.h"
+#include "LTKShapeRecoConfig.h"
+#include "LTKException.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecoConfig
+* DESCRIPTION : Default Constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecoConfig::LTKShapeRecoConfig()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered default constructor of LTKShapeRecoConfig" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting default constructor of LTKShapeRecoConfig" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecoConfig
+* DESCRIPTION : Constructor initializing the member variables
+* ARGUMENTS : lipiRoot - root directory of the Lipi Tool Kit
+* shapeSet - shape set to be used for training/recognition
+* profile - profile to be used for training/recognition
+* shapeRecognizerName - name of the shape recognizer to be used for training/recognition
+* numShapes - number of shapes in the recognition problem
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+LTKShapeRecoConfig::LTKShapeRecoConfig(const string& lipiRoot, const string& shapeSet,
+ const string& profile, const string& shapeRecognizerName, int numShapes) :
+ m_lipiRoot(lipiRoot), m_shapeSet(shapeSet), m_profile(profile),
+ m_shapeRecognizerName(shapeRecognizerName), m_numShapes(numShapes)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered initialization constructor of LTKShapeRecoConfig" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_lipiRoot = " << m_lipiRoot << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_shapeSet = " << m_shapeSet << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_profile = " << m_profile << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_shapeRecognizerName = " << m_shapeRecognizerName << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_numShapes = " << m_numShapes << endl;
+
+ int errorCode;
+ if(m_numShapes <= 0)
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Invalid value for number of shapes :" << m_numShapes << endl;
+
+ throw LTKException(errorCode);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting initialization constructor of LTKShapeRecoConfig" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : readConfig
+* DESCRIPTION : Reads the configuration files
+* ARGUMENTS : configFile - name of the main configuration file
+* RETURNS : SUCCESS on successful reading of the configuration file
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+int LTKShapeRecoConfig::readConfigInfo(const string& configFile)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::readConfig" << endl;
+
+ string shapeSetCfg; // shape set configuration file
+
+ string profileCfg; // profile configuration file
+
+ LTKConfigFileReader* mainProperties; // main config file name value pairs
+
+ LTKConfigFileReader* shapesetProperties; // shapeset config name value pairs
+
+ LTKConfigFileReader* profileProperties; // profile config name value pairs
+
+ // reading the main configuration file
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Main configuration file is " << configFile << endl;
+
+ mainProperties = new LTKConfigFileReader(configFile);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO) <<
+ "Main configuration read" << endl;
+
+ // setting config information
+
+ mainProperties->getConfigValue("shapeset", m_shapeSet);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "shapeSet = " << m_shapeSet << endl;
+
+ mainProperties->getConfigValue("profile", m_profile);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "profile = " << m_profile << endl;
+
+ // composing the shape set configuration file name
+
+ shapeSetCfg = m_lipiRoot + SEPARATOR + m_shapeSet + SEPARATOR + SHAPESETFILE;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Shapeset configuration file is " << shapeSetCfg << endl;
+
+ // reading the shape set configuration file
+
+ shapesetProperties = new LTKConfigFileReader(shapeSetCfg);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO) <<
+ "Shapeset configuration read" << endl;
+
+ // setting config information
+ string numShapesStr;
+ shapesetProperties->getConfigValue(PROJECT_CFG_ATTR_NUMSHAPES_STR, numShapesStr);
+ m_numShapes = atoi(numShapesStr.c_str());
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_numShapes = " << m_numShapes << endl;
+
+ if(m_numShapes <= 0)
+ {
+ delete mainProperties;
+ delete shapesetProperties;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Invalid value for number of shapes : " << m_numShapes << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_SHAPES); // Error while reading project.cfg
+
+ //throw LTKException("numShapes cannot be less than or equal to zero");
+ }
+
+ // composing the proile configuration file name
+
+ profileCfg = m_lipiRoot + SEPARATOR + m_shapeSet + SEPARATOR + m_profile + SEPARATOR + PROFILEFILE;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Profile configuration file is " << profileCfg << endl;
+
+ // reading the profile configuration file
+
+ profileProperties = new LTKConfigFileReader(profileCfg);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO) << "Profile configuration read" << endl;
+
+ // setting config information
+
+ profileProperties->getConfigValue(SHAPE_RECOGNIZER_STRING, m_shapeRecognizerName);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_shapeRecognizerName = " << m_shapeRecognizerName << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting LTKShapeRecoConfig::readConfig" << endl;
+
+ delete mainProperties;
+ delete shapesetProperties;
+ delete profileProperties;
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getLipiRoot
+* DESCRIPTION : returns the root directory of the lipi tool kit
+* ARGUMENTS :
+* RETURNS : root directory of the lipi tool kit
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+const string& LTKShapeRecoConfig::getLipiRoot()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::getLipiRoot" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::getLipiRoot with return value " <<
+ m_lipiRoot << endl;
+
+ return m_lipiRoot;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getShapeSet
+* DESCRIPTION : returns the shape set to be used for training/recognition
+* ARGUMENTS :
+* RETURNS : shape set to be used for training/recognition
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+const string& LTKShapeRecoConfig::getShapeSet()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::getShapeSet" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::getShapeSet with return value " <<
+ m_shapeSet << endl;
+
+ return m_shapeSet;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getProfile
+* DESCRIPTION : returns the profile to be used for training/recognition
+* ARGUMENTS :
+* RETURNS : profile to be used for training/recognition
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+const string& LTKShapeRecoConfig::getProfile()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::getProfile" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::getProfile with return value " <<
+ m_profile << endl;
+
+ return m_profile;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getShapeRecognizerName
+* DESCRIPTION : returns the name of the shape recognizer being used
+* ARGUMENTS :
+* RETURNS : name of the shape recognizer being used
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+const string& LTKShapeRecoConfig::getShapeRecognizerName()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::getShapeRecognizerName" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::getShapeRecognizerName with return value " <<
+ m_shapeRecognizerName << endl;
+
+ return m_shapeRecognizerName;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getNumShapes
+* DESCRIPTION : returns the number of shapes in the recognition problem
+* ARGUMENTS :
+* RETURNS : number of shapes in the recognition problem
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+int LTKShapeRecoConfig::getNumShapes()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::getNumShapes" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::getNumShapes with return value " << m_numShapes << endl;
+
+ return m_numShapes;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setLipiRoot
+* DESCRIPTION : sets the root directory of the lipi tool kit
+* ARGUMENTS : lipiRootStr - root directory of the lipi tool kit
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+int LTKShapeRecoConfig::setLipiRoot(const string& lipiRootStr)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::setLipiRoot" << endl;
+
+ this->m_lipiRoot = lipiRootStr;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_lipiRoot = " << m_lipiRoot << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::setLipiRoot" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setShapeSet
+* DESCRIPTION : sets the shape set to be used for training/recognition
+* ARGUMENTS : shapeSetStr - shape set to be used for training/recognition
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKShapeRecoConfig::setShapeSet(const string& shapeSetStr)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::setShapeSet" << endl;
+
+ this->m_shapeSet = shapeSetStr;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_shapeSet = " << m_shapeSet << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::setShapeSet" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setProfile
+* DESCRIPTION : sets the profile to be used for training/recognition
+* ARGUMENTS : profileStr - profile to be used for training/recognition
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKShapeRecoConfig::setProfile(const string& profileStr)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::setProfile" << endl;
+
+ this->m_profile = profileStr;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_profile = " << m_profile << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::setProfile" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setShapeRecognizerName
+* DESCRIPTION : sets the name of the shape recognizer to be used for training/recognition
+* ARGUMENTS : shapeRecognizerName - name of the shape recognizer to be used for training/recognition
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+int LTKShapeRecoConfig::setShapeRecognizerName(const string& shapeRecognizerName)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::setShapeRecognizerName" << endl;
+
+ this->m_shapeRecognizerName = shapeRecognizerName;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_shapeRecognizerName = " << m_shapeRecognizerName << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::setShapeRecognizerName" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setNumShapes
+* DESCRIPTION : sets the number of shapes in the recongition problem
+* ARGUMENTS : numShapes - number of shapes in the recongition problem
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+int LTKShapeRecoConfig::setNumShapes(int numShapes)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered LTKShapeRecoConfig::setNumShapes" << endl;
+
+ this->m_numShapes = numShapes;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_numShapes = " << m_numShapes << endl;
+
+ if(m_numShapes <= 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Invalid value for number of shapes : " << m_numShapes << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_SHAPES)
+ //return ECONFIG_FILE_OPEN_ERR; // Error while reading project.cfg
+
+ //throw LTKException("m_numShapes cannot be less than or equal to zero");
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKShapeRecoConfig::setNumShapes" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : ~LTKShapeRecoConfig
+* DESCRIPTION : destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* ************************************************************************************/
+
+LTKShapeRecoConfig::~LTKShapeRecoConfig()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Entered destructor of LTKShapeRecoConfig" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting destructor of LTKShapeRecoConfig" << endl;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoResult.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoResult.cpp
new file mode 100644
index 00000000..746d45dc
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoResult.cpp
@@ -0,0 +1,223 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-01-11 13:48:17 +0530 (Tue, 11 Jan 2011) $
+ * $Revision: 827 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKShapeRecoResult which holds the recognition results of the
+ * shape recognition engine
+ *
+ * CONTENTS:
+ * getShapeID
+ * getConfidence
+ * setShapeID
+ * setConfidence
+ *
+ * AUTHOR: Balaji R.
+ *
+ * DATE: December 23, 2004
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKInc.h"
+
+#include "LTKMacros.h"
+
+#include "LTKErrors.h"
+
+#include "LTKErrorsList.h"
+
+#include "LTKShapeRecoResult.h"
+
+#include "LTKLoggerUtil.h"
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecoResult
+* DESCRIPTION : Default Constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecoResult::LTKShapeRecoResult()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::LTKShapeRecoResult()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::LTKShapeRecoResult()" <<endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecoResult
+* DESCRIPTION : Constructor initializing the member variables
+* ARGUMENTS : shapeId - shape id of the result
+* confidence - its corresponding confidence value
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecoResult::LTKShapeRecoResult(int shapeId, float confidence) : m_shapeId(shapeId),
+ m_confidence(confidence)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::LTKShapeRecoResult(int, float)" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::LTKShapeRecoResult(int, float)" <<endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getShapeId
+* DESCRIPTION : returns the shape id of the result
+* ARGUMENTS :
+* RETURNS : shape id of the result
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKShapeRecoResult::getShapeId() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::getShapeId()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::getShapeId()" <<endl;
+ return m_shapeId;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getConfidence
+* DESCRIPTION : returns the confidence value of the result
+* ARGUMENTS :
+* RETURNS : confidence value of the result
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKShapeRecoResult::getConfidence() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::getConfidence()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::getConfidence()" <<endl;
+ return m_confidence;
+}
+
+/**********************************************************************************
+ * AUTHOR : Balaji R.
+ * DATE : 23-DEC-2004
+ * NAME : setShapeId
+ * DESCRIPTION : sets the shape id of the result
+ * ARGUMENTS : shapeId - shape id of the result
+ * RETURNS : SUCCESS on successful set function
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ *************************************************************************************/
+
+int LTKShapeRecoResult::setShapeId(int shapeId)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::setShapeId()" <<endl;
+
+ if(shapeId < 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ getErrorMessage(EINVALID_CLASS_ID)<<
+ " LTKShapeRecoResult::setShapeId()" <<endl;
+
+ LTKReturnError(EINVALID_CLASS_ID);
+ }
+ this->m_shapeId = shapeId;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::setShapeId()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Balaji R.
+ * DATE : 23-DEC-2004
+ * NAME : setConfidence
+ * DESCRIPTION : sets the confidence of the result
+ * ARGUMENTS : confidenceVal - confidence of the result
+ * RETURNS : SUCCESS on successful set function
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ *************************************************************************************/
+
+int LTKShapeRecoResult::setConfidence(float confidenceVal)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoResult::setConfidence()" <<endl;
+
+ if( confidenceVal < 0 || confidenceVal > 1)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ getErrorMessage(EINVALID_CONFIDENCE_VALUE)<<
+ " LTKShapeRecoResult::setShapeId()" <<endl;
+
+ LTKReturnError(EINVALID_CONFIDENCE_VALUE);
+ }
+
+ this->m_confidence = confidenceVal;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoResult::setConfidence()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Balaji R.
+ * DATE : 23-DEC-2004
+ * NAME : ~LTKShapeRecoResult
+ * DESCRIPTION : destructor
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ *************************************************************************************/
+
+LTKShapeRecoResult::~LTKShapeRecoResult()
+{
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoUtil.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoUtil.cpp
new file mode 100644
index 00000000..2d944d0c
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecoUtil.cpp
@@ -0,0 +1,486 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+* FILE DESCR: Implementation for LTKShapeRecoUtil
+*
+* CONTENTS:
+* getAbsolutePath
+* isProjectDynamic
+* initializePreprocessor
+* deletePreprocessor
+* unloadPreprocessor
+* readInkFromFile
+* checkEmptyTraces
+* shapeFeatureVectorToFloatVector
+* shapeFeatureVectorToIntVector
+*
+* AUTHOR: Saravanan R.
+*
+* DATE: January 23, 2004
+* CHANGE HISTORY:
+* Author Date Description of change
+************************************************************************/
+
+#ifdef _WIN32
+#include "windows.h"
+#endif
+
+#include "LTKInc.h"
+#include "LTKLoggerUtil.h"
+#include "LTKTrace.h"
+#include "LTKMacros.h"
+#include "LTKErrors.h"
+#include "LTKException.h"
+#include "LTKErrorsList.h"
+#include "LTKInkFileReader.h"
+#include "LTKTraceGroup.h"
+#include "LTKStringUtil.h"
+#include "LTKConfigFileReader.h"
+#include "LTKShapeRecoUtil.h"
+#include "LTKShapeFeatureExtractor.h"
+#include "LTKShapeFeature.h"
+#include "LTKPreprocessorInterface.h"
+
+
+//FN_PTR_DELETE_SHAPE_FTR_PTR LTKShapeRecoUtil::m_deleteShapeFeatureFunc = NULL;
+
+/**********************************************************************************
+* AUTHOR : Saravanan. R
+* DATE : 11-01-2007
+* NAME : LTKShapeRecoUtil
+* DESCRIPTION : Constructor
+* ARGUMENTS : None
+* RETURNS : None
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKShapeRecoUtil::LTKShapeRecoUtil()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entered LTKShapeRecoUtil::LTKShapeRecoUtil()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::LTKShapeRecoUtil()" <<endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 31-01-2007
+ * NAME : LTKShapeRecoUtil
+ * DESCRIPTION : Destructor
+ * ARGUMENTS : None
+ * RETURNS : None
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+LTKShapeRecoUtil::~LTKShapeRecoUtil()
+{
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 11-01-2007
+ * NAME : getAbsolutePath
+ * DESCRIPTION : This method is used to convert the relative path to the absolute path
+ * ARGUMENTS : pathName : string : Holds the path of the training file
+ * lipiRootPath : string : Holds the lipiroot path
+ *
+ * RETURNS : SUCCESS only
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Descriptionh
+ *************************************************************************************/
+int LTKShapeRecoUtil::getAbsolutePath (const string& inputPath,
+ const string& lipiRootPath,
+ string& outPath)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entered LTKShapeRecoUtil::getAbsolutePath()" <<endl;
+
+ outPath = "";
+ vector<string> tokens;
+
+ int returnStatus = SUCCESS;
+
+ //Split the path name into number of tokens based on the delimter
+ returnStatus = LTKStringUtil::tokenizeString(inputPath, "\\/", tokens);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: " <<
+ getErrorMessage(returnStatus) <<
+ " LTKShapeRecoUtil::getAbsolutePath()" <<endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ //The first token must be the $LIPI_ROOT. Otherwise return from the function
+ if (tokens[0] != LIPIROOT)
+ {
+ outPath = inputPath;
+ return SUCCESS;
+ }
+
+ //Store the Environment variable into the tokens
+ tokens[0] = lipiRootPath;
+
+ //Reinitialize the outPath
+ for(int i=0 ; i < tokens.size() ; i++)
+ {
+ outPath += tokens[i] + SEPARATOR;
+ }
+
+ // Erase the last character '\'
+ outPath.erase(outPath.size()-1,1);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::getAbsolutePath()" <<endl;
+
+ return SUCCESS;
+}
+
+
+/***********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 19-01-2007
+ * NAME : isProjectDynamic
+ * DESCRIPTION : This method reads the project.cfg to find whether the project
+ * is dynamic or not
+ * ARGUMENTS : configFilePath : string : Holds the path of the project.cfg
+ * numShapes : unsigned short : Holds the NumShapes value from config file
+ * returnStauts : int : Holds SUCCESS or ErrorValues
+ * strNumShapes : string : Holds the NumShapes value from config file
+ * RETURNS : true : if the project was dynamic
+ * false : if the project was dynamic
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int LTKShapeRecoUtil::isProjectDynamic(const string& configFilePath,
+ unsigned short& numShapes,
+ string& strNumShapes,
+ bool& outIsDynamic )
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoUtil::isProjectDynamic()" <<endl;
+
+ //Specifies the project is dynamic or not
+ outIsDynamic = false;
+
+ string numShapesCfgAttr = "";
+
+ //As numshapes was unsigned short we use this tempNumShapes as integer,
+ //it is used for checking whether it is less than 0
+ int tempNumShapes = 0;
+ LTKConfigFileReader* projectCfgAttrs = NULL;
+ string valueFromCFG = "0";
+
+ int errorCode = SUCCESS;
+
+ try
+ {
+ //Read the config entries
+ projectCfgAttrs = new LTKConfigFileReader(configFilePath);
+ errorCode = projectCfgAttrs->getConfigValue(PROJECT_CFG_ATTR_NUMSHAPES_STR, numShapesCfgAttr);
+
+ //Checking whether the numshapes was dynamic
+ if(errorCode != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ "NumShapes should be set to dynamic or the number of training classes" <<
+ " LTKShapeRecoUtil::isProjectDynamic()" <<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+ else if( LTKSTRCMP(numShapesCfgAttr.c_str(), DYNAMIC) == 0 )
+ {
+ //Numshapes was dynamic
+ outIsDynamic = true;
+ tempNumShapes = 0;
+ }
+ else
+ {
+ bool isPositiveInteger=true;
+
+ valueFromCFG = numShapesCfgAttr;
+
+ for(int charIndex=0 ; charIndex < valueFromCFG.size() ; ++charIndex)
+ {
+ if(!(valueFromCFG[charIndex]>='0' && valueFromCFG[charIndex]<='9'))
+ {
+ isPositiveInteger=false;
+ break;
+ }
+ }
+
+
+
+ if(!isPositiveInteger)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error" <<
+ "NumShapes should be set to dynamic or the number of training classes" <<
+ " LTKShapeRecoUtil::isProjectDynamic()" <<endl;
+
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ else
+ {
+ tempNumShapes = atoi(valueFromCFG.c_str());
+ if(tempNumShapes==0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error" <<
+ "NumShapes should be set to dynamic or the number of training classes" <<
+ " LTKShapeRecoUtil::isProjectDynamic()" <<endl;
+
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ else
+ {
+ //Numshapes was not dynamic
+ outIsDynamic = false;
+ }
+
+ }
+
+ }
+
+ numShapes = tempNumShapes;
+ strNumShapes = valueFromCFG;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "NumShapes in the project is " << valueFromCFG <<endl;
+
+
+ }
+ catch(LTKException e)
+ {
+ delete projectCfgAttrs;
+ throw e;
+ }
+
+ delete projectCfgAttrs;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::isProjectDynamic()" <<endl;
+
+ return SUCCESS;
+}
+
+
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 30-01-2007
+ * NAME : readInkFromFile
+ * DESCRIPTION : This method reads the Ink file and check from empty traces
+ * ARGUMENTS : string : Holds the Path of the unipen ink file
+string : Holds the Path of the lipi root
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int LTKShapeRecoUtil::readInkFromFile(const string& path, const string& lipiRootPath,
+ LTKTraceGroup& inTraceGroup,
+ LTKCaptureDevice& captureDevice,
+ LTKScreenContext& screenContext)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoUtil::readInkFromFile()" <<endl;
+
+ //inTraceGroup.emptyAllTraces();
+
+ string tempPath = path;
+
+ //Check and convert Relative path to Absolute path
+ string outPath = "";
+ getAbsolutePath(tempPath, lipiRootPath, outPath);
+
+ //Print the path name
+ cout << outPath << endl;
+
+ //Read Ink file to inTraceGroup
+ // errorVal = LTKInkFileReader::readUnipenInkFile(tempPath,inTraceGroup,captureDevice,screenContext);
+ int errorCode = LTKInkFileReader::readUnipenInkFile(outPath,inTraceGroup,captureDevice,screenContext);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(errorCode) <<
+ " LTKShapeRecoUtil::readInkFromFile()" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //Check for empty traces in inTraceGroup
+
+ if (inTraceGroup.containsAnyEmptyTrace())
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: " <<
+ "TraceGroup has empty traces" <<
+ " LTKShapeRecoUtil::readInkFromFile()" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::readInkFromFile()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 30-01-2007
+ * NAME : checkEmptyTraces
+ * DESCRIPTION : This method checks for empty traces
+ * ARGUMENTS : inTraceGroup : LTKTraceGroup :
+ * RETURNS : 1 if it contains empty trace group, 0 otherwise
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+/*
+int LTKShapeRecoUtil::checkEmptyTraces(const LTKTraceGroup& inTraceGroup)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoUtil::checkEmptyTraces()" <<endl;
+
+ int returnVal = SUCCESS;
+
+ vector<LTKTrace> tracesVec = inTraceGroup.getAllTraces(); //traces in trace group
+
+ int numTraces = tracesVec.size();
+
+ int numTracePoints = 0;
+
+ LTKTrace trace; // a trace of the trace group
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "numTraces = " << numTraces <<endl;
+
+
+ for(int traceIndex=0; traceIndex < numTraces; ++traceIndex)
+ {
+ trace = tracesVec.at(traceIndex);
+
+ numTracePoints=trace.getNumberOfPoints();
+
+ if(numTracePoints==0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ getError(EEMPTY_TRACE) <<
+ "Exiting LTKShapeRecoUtil::checkEmptyTraces()" <<endl;
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::checkEmptyTraces()" <<endl;
+ return SUCCESS;
+}
+*/
+int LTKShapeRecoUtil::convertHeaderToStringStringMap(const string& header, stringStringMap& headerSequence)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecoUtil::convertHeaderToStringStringMap()" <<endl;
+
+ vector<string> tokens;
+ vector<string> strList;
+
+ int returnStatus = SUCCESS;
+
+ LTKStringUtil::tokenizeString(header, "<>", tokens);
+
+ for(int i=0 ; i < tokens.size(); ++i)
+ {
+ returnStatus = LTKStringUtil::tokenizeString(tokens[i], "=", strList);
+ if(returnStatus != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(returnStatus) <<
+ " LTKShapeRecoUtil::convertHeaderToStringStringMap()" <<endl;
+ LTKReturnError(returnStatus);
+ }
+ if(strList.size() == 2)
+ {
+ headerSequence[strList[0]] = strList[1];
+ }
+ }
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecoUtil::convertHeaderToStringStringMap()" <<endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Saravanan. R
+* DATE : 14-03-2007
+* NAME : shapeFeatureVectorToFloatVector
+* DESCRIPTION : This method converts the ShapeFeatureVector to float vector
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int LTKShapeRecoUtil::shapeFeatureVectorToFloatVector(const vector<LTKShapeFeaturePtr>& shapeFeature,
+ floatVector& outFloatVector)
+{
+ int returnVal = SUCCESS;
+
+ //Iterators for the LTKShapeFeature
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = shapeFeature.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = shapeFeature.end();
+
+
+ vector<float> shapeFeatureFloatvector;
+
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+
+ //Convert the shapefeature to float vector
+ returnVal = (*shapeFeatureIter)->toFloatVector(shapeFeatureFloatvector);
+
+ if ( returnVal != SUCCESS )
+ {
+ break;
+ }
+
+ outFloatVector.insert(outFloatVector.end(),
+ shapeFeatureFloatvector.begin(),
+ shapeFeatureFloatvector.end());
+
+ shapeFeatureFloatvector.clear();
+
+ }
+
+ return returnVal;
+} \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecognizer.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecognizer.cpp
new file mode 100644
index 00000000..bed1ca48
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeRecognizer.cpp
@@ -0,0 +1,250 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-30 15:57:38 +0530 (Wed, 30 Jul 2008) $
+ * $Revision: 576 $
+ * $Author: kuanish $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKShapeRecognizer which would be used as a place holder in LTKShapeRecognizer
+ * for anyone of the implemented shape recognizers like PCAShapeRecognizer which is derived from this class
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Balaji R.
+ *
+ * DATE: December 23, 2004
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKShapeRecognizer.h"
+#include "LTKLoggerUtil.h"
+#include "LTKException.h"
+#include "LTKErrorsList.h"
+#include "LTKErrors.h"
+#include "LTKInc.h"
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecognizer
+* DESCRIPTION : Default Constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecognizer::LTKShapeRecognizer() : m_cancelRecognition(false)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::LTKShapeRecognizer()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::LTKShapeRecognizer()" <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKShapeRecognizer
+* DESCRIPTION : Initializes the member(s) of the class
+* ARGUMENTS : shapeRecognzierName - name of the derived shape recognizer which is being held
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecognizer::LTKShapeRecognizer(const string& shapeRecognzierName) : m_shapeRecognizerName(shapeRecognzierName), m_cancelRecognition(false)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::LTKShapeRecognizer(const string&)" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::LTKShapeRecognizer(const string&)" <<endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 07-JUN-2007
+* NAME : AddCLass
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeRecognizer::addClass(const LTKTraceGroup& sampleTraceGroup,int& shapeID)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::addClass()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(ESHAPE_RECOCLASS_NOIMPLEMENTATION) <<
+ " LTKShapeRecognizer::addClass()" <<endl;
+
+ LTKReturnError(ESHAPE_RECOCLASS_NOIMPLEMENTATION);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::addClass()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR :
+* DATE :
+* NAME : AddSample
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeRecognizer::addSample(const LTKTraceGroup& sampleTraceGroup,int shapeID)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::AddSample()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(ESHAPE_RECOCLASS_NOIMPLEMENTATION) <<
+ " LTKShapeRecognizer::AddSample()" <<endl;
+
+ LTKReturnError(ESHAPE_RECOCLASS_NOIMPLEMENTATION);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::AddSample()" <<endl;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 07-JUN-2007
+* NAME : Delete Class
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeRecognizer::deleteClass(int shapeID)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::deleteClass()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(ESHAPE_RECOCLASS_NOIMPLEMENTATION) <<
+ " LTKShapeRecognizer::deleteClass()" <<endl;
+
+ LTKReturnError(ESHAPE_RECOCLASS_NOIMPLEMENTATION);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::deleteClass()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-AUG-2007
+* NAME : Adapt
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeRecognizer::adapt(int shapeID )
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::adapt()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(ESHAPE_RECOCLASS_NOIMPLEMENTATION) <<
+ " LTKShapeRecognizer::adapt()" <<endl;
+
+ LTKReturnError(ESHAPE_RECOCLASS_NOIMPLEMENTATION);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::adapt()" <<endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-AUG-2007
+* NAME : Adapt
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeRecognizer::adapt(const LTKTraceGroup& sampleTraceGroup, int shapeID)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeRecognizer::adapt(const LTKTraceGroup&, int)" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " <<
+ getErrorMessage(ESHAPE_RECOCLASS_NOIMPLEMENTATION) <<
+ " LTKShapeRecognizer::adapt()" <<endl;
+
+ LTKReturnError(ESHAPE_RECOCLASS_NOIMPLEMENTATION);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeRecognizer::adapt(const LTKTraceGroup&, int)" <<endl;
+
+ return SUCCESS;
+
+}
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : ~LTKShapeRecognizer
+* DESCRIPTION : destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKShapeRecognizer::~LTKShapeRecognizer()
+{
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.cpp
new file mode 100644
index 00000000..4044c86f
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.cpp
@@ -0,0 +1,288 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 20:12:22 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 784 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+#include "LTKShapeSample.h"
+
+#include "LTKShapeFeature.h"
+
+#include "LTKRefCountedPtr.h"
+
+#include "LTKLoggerUtil.h"
+
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : LTKShapeSample
+ * DESCRIPTION : Default Constructor
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+
+LTKShapeSample::LTKShapeSample()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample::LTKShapeSample()" <<endl;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample::LTKShapeSample()" <<endl;
+
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : LTKShapeSample
+ * DESCRIPTION : Copy Constructor
+ * ARGUMENTS : sampleFeatures - LTKShapeSample to be copied
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+
+LTKShapeSample::LTKShapeSample(const LTKShapeSample& sampleFeatures)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample::LTKShapeSample(const LTKShapeSample& )" <<endl;
+
+ m_featureVector = sampleFeatures.m_featureVector;
+ m_classId = sampleFeatures.m_classId;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample::LTKShapeSample(const LTKShapeSample& )" <<endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : operator=
+ * DESCRIPTION : Overloaded assignment operator
+ * ARGUMENTS : sampleFeatures - LTKShapeSample to be assigned to
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+
+LTKShapeSample& LTKShapeSample::operator=(const LTKShapeSample& sampleFeatures)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample::operator=(const LTKShapeSample& )" <<endl;
+
+ if ( this != &sampleFeatures )
+ {
+ m_featureVector = sampleFeatures.m_featureVector;
+ m_classId = sampleFeatures.m_classId;
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample::operator=(const LTKShapeSample& )" <<endl;
+ return *this;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : ~LTKShapeSample
+ * DESCRIPTION : destructor
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+
+LTKShapeSample::~LTKShapeSample()
+{
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : setFeatureVector
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+void LTKShapeSample::setFeatureVector(const vector<LTKShapeFeaturePtr>& inFeatureVec)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:setFeatureVector()" <<endl;
+
+ m_featureVector = inFeatureVec;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:setFeatureVector()" <<endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : setClassID
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+void LTKShapeSample::setClassID(int inClassId)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:setClassID()" <<endl;
+
+ m_classId = inClassId;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:setClassID()" <<endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : getFeatureVector
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+const vector<LTKShapeFeaturePtr>& LTKShapeSample::getFeatureVector() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:getFeatureVector()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:getFeatureVector()" <<endl;
+
+ return m_featureVector;
+}
+
+/**********************************************************************************
+ * AUTHOR : The Qt Company
+ * DATE : 17-Mar-2015
+ * NAME : getFeatureVectorRef
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+vector<LTKShapeFeaturePtr>& LTKShapeSample::getFeatureVectorRef()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:getFeatureVectorRef()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:getFeatureVectorRef()" <<endl;
+
+ return m_featureVector;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 22-Mar-2007
+ * NAME : getClassID
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ************************************************************************************/
+int LTKShapeSample::getClassID() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:getClassID()" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:getClassID()" <<endl;
+
+ return m_classId;
+}
+
+/**************************************************************************
+ * AUTHOR : Nidhi Sharma
+ * DATE : 28-Nov-2007
+ * NAME : clearShapeSampleFeatures
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ****************************************************************************/
+void LTKShapeSample::clearShapeSampleFeatures()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample:clearShapeSampleFeatures()" <<endl;
+
+ m_featureVector.clear();
+ m_classId = -1;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample:clearShapeSampleFeatures()" <<endl;
+}
+/**************************************************************************
+ * AUTHOR : Balaji MNA
+ * DATE : 30-June-2009
+ * NAME : getCountStrokes
+ * DESCRIPTION : get strokes count
+ * ARGUMENTS : NONE
+ * RETURNS : return number of strokes
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description of change
+ * ****************************************************************************/
+int LTKShapeSample::getCountStrokes() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKShapeSample::getCountStrokes()" <<endl;
+
+ int countStrokes = 0;
+
+ vector<LTKShapeFeaturePtr>::const_iterator featureIter = m_featureVector.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator featureEnd = m_featureVector.end();
+
+ for(; featureIter != featureEnd; ++featureIter)
+ {
+ if ((*featureIter)->isPenUp())
+ ++countStrokes;
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKShapeSample::getCountStrokes()" <<endl;
+
+ return countStrokes;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.h
new file mode 100644
index 00000000..02ec1f7f
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/LTKShapeSample.h
@@ -0,0 +1,142 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 16:41:37 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 783 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+#ifndef __LTKSHAPESAMPLE_H
+#define __LTKSHAPESAMPLE_H
+
+#include "LTKInc.h"
+
+#include "LTKShapeFeatureMacros.h"
+
+class LTKShapeFeature;
+
+
+class LTKShapeSample
+{
+ private:
+ vector<LTKShapeFeaturePtr> m_featureVector;
+ int m_classId;
+
+ public:
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+
+ LTKShapeSample();
+
+ /**
+ * Copy Constructor
+ */
+ LTKShapeSample(const LTKShapeSample& shapeFeatures);
+
+ /**
+ * Destructor
+ */
+ ~LTKShapeSample();
+ //@}
+
+ /**
+ * @name Assignment operator
+ */
+ //@{
+
+ /**
+ * Assignment operator
+ * @param shapeFeatures The object to be copied by assignment
+ *
+ * @return LTKShapeSample object
+ */
+
+ LTKShapeSample& operator=(const LTKShapeSample& shapeFeatures);
+ //@}
+
+ /**
+ * @name Getter Functions
+ */
+ //@{
+
+
+ /**
+ * @brief getter method for feature vector
+ * @param none
+ * @return featureVec Type : LTKShapeFeaturePtrtor
+ */
+ const vector<LTKShapeFeaturePtr>& getFeatureVector() const;
+
+
+ /**
+ * @brief getter method for feature vector
+ * @param none
+ * @return featureVec Type : LTKShapeFeaturePtrtor
+ */
+ vector<LTKShapeFeaturePtr>& getFeatureVectorRef();
+
+
+ /**
+ * @brief setter method for class ID
+ * @param none
+ * @return classID Type : int
+ */
+ int getClassID() const;
+ //@}
+
+
+ /**
+ * @name Setter Functions
+ */
+ //@{
+
+ /**
+ * @brief setter method for feature vector
+ * @param featureVec Type : LTKShapeFeaturePtrtor
+ */
+ void setFeatureVector(const vector<LTKShapeFeaturePtr>& inFeatureVec);
+
+
+ /**
+ * @brief setter method for class ID
+ * @param classID Type : int
+ */
+ void setClassID(int inClassId);
+ //@}
+
+ /**
+ * @brief setter method for strokes count
+ * @param none
+ * @return strokes count Type : int
+ */
+ int getCountStrokes() const;
+
+ void clearShapeSampleFeatures();
+
+ //Since pointer is a member variable we should implement constructor, copy-constructor, assignment operator, virtual destructor
+};
+
+#endif
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/common.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/common.pro
new file mode 100644
index 00000000..a8b0756b
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/common/common.pro
@@ -0,0 +1,13 @@
+TARGET = shaperecommon
+include(../../../lipilib.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../featureextractor/common \
+
+SOURCES += \
+ LTKShapeRecoConfig.cpp \
+ LTKShapeRecognizer.cpp \
+ LTKShapeRecoResult.cpp \
+ LTKShapeRecoUtil.cpp \
+ LTKShapeSample.cpp
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeature.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeature.h
new file mode 100644
index 00000000..c233d3c5
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeature.h
@@ -0,0 +1,224 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-01-11 13:48:17 +0530 (Tue, 11 Jan 2011) $
+ * $Revision: 827 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: function prototype for the LTKShapeFeature class
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Nidhi Sharma
+ *
+ * DATE: 07-FEB-2007
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#ifndef __LTKSHAPEFEATURE_H
+#define __LTKSHAPEFEATURE_H
+#include "LTKTypes.h"
+#include "LTKException.h"
+#include "LTKErrorsList.h"
+#include "LTKMacros.h"
+#include "LTKErrors.h"
+#include "LTKShapeFeatureMacros.h"
+
+/**
+ * \defgroup feature_extractor The feature extractor module
+ * <p>
+ * The feature extractor module consists of following directories
+ * - common
+ * - Builds as a static library called <b> featureextractorcommon.lib</b>
+ *
+ * - Various feature extractors viz PointFloatShapeFeatureExtractor
+ * - These feature extractor are built as DLLs
+ *
+ * User can specify the feature extractor name in the classifier config file
+ * and the corresponding extractor is instantiated at run-time.
+ *
+ * </p>
+ */
+
+/** @ingroup feature_extractor
+* @brief An abstract class that defines the interface for a class representing a feature.
+* @class LTKShapeFeature
+* The LTKShapeFeature is the abstract base class. Any class representing a shape feature
+* is derived from the LTKShapeFeature class.
+*/
+class LTKShapeFeature
+{
+public:
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+
+ LTKShapeFeature(){};
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~LTKShapeFeature()
+ {
+ };
+ //@}
+
+ /** @Purely cirtual functions */
+ //@{
+
+ /**
+ * <b>Responsibility</b><br>
+ * This function initializes the instance of type LTKShapeFeature using the initialization string
+ * passed as parameter.
+ *
+ * @param initString : string& : reference to the initialization string.
+ */
+
+ virtual int initialize(const string& initString)=0;
+
+ virtual int initialize(const floatVector& initFloatVector)=0;
+
+ virtual int initialize(floatVector::const_pointer initFloatData, size_t dataSize) { (void)initFloatData; (void)dataSize; return SUCCESS; }
+
+ /**
+ * <b>Responsibility</b><br>
+ * This function returns the character (char*) representation for the instance of type LTKShapeFeature.
+ *
+ * @param p1 : char* : Pointer to the character array.
+ */
+
+ virtual void toString(string& strFeat) const =0;
+
+ /**
+ * <b>Responsibility</b><br>
+ * Creates a new instance of type LTKShapeFeature and initializes it with the calling instance.
+ *
+ * @param none.
+ *
+ * @return LTKShapeFeature* Pointer to the LTKShapeFeature instance
+ */
+
+ virtual LTKShapeFeaturePtr clone() const =0;
+
+ /**
+ * <b>Responsibility</b><br>
+ * Returns the distance between two instances of LTKShapeFeature.
+ *
+ * @param shapeFeaturePtr : LTKShapeFeature* : Pointer to LTKShapeFeature
+ *
+ * @return distance (float) Distance between two instances of LTKShapeFeature class.
+ */
+
+ virtual void getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const = 0;
+
+ //@}
+
+ /**
+ * <b>Responsibility</b><br>
+ * Returns the representation of LTKShapeFeature instance as a vetor of floats.
+ *
+ * @param floatVec : vector<float>& : Reference to the vector of floats.
+ *
+ * @return FAILURE If no implementation is provided by the derived class
+ */
+ virtual int toFloatVector(vector<float>& floatVec) { return FAILURE; }
+
+ /**
+ * <b>Responsibility</b><br>
+ * Returns the representation of LTKShapeFeature instance as a vetor of integers.
+ *
+ *
+ * @param intVec : vector<float>& : Reference to the vector of integers.
+ *
+ * @return FAILURE If no implementation is provided by the derived class
+ */
+ virtual int toIntVector(vector<int>& intVec) { return FAILURE; }
+
+ //ADAPTATION REQUIREMENTS
+
+ /**
+ * <b>Responsibility</b><br>
+ * Adds two instances of type LTKShapeFeature.
+ *
+ * @param secondFeature : LTKShapeFeature* : Pointer to LTKShapeFeature
+ *
+ * @return LTKShapeFeature* : The pointer to LTKShapeFeature holding the result of adding
+ *
+ * @exception LTKErrorsList::EFTR_RPRCLASS_NOIMPLEMENTATION If no implementation is provided by the derived class
+ */
+
+ virtual int addFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const
+ {
+ LTKReturnError(EFTR_RPRCLASS_NOIMPLEMENTATION);
+ }
+
+ /**
+ * <b>Responsibility</b><br>
+ * Subtract two instances of LTKShapeFeature.
+ *
+ *
+ * @param secondFeature : LTKShapeFeature* : Pointer to LTKShapeFeature
+ *
+ * @return LTKShapeFeature* : The pointer to LTKShapeFeature holding the result of subtraction
+ *
+ * @exception LTKErrorsList::EFTR_RPRCLASS_NOIMPLEMENTATION If no implementation is provided by the derived class
+ */
+
+ virtual int subtractFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const
+ {
+ LTKReturnError(EFTR_RPRCLASS_NOIMPLEMENTATION);
+ }
+
+ /**
+ * <b>Responsibility</b><br>
+ * Scales the instance of LTKShapeFeature by the floating point number alpha passed as parameter.
+ *
+ *
+ * @param secondFeature : LTKShapeFeature* : Pointer to LTKShapeFeature
+ *
+ * @return LTKShapeFeature* : The pointer to scaled LTKShapeFeature
+ *
+ * @exception LTKErrorsList::EFTR_RPRCLASS_NOIMPLEMENTATION If no implementation is provided by the derived class
+ */
+
+ virtual int scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const
+ {
+ LTKReturnError(EFTR_RPRCLASS_NOIMPLEMENTATION);
+ }
+
+ virtual int getFeatureDimension() = 0;
+
+ virtual bool isPenUp() const
+ {
+ LTKReturnError(EFTR_RPRCLASS_NOIMPLEMENTATION);
+ }
+
+};
+
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.cpp
new file mode 100644
index 00000000..1b4e9532
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.cpp
@@ -0,0 +1,64 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2007-05-14 13:35:33 +0530 (Mon, 14 May 2007) $
+ * $Revision: 92 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKShapeFeatureExtractor which would be used as
+ * a place holder in LTKShapeFeatureExtractor
+ * for anyone of the implemented feature extractor
+ * which is derived from this class
+ *
+ * CONTENTS:
+ *
+ * AUTHOR:
+ *
+ * DATE:
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKShapeFeatureExtractor.h"
+#include "LTKErrorsList.h"
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 07-Aug-2007
+* NAME : convertToTraceGroup
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKShapeFeatureExtractor::convertFeatVecToTraceGroup(
+ const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup)
+{
+
+ return(EFTR_RPRCLASS_NOIMPLEMENTATION);
+
+} \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.h
new file mode 100644
index 00000000..51ab4b57
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractor.h
@@ -0,0 +1,102 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-10 15:23:21 +0530 (Thu, 10 Jul 2008) $
+ * $Revision: 556 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Function prototype for feature extraction module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Nidhi Sharma
+ *
+ * DATE: 07-FEB-2007
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#ifndef __LTKFEATUREEXTRACTOR_H
+#define __LTKFEATUREEXTRACTOR_H
+
+
+#include "LTKTypes.h"
+#include "LTKShapeFeatureMacros.h"
+
+// Forward class declarations
+class LTKTraceGroup;
+class LTKShapeFeature;
+
+/**
+* @ingroup feature_extractor
+* @brief An abstract class which is extended by all the feature extractors.
+* @class LTKShapeFeatureExtractor
+*
+*/
+class LTKShapeFeatureExtractor
+{
+public:
+ /**
+ * <b>Responsibility</b><br>
+ * Extract features from the input TraceGroup passed a parameter.
+ *
+ * <b>Description</b>
+ * <p>
+ * Every feature representation class has a feature extractor associated with it. The feature extractor
+ * extracts the features from the trace group passed as parameter.
+ * </p>
+ *
+ * <p>This function is based on run-time polymorphism.
+ * The pointer to the derived class instances are stored in a vector of base class (<i>LTKShapeFeature</i>) pointers.
+ * </p>
+ *
+ * @return Pointer to the vector of LTKShapeFeature pointers.
+ */
+ virtual int extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec)=0;
+
+ /**
+ * <b>Responsibility</b><br>
+ * Returns the instance of the shape feature class associated with the feature extractor.
+ *
+ * @return Pointer to the shape feature class.
+ *
+ */
+ virtual LTKShapeFeaturePtr getShapeFeatureInstance()=0;
+
+
+ /**
+ * <b>Responsibility</b><br>
+ * Constructs traceGroup based on input LTKShapeFeaturePtr
+ *
+ * @return Pointer to Trace Group.
+ *
+ */
+ virtual int convertFeatVecToTraceGroup(
+ const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup);
+};
+
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.cpp
new file mode 100644
index 00000000..07fa2adc
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.cpp
@@ -0,0 +1,222 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-06-25 16:40:26 +0530 (Thu, 25 Jun 2009) $
+ * $Revision: 778 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+* FILE DESCR: Implementation for LTKFeatureExtractor factory class
+*
+* CONTENTS:
+* createFeatureExtractor
+*
+* AUTHOR: Nidhi Sharma
+*
+* DATE: December 23, 2004
+* CHANGE HISTORY:
+* Author Date Description of LTKShapeFeatureExtractorFactory
+************************************************************************/
+#include "LTKShapeFeatureExtractorFactory.h"
+#include "LTKMacros.h"
+#include "LTKErrorsList.h"
+#include "LTKException.h"
+#include "LTKLoggerUtil.h"
+#include "LTKErrors.h"
+#include "LTKOSUtil.h"
+#include "LTKOSUtilFactory.h"
+
+/*************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 07-FEB-2007
+* NAME : createFeatureExtractor
+* DESCRIPTION : create method of a factory class
+* ARGUMENTS :
+* RETURNS : Pointer to the instance of LTKShapeFeatureExtractor
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of LTKFeatureExtractor
+*****************************************************************************/
+
+LTKShapeFeatureExtractorFactory::LTKShapeFeatureExtractorFactory()
+{
+}
+
+/***********************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 07-FEB-2007
+* NAME : createFeatureExtractor
+* DESCRIPTION : create method of a factory class
+* ARGUMENTS :
+* RETURNS : Pointer to the instance of LTKShapeFeatureExtractor
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of LTKFeatureExtractor
+******************************************************************************/
+int LTKShapeFeatureExtractorFactory::createFeatureExtractor(
+ const string& featureExtractorName,
+ const string& lipiRootPath,
+ const string& lipiLibPath,
+ void** m_libHandlerFE,
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "LTKShapeFeatureExtractorFactory::createFeatureExtractor()" << endl;
+
+ string feName = "";
+
+ int errorCode = mapFeatureExtractor(featureExtractorName, feName);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)
+ << getErrorMessage(errorCode)
+ << "LTKShapeFeatureExtractorFactory::createFeatureExtractor:"
+ << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = getFeatureExtractorInst(lipiRootPath, lipiLibPath, feName, m_libHandlerFE,
+ controlInfo, outFeatureExtractor);
+
+ if ( errorCode != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)
+ << getErrorMessage(errorCode) << ":" << feName
+ << "LTKShapeFeatureExtractorFactory::createFeatureExtractor:"
+ << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "LTKShapeFeatureExtractorFactory::createFeatureExtractor()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 11-Dec-2007
+* NAME : getFeatureExtractorInst
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of LTKFeatureExtractor
+*************************************************************************************/
+int LTKShapeFeatureExtractorFactory::getFeatureExtractorInst(
+ const string& lipiRootPath,
+ const string& lipiLibPath,
+ const string& feName,
+ void** m_libHandlerFE,
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ FN_PTR_CREATE_SHAPE_FEATURE_EXTRACTOR createFeatureExtractorPtr;
+ void *functionHandle = NULL;
+
+ LTKOSUtil* utilPtr = LTKOSUtilFactory::getInstance();
+
+ int returnVal = utilPtr->loadSharedLib(lipiLibPath, feName, m_libHandlerFE);
+
+
+ if(returnVal != SUCCESS)
+ {
+ LTKReturnError(ELOAD_FEATEXT_DLL);
+ }
+
+ returnVal = utilPtr->getFunctionAddress(*m_libHandlerFE,
+ CREATE_SHAPE_FEATURE_EXTRACTOR,
+ &functionHandle);
+
+ if(returnVal != SUCCESS)
+ {
+ utilPtr->unloadSharedLib(m_libHandlerFE);
+ *m_libHandlerFE = NULL;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE_FEATEXT);
+ }
+
+ createFeatureExtractorPtr = (FN_PTR_CREATE_SHAPE_FEATURE_EXTRACTOR)functionHandle;
+
+ int errorCode = createFeatureExtractorPtr(controlInfo, outFeatureExtractor);
+
+ if (errorCode != SUCCESS)
+ {
+ LTKReturnError(errorCode);
+ }
+
+ delete utilPtr;
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Saravanan
+ * DATE : 24-03-2007
+ * NAME : mapFeatureExtractor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int LTKShapeFeatureExtractorFactory::mapFeatureExtractor(const string& featureExtractorName,
+ string& outFEName)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "LTKShapeFeatureExtractorFactory::mapFeatureExtractor()" << endl;
+
+ int returnCode = SUCCESS;
+
+ if(LTKSTRCMP(featureExtractorName.c_str(), NAME_POINT_FLOAT_SHAPE_FEATURE_EXTRACTOR) == 0)
+ {
+ outFEName = POINT_FLOAT;
+ }
+ else if(LTKSTRCMP(featureExtractorName.c_str(), NAME_L7_SHAPE_FEATURE_EXTRACTOR) == 0)
+ {
+ outFEName = L7;
+ }
+ else if(LTKSTRCMP(featureExtractorName.c_str(),NAME_NPEN_SHAPE_FEATURE_EXTRACTOR) == 0)
+ {
+ outFEName = NPEN;
+ }
+ else if(LTKSTRCMP(featureExtractorName.c_str(),NAME_SUBSTROKE_SHAPE_FEATURE_EXTRACTOR) == 0)
+ {
+ outFEName = SUBSTROKE;
+ }
+ else
+ {
+ returnCode = EFTR_EXTR_NOT_EXIST;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "LTKShapeFeatureExtractorFactory::mapFeatureExtractor()" << endl;
+
+ return returnCode;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.h
new file mode 100644
index 00000000..d178d6ef
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/LTKShapeFeatureExtractorFactory.h
@@ -0,0 +1,94 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Function prototype for the Factory class LTKShapeFeatureExtractorFactory
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Nidhi Sharma
+ *
+ * DATE: 07-FEB-2007
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#ifndef __LTKFEATUREEXTRACTORFACTORY_H
+#define __LTKFEATUREEXTRACTORFACTORY_H
+#include "LTKTypes.h"
+
+#ifndef _WIN32
+#include <dlfcn.h>
+#else
+#include <windows.h>
+#endif
+
+class LTKShapeFeatureExtractor;
+
+/**
+* @ingroup feature_extractor
+* @brief A factory class which return a pointer to the feature extractor.
+* @class LTKShapeFeatureExtractorFactory
+*
+*
+* <p>
+* A factory class which return a pointer to the feature extractor depending
+* on the featureExtractorType passed to it
+* </p>
+*/
+typedef int (*FN_PTR_CREATE_SHAPE_FEATURE_EXTRACTOR)
+ (const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+class LTKShapeFeatureExtractorFactory
+{
+
+public:
+
+ LTKShapeFeatureExtractorFactory();
+
+ int createFeatureExtractor(const string& featureExtractorType,
+ const string& lipiRootPath,
+ const string& lipiLibPath,
+ void** m_libHandlerFE,
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+ int getFeatureExtractorInst(const string& lipiRootPath,
+ const string& lipiLibPath,
+ const string& feName,
+ void** m_libHandlerFE,
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+private:
+ int mapFeatureExtractor(const string& featureExtractorName,
+ string& outFECode);
+};
+
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/common.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/common.pro
new file mode 100644
index 00000000..ae6ce1d2
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/common/common.pro
@@ -0,0 +1,9 @@
+TARGET = featureextractorcommon
+include(../../../../lipilib.pri)
+
+INCLUDEPATH += \
+ ../../../../util/lib \
+
+SOURCES += \
+ LTKShapeFeatureExtractorFactory.cpp \
+ LTKShapeFeatureExtractor.cpp
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/featureextractor.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/featureextractor.pro
new file mode 100644
index 00000000..538b9f29
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/featureextractor.pro
@@ -0,0 +1,13 @@
+TEMPLATE = subdirs
+
+SUBDIRS += \
+ common \
+ l7 \
+ npen \
+ pointfloat \
+ substroke
+
+l7.depends = common
+npen.depends = common
+pointfloat.depends = common
+substroke.depends = common
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.cpp
new file mode 100644
index 00000000..16eaaca4
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.cpp
@@ -0,0 +1,673 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR : Implementation of L7ShapeFeature class
+ * AUTHOR : Naveen Sundar G.
+ * DATE : August 30, 2005
+ * CHANGE HISTORY :
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "L7ShapeFeature.h"
+#include "LTKStringUtil.h"
+#include <sstream>
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : L7ShapeFeature
+* DESCRIPTION : Constructor for the L7ShapeFeature class.
+* ARGUMENTS : none
+* RETURNS :
+* NOTES : Initializes the string delimiter used in writing feature values to a file.
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+L7ShapeFeature::L7ShapeFeature():
+m_data_delimiter(",")
+{
+}
+
+/***************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 12-Dec-2007
+* NAME : L7ShapeFeature
+* DESCRIPTION : Parameterized Constructor for the L7ShapeFeature class.
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*****************************************************************************/
+L7ShapeFeature::L7ShapeFeature(float inX, float inY, float inXFirstDerv,
+ float inYFirstDerv, float inXSecondDerv,
+ float inYSecondDerv, float inCurvature,
+ bool inPenUp):
+m_x(inX),
+m_y(inY),
+m_xFirstDerv(inXFirstDerv),
+m_yFirstDerv(inYFirstDerv),
+m_xSecondDerv(inXSecondDerv),
+m_ySecondDerv(inYSecondDerv),
+m_curvature(inCurvature),
+m_penUp(inPenUp),
+m_data_delimiter(",")
+{
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : ~L7ShapeFeature
+* DESCRIPTION : Destructor for the L7ShapeFeature class
+* ARGUMENTS : none
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+L7ShapeFeature::~L7ShapeFeature()
+{
+
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getX
+* DESCRIPTION : Get method for the x co-ordinate value
+* ARGUMENTS : none
+* RETURNS : X co-ordinate of the shape feature
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getX() const
+{
+ return m_x;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getY
+* DESCRIPTION : Get method for the y co-ordinate value
+* ARGUMENTS : none
+* RETURNS : Y co-ordinate of the shape feature
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getY() const
+{
+ return m_y;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getXFirstDerv
+* DESCRIPTION : Get method for the first derivative value along the X axis
+* ARGUMENTS : none
+* RETURNS : First derivative value along the X axis.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getXFirstDerv() const
+{
+ return m_xFirstDerv;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getYFirstDerv
+* DESCRIPTION : Get method for the first derivative value along the Y axis
+* ARGUMENTS : none
+* RETURNS : First derivative value along the Y axis.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getYFirstDerv() const
+{
+ return m_yFirstDerv;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getXSecondDerv
+* DESCRIPTION : Get method for the second derivative value along the X axis.
+* ARGUMENTS : none
+* RETURNS : Second derivative value along the X axis.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getXSecondDerv() const
+{
+ return m_xSecondDerv;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getYSecondDerv
+* DESCRIPTION : Get method for the second derivative value along the Y axis.
+* ARGUMENTS : none
+* RETURNS : Second derivative value along the Y axis.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getYSecondDerv() const
+{
+ return m_ySecondDerv;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getCurvature
+* DESCRIPTION : Get method for the curvature
+* ARGUMENTS : none
+* RETURNS : The curvature value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float L7ShapeFeature::getCurvature() const
+{
+ return m_curvature;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : isPenUp
+* DESCRIPTION : Get method for the penUp
+* ARGUMENTS : none
+* RETURNS : The PenUp value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Balaji MNA 01-July-2009 Rename getPenUp to isPenUp
+*************************************************************************************/
+bool L7ShapeFeature::isPenUp() const
+{
+ return m_penUp;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setX
+* DESCRIPTION : Set method for the X co-ordinate value
+* ARGUMENTS : X co-ordinate value to be set
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setX(float x)
+{
+ m_x = x;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setY
+* DESCRIPTION : Set method for the Y co-ordinate value
+* ARGUMENTS : Y co-ordinate value to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setY(float y)
+{
+ m_y = y;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setXFirstDerv
+* DESCRIPTION : Set method for the first derivative along the X axis
+* ARGUMENTS : The first derivative value along the X axis
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setXFirstDerv(float xFirstDerv)
+{
+ m_xFirstDerv = xFirstDerv;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setYFirstDerv
+* DESCRIPTION : Set method for the first derivative along the Y axis
+* ARGUMENTS : The first derivative value along the Y axis to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setYFirstDerv(float yFirstDerv)
+{
+ m_yFirstDerv = yFirstDerv;
+}/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setXSecondDerv
+* DESCRIPTION : Set method for the second derivative along the X axis
+* ARGUMENTS : The second derivative value along the X axis to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setXSecondDerv(float xSecondDerv)
+{
+ m_xSecondDerv = xSecondDerv;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setYSecondDerv
+* DESCRIPTION : Set method for the second derivative value along the y axis
+* ARGUMENTS : The second derivative value along the Y axis to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setYSecondDerv(float ySecondDerv)
+{
+ m_ySecondDerv = ySecondDerv;
+}/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setCurvature
+* DESCRIPTION : This method sets the curvature
+* ARGUMENTS : The curvature value to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setCurvature(float curvature)
+{
+ m_curvature=curvature;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : setPenUp
+* DESCRIPTION : This method sets the penUp
+* ARGUMENTS : The penUp value to be set
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::setPenUp(bool penUp)
+{
+ m_penUp=penUp;
+
+
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : clone
+* DESCRIPTION : Clone method for an L7ShapeFeature object
+* ARGUMENTS : none
+* RETURNS : A copy of the invoking L7ShapeFeature object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKShapeFeaturePtr L7ShapeFeature::clone() const
+{
+ L7ShapeFeature* l7Inst = new L7ShapeFeature();
+
+ l7Inst->setX(this->getX());
+ l7Inst->setY(this->getY());
+ l7Inst->setXFirstDerv(this->getXFirstDerv());
+ l7Inst->setYFirstDerv(this->getYFirstDerv());
+ l7Inst->setXSecondDerv(this->getXSecondDerv());
+ l7Inst->setYSecondDerv(this->getYSecondDerv());
+ l7Inst->setCurvature(this->getCurvature());
+ l7Inst->setPenUp(this->isPenUp());
+
+ return (LTKShapeFeaturePtr)l7Inst;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getDistance
+* DESCRIPTION : Returns the distance between two L7ShapeFeature objects
+* ARGUMENTS : An L7ShapeFeature object the distance of which is to be found from the invoking L7ShapeFeature object
+* RETURNS : The squared Euclidean distance
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const
+{
+ float xDiff = 0, yDiff = 0;
+ float xFirstDervDiff=0, yFirstDervDiff=0, xSecondDervDiff=0, ySecondDervDiff=0;
+ float curvatureDiff=0;
+
+ L7ShapeFeature *inFeature = (L7ShapeFeature*)(shapeFeaturePtr.operator ->());
+
+ xDiff = m_x - inFeature->getX();
+ yDiff = m_y - inFeature->getY();
+ xFirstDervDiff = m_xFirstDerv - inFeature->getXFirstDerv();
+ xFirstDervDiff = m_yFirstDerv - inFeature->getYFirstDerv();
+ xSecondDervDiff = m_xSecondDerv - inFeature->getXSecondDerv();
+ ySecondDervDiff = m_ySecondDerv - inFeature->getYSecondDerv();
+ curvatureDiff = m_curvature - inFeature->getCurvature();
+
+ outDistance = ( (xDiff * xDiff) + (yDiff * yDiff) );
+ outDistance += ( (xFirstDervDiff * xFirstDervDiff) + (yFirstDervDiff * yFirstDervDiff) );
+ outDistance += ( (xSecondDervDiff * xSecondDervDiff) + (ySecondDervDiff * ySecondDervDiff) );
+ outDistance += ( (curvatureDiff * curvatureDiff));
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : initialize
+* DESCRIPTION : This method initializes an L7ShapeFeature object from a string
+* ARGUMENTS : The string containing the feature values
+* RETURNS : SUCCESS on successful completion
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::initialize(const string& initString)
+{
+ stringVector tokens;
+
+ LTKStringUtil::tokenizeString(initString, m_data_delimiter, tokens);
+
+ //Token size must be eight
+ if(tokens.size() != 8)
+ return FAILURE; //Returning an error
+
+ m_x = LTKStringUtil::convertStringToFloat(tokens[0]);
+ m_y = LTKStringUtil::convertStringToFloat(tokens[1]);
+ m_xFirstDerv = LTKStringUtil::convertStringToFloat(tokens[2]);
+ m_yFirstDerv = LTKStringUtil::convertStringToFloat(tokens[3]);
+ m_xSecondDerv = LTKStringUtil::convertStringToFloat(tokens[4]);
+ m_ySecondDerv = LTKStringUtil::convertStringToFloat(tokens[5]);
+ m_curvature= LTKStringUtil::convertStringToFloat(tokens[6]);
+
+ if(atoi(tokens[7].c_str()) == 1)
+ m_penUp = true;
+ else
+ m_penUp = false;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : toString
+* DESCRIPTION : This method prints the components of the feature object a string.
+* ARGUMENTS : pointer to char
+* RETURNS : The feature object in string format
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeature::toString(string& strFeat) const
+{
+ ostringstream tempString;
+
+ tempString << m_x << m_data_delimiter << m_y << m_data_delimiter <<
+ m_xFirstDerv << m_data_delimiter <<
+ m_yFirstDerv << m_data_delimiter <<
+ m_xSecondDerv << m_data_delimiter <<
+ m_ySecondDerv << m_data_delimiter <<
+ m_curvature << m_data_delimiter <<
+ m_penUp ;
+
+
+ strFeat = tempString.str();
+
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : addFeature
+* DESCRIPTION : This method adds the passed L7ShapeFeature object to the invoking L7ShapeFeature object
+* ARGUMENTS : The feature instance to be added
+* RETURNS : The result feature object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::addFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ L7ShapeFeature* resultFeature = new L7ShapeFeature();
+
+ L7ShapeFeature *inFeature = (L7ShapeFeature*)(secondFeature.operator ->());
+
+ resultFeature->setX(m_x + inFeature->getX());
+ resultFeature->setY(m_y + inFeature->getY());
+ resultFeature->setXFirstDerv(m_xFirstDerv + inFeature->getXFirstDerv());
+ resultFeature->setYFirstDerv(m_yFirstDerv + inFeature->getYFirstDerv());
+ resultFeature->setXSecondDerv(m_xSecondDerv + inFeature->getXSecondDerv());
+ resultFeature->setYSecondDerv(m_ySecondDerv + inFeature->getYSecondDerv());
+ resultFeature->setCurvature(m_curvature + inFeature->getCurvature());
+ resultFeature->setPenUp(m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : subtractFeature
+* DESCRIPTION : This method subtracts the elements of the passed L7ShapeFeature object from the invoking L7ShapeFeature object.
+* ARGUMENTS :
+* RETURNS : The result feature object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::subtractFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ L7ShapeFeature* resultFeature = new L7ShapeFeature();
+
+ L7ShapeFeature *inFeature = (L7ShapeFeature*)(secondFeature.operator ->());
+
+ resultFeature->setX(m_x-inFeature->getX());
+ resultFeature->setY(m_y-inFeature->getY());
+ resultFeature->setXFirstDerv(m_xFirstDerv - inFeature->getXFirstDerv());
+ resultFeature->setYFirstDerv(m_yFirstDerv - inFeature->getYFirstDerv());
+ resultFeature->setXSecondDerv(m_xSecondDerv - inFeature->getXSecondDerv());
+ resultFeature->setYSecondDerv(m_ySecondDerv - inFeature->getYSecondDerv());
+ resultFeature->setCurvature(m_curvature - inFeature->getCurvature());
+ resultFeature->setPenUp(m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : scaleFeature
+* DESCRIPTION : This method mulitplies the elements of the invoking L7ShapeFeature object by alpha.
+* ARGUMENTS : alpha which is the scaling factor
+* RETURNS : The scaled feature object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const
+{
+ L7ShapeFeature* resultFeature = new L7ShapeFeature();
+
+ resultFeature->setX(m_x * alpha);
+ resultFeature->setY(m_y * alpha);
+ resultFeature->setXFirstDerv(m_xFirstDerv * alpha);
+ resultFeature->setYFirstDerv(m_yFirstDerv * alpha);
+ resultFeature->setXSecondDerv(m_xSecondDerv * alpha);
+ resultFeature->setYSecondDerv(m_ySecondDerv * alpha);
+ resultFeature->setCurvature(m_curvature * alpha);
+ resultFeature->setPenUp(m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : toFloatVector
+* DESCRIPTION : This method converts the feature instance to a floatVector.
+* ARGUMENTS : The float vector passed by reference
+* RETURNS : 0 on success.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::toFloatVector(floatVector& floatVec)
+{
+ floatVec.push_back(m_x);
+ floatVec.push_back(m_y);
+ floatVec.push_back(m_xFirstDerv);
+ floatVec.push_back(m_yFirstDerv);
+ floatVec.push_back(m_xSecondDerv);
+ floatVec.push_back(m_ySecondDerv);
+ floatVec.push_back(m_curvature);
+
+ if(m_penUp == true)
+ floatVec.push_back(1.0);
+ else
+ floatVec.push_back(0.0);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : toIntVector
+* DESCRIPTION : This method converts the feature instance to an intVector.
+* ARGUMENTS : The integer vector passed by reference
+* RETURNS : 0 on success.
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeature::toIntVector(intVector& intVec)
+{
+ intVec.push_back(m_x);
+ intVec.push_back(m_y);
+ intVec.push_back(m_xFirstDerv);
+ intVec.push_back(m_yFirstDerv);
+ intVec.push_back(m_xSecondDerv);
+ intVec.push_back(m_ySecondDerv);
+ intVec.push_back(m_curvature);
+ intVec.push_back(m_penUp);
+
+ return SUCCESS;
+}
+
+/***************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 23-Apr-2008
+* NAME : initialize
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Date Description:
+
+*****************************************************************************/
+int L7ShapeFeature::initialize(const floatVector& initFloatVector)
+{
+
+ if (initFloatVector.size() == 0)
+ {
+ return FAILURE;
+ }
+
+ m_x = initFloatVector[0];
+ m_y = initFloatVector[1];
+ m_xFirstDerv = initFloatVector[2];
+ m_yFirstDerv = initFloatVector[3];
+ m_xSecondDerv = initFloatVector[4];
+ m_ySecondDerv = initFloatVector[5];
+ m_curvature = initFloatVector[6];
+
+ if(initFloatVector[7] == 1)
+ {
+ m_penUp = true;
+ }
+ else
+ {
+ m_penUp = false;
+ }
+
+ return SUCCESS;
+}
+
+/***************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 23-Apr-2008
+* NAME : getFeatureDimension
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Date Description:
+
+*****************************************************************************/
+
+int L7ShapeFeature::getFeatureDimension()
+{
+ return 8;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.h
new file mode 100644
index 00000000..6c767112
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeature.h
@@ -0,0 +1,267 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+#include "LTKShapeFeature.h"
+
+
+
+/** @ingroup L7ShapeFeatureExtractor
+* @brief The feature representation class for L7 features
+* This class represents X and Y coordinates, Normalized X and Y First Derivatives, Normalized X and Y Second Derivatives and the Curvature values of a point.
+* @class L7ShapeFeature
+*
+*/
+class L7ShapeFeature : public LTKShapeFeature
+{
+ /** @name private data members */
+ //@{
+
+private:
+ /** @brief X value */
+ float m_x;
+
+ /** @brief Y value */
+ float m_y;
+
+ /** @brief Normalized First Derivative w.r.t X */
+ float m_xFirstDerv;
+
+ /** @brief Normalized First Derivative w.r.t Y */
+ float m_yFirstDerv;
+
+ /** @brief Normalized Second Derivative w.r.t X */
+ float m_xSecondDerv;
+
+ /** @brief Normalized Second Derivative w.r.t Y */
+ float m_ySecondDerv;
+
+ /** @brief Curvature value */
+ float m_curvature;
+
+ /** @brief Pen-up information */
+ bool m_penUp;
+
+ /** @brief Delimiter character */
+ string m_data_delimiter;
+ //@}
+
+public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+ L7ShapeFeature();
+
+ /** parameterized constructor
+ */
+ L7ShapeFeature(float inX, float inY, float inXFirstDerv, float inYFirstDerv,
+ float inXSecondDerv, float inYSecondDerv, float inCurvature,
+ bool inPenUp);
+
+ /**
+ * Default destructor.
+ */
+ ~L7ShapeFeature();
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_x
+ */
+ float getX() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_y
+ */
+ float getY() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_xFirstDerv
+ */
+ float getXFirstDerv() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_yFirstDerv
+ */
+ float getYFirstDerv() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_xSecondDerv
+ */
+ float getXSecondDerv() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_ySecondDerv
+ */
+ float getYSecondDerv() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_curvature
+ */
+ float getCurvature() const;
+
+ /**
+ * Returns the value of the class data member L7ShapeFeature::m_penUp
+ */
+ bool isPenUp() const;
+
+ /**
+ * Sets the value of L7ShapeFeature::m_x
+ */
+ void setX(float x);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_y
+ */
+ void setY(float y);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_xFirstDerv
+ */
+ void setXFirstDerv(float xFirstDerv);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_yFirstDerv
+ */
+
+ void setYFirstDerv(float yFirstDerv);
+ /**
+ * Sets the value of L7ShapeFeature::m_xSecondDerv
+ */
+ void setXSecondDerv(float xSecondDerv);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_ySecondDerv
+ */
+ void setYSecondDerv(float ySecondDerv);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_curvature
+ */
+ void setCurvature(float curvature);
+
+ /**
+ * Sets the value of L7ShapeFeature::m_penUp
+ */
+ void setPenUp(bool penUp);
+
+
+ /**
+ * @brief Initializes an instance of L7ShapeFeature from the string passed as parameter.
+ *
+ * <b>Semantics</b>
+ *
+ * - Tokenize the input string on L7ShapeFeature::m_data_delimiter using StringTokenizer::tokenizeString
+ * - Initialize the data members of the class with the tokens returned.
+ *
+ * @param initString : string& : Reference to the initialization string.
+ *
+ * @return FAILURE : If the initalization string contains more than or less than seven tokens (after tokenizing on L7ShapeFeature::m_data_delimiter)
+ * @return SUCCESS : If initialization done without any errors.
+ *
+ */
+
+ //see interface
+ int initialize(const string& initString);
+
+ int initialize(const floatVector& initFloatVector);
+
+ /**
+ * @brief Gives the string representation of the L7ShapeFeature instance
+ */
+ //see interface
+ void toString(string& strFeat) const;
+
+ /**
+ * This method implements the clone pattern and returns a cloned instance of the invoking L7ShapeFeature object
+ */
+ LTKShapeFeaturePtr clone() const;
+
+
+ /**
+ * @brief Computes the Euclidean Distance between two L7ShapeFeature instances.
+ * Computes the square root of ( (m_x-passed_x)^2 + (m_y-passed_y)^2+ (m_xFirstDerv-passed_x1)^2 +(m_yFirstDerv-passed_y1)^2+(m_xSecondDerv-passed_x2)^2+(m_ySecondDerv-passed_y2)^2+(m_curvature-passed_curvature)^2).
+ * @param f : LTKShapeFeature* : Base class pointer holding a pointer to L7ShapeFeature instance from which the distance to the invoking object is to be computed.
+ *
+ * @return float : Distance between two points in the LocalSeven feature representation
+ *
+ */
+ void getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const;
+
+ /**
+ * @brief Adds two L7ShapeFeature instances.
+ * Computes the sum of the member variables of the passed LTKShapeFeature object and the invoking LTKShapeFeature object. The new member variables are stored in a newly created L7ShapeFeature object. Neither the invoking nor the passed object object are changed.
+ * new_x=m_x+ (*secondFeature).m_x;
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding a pointer to the L7ShapeFeature instance which is to be added to the invoking L7ShapeFeature object.
+ *
+ * @return LTKShapeFeature* : Base class pointer to the L7ShapeFeature instance holding the result of the addition operation.
+ *
+ */
+ int addFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const;
+
+ /**
+ * @brief Subtracts two L7ShapeFeature instances.
+ * Subtracts the member variables of the passed LTKShapeFeature object from the invoking LTKShapeFeature object. The new member variables are stored in a newly created L7ShapeFeature object, which is returned. Neither the invoking nor the passed object object are changed.
+ * new_x=m_x-(*secondFeature).m_x;
+ *
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding a pointer to the L7ShapeFeature instance which is to be subtracted.
+ *
+ * @return LTKShapeFeature* : Base class pointer to the L7ShapeFeature instance holding the result of the subtraction operation.
+ *
+ */
+ int subtractFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const;
+
+ /**
+ * @brief Scales the L7ShapeFeature feature by a scalar (float value).
+ * Mulitplies all the member variables of the invoking L7ShapeFeature object by alpha. The new member variables are stored in a newly created L7ShapeFeature object, which is returned. The invoking LTKShapeFeature object is not changed.
+ * new_x=alpha*m_x
+ *
+ * @param alpha : float: The float value by which all the member variables should be multiplied.
+ * @return LTKShapeFeature* : Base class pointer to the L7ShapeFeature instance holding the result of the scaling operation .
+ *
+ */
+ int scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const;
+
+ /**
+ * Converts the LocalSeven feature instance into a float vector. The elements of the float vector are m_x,m_y,m_xFirstDerv,m_yFirstDerv,m_xSecondDerv,m_ySecondDerv and m_curvature in this order.
+ * @param floatVec: vector<float>&: The float vector which will contain the member values.
+ * @return int : returns SUCCESS or FAILURE
+ *
+ */
+ int toFloatVector(vector<float>& floatVec);
+
+ /**
+ * Converts the LocalSeven feature instance into a integer vector. The elements of the int vector are m_x,m_y,m_xFirstDerv,m_yFirstDerv,m_xSecondDerv,m_ySecondDerv and m_curvature in this order.
+ * @param intVec: vector<int>&: The int vector which will contain the member values.
+ * @return int : returns SUCCESS or FAILURE
+ *
+ */
+ int toIntVector(vector<int>& intVec);
+
+ int getFeatureDimension();
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp
new file mode 100644
index 00000000..19e6a9c1
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp
@@ -0,0 +1,587 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of RunShaperec tool
+ *
+ * CONTENTS:
+ * extractFeatures
+ * getShapeFeatureInstance
+ * clearFeatureVector
+ * computeDerivativeDenominator
+ * computeDerivative
+ *
+ * AUTHOR: Naveen Sundar G.
+ *
+ * DATE: August 30, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+
+#include "L7ShapeFeatureExtractor.h"
+#include "L7ShapeFeature.h"
+#include "LTKTraceGroup.h"
+#include "LTKTrace.h"
+#include "LTKChannel.h"
+#include "LTKTraceFormat.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKLoggerUtil.h"
+
+/******************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : L7ShapeFeatureExtractor
+* DESCRIPTION : parameterized constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*******************************************************************************/
+L7ShapeFeatureExtractor::L7ShapeFeatureExtractor(const LTKControlInfo& controlInfo):
+m_radius(FEATEXTR_L7_DEF_RADIUS)
+{
+ string cfgFilePath = "";
+
+ // Config file
+ if ( ! ((controlInfo.lipiRoot).empty()) &&
+ ! ((controlInfo.projectName).empty()) &&
+ ! ((controlInfo.profileName).empty()) &&
+ ! ((controlInfo.cfgFileName).empty()))
+ {
+ // construct the cfg path using project and profile name
+ cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING +
+ (controlInfo.projectName) + PROFILE_PATH_STRING +
+ (controlInfo.profileName) + SEPARATOR +
+ (controlInfo.cfgFileName) + CONFIGFILEEXT;
+ }
+ else if ( ! ((controlInfo.cfgFilePath).empty() ))
+ {
+ cfgFilePath = controlInfo.cfgFilePath;
+ }
+ else
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+
+ int returnVal = readConfig(cfgFilePath);
+
+ if (returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: L7ShapeFeatureExtractor::L7ShapeFeatureExtractor()" <<endl;
+
+ throw LTKException(returnVal);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "L7ShapeFeatureExtractor::L7ShapeFeatureExtractor()" << endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : readConfig
+* DESCRIPTION : read the config values from cfg file and set member variables
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+
+int L7ShapeFeatureExtractor::readConfig(const string& cfgFilePath)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "L7ShapeFeatureExtractor::readConfig()" << endl;
+
+ LTKConfigFileReader* configurableProperties = NULL;
+ string tempStringVar = "";
+
+ try
+ {
+ configurableProperties = new LTKConfigFileReader(cfgFilePath);
+
+ int errorCode = configurableProperties->getConfigValue(L7RADIUS, tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if (setRadius(atoi((tempStringVar).c_str())) != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ ECONFIG_FILE_RANGE << " : " <<
+ getErrorMessage(ECONFIG_FILE_RANGE) <<
+ " L7ShapeFeatureExtractor::readConfig" <<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+
+ catch(LTKException e)
+ {
+ delete configurableProperties;
+
+ int eCode = e.getErrorCode();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << eCode <<
+ " : " << getErrorMessage(eCode) <<
+ " L7ShapeFeatureExtractor::readConfig" <<endl;
+
+ LTKReturnError(eCode);
+ }
+ delete configurableProperties;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "L7ShapeFeatureExtractor::readConfig()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : setRadius
+* DESCRIPTION : set the radius(the size of window) to compute L7 features
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+int L7ShapeFeatureExtractor::setRadius(int radius)
+{
+ int returnVal = FAILURE;
+
+ if ( radius > 0 )
+ {
+ m_radius = radius;
+ returnVal = SUCCESS;
+ }
+
+ return returnVal;
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 15-Feb-2008
+* NAME : getRadius
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+int L7ShapeFeatureExtractor::getRadius()
+{
+ return m_radius;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : extractFeatures
+* DESCRIPTION : Extracts L7 features from a trace group
+* ARGUMENTS : The trace group from which features have to be extracted
+* RETURNS : vector of L7ShapeFeature objects
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "L7ShapeFeatureExtractor::extractFeatures()" << endl;
+
+ L7ShapeFeature* featurePtr = NULL;
+ float delta;
+ int currentStrokeSize;
+ int numPoints;
+
+ int numberOfTraces = inTraceGroup.getNumTraces();
+
+ if (numberOfTraces == 0 )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error :" <<
+ EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP) <<
+ "L7ShapeFeatureExtractor::extractFeatures()" << endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+
+ LTKTraceVector allTraces = inTraceGroup.getAllTraces();
+ LTKTraceVector::iterator traceIter = allTraces.begin();
+ LTKTraceVector::iterator traceEnd = allTraces.end();
+
+ //the feature vector
+ vector<float> xVec;
+ vector<float> yVec;
+ vector<bool> penUp;
+
+ //concatentating the strokes
+ for (; traceIter != traceEnd ; ++traceIter)
+ {
+ floatVector tempxVec, tempyVec;
+
+ (*traceIter).getChannelValues("X", tempxVec);
+
+ (*traceIter).getChannelValues("Y", tempyVec);
+
+ currentStrokeSize = tempxVec.size();
+
+ if (currentStrokeSize == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error :" <<
+ EEMPTY_TRACE<< " : " << getErrorMessage(EEMPTY_TRACE) <<
+ "L7ShapeFeatureExtractor::extractFeatures()" << endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ for(int point=0;point<currentStrokeSize;point++)
+ {
+ xVec.push_back(tempxVec[point]);
+ yVec.push_back(tempyVec[point]);
+
+ if(point == currentStrokeSize - 1 )
+ {
+ penUp.push_back(true);
+ }
+ else
+ {
+ penUp.push_back(false);
+ }
+ }
+ }
+ //concatentating the strokes
+
+ numPoints=xVec.size();
+
+ vector<float> normfirstderv_x(numPoints); // Array to store the first normalized derivative w.r.t x
+ vector<float> normfirstderv_y(numPoints); // Array to store the first normalized derivative w.r.t y
+ vector<float> normsecondderv_x(numPoints); // Array to store the second normalized derivative w.r.t x
+ vector<float> normsecondderv_y(numPoints); // Array to store the second normalized derivative w.r.t y
+ vector<float> curvature(numPoints); // Array to store the curvature
+
+ computeDerivative(xVec,yVec,normfirstderv_x,normfirstderv_y,m_radius);
+
+ computeDerivative(normfirstderv_x,normfirstderv_y,normsecondderv_x,normsecondderv_y,m_radius);
+
+ for(int i=0; i<numPoints; ++i)
+ {
+ //computing the curvature
+ delta= sqrt(pow(pow(normfirstderv_x[i],2)+pow(normfirstderv_y[i],2),3));
+ curvature[i]= ((normfirstderv_x[i]*normsecondderv_y[i]) - (normsecondderv_x[i]*normfirstderv_y[i]))/(delta+EPS);
+
+ featurePtr = new L7ShapeFeature(xVec[i], yVec[i],
+ normfirstderv_x[i], normfirstderv_y[i],
+ normsecondderv_x[i], normsecondderv_y[i],
+ curvature[i], penUp[i]);
+ //populating the feature vector
+ outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
+ featurePtr = NULL;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "L7ShapeFeatureExtractor::extractFeatures()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : getShapeFeatureInstance
+* DESCRIPTION : Returns an L7ShapeFeature instance
+* ARGUMENTS :
+* RETURNS : An L7ShapeFeature instance
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKShapeFeaturePtr L7ShapeFeatureExtractor::getShapeFeatureInstance()
+{
+ LTKShapeFeaturePtr tempPtr(new L7ShapeFeature);
+ return tempPtr;
+}
+
+
+/******************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : Sept-10-2007
+* NAME : convertFeatVecToTraceGroup
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int L7ShapeFeatureExtractor::convertFeatVecToTraceGroup(
+ const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "L7ShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+
+ vector<LTKChannel> channels; // channels of a trace
+
+ LTKChannel xChannel("X", DT_INT, true); // x-coordinate channel of the trace
+ LTKChannel yChannel("Y", DT_INT, true); // y-coordinate channel of the trace
+
+ //initializing the channels of the trace
+ channels.push_back(xChannel);
+ channels.push_back(yChannel);
+
+ // composing the trace format object
+ LTKTraceFormat traceFormat(channels);
+
+ vector<float> point; // a point of a trace
+
+ LTKTrace trace(traceFormat);
+
+ for(int count=0;count<(int)shapeFeature.size();count++)
+ {
+ float Xpoint, Ypoint;
+ bool penUp;
+
+ L7ShapeFeature* ptr = (L7ShapeFeature*)(shapeFeature[count].operator ->());
+ Xpoint = ptr->getX();
+ Ypoint = ptr->getY();
+ penUp = ptr->isPenUp();
+
+
+
+ point.push_back(Xpoint);
+ point.push_back(Ypoint);
+
+ trace.addPoint(point);
+ point.clear();
+
+
+ if(penUp == true) // end of a trace, clearing the trace now
+ {
+ outTraceGroup.addTrace(trace);
+ trace.emptyTrace();
+ LTKTrace tempTrace(traceFormat);
+ trace = tempTrace;
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "L7ShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : computeDerivativeDenominator
+* DESCRIPTION : Computes the denominator to be used in the derivative computation
+* ARGUMENTS : The index used in derivative computation
+* RETURNS : The denominator
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int L7ShapeFeatureExtractor::computeDerivativeDenominator(int index)
+{
+ int denominator=0;
+
+ for (int i=1;i<=index;i++)
+ {
+
+ denominator=denominator+i*i;
+ }
+ return 2*denominator;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 10-AUGUST-2007
+* NAME : computeDerivative
+* DESCRIPTION : Computes the derivative
+* ARGUMENTS : The input and output vectors. The output vectors are the derivatives of the input vectors
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void L7ShapeFeatureExtractor::computeDerivative(const vector<float>& xVec,
+ const vector<float>& yVec,
+ vector<float>& dx,
+ vector<float>& dy,
+ int index)
+{
+ int size = xVec.size();
+ int denominator = computeDerivativeDenominator(index);
+ float x,y,diffx,diffy,delta;
+ float firstderv_x,firstderv_y;
+ int i,j;
+
+ if(index<size-index)
+ {
+ for(i=index; i<size-index; ++i)
+ {
+ x= xVec[i];
+ y= yVec[i];
+ diffx=0;
+ diffy=0;
+
+ for( j=1;j<=index;j++)
+ {
+ diffx = diffx + j*(xVec[i+j]-xVec[i-j]) ;
+ diffy = diffy + j*(yVec[i+j]-yVec[i-j]) ;
+ }
+
+ firstderv_x = diffx/denominator;
+ firstderv_y = diffy/denominator;
+ delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2));
+ if(delta!=0)
+ {
+ dx[i] = firstderv_x/(delta);
+ dy[i] = firstderv_y/(delta);
+ }
+ else
+ {
+ dx[i] = 0;
+ dy[i] = 0;
+ }
+
+
+ }
+
+ for(i=0;i<index;i++)
+ {
+ x= xVec[i];
+ y= yVec[i];
+ diffx=0;
+ diffy=0;
+
+ for( j=1;j<=index;j++)
+ {
+ diffx = diffx + j*(xVec[i+j]-x) ;
+ diffy = diffy + j*(yVec[i+j]-y) ;
+ }
+ firstderv_x = diffx/denominator;
+ firstderv_y = diffy/denominator;
+ delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2));
+ if(delta!=0)
+ {
+ dx[i] = firstderv_x/(delta);
+ dy[i] = firstderv_y/(delta);
+ }
+ else
+ {
+ dx[i] = 0;
+ dy[i] = 0;
+ }
+
+ }
+
+ for(i=size-index;i<=size-1;i++)
+ {
+ x= xVec[i];
+ y= yVec[i];
+ diffx=0;
+ diffy=0;
+
+ for( j=1;j<=index;j++)
+ {
+ diffx = diffx + j*(x-xVec[i-j]) ;
+ diffy = diffy + j*(y-yVec[i-j]) ;
+ }
+ firstderv_x = diffx/denominator;
+ firstderv_y = diffy/denominator;
+ delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2));
+ if(delta!=0)
+ {
+ dx[i] = firstderv_x/(delta);
+ dy[i] = firstderv_y/(delta);
+ }
+ else
+ {
+ dx[i] = 0;
+ dy[i] = 0;
+ }
+ }
+ }
+ if(index>size-index)
+ {
+ for(i=0; i<size; ++i)
+ {
+ x= xVec[i];
+ y= yVec[i];
+ diffx=0;
+ diffy=0;
+ if((0<i+j)&(i+j<size))
+ {
+ for( j=1;j<=index;j++)
+ {
+ diffx = diffx + j*(xVec[i+j]-x) ;
+ diffy = diffy + j*(yVec[i+j]-y) ;
+ }
+ }
+ else
+ {
+ for(j=1;j<=index;j++)
+ {
+ diffx = diffx + j*(x-xVec[i-j]) ;
+ diffy = diffy + j*(y-yVec[i-j]) ;
+ }
+ }
+
+ firstderv_x = diffx/denominator;
+ firstderv_y = diffy/denominator;
+ delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2));
+ if(delta!=0)
+ {
+ dx[i] = firstderv_x/(delta);
+ dy[i] = firstderv_y/(delta);
+ }
+ else
+ {
+ dx[i] = 0;
+ dy[i] = 0;
+ }
+
+ }
+ }
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.h
new file mode 100644
index 00000000..9c48636d
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.h
@@ -0,0 +1,112 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+#include "LTKShapeFeatureExtractor.h"
+/** @ingroup L7ShapeFeatureExtractor
+* @brief The feature extractor for L7 features.
+* @class L7ShapeFeatureExtractor
+*
+*/
+#define FEATEXTR_L7_DEF_RADIUS 2
+
+
+class L7ShapeFeatureExtractor : public LTKShapeFeatureExtractor
+{
+private:
+ int m_radius;
+
+public:
+ /** @brief Constructor for the L7 feature extractor
+ * Gets the cfg file path from the contorInfo
+ * Reads the cfg variables and poputlates the member variables
+ * @param controlInfo: LTKControlInfo : The control information
+ * @return no return value as it is a constructor
+ */
+ L7ShapeFeatureExtractor(const LTKControlInfo& controlInfo);
+
+ /** @brief Extracts L7 features from an LTKTraceGroup
+ * The XY Coordinate values are extracted from the trace gruoup.
+ * Using the coordinate values, normalized first derivatives are computed.
+ * After computing the first derivatives, the normalized second derivatives and the curvature are computed. The second derivative and curvature computation occur simultaneously.
+ * @param inTraceGroup: LTKTraceGroup& : The trace group from which local seven features have to be extracted
+ * @return LTKShapeFeaturePtr* : A vector of pointers to LTKShapeFeature objects. The pointers point to instances of the L7ShapeFeature class. The vector contains local-seven features extracted from the trace group.
+ */
+
+ int extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec);
+
+ /** @brief Returns an instance of the L7ShapeFeature class
+ * @return LTKShapeFeature*: The returned empty L7ShapeFeature instance.
+ */
+ LTKShapeFeaturePtr getShapeFeatureInstance();
+
+ /** @brief Converts a feature vector to trace group
+ * @param shapeFeature : LTKShapeFeaturePtr* : The feature vector to be converted to a trace group.
+ * @param outTraceGroup : LTKTraceGroup& : The output trace group
+ */
+ //see interface
+ int convertFeatVecToTraceGroup(const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup);
+
+ int getRadius();
+
+private:
+
+ /** @brief Computes the denominator for derivative calculation
+ * @param index : int: The index used in derivative computation
+ * @return int : The denominator used in derivative computation
+ */
+ int computeDerivativeDenominator(int index);
+
+ /** @brief Computes the derivative for two input sequences
+ * @param xVec : vector<float>&: Input x vector.
+ * @param yVec : vector<float>&: Input y vector.
+ * @param dx : vector<float>&: Derivative vector of x
+ * @param dy : vector<float>&: Derivative vector of y
+ * @param index : int : The window size used in derivative computation
+ *
+ */
+ void computeDerivative(const vector<float>& xVec,
+ const vector<float>& yVec,
+ vector<float>& dx,
+ vector<float>& dy,
+ int index);
+
+ /** @brief reads the cfg file and sets the member variables
+ * @param cfgFilePath : const string&: The path of the cfg file to be opened
+ * @return int : The sucess or failure of the function
+ */
+ int readConfig(const string& cfgFilePath);
+
+ /** @validates the value passed and sets the member variable
+ * @param radius : const int: The value of the variable to be set
+ * @return int : The sucess or failure of the function
+ */
+ int setRadius(int radius);
+
+
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.cpp
new file mode 100644
index 00000000..eca6cf84
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.cpp
@@ -0,0 +1,105 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+// l7.cpp : Defines the entry point for the DLL application.
+
+#include "l7.h"
+#include "L7ShapeFeatureExtractor.h"
+#include "LTKShapeFeatureExtractor.h"
+#include "L7ShapeFeature.h"
+#include "LTKErrors.h"
+
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G
+* DATE : 10-Aug-2007
+* NAME : createFeatureExtractor
+* DESCRIPTION : Creates instance of type l7ShapeFeatureExtractor and retuns of type
+ LTKShapeFeatureExtractor. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKShapeFeatureExtractor.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int createShapeFeatureExtractor(const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ try
+ {
+ *outFeatureExtractor = new L7ShapeFeatureExtractor(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *outFeatureExtractor = NULL;
+
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G
+* DATE : 10-Aug-2007
+* NAME : deleteShapeFeatureExtractor
+* DESCRIPTION : Destroy the instance by taking the address as its argument.
+* ARGUMENTS : Address of LTKShapeRecognizerFeatureExtractor instnace.
+* RETURNS : Returns 0 on Success
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *obj)
+{
+ if ( obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.def
new file mode 100644
index 00000000..9a185d39
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createShapeFeatureExtractor @1
+ deleteShapeFeatureExtractor @2
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.h
new file mode 100644
index 00000000..c0f64a01
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.h
@@ -0,0 +1,94 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the L7_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// L7_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef L7_EXPORTS
+#define L7_API __declspec(dllexport)
+#else
+#define L7_API __declspec(dllimport)
+#endif //ifdef L7_EXPORTS
+#else
+#define L7_API
+#endif //#ifdef _WIN32
+
+#include "LTKTypes.h"
+
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+/** @defgroup L7ShapeFeatureExtractor
+*@brief The L7ShapeFeatureExtractor
+*/
+
+/**
+* @ingroup L7ShapeFeatureExtractor
+* @file L7.cpp
+* <p>
+* The functions exported by the DLL
+* - ::createShapeFeatureExtractor
+* - ::deleteShapeFeatureExtractor
+* - ::getCurrentVersion
+* - ::deleteShapeFeaturePtr
+*/
+
+/**
+* @brief Returns a pointer to the instance of L7ShapeFeatureExtractor
+*
+* <p>
+* This function is based on run-time polymorphism. It creates an instance of
+* L7ShapeFeatureExtractor at run-time and returns it as a pointer to the base class <i>LTKShapeFeatureExtractor</i>
+* </p>
+*
+* @param none
+*
+* @return Pointer to LTKShapeFeatureExtractor
+*/
+//extern "C" L7_API int createShapeFeatureExtractor(const LTKControlInfo& controlInfo, LTKShapeFeatureExtractor**);
+extern "C" L7_API int createShapeFeatureExtractor(
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+/**
+* @brief Deletes the feature extractor instance.
+*
+* <p>
+* This function cleans up all the memory allocations done by the feature extractor by calling it's destructor.
+* </p>
+*
+* @param featureExtractorPtr - Pointer to LTKShapeFeatureExtractor.
+*
+* @return 0 on Success
+*/
+
+//smart pointer for LTKShapeFeatureExtractor??
+extern "C" L7_API int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *featureExtractorPtr);
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.pro
new file mode 100644
index 00000000..2372c2cf
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/l7/l7.pro
@@ -0,0 +1,22 @@
+LIPILIBS = ltkcommon ltkutil featureextractorcommon
+include(../../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../../util/lib \
+ ../common \
+
+HEADERS += \
+ l7.h \
+ L7ShapeFeature.h \
+ L7ShapeFeatureExtractor.h \
+
+SOURCES += \
+ l7.cpp \
+ L7ShapeFeature.cpp \
+ L7ShapeFeatureExtractor.cpp \
+
+win32 {
+ DEFINES += L7_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = l7.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.cpp
new file mode 100644
index 00000000..1d142230
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.cpp
@@ -0,0 +1,103 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+// NPen.cpp : Defines the entry point for the DLL application.
+
+#include "NPen.h"
+#include "NPenShapeFeatureExtractor.h"
+#include "LTKShapeFeatureExtractor.h"
+#include "NPenShapeFeature.h"
+#include "LTKErrors.h"
+
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+/**********************************************************************************
+* AUTHOR : Bharath A
+* DATE : 12-Jun-2008
+* NAME : createFeatureExtractor
+* DESCRIPTION : Creates instance of type NPenShapeFeatureExtractor and retuns of type
+ LTKShapeFeatureExtractor. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKShapeFeatureExtractor.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int createShapeFeatureExtractor(const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ try
+ {
+ *outFeatureExtractor = new NPenShapeFeatureExtractor(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *outFeatureExtractor = NULL;
+
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Bharath A
+* DATE : 12-Jun-2008
+* NAME : deleteShapeFeatureExtractor
+* DESCRIPTION : Destroy the instance by taking the address as its argument.
+* ARGUMENTS : Address of LTKShapeRecognizerFeatureExtractor instnace.
+* RETURNS : Returns 0 on Success
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *obj)
+{
+ if ( obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.def
new file mode 100644
index 00000000..9a185d39
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createShapeFeatureExtractor @1
+ deleteShapeFeatureExtractor @2
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.h
new file mode 100644
index 00000000..c1a410d7
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPen.h
@@ -0,0 +1,92 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the NPen_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// NPen_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef NPen_EXPORTS
+#define NPen_API __declspec(dllexport)
+#else
+#define NPen_API __declspec(dllimport)
+#endif //ifdef NPen_EXPORTS
+#else
+#define NPen_API
+#endif //#ifdef _WIN32
+
+#include "LTKTypes.h"
+
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+/** @defgroup NPenShapeFeatureExtractor
+*@brief The NPenShapeFeatureExtractor
+*/
+
+/**
+* @ingroup NPenShapeFeatureExtractor
+* @file NPen.cpp
+* <p>
+* The functions exported by the DLL
+* - ::createShapeFeatureExtractor
+* - ::deleteShapeFeatureExtractor
+* - ::getCurrentVersion
+* - ::deleteShapeFeaturePtr
+*/
+
+/**
+* @brief Returns a pointer to the instance of NPenShapeFeatureExtractor
+*
+* <p>
+* This function is based on run-time polymorphism. It creates an instance of
+* NPenShapeFeatureExtractor at run-time and returns it as a pointer to the base class <i>LTKShapeFeatureExtractor</i>
+* </p>
+*
+* @param none
+*
+* @return Pointer to LTKShapeFeatureExtractor
+*/
+//extern "C" NPen_API int createShapeFeatureExtractor(const LTKControlInfo& controlInfo, LTKShapeFeatureExtractor**);
+extern "C" NPen_API int createShapeFeatureExtractor(
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+/**
+* @brief Deletes the feature extractor instance.
+*
+* <p>
+* This function cleans up all the memory allocations done by the feature extractor by calling it's destructor.
+* </p>
+*
+* @param featureExtractorPtr - Pointer to LTKShapeFeatureExtractor.
+*
+* @return 0 on Success
+*/
+
+//smart pointer for LTKShapeFeatureExtractor??
+extern "C" NPen_API int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *featureExtractorPtr);
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.cpp
new file mode 100644
index 00000000..a05867be
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.cpp
@@ -0,0 +1,340 @@
+#include "NPenShapeFeature.h"
+#include "LTKStringUtil.h"
+#include "LTKPreprocDefaults.h"
+
+#include <sstream>
+
+
+NPenShapeFeature::NPenShapeFeature():m_data_delimiter(",")
+ {
+
+ }
+
+
+ NPenShapeFeature::NPenShapeFeature(float inX, float inY, float cosAlpha, float inSinAlpha,
+ float inCosBeta, float inSinBeta, float inAspect, float inCurliness,
+ float inLinearity, float inSlope, bool isPenUp):m_data_delimiter(",")
+ {
+
+ }
+
+
+ NPenShapeFeature::~NPenShapeFeature()
+ {
+
+ }
+
+
+ float NPenShapeFeature::getX() const
+ {
+ return m_x;
+ }
+
+
+ float NPenShapeFeature::getY() const
+ {
+ return m_y;
+ }
+
+
+ float NPenShapeFeature::getCosAlpha() const
+ {
+ return m_cosAlpha;
+ }
+
+
+ float NPenShapeFeature::getSinAlpha() const
+ {
+ return m_sinAlpha;
+ }
+
+
+ float NPenShapeFeature::getCosBeta() const
+ {
+ return m_cosBeta;
+ }
+
+
+ float NPenShapeFeature::getSinBeta() const
+ {
+ return m_sinBeta;
+ }
+
+ float NPenShapeFeature::getAspect() const
+ {
+ return m_aspect;
+ }
+
+
+ float NPenShapeFeature::getCurliness() const
+ {
+ return m_curliness;
+ }
+
+
+ float NPenShapeFeature::getLinearity() const
+ {
+ return m_linearity;
+ }
+
+
+ float NPenShapeFeature::getSlope() const
+ {
+ return m_slope;
+ }
+
+
+ bool NPenShapeFeature::isPenUp() const
+ {
+ return m_isPenUp;
+ }
+
+
+ void NPenShapeFeature::setX(float x)
+ {
+ m_x = x;
+ }
+
+
+ void NPenShapeFeature::setY(float y)
+ {
+ m_y = y;
+ }
+
+
+ void NPenShapeFeature::setCosAlpha(float cosAlpha)
+ {
+ m_cosAlpha = cosAlpha;
+ }
+
+
+ void NPenShapeFeature::setSinAlpha(float sinAlpha)
+ {
+ m_sinAlpha = sinAlpha;
+ }
+
+
+ void NPenShapeFeature::setCosBeta(float cosBeta)
+ {
+ m_cosBeta = cosBeta;
+ }
+
+
+ void NPenShapeFeature::setSinBeta(float sinBeta)
+ {
+ m_sinBeta = sinBeta;
+ }
+
+
+ void NPenShapeFeature::setAspect(float aspect)
+ {
+ m_aspect = aspect;
+ }
+
+ void NPenShapeFeature::setCurliness(float curliness)
+ {
+ m_curliness = curliness;
+ }
+
+ void NPenShapeFeature::setLinearity(float linearity)
+ {
+ m_linearity = linearity;
+ }
+
+ void NPenShapeFeature::setSlope(float slope)
+ {
+ m_slope = slope;
+ }
+
+
+ void NPenShapeFeature::setPenUp(bool isPenUp)
+ {
+ m_isPenUp = isPenUp;
+ }
+
+
+
+ int NPenShapeFeature::initialize(const string& initString)
+ {
+ stringVector tokens;
+ LTKStringUtil::tokenizeString(initString,m_data_delimiter,tokens);
+
+ if(tokens.size() != 11)
+ {
+ return FAILURE;
+ }
+
+ m_x = LTKStringUtil::convertStringToFloat(tokens[0]);
+
+ m_y = LTKStringUtil::convertStringToFloat(tokens[1]);
+
+
+ m_cosAlpha = LTKStringUtil::convertStringToFloat(tokens[2]);
+
+ m_sinAlpha = LTKStringUtil::convertStringToFloat(tokens[3]);
+
+ m_cosBeta = LTKStringUtil::convertStringToFloat(tokens[4]);
+
+ m_sinBeta = LTKStringUtil::convertStringToFloat(tokens[5]);
+
+ m_aspect = LTKStringUtil::convertStringToFloat(tokens[6]);
+
+ m_curliness = LTKStringUtil::convertStringToFloat(tokens[7]);
+
+ m_linearity = LTKStringUtil::convertStringToFloat(tokens[8]);
+
+ m_slope = LTKStringUtil::convertStringToFloat(tokens[9]);
+
+ if(fabs(LTKStringUtil::convertStringToFloat(tokens[10]) - 1.0f) < EPS)
+ {
+ m_isPenUp = true;
+ }
+ else
+ {
+ m_isPenUp = false;
+ }
+
+ return SUCCESS;
+
+
+ }
+
+
+ void NPenShapeFeature::toString(string& strFeat) const
+ {
+ ostringstream tempString;
+
+ tempString << m_x << m_data_delimiter << m_y << m_data_delimiter <<
+ m_cosAlpha << m_data_delimiter <<
+ m_sinAlpha << m_data_delimiter <<
+ m_cosBeta << m_data_delimiter <<
+ m_sinBeta << m_data_delimiter <<
+ m_aspect << m_data_delimiter <<
+ m_curliness << m_data_delimiter <<
+ m_linearity << m_data_delimiter <<
+ m_slope << m_data_delimiter<<
+ m_isPenUp;
+
+ strFeat = tempString.str();
+
+
+ }
+
+
+ LTKShapeFeaturePtr NPenShapeFeature::clone() const
+ {
+ NPenShapeFeature* npenSF = new NPenShapeFeature();
+
+
+ npenSF->setX(this->getX());
+ npenSF->setY(this->getY());
+ npenSF->setCosAlpha(this->getCosAlpha());
+ npenSF->setSinAlpha(this->getSinAlpha());
+ npenSF->setCosBeta(this->getCosBeta());
+ npenSF->setSinBeta(this->getSinBeta());
+ npenSF->setAspect(this->getAspect());
+ npenSF->setCurliness(this->getCurliness());
+ npenSF->setLinearity(this->getLinearity());
+ npenSF->setSlope(this->getSlope());
+ npenSF->setPenUp(this->isPenUp());
+
+
+
+ return (LTKShapeFeaturePtr)npenSF;
+ }
+
+
+
+ void NPenShapeFeature::getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const
+ {
+ outDistance = 0.0;
+
+ NPenShapeFeature *inFeature = (NPenShapeFeature*)(shapeFeaturePtr.operator ->());
+
+ outDistance += (m_x - inFeature->getX())*(m_x - inFeature->getX());
+ outDistance += (m_y - inFeature->getY())*(m_y - inFeature->getY());
+ outDistance += (m_cosAlpha - inFeature->getCosAlpha())*(m_cosAlpha - inFeature->getCosAlpha());
+ outDistance += (m_sinAlpha - inFeature->getSinAlpha())*(m_sinAlpha - inFeature->getSinAlpha());
+ outDistance += (m_cosBeta - inFeature->getCosBeta())*(m_cosBeta - inFeature->getCosBeta());
+ outDistance += (m_sinBeta - inFeature->getSinBeta())*(m_sinBeta - inFeature->getSinBeta());
+ outDistance += (m_aspect - inFeature->getAspect())*(m_aspect - inFeature->getAspect());
+ outDistance += (m_curliness - inFeature->getCurliness())*(m_curliness - inFeature->getCurliness());
+ outDistance += (m_linearity - inFeature->getLinearity())*(m_linearity - inFeature->getLinearity());
+ outDistance += (m_slope - inFeature->getSlope())*(m_slope - inFeature->getSlope());
+ }
+
+
+ int NPenShapeFeature::toFloatVector(vector<float>& floatVec)
+ {
+ floatVec.push_back(m_x);
+ floatVec.push_back(m_y);
+ floatVec.push_back(m_cosAlpha);
+ floatVec.push_back(m_sinAlpha);
+ floatVec.push_back(m_cosBeta);
+ floatVec.push_back(m_sinBeta);
+ floatVec.push_back(m_aspect);
+ floatVec.push_back(m_curliness);
+ floatVec.push_back(m_linearity);
+ floatVec.push_back(m_slope);
+
+ if(isPenUp())
+ {
+ floatVec.push_back(1.0f);
+ }
+ else
+ {
+ floatVec.push_back(0.0f);
+ }
+
+ return SUCCESS;
+ }
+
+
+ int NPenShapeFeature::getFeatureDimension()
+ {
+
+ return 11;
+ }
+
+
+ int NPenShapeFeature::initialize(const floatVector& initFloatVector)
+ {
+
+
+ if(initFloatVector.size() != 11)
+ {
+ return FAILURE;
+ }
+
+ m_x = initFloatVector[0];
+
+ m_y = initFloatVector[1];
+
+
+ m_cosAlpha = initFloatVector[2];
+
+ m_sinAlpha = initFloatVector[3];
+
+ m_cosBeta = initFloatVector[4];
+
+ m_sinBeta = initFloatVector[5];
+
+ m_aspect = initFloatVector[6];
+
+ m_curliness = initFloatVector[7];
+
+ m_linearity = initFloatVector[8];
+
+ m_slope = initFloatVector[9];
+
+ if(fabs(initFloatVector[10] - 1.0f) < EPS)
+ {
+ m_isPenUp = true;
+ }
+ else
+ {
+ m_isPenUp = false;
+ }
+
+ return SUCCESS;
+ }
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.h
new file mode 100644
index 00000000..1f9f5f08
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeature.h
@@ -0,0 +1,253 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+#include "LTKShapeFeature.h"
+
+#define DELIMITER_SIZE 5
+
+
+/** @ingroup NPenShapeFeatureExtractor
+* @brief The feature representation class for NPen features
+* This class represents NPen++ features such as X, Y, cos/sin alpha, cos/sin beta, aspect, curliness, linearity, slope and pen-up/down bit
+* @class NPenShapeFeature
+*
+*/
+class NPenShapeFeature : public LTKShapeFeature
+{
+ /** @name private data members */
+ //@{
+
+private:
+ /** @brief X value */
+ float m_x;
+
+ /** @brief Y value */
+ float m_y;
+
+
+ float m_cosAlpha;
+
+ float m_sinAlpha;
+
+ float m_cosBeta;
+
+ float m_sinBeta;
+
+ float m_aspect;
+
+ float m_curliness;
+
+ float m_linearity;
+
+ float m_slope;
+
+ bool m_isPenUp;
+
+
+ string m_data_delimiter;
+ //@}
+
+public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+ NPenShapeFeature();
+
+ /** parameterized constructor
+ */
+ NPenShapeFeature(float inX, float inY, float cosAlpha, float inSinAlpha,
+ float inCosBeta, float inSinBeta, float inAspect, float inCurliness,
+ float inLinearity, float inSlope, bool isPenUp);
+
+ /**
+ * Default destructor.
+ */
+ ~NPenShapeFeature();
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_x
+ */
+ float getX() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_y
+ */
+ float getY() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_cosAlpha
+ */
+ float getCosAlpha() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_sinAlpha
+ */
+ float getSinAlpha() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_cosBeta
+ */
+ float getCosBeta() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_sinBeta
+ */
+ float getSinBeta() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_aspect
+ */
+ float getAspect() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_curliness
+ */
+ float getCurliness() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_linearity
+ */
+ float getLinearity() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_slope
+ */
+ float getSlope() const;
+
+ /**
+ * Returns the value of the class data member NPenShapeFeature::m_penUp
+ */
+ bool isPenUp() const;
+
+ /**
+ * Sets the value of NPenShapeFeature::m_x
+ */
+ void setX(float x);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_y
+ */
+ void setY(float y);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_cosAlpha
+ */
+ void setCosAlpha(float cosAlpha);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_sinAlpha
+ */
+ void setSinAlpha(float sinAlpha);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_cosBeta
+ */
+ void setCosBeta(float cosBeta);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_sinBeta
+ */
+ void setSinBeta(float sinBeta);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_aspect
+ */
+ void setAspect(float aspect);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_curliness
+ */
+ void setCurliness(float curliness);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_linearity
+ */
+ void setLinearity(float linearity);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_slope
+ */
+ void setSlope(float slope);
+
+ /**
+ * Sets the value of NPenShapeFeature::m_penUp
+ */
+ void setPenUp(bool penUp);
+
+
+ /**
+ * @brief Initializes an instance of NPenShapeFeature from the string passed as parameter.
+ *
+ * <b>Semantics</b>
+ *
+ * - Tokenize the input string on NPenShapeFeature::m_data_delimiter using StringTokenizer::tokenizeString
+ * - Initialize the data members of the class with the tokens returned.
+ *
+ * @param initString : string& : Reference to the initialization string.
+ *
+ * @return FAILURE : If the initalization string contains more than or less than seven tokens (after tokenizing on NPenShapeFeature::m_data_delimiter)
+ * @return SUCCESS : If initialization done without any errors.
+ *
+ */
+
+ //see interface
+ int initialize(const string& initString);
+
+ /**
+ * @brief Gives the string representation of the NPenShapeFeature instance
+ */
+ //see interface
+ void toString(string& strFeat) const;
+
+ /**
+ * This method implements the clone pattern and returns a cloned instance of the invoking NPenShapeFeature object
+ */
+ LTKShapeFeaturePtr clone() const;
+
+
+
+ void getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const;
+
+ /**
+ * Converts the local feature instance into a float vector. The elements of the float vector are m_x, m_y, m_cosAlpha, m_sinAlpha, m_cosBeta, m_sinBeta, m_aspect, m_curliness, m_linearity, m_slope and m_isPenUp in the order.
+ * @param floatVec: vector<float>&: The float vector which will contain the member values.
+ * @return int : returns SUCCESS or FAILURE
+ *
+ */
+ int toFloatVector(vector<float>& floatVec);
+
+
+ int getFeatureDimension();
+
+
+
+ int initialize(const floatVector& initFloatVector);
+
+
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.cpp
new file mode 100644
index 00000000..e20b63dc
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.cpp
@@ -0,0 +1,722 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of RunShaperec tool
+ *
+ * CONTENTS:
+ * extractFeatures
+ * getShapeFeatureInstance
+ * clearFeatureVector
+ *
+ * AUTHOR: Bharath A
+ *
+ * DATE: June 11, 2008
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+
+#include "NPenShapeFeatureExtractor.h"
+#include "NPenShapeFeature.h"
+#include "LTKTraceGroup.h"
+#include "LTKTrace.h"
+#include "LTKChannel.h"
+#include "LTKTraceFormat.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKLoggerUtil.h"
+#include "LTKPreprocDefaults.h"
+
+/******************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : NPenShapeFeatureExtractor
+* DESCRIPTION : parameterized constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*******************************************************************************/
+NPenShapeFeatureExtractor::NPenShapeFeatureExtractor(const LTKControlInfo& controlInfo):
+m_windowSize(FEATEXTR_NPEN_DEF_WINDOW_SIZE)
+{
+ string cfgFilePath = "";
+
+ // Config file
+ if ( ! ((controlInfo.lipiRoot).empty()) &&
+ ! ((controlInfo.projectName).empty()) &&
+ ! ((controlInfo.profileName).empty()) &&
+ ! ((controlInfo.cfgFileName).empty()))
+ {
+ // construct the cfg path using project and profile name
+ cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING +
+ (controlInfo.projectName) + PROFILE_PATH_STRING +
+ (controlInfo.profileName) + SEPARATOR +
+ (controlInfo.cfgFileName) + CONFIGFILEEXT;
+ }
+ else if ( ! ((controlInfo.cfgFilePath).empty() ))
+ {
+ cfgFilePath = controlInfo.cfgFilePath;
+ }
+ else
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+
+
+ int returnVal = readConfig(cfgFilePath);
+
+ if (returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: NPenShapeFeatureExtractor::NPenShapeFeatureExtractor()" <<endl;
+
+ throw LTKException(returnVal);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NPenShapeFeatureExtractor::NPenShapeFeatureExtractor()" << endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : readConfig
+* DESCRIPTION : read the config values from cfg file and set member variables
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+
+int NPenShapeFeatureExtractor::readConfig(const string& cfgFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NPenShapeFeatureExtractor::readConfig()" << endl;
+
+ LTKConfigFileReader* configurableProperties = NULL;
+ string tempStringVar = "";
+
+ try
+ {
+ configurableProperties = new LTKConfigFileReader(cfgFilePath);
+
+ int errorCode = configurableProperties->getConfigValue(NPEN_WINDOW_SIZE, tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if (setWindowSize(atoi((tempStringVar).c_str())) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ ECONFIG_FILE_RANGE << " : " <<
+ getErrorMessage(ECONFIG_FILE_RANGE) <<
+ " NPenShapeFeatureExtractor::readConfig" <<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+
+ catch(LTKException e)
+ {
+ delete configurableProperties;
+
+ int eCode = e.getErrorCode();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << eCode <<
+ " : " << getErrorMessage(eCode) <<
+ " NPenShapeFeatureExtractor::readConfig" <<endl;
+
+ LTKReturnError(eCode);
+ }
+ delete configurableProperties;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NPenShapeFeatureExtractor::readConfig()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 1-Oct-2007
+* NAME : setRadius
+* DESCRIPTION : set the radius(the size of window) to compute NPen features
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+int NPenShapeFeatureExtractor::setWindowSize(int windowSize)
+{
+ int returnVal = FAILURE;
+
+ if ( windowSize > 0 && (windowSize%2 == 1))
+ {
+ m_windowSize = windowSize;
+ returnVal = SUCCESS;
+ }
+
+ return returnVal;
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 15-Feb-2008
+* NAME : getRadius
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date
+*************************************************************************************/
+int NPenShapeFeatureExtractor::getWindowSize()
+{
+ return m_windowSize;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Bharath A
+* DATE : 12-Jun-2008
+* NAME : extractFeatures
+* DESCRIPTION : Extracts NPen features from a trace group
+* ARGUMENTS : The trace group from which features have to be extracted
+* RETURNS : vector of NPenShapeFeature objects
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int NPenShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NPenShapeFeatureExtractor::extractFeatures()" << endl;
+
+ NPenShapeFeature* featurePtr = NULL;
+
+ vector<vector<float> > floatFeatureValues;
+
+
+
+ int errorCode;
+
+ if(inTraceGroup.getNumTraces() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: FeatureExtractor::findAllFeatures"<<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+
+ vector<vector<float> > concatenatedCoord;
+ int currPenUpPointIndex = -1;
+ vector<int> penUpPointsIndices;
+
+
+ int halfWindowSize = m_windowSize/2;
+
+ if(halfWindowSize==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: FeatureExtractor::findAllFeatures"<<endl;
+
+ LTKReturnError(EINVALID_NUM_OF_POINTS);
+ }
+
+
+ for(int t=0;t<inTraceGroup.getNumTraces();++t)
+ {
+
+ LTKTrace eachTrace;
+ inTraceGroup.getTraceAt(t,eachTrace);
+
+ if(eachTrace.isEmpty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: FeatureExtractor::findAllFeatures"<<endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+
+ }
+
+ vector<float> xVec;
+ vector<float> yVec;
+
+ eachTrace.getChannelValues(X_CHANNEL_NAME,xVec);
+ eachTrace.getChannelValues(Y_CHANNEL_NAME,yVec);
+
+ if(t==0)
+ {
+ vector<float> firstPoint;
+ firstPoint.push_back(xVec[0]);
+ firstPoint.push_back(yVec[0]);
+
+ concatenatedCoord.insert(concatenatedCoord.begin(),halfWindowSize,firstPoint);
+ }
+
+ for(int p=0;p<xVec.size();++p)
+ {
+ vector<float> point;
+ point.push_back(xVec[p]);
+ point.push_back(yVec[p]);
+
+ concatenatedCoord.push_back(point);
+
+ }
+
+ currPenUpPointIndex += xVec.size();
+
+ penUpPointsIndices.push_back(currPenUpPointIndex);
+
+ if(t==(inTraceGroup.getNumTraces()-1))
+ {
+ vector<float> lastPoint;
+ lastPoint.push_back(xVec[xVec.size()-1]);
+ lastPoint.push_back(yVec[yVec.size()-1]);
+
+ concatenatedCoord.insert(concatenatedCoord.end(),halfWindowSize,lastPoint);
+ }
+
+ }
+
+
+
+ /* 0 - normalized x
+ 1 - normalized y
+ 2 - cos alpha
+ 3 - sin alpha
+ 4 - cos beta
+ 5 - sin beta
+ 6 - aspect
+ 7 - curliness
+ 8 - linearity
+ 9 - slope
+ 10 - pen-up / pen-down stroke (0 for pen-down and 1 for pen-up)*/
+
+ float deltaX=0;
+ float deltaY=0;
+ float hypotenuse=0;
+
+
+ float cosalpha=0;
+ float sinalpha=0;
+ float cosbeta=0;
+ float sinbeta=0;
+ float ispenup=0;
+ float aspect=0;
+ float curliness=0;
+ float linearity=0;
+ float slope=0;
+
+
+ float xMin,yMin,xMax,yMax; //for vicnity bounding box;
+ float bbWidth,bbHeight;
+ float maxOfWidthHeight;
+
+
+
+ currPenUpPointIndex = 0;
+
+
+ for(int f=halfWindowSize;f<(concatenatedCoord.size()-halfWindowSize);++f)
+ {
+
+ vector<float> eachPointFeature;
+
+ eachPointFeature.push_back(concatenatedCoord[f][0]); //x
+ eachPointFeature.push_back(concatenatedCoord[f][1]); //y
+
+ deltaX = concatenatedCoord[f-1][0] - concatenatedCoord[f+1][0];
+ deltaY = concatenatedCoord[f-1][1] - concatenatedCoord[f+1][1];
+
+ hypotenuse = sqrt((deltaX*deltaX)+(deltaY*deltaY));
+
+ if(hypotenuse < EPS)
+ {
+ cosalpha = 1;
+ sinalpha = 0;
+ }
+ else
+ {
+ cosalpha = deltaX / hypotenuse;
+ sinalpha = deltaY / hypotenuse;
+ }
+
+ eachPointFeature.push_back(cosalpha);
+ eachPointFeature.push_back(sinalpha);
+
+ eachPointFeature.push_back(cosbeta); //creating empty spaces for cosine and sine betas for future assignment
+ eachPointFeature.push_back(sinbeta);
+
+ vector<vector<float> > vicinity;
+
+ float vicinityTrajLen = 0.0f;
+
+ for(int v=f-halfWindowSize;v<=f+halfWindowSize;++v)
+ {
+ vicinity.push_back(concatenatedCoord[v]);
+
+ if(v<(f+halfWindowSize))
+ {
+ vicinityTrajLen += (sqrt(((concatenatedCoord[v+1][1]-concatenatedCoord[v][1])*(concatenatedCoord[v+1][1]-concatenatedCoord[v][1]))+((concatenatedCoord[v+1][0]-concatenatedCoord[v][0])*(concatenatedCoord[v+1][0]-concatenatedCoord[v][0]))));
+ }
+ }
+
+ findVicinityBoundingBox(vicinity,xMin,yMin,xMax,yMax);
+
+ bbWidth = xMax - xMin;
+
+ bbHeight = yMax - yMin;
+
+ if(fabs(bbHeight+bbWidth)<EPS)
+ {
+ aspect = 0.0;
+ }
+ else
+ {
+ aspect = (bbHeight-bbWidth)/(bbHeight+bbWidth);
+ }
+
+
+ eachPointFeature.push_back(aspect);
+
+
+ maxOfWidthHeight = ( bbWidth > bbHeight) ? bbWidth : bbHeight;
+
+ if(fabs(maxOfWidthHeight) < EPS)
+ {
+ curliness = 0.0f;
+ }
+ else
+ {
+ curliness = (vicinityTrajLen / maxOfWidthHeight) - 2;
+ }
+
+ eachPointFeature.push_back(curliness);
+
+ computeLinearityAndSlope(vicinity,linearity,slope);
+
+ eachPointFeature.push_back(linearity);
+ eachPointFeature.push_back(slope);
+
+ if(penUpPointsIndices[currPenUpPointIndex] == (f-halfWindowSize))
+ {
+ ispenup = 1;
+ ++currPenUpPointIndex;
+ }
+ else
+ {
+ ispenup = 0;
+ }
+ eachPointFeature.push_back(ispenup); //currently assuming pen-up strokes are not resampled
+
+ floatFeatureValues.push_back(eachPointFeature);
+
+ }
+
+
+ //duplicating first and last features
+ vector<float> firstFeaturePoint = floatFeatureValues[0];
+
+ floatFeatureValues.insert(floatFeatureValues.begin(),1,firstFeaturePoint);
+
+ vector<float> lastFeaturePoint = floatFeatureValues[floatFeatureValues.size()-1];
+
+ floatFeatureValues.insert(floatFeatureValues.end(),1,lastFeaturePoint);
+
+
+ for(int ff=1;ff<(floatFeatureValues.size()-1);++ff)
+ {
+
+ floatFeatureValues[ff][4] = (floatFeatureValues[ff-1][2]*floatFeatureValues[ff+1][2]) + (floatFeatureValues[ff-1][3]*floatFeatureValues[ff+1][3]);
+ floatFeatureValues[ff][5] = (floatFeatureValues[ff-1][2]*floatFeatureValues[ff+1][3]) - (floatFeatureValues[ff-1][3]*floatFeatureValues[ff+1][2]);
+
+ }
+
+ //removing the extraneous feature points at the beginning and end
+ floatFeatureValues.erase(floatFeatureValues.begin(),floatFeatureValues.begin()+1);
+ floatFeatureValues.pop_back();
+
+
+ for(int a=0;a<floatFeatureValues.size();++a)
+ {
+ NPenShapeFeature* ptrFeature = new NPenShapeFeature();
+ ptrFeature->setX(floatFeatureValues[a][0]);
+ ptrFeature->setY(floatFeatureValues[a][1]);
+ ptrFeature->setCosAlpha((1+floatFeatureValues[a][2])*((float)PREPROC_DEF_NORMALIZEDSIZE/2.0));
+ ptrFeature->setSinAlpha((1+floatFeatureValues[a][3])*((float)PREPROC_DEF_NORMALIZEDSIZE/2.0));
+ ptrFeature->setCosBeta((1+floatFeatureValues[a][4])*((float)PREPROC_DEF_NORMALIZEDSIZE/2.0));
+ ptrFeature->setSinBeta((1+floatFeatureValues[a][5])*((float)PREPROC_DEF_NORMALIZEDSIZE/2.0));
+ ptrFeature->setAspect(floatFeatureValues[a][6]);
+ ptrFeature->setCurliness(floatFeatureValues[a][7]);
+ ptrFeature->setLinearity(floatFeatureValues[a][8]);
+ ptrFeature->setSlope((1+floatFeatureValues[a][9])*((float)PREPROC_DEF_NORMALIZEDSIZE/2.0));
+
+ if(fabs(floatFeatureValues[a][10]-1.0f) < EPS)
+ {
+ ptrFeature->setPenUp(true);
+ }
+ else
+ {
+ ptrFeature->setPenUp(false);
+ }
+
+ outFeatureVec.push_back(LTKShapeFeaturePtr(ptrFeature));
+
+ ptrFeature = NULL;
+
+ }
+
+
+
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NPenShapeFeatureExtractor::extractFeatures()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Bharath A
+* DATE : 12-Jun-2008
+* NAME : getShapeFeatureInstance
+* DESCRIPTION : Returns an NPenShapeFeature instance
+* ARGUMENTS :
+* RETURNS : An NPenShapeFeature instance
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKShapeFeaturePtr NPenShapeFeatureExtractor::getShapeFeatureInstance()
+{
+ LTKShapeFeaturePtr tempPtr(new NPenShapeFeature);
+ return tempPtr;
+}
+
+
+/******************************************************************************
+* AUTHOR : Bharath A
+* DATE : 12-Jun-2008
+* NAME : convertFeatVecToTraceGroup
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int NPenShapeFeatureExtractor::convertFeatVecToTraceGroup(
+ const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NPenShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+
+ vector<LTKChannel> channels; // channels of a trace
+
+ LTKChannel xChannel("X", DT_FLOAT, true); // x-coordinate channel of the trace
+ LTKChannel yChannel("Y", DT_FLOAT, true); // y-coordinate channel of the trace
+
+ //initializing the channels of the trace
+ channels.push_back(xChannel);
+ channels.push_back(yChannel);
+
+ // composing the trace format object
+ LTKTraceFormat traceFormat(channels);
+
+ vector<float> point; // a point of a trace
+
+ LTKTrace trace(traceFormat);
+
+ for(int count=0;count<(int)shapeFeature.size();count++)
+ {
+ float Xpoint, Ypoint;
+ bool penUp;
+
+ NPenShapeFeature* ptr = (NPenShapeFeature*)(shapeFeature[count].operator ->());
+ Xpoint = ptr->getX();
+ Ypoint = ptr->getY();
+ penUp = ptr->isPenUp();
+
+
+
+ point.push_back(Xpoint);
+ point.push_back(Ypoint);
+
+ trace.addPoint(point);
+ point.clear();
+
+
+ if(penUp == true) // end of a trace, clearing the trace now
+ {
+ outTraceGroup.addTrace(trace);
+ trace.emptyTrace();
+ LTKTrace tempTrace(traceFormat);
+ trace = tempTrace;
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NPenShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+ return SUCCESS;
+
+}
+
+
+void NPenShapeFeatureExtractor::findVicinityBoundingBox(vector<vector<float> >& inputXYCoords, float& xMin, float& yMin, float& xMax, float& yMax)
+ {
+ xMin = FLT_MAX;
+ yMin = FLT_MAX;
+
+ xMax = -FLT_MAX;
+ yMax = -FLT_MAX;
+
+ for(int i=0;i<inputXYCoords.size();++i)
+ {
+ if(inputXYCoords[i][0] < xMin)
+ {
+ xMin = inputXYCoords[i][0];
+ }
+
+ if(inputXYCoords[i][0] > xMax)
+ {
+ xMax = inputXYCoords[i][0];
+ }
+
+ if(inputXYCoords[i][1] < yMin)
+ {
+ yMin = inputXYCoords[i][1];
+ }
+
+ if(inputXYCoords[i][1] > yMax)
+ {
+ yMax = inputXYCoords[i][1];
+ }
+ }
+
+ }
+
+
+
+int NPenShapeFeatureExtractor::computeLinearityAndSlope(const vector<vector<float> >& vicinity,float& linearity,float& slope)
+ {
+ if(vicinity.size()<3)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: FeatureExtractor::computeLinearity"<<endl;
+
+ LTKReturnError(FAILURE);
+ }
+
+ float x1 = vicinity[0][0];
+ float y1 = vicinity[0][1];
+
+ float x2 = vicinity[vicinity.size()-1][0];
+ float y2 = vicinity[vicinity.size()-1][1];
+
+ float avgX = 0.0f;
+ float avgY = 0.0f;
+
+ float denominator = sqrt(((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1)));
+
+ /*if(denominator < EPS)
+ {
+ linearity = 0.0f;
+ slope = 1.0f;
+
+ return SUCCESS;
+ }*/
+
+ if(denominator < EPS)
+ {
+ slope = 1.0f;
+
+
+ //considering the case of loop where the end points are the same
+ avgX = (x1+x2)/2.0f;
+ avgY = (y1+y2)/2.0f;
+ }
+ else if(fabs(x2-x1) < EPS)
+ {
+ slope = 0.0f;
+ }
+ else
+ {
+ slope = cos(atan((y2-y1)/(x2-x1)));
+ }
+
+
+ float x0 = 0.0f;
+ float y0 = 0.0f;
+
+ float distance = 0.0f;
+
+
+ linearity = 0.0f;
+
+ for(int v=1; v<(vicinity.size()-1); ++v)
+ {
+
+ if(vicinity[v].size() < 2)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: FeatureExtractor::computeLinearity"<<endl;
+
+ LTKReturnError(FAILURE);
+ }
+
+ x0 = vicinity[v][0];
+ y0 = vicinity[v][1];
+
+ if(denominator < EPS)
+ {
+ distance = sqrt(((avgX-x0)*(avgX-x0))+((avgY-y0)*(avgY-y0)));
+ }
+ else
+ {
+ distance = fabs(((x2-x1)*(y1-y0))-((x1-x0)*(y2-y1))) / denominator;
+ }
+
+ linearity += (distance*distance);
+
+ }
+
+ linearity /= (vicinity.size()-2); // 2 to exclude the end points of vicinity while computing average squared distance
+
+ return SUCCESS;
+ }
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.h
new file mode 100644
index 00000000..18ca347e
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/NPenShapeFeatureExtractor.h
@@ -0,0 +1,97 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $
+ * $Revision: 423 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+#include "LTKShapeFeatureExtractor.h"
+/** @ingroup NPenShapeFeatureExtractor
+* @brief The feature extractor for NPen features.
+* @class NPenShapeFeatureExtractor
+*
+*/
+#define FEATEXTR_NPEN_DEF_WINDOW_SIZE 5
+
+class LTKLoggerInterface;
+
+class NPenShapeFeatureExtractor : public LTKShapeFeatureExtractor
+{
+private:
+ int m_windowSize;
+ LTKLoggerInterface* m_ptrLog;
+
+public:
+ /** @brief Constructor for the NPen feature extractor
+ * Gets the cfg file path from the contorInfo
+ * Reads the cfg variables and poputlates the member variables
+ * @param controlInfo: LTKControlInfo : The control information
+ * @return no return value as it is a constructor
+ */
+ NPenShapeFeatureExtractor(const LTKControlInfo& controlInfo);
+
+ /** @brief Extracts NPen features from an LTKTraceGroup
+ * The XY Coordinate values are extracted from the trace gruoup.
+ * Using the coordinate values, normalized first derivatives are computed.
+ * After computing the first derivatives, the normalized second derivatives and the curvature are computed. The second derivative and curvature computation occur simultaneously.
+ * @param inTraceGroup: LTKTraceGroup& : The trace group from which local seven features have to be extracted
+ * @return LTKShapeFeaturePtr* : A vector of pointers to LTKShapeFeature objects. The pointers point to instances of the NPenShapeFeature class. The vector contains local-seven features extracted from the trace group.
+ */
+
+ int extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec);
+
+ /** @brief Returns an instance of the NPenShapeFeature class
+ * @return LTKShapeFeature*: The returned empty NPenShapeFeature instance.
+ */
+ LTKShapeFeaturePtr getShapeFeatureInstance();
+
+ /** @brief Converts a feature vector to trace group
+ * @param shapeFeature : LTKShapeFeaturePtr* : The feature vector to be converted to a trace group.
+ * @param outTraceGroup : LTKTraceGroup& : The output trace group
+ */
+ //see interface
+ int convertFeatVecToTraceGroup(const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup);
+
+ int getWindowSize();
+
+private:
+
+
+ /** @brief reads the cfg file and sets the member variables
+ * @param cfgFilePath : const string&: The path of the cfg file to be opened
+ * @return int : The sucess or failure of the function
+ */
+ int readConfig(const string& cfgFilePath);
+
+ /** @validates the value passed and sets the member variable
+ * @param radius : const int: The value of the variable to be set
+ * @return int : The sucess or failure of the function
+ */
+ int setWindowSize(int radius);
+
+
+ void findVicinityBoundingBox(vector<vector<float> >& inputXYCoords, float& xMin, float& yMin, float& xMax, float& yMax);
+
+ int computeLinearityAndSlope(const vector<vector<float> >& vicinity,float& linearity,float& slope);
+
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/npen.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/npen.pro
new file mode 100644
index 00000000..dacec369
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/npen/npen.pro
@@ -0,0 +1,22 @@
+LIPILIBS = ltkcommon ltkutil featureextractorcommon
+include(../../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../../util/lib \
+ ../common \
+
+HEADERS += \
+ NPen.h \
+ NPenShapeFeature.h \
+ NPenShapeFeatureExtractor.h \
+
+SOURCES += \
+ NPen.cpp \
+ NPenShapeFeature.cpp \
+ NPenShapeFeatureExtractor.cpp \
+
+win32 {
+ DEFINES += NPEN_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = NPen.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.cpp
new file mode 100644
index 00000000..81678e45
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.cpp
@@ -0,0 +1,106 @@
+/*****************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+* THE SOFTWARE.
+******************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+// pointFloat.cpp : Defines the entry point for the DLL application.
+
+#include "PointFloat.h"
+#include "PointFloatShapeFeatureExtractor.h"
+#include "LTKShapeFeatureExtractor.h"
+#include "PointFloatShapeFeature.h"
+#include "LTKErrors.h"
+
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+/***************************************************************************
+* AUTHOR : Saravanan R
+* DATE : 15-Mar-2007
+* NAME : createFeatureExtractor
+* DESCRIPTION : Creates instance of type PointFloatShapeFeatureExtractor and retuns of type
+ LTKShapeFeatureExtractor. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKShapeFeatureExtractor.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*******************************************************************************/
+int createShapeFeatureExtractor(const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ try
+ {
+ *outFeatureExtractor = new PointFloatShapeFeatureExtractor(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *outFeatureExtractor = NULL;
+
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+/****************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 15-Mar-2007
+* NAME : deleteShapeFeatureExtractor
+* DESCRIPTION : Destroy the instance by taking the address as its argument.
+* ARGUMENTS : Address of LTKShapeRecognizerFeatureExtractor instnace.
+* RETURNS : Returns 0 on Success
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*****************************************************************************/
+int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *obj)
+{
+ if ( obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+
+ return 0;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.def
new file mode 100644
index 00000000..9a185d39
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createShapeFeatureExtractor @1
+ deleteShapeFeatureExtractor @2
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.h
new file mode 100644
index 00000000..91ee5e6b
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloat.h
@@ -0,0 +1,110 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+* FILE DESCR: Definitions for PointFloat dll exporting functions.
+*
+* CONTENTS:
+*
+* AUTHOR: Vijayakumara M.
+*
+* DATE: 28-July-2005
+* CHANGE HISTORY:
+* Author Date Description
+************************************************************************/
+#ifndef __POINTFLOAT_H__
+#define __POINTFLOAT_H__
+
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the POINTFLOAT_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// POINTFLOAT_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef POINTFLOAT_EXPORTS
+#define POINTFLOAT_API __declspec(dllexport)
+#else
+#define POINTFLOAT_API __declspec(dllimport)
+#endif //ifdef POINTFLOAT_EXPORTS
+#else
+#define POINTFLOAT_API
+#endif //#ifdef _WIN32
+
+
+#include "LTKTypes.h"
+#include "LTKLoggerUtil.h"
+
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+/** @defgroup PointFloatShapeFeatureExtractor
+*@brief The PointFloatShapeFeatureExtractor
+*/
+
+/**
+* @ingroup PointFloatShapeFeatureExtractor
+* @file PointFloat.cpp
+* <p>
+* The functions exported by the DLL
+* - ::createShapeFeatureExtractor
+* - ::deleteShapeFeatureExtractor
+* - ::getCurrentVersion
+* - ::deleteShapeFeaturePtr
+*/
+
+/**
+* @brief Returns a pointer to the instance of PointFloatShapeFeatureExtractor
+*
+* <p>
+* This function is based on run-time polymorphism. It creates an instance of
+* PointFloatShapeFeatureExtractor at run-time and returns it as a pointer to the base class <i>LTKShapeFeatureExtractor</i>
+* </p>
+*
+* @param none
+*
+* @return Pointer to LTKShapeFeatureExtractor
+*/
+extern "C" POINTFLOAT_API int createShapeFeatureExtractor(
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+/**
+* @brief Deletes the feature extractor instance.
+*
+* <p>
+* This function cleans up all the memory allocations done by the feature extractor by calling it's destructor.
+* </p>
+*
+* @param featureExtractorPtr - Pointer to LTKShapeFeatureExtractor.
+*
+* @return 0 on Success
+*/
+extern "C" POINTFLOAT_API int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *featureExtractorPtr);
+
+#endif //#ifndef __POINTFLOAT_H__
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.cpp
new file mode 100644
index 00000000..02e5c9c7
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.cpp
@@ -0,0 +1,517 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 20:12:22 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 784 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+#include "PointFloatShapeFeature.h"
+#include "LTKStringUtil.h"
+#include <sstream>
+
+const string PointFloatShapeFeature::m_data_delimiter = ",";
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : Default Constructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+PointFloatShapeFeature::PointFloatShapeFeature()
+{
+}
+
+/******************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 10-Dec-2007
+* NAME : Parameterized Constructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+PointFloatShapeFeature::PointFloatShapeFeature(float inX, float inY,
+ float inSinTheta, float inCosTheta, bool inPenUp):
+m_x(inX),
+m_y(inY),
+m_sinTheta(inSinTheta),
+m_cosTheta(inCosTheta),
+m_penUp(inPenUp)
+{
+}
+
+/*****************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : Default Constructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+PointFloatShapeFeature::~PointFloatShapeFeature()
+{
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : getX
+* DESCRIPTION :
+* ARGUMENTS : none
+* RETURNS : float : x value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+float PointFloatShapeFeature::getX() const
+{
+ return m_x;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE :15-Mar-2007
+* NAME : getY
+* DESCRIPTION :
+* ARGUMENTS : none
+* RETURNS : float : y value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+float PointFloatShapeFeature::getY() const
+{
+ return m_y;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE :13-Sept-2007
+* NAME : getSinTheta
+* DESCRIPTION :
+* ARGUMENTS : none
+* RETURNS : float : sintheta value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+float PointFloatShapeFeature::getSinTheta() const
+{
+ return m_sinTheta;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE :13-Sept-2007
+* NAME : getCosTheta
+* DESCRIPTION :
+* ARGUMENTS : none
+* RETURNS : float : costheta value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+float PointFloatShapeFeature::getCosTheta() const
+{
+ return m_cosTheta;
+}
+
+/***************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE :13-Sept-2007
+* NAME : isPenUp
+* DESCRIPTION :
+* ARGUMENTS : none
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+* Balaji MNA 01-July-2009 Rename getPenUp to isPenUp
+******************************************************************************/
+bool PointFloatShapeFeature::isPenUp() const
+{
+ return m_penUp;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : setX
+* DESCRIPTION :
+* ARGUMENTS : float : x value
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void PointFloatShapeFeature::setX(float x)
+{
+ m_x = x;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : setY
+* DESCRIPTION :
+* ARGUMENTS : float : y value
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void PointFloatShapeFeature::setY(float y)
+{
+ m_y = y;
+}
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 13-Sept_2007
+* NAME : setSinTheta
+* DESCRIPTION :
+* ARGUMENTS : float : sintheta value
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void PointFloatShapeFeature::setSinTheta(float sintheta)
+{
+ m_sinTheta = sintheta;
+}
+
+/**********************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 13-Sept_2007
+* NAME : setTheta
+* DESCRIPTION :
+* ARGUMENTS : float : costheta value
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void PointFloatShapeFeature::setCosTheta(float costheta)
+{
+ m_cosTheta = costheta;
+}
+
+/**************************************************************************
+* AUTHOR : Naveen Sundar G.
+* DATE : 13-Sept_2007
+* NAME : setPenUp
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*****************************************************************************/
+void PointFloatShapeFeature::setPenUp(bool penUp)
+{
+ m_penUp = penUp;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : clone
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+LTKShapeFeaturePtr PointFloatShapeFeature::clone() const
+{
+ PointFloatShapeFeature* pointInst = new PointFloatShapeFeature();
+
+ pointInst->setX(this->getX());
+ pointInst->setY(this->getY());
+ pointInst->setSinTheta(this->getSinTheta());
+ pointInst->setCosTheta(this->getCosTheta());
+ pointInst->setPenUp(this->isPenUp());
+
+ return (LTKShapeFeaturePtr)pointInst;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : getDistance
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+void PointFloatShapeFeature::getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr,
+ float& outDistance) const
+{
+ PointFloatShapeFeature *inPointFloatFeature = (PointFloatShapeFeature*)(shapeFeaturePtr.operator ->());
+
+ float xDiff = (m_x) - inPointFloatFeature->m_x;
+
+ float yDiff = (m_y) - inPointFloatFeature->m_y;
+
+ float sinthetaDiff = (m_sinTheta) - inPointFloatFeature->m_sinTheta;
+
+ float costhetaDiff = (m_cosTheta) - inPointFloatFeature->m_cosTheta;
+
+ outDistance = ( (xDiff * xDiff) + (yDiff * yDiff) +
+ (sinthetaDiff * sinthetaDiff) + (costhetaDiff * costhetaDiff) );
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : initialize
+* DESCRIPTION : To convert the string to xy value
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+int PointFloatShapeFeature::initialize(const string& initString)
+{
+ stringVector tokens;
+
+ LTKStringUtil::tokenizeString(initString, m_data_delimiter, tokens);
+
+ //Token size must be 4
+// if(tokens.size() != 4)
+ if(tokens.size() != 5)
+ return FAILURE; //Returning an error
+
+ m_x = LTKStringUtil::convertStringToFloat(tokens[0]);
+ m_y = LTKStringUtil::convertStringToFloat(tokens[1]);
+ m_sinTheta = LTKStringUtil::convertStringToFloat(tokens[2]);
+ m_cosTheta = LTKStringUtil::convertStringToFloat(tokens[3]);
+
+ if(atoi(tokens[4].c_str()) == 1)
+ {
+ m_penUp = true;
+ }
+ else
+ {
+ m_penUp = false;
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 15-Mar-2007
+* NAME : toString
+* DESCRIPTION : To convert the points to a string
+* ARGUMENTS : string : holds the string value of xy points
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+void PointFloatShapeFeature::toString(string& strFeat) const
+{
+ ostringstream tempString;
+
+ tempString << m_x << m_data_delimiter << m_y << m_data_delimiter <<
+ m_sinTheta << m_data_delimiter << m_cosTheta <<
+ m_data_delimiter << m_penUp;
+
+ strFeat = tempString.str();
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 30-Mar-2007
+* NAME : addFeature
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+int PointFloatShapeFeature::addFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ PointFloatShapeFeature* resultFeature = new PointFloatShapeFeature();
+
+ PointFloatShapeFeature *inFeature = (PointFloatShapeFeature*)(secondFeature.operator ->());
+
+ resultFeature->setX(m_x + inFeature->getX());
+ resultFeature->setY (m_y + inFeature->getY());
+ resultFeature->setSinTheta (m_sinTheta + inFeature->getSinTheta());
+ resultFeature->setCosTheta (m_cosTheta + inFeature->getCosTheta());
+ resultFeature->setPenUp (m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 30-Mar-2007
+* NAME : subtractFeature
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+int PointFloatShapeFeature::subtractFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ PointFloatShapeFeature* resultFeature=new PointFloatShapeFeature();
+
+ PointFloatShapeFeature *inFeature = (PointFloatShapeFeature*)(secondFeature.operator ->());
+
+ resultFeature->setX (m_x - inFeature->getX());
+ resultFeature->setY (m_y - inFeature->getY());
+ resultFeature->setSinTheta (m_sinTheta - inFeature->getSinTheta());
+ resultFeature->setCosTheta (m_cosTheta - inFeature->getCosTheta());
+ resultFeature->setPenUp (m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 30-Mar-2007
+* NAME : scaleFeature
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description: Implemented Support for theta
+*************************************************************************************/
+int PointFloatShapeFeature::scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const
+{
+ PointFloatShapeFeature* resultFeature=new PointFloatShapeFeature();
+
+ resultFeature->setX (m_x * alpha);
+ resultFeature->setY (m_y * alpha);
+ resultFeature->setSinTheta (m_sinTheta * alpha);
+ resultFeature->setCosTheta (m_cosTheta * alpha);
+ resultFeature->setPenUp(m_penUp);
+
+ outResult = LTKShapeFeaturePtr(resultFeature);
+
+ return SUCCESS;
+}
+
+/***************************************************************************
+* AUTHOR : Saravanan R.
+* DATE : 30-Mar-2007
+* NAME : scaleFeature
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Naveen Sundar G. Date: 13-Sept-2007 Description:
+ Implemented Support for theta
+*****************************************************************************/
+int PointFloatShapeFeature::toFloatVector(floatVector& floatVec)
+{
+ floatVec.push_back(m_x);
+ floatVec.push_back(m_y);
+ floatVec.push_back(m_sinTheta);
+ floatVec.push_back(m_cosTheta);
+ if(m_penUp == true)
+ floatVec.push_back(1.0);
+ else
+ floatVec.push_back(0.0);
+
+ return SUCCESS;
+}
+
+/***************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 23-Apr-2008
+* NAME : initialize
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Date Description:
+
+*****************************************************************************/
+int PointFloatShapeFeature::initialize(const floatVector& initFloatVector)
+{
+ return initialize(initFloatVector.data(), initFloatVector.size());
+}
+
+int PointFloatShapeFeature::initialize(floatVector::const_pointer initFloatData, size_t dataSize)
+{
+ if (dataSize < 5)
+ {
+ return FAILURE;
+ }
+
+ m_x = *(initFloatData++);
+ m_y = *(initFloatData++);
+ m_sinTheta = *(initFloatData++);
+ m_cosTheta = *(initFloatData++);
+ m_penUp = *(initFloatData++) != 0;
+
+ return SUCCESS;
+}
+
+/***************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 23-Apr-2008
+* NAME : getFeatureDimension
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author: Date Description:
+
+*****************************************************************************/
+
+int PointFloatShapeFeature::getFeatureDimension()
+{
+ return 5;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.h
new file mode 100644
index 00000000..4e05a0ca
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeature.h
@@ -0,0 +1,199 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 20:12:22 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 784 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+#ifndef __POINTFLOATSHAPEFEATURE_H
+#define __POINTFLOATSHAPEFEATURE_H
+
+#include "LTKShapeFeature.h"
+
+
+/** @defgroup PointFloatShapeFeatureExtractor
+*/
+
+/** @ingroup PointFloatShapeFeatureExtractor
+* @brief The feature representation class for X, Y features (float)
+* @class PointFloatShapeFeature
+*
+*/
+class PointFloatShapeFeature : public LTKShapeFeature
+{
+ /** @name private data members */
+ //@{
+
+private:
+ /** @brief X value */
+ float m_x;
+
+ /** @brief Y value */
+ float m_y;
+
+ /** @brief sin theta value */
+ float m_sinTheta;
+
+ /** @brief cos theta value */
+ float m_cosTheta;
+
+ /** @brief Pen-up information */
+ bool m_penUp;
+
+ /** @brief Delimiter character */
+ static const string m_data_delimiter;
+ //@}
+
+public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+ PointFloatShapeFeature();
+
+ /** Parameterized Constructor */
+ PointFloatShapeFeature(float inX, float inY, float inSinTheta,
+ float inCosTheta, bool inPenUp);
+
+ /**
+ * Default destructor.
+ */
+ ~PointFloatShapeFeature();
+
+ /**
+ * Returns the value of class data member PointFloatShapeFeature::m_x
+ */
+ float getX() const;
+
+ /**
+ * Returns the value of PointFloatShapeFeature::m_y
+ */
+ float getY() const;
+
+ /**
+ * Returns the value of PointFloatShapeFeature::m_sinTheta
+ */
+ float getSinTheta() const;
+
+ /**
+ * Returns the value of PointFloatShapeFeature::m_cosTheta
+ */
+ float getCosTheta() const;
+
+ bool isPenUp() const;
+
+
+ /**
+ * Sets the value of PointFloatShapeFeature::m_x
+ */
+
+ void setX(float x);
+
+ /**
+ * Sets the value of PointFloatShapeFeature::m_y
+ */
+ void setY(float y);
+
+ /**
+ * Sets the value of PointFloatShapeFeature::m_sinTheta
+ */
+
+ //int setSinTheta(float y);
+ void setSinTheta(float y);
+
+
+ /**
+ * Sets the value of PointFloatShapeFeature::m_cosTheta
+ */
+ //int setCosTheta(float y);
+ void setCosTheta(float y);
+
+
+ void setPenUp(bool penUp);
+ /**
+ * @brief Initializes the PointFloatShapeFeature from the string passed as parameter.
+ *
+ * <b>Semantics</b>
+ *
+ * - Tokenize the input string on PointFloatShapeFeature::m_data_delimiter using StringTokenizer::tokenizeString
+ * - Initialize the data members of the class with the tokens returned.
+ *
+ * @param initString : string& : Reference to the initialization string.
+ *
+ * @return FAILURE : If the initalization string contains more than two tokens (after tokenizing on PointFloatShapeFeature::m_data_delimiter)
+ * @return SUCCESS : If initialization done without any errors.
+ *
+ */
+ int initialize(const string& initString);
+
+ int initialize(const floatVector& initFloatVector);
+
+ int initialize(floatVector::const_pointer initFloatData, size_t dataSize);
+
+ int toFloatVector(vector<float>& floatVec);
+
+ /**
+ * @brief Gives the string representation of the PointFloatShapeFeature instance
+ */
+ void toString(string& strFeat) const;
+ /**
+ * This method sets the value of x
+ */
+
+ LTKShapeFeaturePtr clone() const;
+
+ void getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const;
+
+
+
+ /**
+ * @brief Adds two PoinFloatShapeFeature instances.
+ *
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding pointer to PointFloatShapeFeature instance
+ *
+ * @return LTKShapeFeature* : Pointer to PointFloatShapeFeature instance holding the result of addition.
+ *
+ */
+ int addFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const ;
+
+ /**
+ * @brief Subtracts two PoinFloatShapeFeature instances.
+ *
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding pointer to PointFloatShapeFeature instance
+ *
+ * @return LTKShapeFeature* : Pointer to PointFloatShapeFeature instance holding the result of subtraction.
+ *
+ */
+ int subtractFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const ;
+
+ int scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const ;
+
+ int getFeatureDimension();
+
+};
+
+#endif
+//#ifndef __POINTFLOATSHAPEFEATURE_H
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.cpp
new file mode 100644
index 00000000..49260852
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.cpp
@@ -0,0 +1,394 @@
+/*****************************************************************************************
+ * Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+ * Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 20:12:22 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 784 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation for PointFloat Shape FeatureExtractor module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Saravanan R.
+ *
+ * DATE: March 15, 2007
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "PointFloatShapeFeatureExtractor.h"
+#include "PointFloatShapeFeature.h"
+#include "LTKTraceGroup.h"
+#include "LTKTrace.h"
+#include "LTKChannel.h"
+#include "LTKTraceFormat.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+#include "LTKPreprocDefaults.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKLoggerUtil.h"
+
+
+/**********************************************************************************
+ * AUTHOR : Naveen Sundar G
+ * DATE : 1-Oct-2007
+ * NAME : PointFloatShapeFeatureExtractor
+ * DESCRIPTION : parameterized constructor
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date
+ *************************************************************************************/
+PointFloatShapeFeatureExtractor::PointFloatShapeFeatureExtractor(
+ const LTKControlInfo& controlInfo)
+{
+ string cfgFilePath = "";
+
+ // Config file
+ if ( ! ((controlInfo.lipiRoot).empty()) &&
+ ! ((controlInfo.projectName).empty()) &&
+ ! ((controlInfo.profileName).empty()) &&
+ ! ((controlInfo.cfgFileName).empty()))
+ {
+ // construct the cfg path using project and profile name
+ cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING +
+ (controlInfo.projectName) + PROFILE_PATH_STRING +
+ (controlInfo.profileName) + SEPARATOR +
+ (controlInfo.cfgFileName) + CONFIGFILEEXT;
+ }
+ else if ( ! ((controlInfo.cfgFilePath).empty() ))
+ {
+ cfgFilePath = controlInfo.cfgFilePath;
+ }
+ else
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+
+ int returnVal = readConfig(cfgFilePath);
+
+ if (returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: PointFloatShapeFeatureExtractor::PointFloatShapeFeatureExtractor()"
+ << endl;
+
+ throw LTKException(returnVal);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "PointFloatShapeFeatureExtractor::PointFloatShapeFeatureExtractor()" << endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Naveen Sundar G
+ * DATE : 1-Oct-2007
+ * NAME : readConfig
+ * DESCRIPTION : read the config values from cfg file and set member variables
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date
+ *************************************************************************************/
+
+int PointFloatShapeFeatureExtractor::readConfig(const string& cfgFilePath)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "PointFloatShapeFeatureExtractor::readConfig()" << endl;
+
+ LTKConfigFileReader* configurableProperties = NULL;
+ string tempStringVar = "";
+
+ try
+ {
+ configurableProperties = new LTKConfigFileReader(cfgFilePath);
+ }
+
+ catch(LTKException e)
+ {
+ delete configurableProperties;
+
+ int eCode = e.getErrorCode();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << eCode <<
+ " : " << getErrorMessage(eCode) <<
+ " PointFloatShapeFeatureExtractor::readConfig" <<endl;
+
+ LTKReturnError(eCode);
+ }
+
+ delete configurableProperties;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "PointFloatShapeFeatureExtractor::readConfig()" << endl;
+ return SUCCESS;
+
+}
+
+/**************************************************************************
+ * AUTHOR : Naveen Sundar G
+ * DATE :
+ * NAME :
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date
+ ****************************************************************************/
+
+int PointFloatShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "PointFloatShapeFeatureExtractor::extractFeatures()" << endl;
+
+ PointFloatShapeFeature *featurePtr = NULL;
+ float x,y,deltax;
+ int numPoints=0; // number of pts
+ int count=0;
+ int currentStrokeSize;
+ float sintheta, costheta,sqsum;
+ int i;
+
+ int numberOfTraces = inTraceGroup.getNumTraces();
+
+ if (numberOfTraces == 0 )
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP)<<
+ " PointFloatShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+ LTKTraceVector allTraces = inTraceGroup.getAllTraces();
+ LTKTraceVector::iterator traceIter = allTraces.begin();
+ LTKTraceVector::iterator traceEnd = allTraces.end();
+
+
+ //***CONCATENTATING THE STROKES***
+ for (; traceIter != traceEnd ; ++traceIter)
+ {
+ floatVector tempxVec, tempyVec;
+
+ (*traceIter).getChannelValues("X", tempxVec);
+
+ (*traceIter).getChannelValues("Y", tempyVec);
+
+ // Number of points in the stroke
+ numPoints = numPoints + tempxVec.size();
+ }
+
+ //***THE CONCATENATED FULL STROKE***
+ floatVector xVec(numPoints);
+ floatVector yVec(numPoints);
+
+
+ traceIter = allTraces.begin();
+ traceEnd = allTraces.end();
+
+ boolVector penUp;
+ // Add the penUp here
+ for (; traceIter != traceEnd ; ++traceIter)
+ {
+ floatVector tempxVec, tempyVec;
+
+ (*traceIter).getChannelValues("X", tempxVec);
+
+ (*traceIter).getChannelValues("Y", tempyVec);
+
+ currentStrokeSize = tempxVec.size();
+
+ if (currentStrokeSize == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_TRACE << " : " << getErrorMessage(EEMPTY_TRACE) <<
+ " PointFloatShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ for( int point=0; point < currentStrokeSize ; point++ )
+ {
+ xVec[count] = tempxVec[point];
+ yVec[count] = tempyVec[point];
+ count++;
+
+ if(point == currentStrokeSize - 1 )
+ {
+ penUp.push_back(true);
+ }
+ else
+ {
+ penUp.push_back(false);
+ }
+ }
+
+ }
+ //***CONCATENTATING THE STROKES***
+
+ vector<float> theta(numPoints);
+ vector<float> delta_x(numPoints-1);
+ vector<float> delta_y(numPoints-1);
+
+ for(i=0; i<numPoints-1; ++i)
+ {
+ delta_x[i]=xVec[i+1]-xVec[i];
+ delta_y[i]=yVec[i+1]-yVec[i];
+
+ }
+
+ //Add the controlInfo here
+ sqsum = sqrt( pow(xVec[0],2)+ pow(yVec[0],2))+ EPS;
+
+ sintheta = (1+yVec[0]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
+
+ costheta = (1+xVec[0]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
+
+ featurePtr = new PointFloatShapeFeature(xVec[0],
+ yVec[0],
+ sintheta,
+ costheta,
+ penUp[0]);
+
+ outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
+ featurePtr = NULL;
+
+
+ for( i=1; i<numPoints; ++i)
+ {
+
+ //Add the controlInfo here
+
+ sqsum = sqrt(pow(delta_x[i-1],2) + pow(delta_y[i-1],2))+EPS;
+ sintheta = (1+delta_y[i-1]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
+ costheta = (1+delta_x[i-1]/sqsum)*PREPROC_DEF_NORMALIZEDSIZE/2;
+
+ featurePtr = new PointFloatShapeFeature(xVec[i],
+ yVec[i],
+ sintheta,
+ costheta,
+ penUp[i]);
+ //***POPULATING THE FEATURE VECTOR***
+ outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
+ featurePtr = NULL;
+
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "PointFloatShapeFeatureExtractor::extractFeatures()" << endl;
+
+ return SUCCESS;
+}
+
+/**************************************************************************
+ * AUTHOR : Naveen Sundar G
+ * DATE :
+ * NAME :
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date
+ ****************************************************************************/
+LTKShapeFeaturePtr PointFloatShapeFeatureExtractor::getShapeFeatureInstance()
+{
+ LTKShapeFeaturePtr tempPtr(new PointFloatShapeFeature);
+ return tempPtr;
+}
+
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : Aug-07-2007
+ * NAME : convertToTraceGroup
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int PointFloatShapeFeatureExtractor::convertFeatVecToTraceGroup(
+ const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "PointFloatShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+
+ vector<LTKChannel> channels; // channels of a trace
+
+ LTKChannel xChannel("X", DT_INT, true); // x-coordinate channel of the trace
+ LTKChannel yChannel("Y", DT_INT, true); // y-coordinate channel of the trace
+
+ //initializing the channels of the trace
+ channels.push_back(xChannel);
+ channels.push_back(yChannel);
+
+ // composing the trace format object
+ LTKTraceFormat traceFormat(channels);
+
+ vector<float> point; // a point of a trace
+
+ LTKTrace trace(traceFormat);
+ int featureVectorSize = shapeFeature.size();
+
+ for(int count=0; count < featureVectorSize; count++)
+ {
+ float Xpoint, Ypoint;
+ bool penUp;
+
+ PointFloatShapeFeature* ptr = (PointFloatShapeFeature*)(shapeFeature[count].operator ->());
+ Xpoint = ptr->getX();
+ Ypoint = ptr->getY();
+ penUp = ptr->isPenUp();
+
+
+
+ point.push_back(Xpoint);
+ point.push_back(Ypoint);
+
+ trace.addPoint(point);
+ point.clear();
+
+
+ if(penUp == true) // end of a trace, clearing the trace now
+ {
+ outTraceGroup.addTrace(trace);
+ trace.emptyTrace();
+ LTKTrace tempTrace(traceFormat);
+ trace = tempTrace;
+ }
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "PointFloatShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl;
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.h
new file mode 100644
index 00000000..59f14e20
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/PointFloatShapeFeatureExtractor.h
@@ -0,0 +1,70 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2009-07-01 16:41:37 +0530 (Wed, 01 Jul 2009) $
+ * $Revision: 783 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+#ifndef __POINTFLOATSHAPEFEATUREEXTRACTOR_H
+#define __POINTFLOATSHAPEFEATUREEXTRACTOR_H
+
+#define SUPPORTED_MIN_VERSION "4.0.0"
+#define FEATEXTR_POINTFLOAT_DEF_SIZE 10
+
+#include "LTKShapeFeatureExtractor.h"
+
+
+class PointFloatShapeFeatureExtractor : public LTKShapeFeatureExtractor
+{
+public:
+ /** @brief Constructor for the PointFloata feature extractor
+ * Gets the cfg file path from the contorInfo
+ * Reads the cfg variables and poputlates the member variables
+ * @param controlInfo: LTKControlInfo : The control information
+ * @return no return value as it is a constructor
+ */
+
+ PointFloatShapeFeatureExtractor(const LTKControlInfo& controlInfo);
+
+ int extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec);
+
+ LTKShapeFeaturePtr getShapeFeatureInstance();
+
+
+ int convertFeatVecToTraceGroup(const vector<LTKShapeFeaturePtr>& shapeFeature,
+ LTKTraceGroup& outTraceGroup);
+
+private:
+ /** @brief reads the cfg file and sets the member variables
+ * @param cfgFilePath : const string&: The path of the cfg file to be opened
+ * @return int : The sucess or failure of the function
+ */
+ //int readConfigFile(const string& cfgFilePath);
+ int readConfig(const string& cfgFilePath);
+
+};
+
+
+#endif
+//#ifndef __POINTFLOATSHAPEFEATUREEXTRACTOR_H
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/pointfloat.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/pointfloat.pro
new file mode 100644
index 00000000..39eff0ee
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/pointfloat/pointfloat.pro
@@ -0,0 +1,22 @@
+LIPILIBS = ltkcommon ltkutil featureextractorcommon
+include(../../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../../util/lib \
+ ../common \
+
+HEADERS += \
+ PointFloat.h \
+ PointFloatShapeFeature.h \
+ PointFloatShapeFeatureExtractor.h \
+
+SOURCES += \
+ PointFloat.cpp \
+ PointFloatShapeFeature.cpp \
+ PointFloatShapeFeatureExtractor.cpp \
+
+win32 {
+ DEFINES += POINTFLOAT_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = PointFloat.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.cpp
new file mode 100644
index 00000000..8484b39d
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.cpp
@@ -0,0 +1,115 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+// SubStroke.cpp : Defines the entry point for the DLL application.
+
+#include "SubStroke.h"
+#include "SubStrokeShapeFeatureExtractor.h"
+#include "LTKShapeFeatureExtractor.h"
+#include "SubStrokeShapeFeature.h"
+#include "LTKErrors.h"
+
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain(HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : createShapeFeatureExtractor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int createShapeFeatureExtractor(const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor)
+{
+ try
+ {
+ *outFeatureExtractor = new SubStrokeShapeFeatureExtractor(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *outFeatureExtractor = NULL;
+
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : deleteShapeFeatureExtractor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *obj)
+{
+ if ( obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+
+ return 0;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.def
new file mode 100644
index 00000000..c35a826e
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createShapeFeatureExtractor @1
+ deleteShapeFeatureExtractor @2 \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.h
new file mode 100644
index 00000000..125ab5ae
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStroke.h
@@ -0,0 +1,98 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+
+#ifndef __SUBSTROKE_H__
+#define __SUBSTROKE_H__
+
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the SUBSTROKE_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// SUBSTROKE_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef SUBSTROKE_EXPORTS
+#define SUBSTROKE_API __declspec(dllexport)
+#else
+#define SUBSTROKE_API __declspec(dllimport)
+#endif //ifdef SUBSTROKE_EXPORTS
+#else
+#define SUBSTROKE_API
+#endif //#ifdef _WIN32
+
+
+#include "LTKTypes.h"
+#include "LTKLoggerUtil.h"
+
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+/** @defgroup SubStrokeShapeFeatureExtractor
+*@brief The SubStrokeShapeFeatureExtractor
+*/
+
+/**
+* @ingroup SubStrokeShapeFeatureExtractor
+* @file SubStroke.cpp
+* <p>
+* The functions exported by the DLL
+* - ::createShapeFeatureExtractor
+* - ::deleteShapeFeatureExtractor
+*/
+
+/**
+* @brief Returns a pointer to the instance of SubStrokeShapeFeatureExtractor
+*
+* <p>
+* This function is based on run-time polymorphism. It creates an instance of
+* SubStrokeShapeFeatureExtractor at run-time and returns it as a pointer to the base class <i>LTKShapeFeatureExtractor</i>
+* </p>
+*
+* @param none
+*
+* @return Pointer to LTKShapeFeatureExtractor
+*/
+extern "C" SUBSTROKE_API int createShapeFeatureExtractor(
+ const LTKControlInfo& controlInfo,
+ LTKShapeFeatureExtractor** outFeatureExtractor);
+
+/**
+* @brief Deletes the feature extractor instance.
+*
+* <p>
+* This function cleans up all the memory allocations done by the feature extractor by calling it's destructor.
+* </p>
+*
+* @param featureExtractorPtr - Pointer to LTKShapeFeatureExtractor.
+*
+* @return 0 on Success
+*/
+extern "C" SUBSTROKE_API int deleteShapeFeatureExtractor(LTKShapeFeatureExtractor *featureExtractorPtr);
+
+#endif //#ifndef __SUBSTROKE_H__ \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.cpp
new file mode 100644
index 00000000..fb282d31
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.cpp
@@ -0,0 +1,675 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation for SubStrokeShapeFeature module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Tanmay Mondal
+ *
+ * DATE: February 2009
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+#include "SubStrokeShapeFeature.h"
+#include "LTKStringUtil.h"
+#include <sstream>
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : Default Constructor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+SubStrokeShapeFeature::SubStrokeShapeFeature():
+m_data_delimiter(",")
+{
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : Parameterized Constructor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+SubStrokeShapeFeature::SubStrokeShapeFeature(vector<float>& inSlopeVector,float inCgX,float inCgY,float inLength):
+m_slopeVector(inSlopeVector),
+m_xComponentOfCenterOfGravity(inCgX),
+m_yComponentOfCenterOfGravity(inCgY),
+m_subStrokeLength(inLength),
+m_data_delimiter(",")
+{
+}
+
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : Default Destructor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+SubStrokeShapeFeature::~SubStrokeShapeFeature()
+{
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : clone
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+LTKShapeFeaturePtr SubStrokeShapeFeature::clone() const
+{
+ SubStrokeShapeFeature* pointInst = new SubStrokeShapeFeature();
+
+ //set the value of the tan theta
+ vector<float> tempSlopeVector;
+
+ this->getSlopeVector(tempSlopeVector);
+
+ pointInst->setSlopeVector(tempSlopeVector);
+
+ //set the value of center of gravity
+ pointInst->setXcomponentOfCenterOfGravity(this->getXcomponentOfCenterOfGravity());
+ pointInst->setYcomponentOfCenterOfGravity(this->getYcomponentOfCenterOfGravity());
+
+ //set the value of the length
+ pointInst->setSubStrokeLength(this->getSubStrokeLength());
+
+ return (LTKShapeFeaturePtr)pointInst;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getDistance
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr,
+ float& outDistance) const
+{
+
+ float xDiff = 0.0, yDiff =0.0;
+
+ float sumSlopeDiff = 0.0;
+
+ int slopeIndex = 0;
+
+ int numSlope = 0;
+
+ float slopeDiff = 0.0, tempSlopeDiff1 = 0.0, tempSlopeDiff2 = 0.0;
+
+ float lengthDiff = 0.0;
+
+ floatVector featureVector;
+
+ SubStrokeShapeFeature *inSubStrokeFeature = (SubStrokeShapeFeature*)(shapeFeaturePtr.operator ->());
+
+ inSubStrokeFeature->getSlopeVector(featureVector);
+
+ numSlope = featureVector.size();
+
+ // feature vector dimension for each substroke is 8 (NUMBER_OF_SLOPE + 3)
+ // The constant 3 in the above corresponds to x,y coordinates of center of gravity of the substroke and its length
+
+ if(numSlope != (inSubStrokeFeature->getFeatureDimension()-3))
+ {
+ //write log
+ return; // error
+ }
+
+ // compute the distance between the slope vectors of two instances of SubStrokeShapeFeature
+ for(slopeIndex = 0; slopeIndex < numSlope; ++slopeIndex)
+ {
+ // difference between two slope components
+ tempSlopeDiff1 = fabs((m_slopeVector[slopeIndex]) - featureVector[slopeIndex]);
+
+ tempSlopeDiff2 = fabs((360.0 - tempSlopeDiff1));
+
+ // take the minimum of the above two differences to take care of the circular nature of slope function
+ if(tempSlopeDiff1 > tempSlopeDiff2)
+ slopeDiff = tempSlopeDiff2;
+ else
+ slopeDiff = tempSlopeDiff1;
+
+ sumSlopeDiff += slopeDiff;
+
+ }
+
+ // compute the distance between the center of gravity of two instances of SubStrokeShapeFeature
+ xDiff = fabs((m_xComponentOfCenterOfGravity) - inSubStrokeFeature->getXcomponentOfCenterOfGravity());
+
+ yDiff = fabs((m_yComponentOfCenterOfGravity) - inSubStrokeFeature->getYcomponentOfCenterOfGravity());
+
+ // compute the difference between the length of two instances of SubStrokeShapeFeature
+ lengthDiff = fabs((m_subStrokeLength) - inSubStrokeFeature->getSubStrokeLength());
+
+ outDistance = (sumSlopeDiff + (xDiff * xDiff) + (yDiff * yDiff) + lengthDiff);
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : initialize
+ * DESCRIPTION : initialize the feature instance from string
+ * ARGUMENTS : string: initString
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeature::initialize(const string& initString)
+{
+
+ int index;
+
+ stringVector tokens;
+
+ LTKStringUtil::tokenizeString(initString, m_data_delimiter, tokens);
+
+ int tokensSize = tokens.size();
+
+ //code for converting the string feature in to value and initialised the feature vector
+ if(tokensSize != getFeatureDimension())
+ {
+ //write log
+ //invalide size of feature vector
+ return FAILURE; //returning an error
+ }
+
+ for( index = 0; index < tokensSize - 3; ++index )
+ {
+ m_slopeVector.push_back(LTKStringUtil::convertStringToFloat(tokens[index]));
+ }
+
+ m_xComponentOfCenterOfGravity = LTKStringUtil::convertStringToFloat(tokens[index]);
+
+ m_yComponentOfCenterOfGravity = LTKStringUtil::convertStringToFloat(tokens[index+1]);
+
+ m_subStrokeLength = LTKStringUtil::convertStringToFloat(tokens[index+2]);
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : initialize
+ * DESCRIPTION : initialize the feature instance
+ * ARGUMENTS : floatVector: initFloatVector
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeature::initialize(const floatVector& initFloatVector)
+{
+
+ int index;
+
+ int vectorSize = initFloatVector.size();
+
+ if(vectorSize != getFeatureDimension() )
+ {
+ //write log
+ //invalide size of feature vector
+ return FAILURE; //returning an error
+ }
+
+ for( index = 0; index < vectorSize - 3; ++index )
+ {
+ m_slopeVector.push_back(initFloatVector[index]);
+ }
+
+ m_xComponentOfCenterOfGravity = initFloatVector[index];
+
+ m_yComponentOfCenterOfGravity = initFloatVector[index+1];
+
+ m_subStrokeLength = initFloatVector[index+2];
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : toFloatVector
+ * DESCRIPTION : To convert feature to a float vector
+ * ARGUMENTS : vector<float>: holds the floating point value of feature
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeature::toFloatVector(vector<float>& outFloatVec)
+{
+
+ int slopeIndex;
+
+ int numSlope = m_slopeVector.size();
+
+ if(numSlope != (getFeatureDimension() - 3))
+ {
+ //write log
+ //invalide size of angle vector
+ return FAILURE; //returning an error
+ }
+
+ for( slopeIndex = 0; slopeIndex < numSlope; ++slopeIndex)
+ {
+ outFloatVec.push_back(m_slopeVector[slopeIndex]);
+ }
+
+ outFloatVec.push_back(m_xComponentOfCenterOfGravity);
+
+ outFloatVec.push_back(m_yComponentOfCenterOfGravity);
+
+ outFloatVec.push_back(m_subStrokeLength);
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : toString
+ * DESCRIPTION : To convert the feature to a string
+ * ARGUMENTS : string : holds the string value of feature
+ * RETURNS : NONE
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::toString(string& outStrFeat) const
+{
+
+ ostringstream tempString;
+
+ int slopeIndex;
+
+ int numSlope = m_slopeVector.size();
+
+ if(numSlope != NUMBER_OF_SLOPE)
+ {
+ //write log
+ //invalide size of angle vector
+ return; //returning an error
+ }
+
+ //convert the value of the feture vector to string
+ for( slopeIndex = 0; slopeIndex < numSlope; slopeIndex++)
+ {
+ tempString << m_slopeVector[slopeIndex] << m_data_delimiter;
+ }
+
+ tempString << m_xComponentOfCenterOfGravity << m_data_delimiter
+ << m_yComponentOfCenterOfGravity << m_data_delimiter
+ << m_subStrokeLength;
+
+
+ outStrFeat = tempString.str();
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getSlopeVector
+ * DESCRIPTION :
+ * ARGUMENTS : vector<float>: outSlopeVector
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::getSlopeVector(vector<float>& outSlopeVector) const
+{
+ outSlopeVector = m_slopeVector;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getSubStrokeLength
+ * DESCRIPTION : Ratio of the length and normalised height
+ * ARGUMENTS : none
+ * RETURNS : float: m_subStrokeLength
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+float SubStrokeShapeFeature::getSubStrokeLength() const
+{
+ return m_subStrokeLength;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getXcomponentOfCenterOfGravity
+ * DESCRIPTION : X co-ordinate of CG
+ * ARGUMENTS : none
+ * RETURNS : float: m_xComponentOfCenterOfGravity
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+float SubStrokeShapeFeature::getXcomponentOfCenterOfGravity() const
+{
+ return m_xComponentOfCenterOfGravity;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getYcomponentOfCenterOfGravity
+ * DESCRIPTION : Y co-ordinate of CG
+ * ARGUMENTS : none
+ * RETURNS : float: m_yComponentOfCenterOfGravity
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+float SubStrokeShapeFeature::getYcomponentOfCenterOfGravity() const
+{
+ return m_yComponentOfCenterOfGravity;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : setSlopeVector
+ * DESCRIPTION : set the slope vector of substroke
+ * ARGUMENTS : vector<float>: inSlopeVector
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::setSlopeVector(const vector<float>& inSlopeVector)
+{
+ m_slopeVector = inSlopeVector;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : setSubStrokeLength
+ * DESCRIPTION : set the length of the substroke
+ * ARGUMENTS : float: length
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::setSubStrokeLength(float inSubStrokeLength)
+{
+ m_subStrokeLength = inSubStrokeLength;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : setXcomponentOfCenterOfGravity
+ * DESCRIPTION :
+ * ARGUMENTS : float: x value
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::setXcomponentOfCenterOfGravity(float inX)
+{
+ m_xComponentOfCenterOfGravity = inX;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : setYcomponentOfCenterOfGravity
+ * DESCRIPTION :
+ * ARGUMENTS : float: y value
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+void SubStrokeShapeFeature::setYcomponentOfCenterOfGravity(float inY)
+{
+ m_yComponentOfCenterOfGravity = inY;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : addFeature
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeature::addFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : subtractFeature
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeature::subtractFeature(const LTKShapeFeaturePtr& secondFeature,
+ LTKShapeFeaturePtr& outResult ) const
+{
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : scaleFeature
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeature::scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const
+{
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getFeatureDimension
+ * DESCRIPTION :
+ * ARGUMENTS : none
+ * RETURNS : int: dimension of the feature
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeature::getFeatureDimension()
+{
+ // The constant 3 in the above corresponds to x,y coordinates of center of gravity of the substroke and its length
+ return (NUMBER_OF_SLOPE + 3);
+}
+/**********************************************************************************
+* AUTHOR : Balaji MNA.
+* DATE : 01-July-2009
+* NAME : isPenUp
+* DESCRIPTION : Get method for the penUp
+* ARGUMENTS : none
+* RETURNS : The PenUp value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+bool SubStrokeShapeFeature::isPenUp() const
+{
+ return 0;
+
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.h
new file mode 100644
index 00000000..791ed9a7
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeature.h
@@ -0,0 +1,200 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Definitions for SubStrokeShapeFeature module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Tanmay Mondal
+ *
+ * DATE: February 2009
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+#ifndef __SUBSTROKESHAPEFEATURE_H
+#define __SUBSTROKESHAPEFEATURE_H
+
+#include "LTKShapeFeature.h"
+
+#define NUMBER_OF_SLOPE 5
+
+
+class SubStrokeShapeFeature : public LTKShapeFeature
+{
+ /** @name private data members */
+ //@{
+
+private:
+
+ /** @brief slope value
+ m_slopeVector slop(five angle) extracted from one substrokes*/
+ vector<float> m_slopeVector;
+
+ /** @brief x value
+ m_xComponentOfCenterOfGravity, normalised x - value (by width) of the center of gravity of substrokes*/
+ float m_xComponentOfCenterOfGravity;
+
+ /**@brief y value
+ m_yComponentOfCenterOfGravity, normalised y - value (by height) of the center of gravity of substrokes*/
+ float m_yComponentOfCenterOfGravity;
+
+ /** @brief length value
+ m_subStrokeLength, this is the ratio of the total length of the substrokes and the normalised height of the character*/
+ float m_subStrokeLength;
+
+ /** @brief Delimiter character */
+ string m_data_delimiter;
+ //@}
+
+public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ /**
+ * Default Constructor.
+ */
+ SubStrokeShapeFeature();
+
+ /** Parameterized Constructor */
+ SubStrokeShapeFeature(vector<float>& inSlopeVector,float inCgX,float inCgY,float inLength);
+
+ /**
+ * Default destructor.
+ */
+ ~SubStrokeShapeFeature();
+
+ /**
+ * Returns the value of SubStrokeShapeFeature:: m_slopeVector
+ */
+ void getSlopeVector(vector<float>& outSlopeVector) const;
+
+ /**
+ * Returns the value of SubStrokeShapeFeature::m_subStrokeLength
+ */
+ float getSubStrokeLength() const;
+
+ /**
+ * Returns the value of SubStrokeShapeFeature::m_xComponentOfCenterOfGravity
+ */
+ float getXcomponentOfCenterOfGravity() const;
+
+ /**
+ * Returns the value of SubStrokeShapeFeature::m_yComponentOfCenterOfGravity
+ */
+ float getYcomponentOfCenterOfGravity() const;
+
+ /**
+ * Sets the value of SubStrokeShapeFeature::m_slopeVector
+ */
+ void setSlopeVector(const vector<float>& inSlopeVector);
+
+ /**
+ * Set the value of SubStrokeShapeFeature::m_subStrokeLength
+ */
+ void setSubStrokeLength(float inSubStrokeLength);
+
+ /**
+ * Set the value of SubStrokeShapeFeature::m_xComponentOfCenterOfGravity
+ */
+ void setXcomponentOfCenterOfGravity(float inX);
+
+ /**
+ * Set the value of SubStrokeShapeFeature::m_yComponentOfCenterOfGravity
+ */
+ void setYcomponentOfCenterOfGravity(float inY);
+
+
+ /**
+ * @brief Initializes the SubStrokeShapeFeature from the string passed as parameter.
+ *
+ * <b>Semantics</b>
+ *
+ * - Tokenize the input string on SubStrokeShapeFeature::m_data_delimiter using StringTokenizer::tokenizeString
+ * - Initialize the data members of the class with the tokens returned.
+ *
+ * @param initString : string& : Reference to the initialization string.
+ *
+ * @return FAILURE : If the initalization string contains more than two tokens (after tokenizing on AngleShapeFeature::m_data_delimiter)
+ * @return SUCCESS : If initialization done without any errors.
+ *
+ */
+ int initialize(const string& initString);
+
+ int initialize(const floatVector& initFloatVector);
+
+ /**
+ * @brief Gives the floating point representation of the SubStrokeShapeFeature instance
+ */
+ int toFloatVector(vector<float>& outFloatVec);
+
+ /**
+ * @brief Gives the string representation of the SubStrokeShapeFeature instance
+ */
+ void toString(string& outStrFeat) const;
+
+
+ LTKShapeFeaturePtr clone() const;
+
+ /**
+ * @brief Gives the distance between two SubStrokeShapeFeature instance
+ */
+ void getDistance(const LTKShapeFeaturePtr& shapeFeaturePtr, float& outDistance) const;
+
+ /**
+ * @brief Adds two SubStrokeShapeFeature instances.
+ *
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding pointer to SubStrokeShapeFeature instance
+ *
+ * @return LTKShapeFeature* : Pointer to SubStrokeShapeFeature instance holding the result of addition.
+ *
+ */
+ int addFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const ;
+
+ /**
+ * @brief Subtracts two SubStrokeShapeFeature instances.
+ *
+ * @param secondFeature : LTKShapeFeature* : Base class pointer holding pointer to SubStrokeShapeFeature instance
+ *
+ * @return LTKShapeFeature* : Pointer to SubStrokeShapeFeature instance holding the result of subtraction.
+ *
+ */
+ int subtractFeature(const LTKShapeFeaturePtr& secondFeature, LTKShapeFeaturePtr& outResult ) const ;
+
+ int scaleFeature(float alpha, LTKShapeFeaturePtr& outResult) const ;
+
+ int getFeatureDimension();
+
+ /**
+ * Returns the value of the class data member SubStrokeShapeFeature::m_penUp
+ */
+ bool isPenUp() const;
+};
+
+#endif //#ifndef __SUBSTROKESHAPEFEATURE_H
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.cpp
new file mode 100644
index 00000000..87e0cd05
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.cpp
@@ -0,0 +1,1035 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation for SubStroke feature extractor module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Tanmay Mondal
+ *
+ * DATE: February 2009
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "SubStrokeShapeFeatureExtractor.h"
+#include "SubStrokeShapeFeature.h"
+#include "LTKTraceGroup.h"
+#include "LTKTrace.h"
+#include "LTKChannel.h"
+#include "LTKTraceFormat.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+#include "LTKPreprocDefaults.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKLoggerUtil.h"
+
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : SubStrokeShapeFeatureExtractor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+SubStrokeShapeFeatureExtractor::SubStrokeShapeFeatureExtractor(const LTKControlInfo& controlInfo)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::SubStrokeShapeFeatureExtractor()" << endl;
+
+ string cfgFilePath = "";
+
+ // Config file
+ if ( ! ((controlInfo.lipiRoot).empty()) &&
+ ! ((controlInfo.projectName).empty()) &&
+ ! ((controlInfo.profileName).empty()) &&
+ ! ((controlInfo.cfgFileName).empty()))
+ {
+ cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING +
+ (controlInfo.projectName) + PROFILE_PATH_STRING +
+ (controlInfo.profileName) + SEPARATOR +
+ (controlInfo.cfgFileName) + CONFIGFILEEXT;
+ }
+ else if ( ! ((controlInfo.cfgFilePath).empty() ))
+ {
+ cfgFilePath = controlInfo.cfgFilePath;
+ }
+ else
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::SubStrokeShapeFeatureExtractor()" << endl;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getShapeFeatureInstance
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+LTKShapeFeaturePtr SubStrokeShapeFeatureExtractor::getShapeFeatureInstance()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::getShapeFeatureInstance()" << endl;
+
+ LTKShapeFeaturePtr tempPtr(new SubStrokeShapeFeature);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::getShapeFeatureInstance()" << endl;
+
+ return tempPtr;
+}
+
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : extractFeatures
+ * DESCRIPTION : calculate the feature of the Ink file
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::extractFeatures()" << endl;
+
+ int numberOfTraces = inTraceGroup.getNumTraces();
+
+ //validating inTraceGroup
+ if (numberOfTraces == 0 )
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP)<<
+ " SubStrokeShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+ SubStrokeShapeFeature *featurePtr = NULL;
+
+ int numberOfSubstrokes = 0; // number of substrokes from a trace group
+
+ int slopeIndex = 0; // index of the point
+
+ int totalNumberOfSlopeValues = 0; // total number of slope values for input tracegroup
+
+ int lengthIndex=0; // index of the substroke length vector
+
+ int cgIndex = 0; // index of the center of gravity vector
+
+ float maxX=0.0,maxY=0.0,minX=0.0,minY=0.0;
+
+ float subStokeLength = 0.0; // length of one substroke
+
+ float centerOfGravityX = 0.0; // x component of center of gravity of one substroke
+
+ float centerOfGravityY = 0.0; // y component of center of gravity of one substroke
+
+ vector<float> subStrokeSlopeVector; // slope values obtained from all the substrokes
+
+ vector<float> subStrokeLengthVector; // lengths of all substrokes
+
+ vector<float> subStrokeCenterOfGravityVector; // center of gravity of all substrokes
+
+ vector<float> tempSlope; // slope values of one substroke
+
+ vector<struct subStrokePoint> subStrokeVec; // store all the sub-strokes
+
+ // extract the substrokes from input trace group, and populate subStrokeVec
+ int errorCode = extractSubStrokesFromInk(inTraceGroup, subStrokeVec);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ // compute the features from each substroke in subStrokeVec
+ errorCode = extractFeaturesFromSubStroke(subStrokeVec,subStrokeSlopeVector,subStrokeLengthVector,subStrokeCenterOfGravityVector);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ inTraceGroup.getBoundingBox(minX,minY,maxX,maxY);
+
+ //computing size of subStrokeSlopeVector
+ totalNumberOfSlopeValues = subStrokeSlopeVector.size();
+
+ if(totalNumberOfSlopeValues == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_SLOPE_VECTOR << " : " << getErrorMessage(EEMPTY_SLOPE_VECTOR)<<
+ " SubStrokeShapeFeatureExtractor::extractFeatures" <<endl;
+
+ LTKReturnError(EEMPTY_SLOPE_VECTOR);
+ }
+
+
+ //populating outFeatureVec with the features computed
+ for(slopeIndex=0; slopeIndex < totalNumberOfSlopeValues; ++slopeIndex)
+ {
+ if(subStrokeSlopeVector.at(slopeIndex) == SUBSTROKES_ANGLE_DELIMITER)
+ {
+ if(tempSlope.size() != NUMBER_OF_SLOPE)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_SLOPE_VECTOR_DIMENSION << " : " << getErrorMessage(EINVALID_SLOPE_VECTOR_DIMENSION)<<
+ " SubStrokeShapeFeatureExtractor::extractFeatures" <<endl;
+
+ return FAILURE;
+ }
+
+ centerOfGravityX = ((subStrokeCenterOfGravityVector.at(cgIndex) / (maxX - minX)) * 100.0);
+
+ centerOfGravityY = ((subStrokeCenterOfGravityVector.at((cgIndex + 1)) / (maxY - minY)) * 100.0);
+
+ subStokeLength = ((subStrokeLengthVector.at(lengthIndex) / (maxY - minY)) * 100.0);
+
+ featurePtr = new SubStrokeShapeFeature(tempSlope,centerOfGravityX ,centerOfGravityY,subStokeLength);
+
+ //***FEATURE VECTOR***
+
+ outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr));
+
+ featurePtr = NULL;
+
+ ++numberOfSubstrokes;
+
+ tempSlope.clear();
+
+ ++lengthIndex;
+
+ cgIndex += 2;
+
+ continue;
+ }
+ tempSlope.push_back(subStrokeSlopeVector.at(slopeIndex));
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::extractFeatures()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : computeSlope
+ * DESCRIPTION : calculate slope of the line joining given two points
+ * ARGUMENTS :
+ * RETURNS : float
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeatureExtractor::computeSlope(const float inDeltaX, const float inDeltaY, float& outSlope)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::computeSlope()" << endl;
+
+ outSlope = -1.0;
+
+ if(inDeltaX == 0.0)
+ {
+ if(inDeltaY > 0.0)
+ {
+ outSlope = 90.0;
+ }
+ if(inDeltaY < 0.0)
+ {
+ outSlope = 270.0;
+ }
+ if(inDeltaY == 0.0)
+ {
+ outSlope = 0.0;
+ }
+ }
+
+ if(inDeltaX > 0.0)
+ {
+ outSlope = (((atan(inDeltaY/inDeltaX)) * PI_DEGREE) / PI);
+
+ if(outSlope < 0.0)
+ {
+ outSlope += (2 * PI_DEGREE);
+ }
+ }
+
+ if(inDeltaX < 0.0)
+ {
+ outSlope = (((atan(inDeltaY/inDeltaX)) * PI_DEGREE) / PI);
+
+ outSlope += PI_DEGREE;
+ }
+
+ if(outSlope < 0.0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_SLOPE << " : " << getErrorMessage(EINVALID_SLOPE)<<
+ " SubStrokeShapeFeatureExtractor::computeSlope" <<endl;
+
+ LTKReturnError(EINVALID_SLOPE);
+ }
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::computeSlope()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : extractSubStrokesFromInk
+ * DESCRIPTION : extract substroke from the Ink
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk(const LTKTraceGroup& inTraceGroup, vector<struct subStrokePoint>& outSubStrokeVector)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk()" << endl;
+
+ int numberOfTraces = inTraceGroup.getNumTraces();
+
+ if (numberOfTraces == 0 )
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP)<<
+ " SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+ int errorCode = -1;
+
+ int dimension = 0; // stores the number of points in each trace of the inTraceGroup
+
+ int landMarkPoint = 0; // first point of each sub-stroke
+
+ float landMarkSlope = 0.0; // slope of the line joining the land mark point and the following point
+
+ float nextSlope = 0.0; // slope of the line joining the consicutive two points
+
+ struct subStrokePoint tempSubStroke; // stores sub-stroke
+
+ vector<struct subStrokePoint> subStrokeVec; // stores all the sub-strokes
+
+ vector<float> slopeVector; // stores the angle made with x-axis for each point of trace
+
+ bool segment; // true if stroke segment into substroke
+
+ LTKTraceVector allTraces = inTraceGroup.getAllTraces();
+
+ LTKTraceVector::iterator traceIter = allTraces.begin();
+ LTKTraceVector::iterator traceEnd = allTraces.end();
+
+ // Segmenting inTraceGroup into substrokes
+ for (; traceIter != traceEnd ; ++traceIter)
+ {
+ floatVector tempxVec, tempyVec;
+
+ //compute all the slope values from points on the trace
+ if( (errorCode = getSlopeFromTrace(*traceIter,slopeVector)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ // computing total number of points present in a trace
+ dimension = (*traceIter).getNumberOfPoints();
+
+ // Validating the slopeVector, its size should be equal to one less than number of points in trace
+ if((dimension-1) != slopeVector.size())
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_SLOPE_VECTOR_DIMENSION << " : " << getErrorMessage(EINVALID_SLOPE_VECTOR_DIMENSION)<<
+ " SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk" <<endl;
+
+ LTKReturnError(EINVALID_SLOPE_VECTOR_DIMENSION);
+ }
+
+ (*traceIter).getChannelValues("X", tempxVec);
+
+ (*traceIter).getChannelValues("Y", tempyVec);
+
+ // initialised landmark point for next stroke, assume that the first point is
+ // landmark point for every stroke
+ landMarkPoint = 0;
+
+
+ int pointIndex = 0;
+ for( pointIndex = 0; pointIndex < (dimension - 1); ++pointIndex)
+ {
+
+ //for the first point in the trace, landMarkSlope and
+ //nextSlope will be the same
+ landMarkSlope = slopeVector[landMarkPoint];
+
+ nextSlope = slopeVector[pointIndex];
+
+ //check of the trace can be segmented at the current point
+ if( (errorCode = canSegmentStrokes(landMarkSlope,nextSlope, segment)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if( segment )
+ {
+ // Segment the stroke into substroke
+ outSubStrokeVector[outSubStrokeVector.size() - 1].penUp = true;
+
+ // set new landmark point for next substrokes of stroke
+ landMarkPoint = pointIndex;
+
+ } // end if ( segment )
+
+ //substrokes continue
+ tempSubStroke.X = tempxVec[pointIndex];
+ tempSubStroke.Y = tempyVec[pointIndex];
+ tempSubStroke.penUp = false;
+
+ outSubStrokeVector.push_back(tempSubStroke);
+
+
+ } // end for
+
+ // terminal point of a stroke
+ tempSubStroke.X = tempxVec[pointIndex];
+ tempSubStroke.Y = tempyVec[pointIndex];
+ tempSubStroke.penUp = true;
+
+ outSubStrokeVector.push_back(tempSubStroke);
+
+ } // end traceItr
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::extractSubStrokesFromInk()" << endl;
+
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : extractFeatureFromSubStroke
+ * DESCRIPTION :
+ * ARGUMENTS : extract feature vector of dimension (NUMBER_OF_THETA+3) from a given substroke
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+ int SubStrokeShapeFeatureExtractor::extractFeaturesFromSubStroke(const vector<struct subStrokePoint>& inSubStrokeVector, vector<float>& outSlope, vector<float>& outLength, vector<float>& outCenterOfGravity)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::extractFeatureFromSubStroke()" << endl;
+
+ int numSubStrokesPoints = 0;
+
+ //total number of points present in all substrokes
+ numSubStrokesPoints = inSubStrokeVector.size();
+
+ //validating inSubStrokeVector
+ if( numSubStrokesPoints <= 0 )
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ ENO_SUBSTROKE << " : " << getErrorMessage(ENO_SUBSTROKE)<<
+ " SubStrokeShapeFeatureExtractor::extractFeaturesFromSubStroke" <<endl;
+
+ LTKReturnError(ENO_SUBSTROKE);
+ }
+
+ int ptIndex = 0; // index of point in a trace
+
+ int pointIndex = 0; // counter variable to loop over the points in a trace
+
+ int currentPointIndex =0; // index of the current point
+
+ int startIndxOfSubStrokes = 0; // starting index of the substroke
+
+ float x = 0.0; // value of x-coordinate
+
+ float y = 0.0; // value of y-coordinate
+
+ float slope = 0.0; // store slope value
+
+ float xDiff = 0.0; // difference in x-direction
+
+ float yDiff = 0.0; // difference in y-direction
+
+ float xTemp = 0.0; // temporary variable for x-coordinate
+
+ float yTemp = 0.0; // temporary variable for y-coordinate
+
+ float unitLength = 0.0; // length of each substroke after resampling
+
+ float pointDistance = 0.0; // distance detween two consecutive point
+
+ float residualDistance = 0.0; // distance between the last resampled point and the next original sample point
+
+ float cumulativeDistance = 0.0; // sum of distances between consecutive points
+
+ float segmentRatioLeft = 0.0, segmentRatioRight = 0.0; // ratio for segmenting the line joining two points
+
+ float dx = 0.0, dy = 0.0;
+
+ floatVector distanceVec; // vector to store distances between points
+
+ struct subStrokePoint tempStroke;
+
+ //vector to store all the substrokes
+ vector<struct subStrokePoint> subStrokeVec;
+
+ //*************************************************************************//
+ // represent each extracted substroke from ink by six equidistant points
+ //*************************************************************************//
+ for(int ptIdx = 0; ptIdx < numSubStrokesPoints; ++ptIdx)
+ {
+ if(inSubStrokeVector[ptIdx].penUp)
+ {
+ // ignore substrokes whose length are less than thresold value
+ if(unitLength < SUBSTROKES_LENGTH_REJECT_THRESHOLD)
+ {
+ // initialised for next substroke
+ unitLength = 0.0;
+
+ residualDistance = 0.0;
+
+ ptIndex = 0;
+
+ distanceVec.clear();
+
+ //starting index of the next substroke
+ startIndxOfSubStrokes = ptIdx+1;
+
+ continue;
+ }
+
+ // length of the extracted sub-strokes(curve length)
+ outLength.push_back(unitLength);
+
+ // dividing to get NUMBER_OF_SLOPE number of points on each substroke
+ unitLength /= (NUMBER_OF_SLOPE);
+
+ // adding x of first point
+ x = inSubStrokeVector[startIndxOfSubStrokes].X;
+
+ // adding y of first point
+ y = inSubStrokeVector[startIndxOfSubStrokes].Y;
+
+ tempStroke.X = x;
+ tempStroke.Y = y;
+ tempStroke.penUp = false;
+
+ // pushing back the first point to subStrokeVec
+ subStrokeVec.push_back(tempStroke);
+
+ // Genareting four equidistant points
+ for(pointIndex = 1; pointIndex < (NUMBER_OF_SLOPE); ++pointIndex)
+ {
+ cumulativeDistance = residualDistance;
+
+ while(cumulativeDistance < unitLength)
+ {
+ cumulativeDistance += distanceVec.at(ptIndex++);
+
+ if(ptIndex == 1)
+ {
+ currentPointIndex = (startIndxOfSubStrokes + ptIndex);
+ }
+ else
+ {
+ currentPointIndex++;
+ }
+ }
+
+ if(ptIndex < 1) ptIndex = 1;
+
+ segmentRatioRight = cumulativeDistance - unitLength;
+
+ segmentRatioLeft = distanceVec.at(ptIndex -1) - segmentRatioRight;
+
+ //interpolating to get equidistant points
+ if( fabs(segmentRatioLeft+segmentRatioRight) > EPS)
+ {
+ xTemp = (segmentRatioLeft* inSubStrokeVector[currentPointIndex].X + segmentRatioRight* inSubStrokeVector[currentPointIndex - 1].X)/(segmentRatioLeft+segmentRatioRight);
+
+ yTemp = (segmentRatioLeft* inSubStrokeVector[currentPointIndex].Y + segmentRatioRight* inSubStrokeVector[currentPointIndex - 1].Y)/(segmentRatioLeft+segmentRatioRight);
+ }
+ else
+ {
+ xTemp = inSubStrokeVector[currentPointIndex].X;
+
+ yTemp = inSubStrokeVector[currentPointIndex].Y;
+ }
+
+ tempStroke.X = xTemp;
+ tempStroke.Y = yTemp;
+ tempStroke.penUp = false;
+
+ subStrokeVec.push_back(tempStroke);
+
+ residualDistance = segmentRatioRight;
+ }
+
+ // adding x of the last point of the substroke
+ x = inSubStrokeVector[ptIdx].X;
+
+ // adding y of the last point of the substroke
+ y = inSubStrokeVector[ptIdx].Y;
+
+ tempStroke.X = x;
+ tempStroke.Y = y;
+ tempStroke.penUp = true;
+
+ subStrokeVec.push_back(tempStroke);
+
+ // initialised for next substroke
+ unitLength = 0.0;
+
+ residualDistance = 0.0;
+
+ ptIndex = 0;
+
+ distanceVec.clear();
+
+ //starting index of the next substroke
+ startIndxOfSubStrokes = ptIdx+1;
+ }
+ else
+ {
+
+ xDiff = (inSubStrokeVector[ptIdx].X - inSubStrokeVector[ptIdx + 1].X);
+
+ yDiff = (inSubStrokeVector[ptIdx].Y - inSubStrokeVector[ptIdx + 1].Y);
+
+ //distance between points.
+ pointDistance = (float) (sqrt(xDiff*xDiff + yDiff*yDiff));
+
+ // finding the length of a substroke.
+ unitLength += pointDistance;
+
+ //storing distances between every two consecutive points in a substroke.
+ distanceVec.push_back(pointDistance);
+ }
+ }
+
+
+ //************************************************************************************************//
+ // compute the feature vector for each substroke after representing them by six equidistant points
+ //************************************************************************************************//
+
+ // total number of points in all substrokes after genarating equidistant points
+ numSubStrokesPoints = 0;
+
+ numSubStrokesPoints = subStrokeVec.size();
+
+ if( numSubStrokesPoints <= 0 )
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ ENO_SUBSTROKE << " : " << getErrorMessage(ENO_SUBSTROKE)<<
+ " SubStrokeShapeFeatureExtractor::extractFeaturesFromSubStroke" <<endl;
+
+ LTKReturnError(ENO_SUBSTROKE);
+ }
+
+
+ int errorCode = -1;
+
+ float sumOfX = 0.0;
+ float sumOfY = 0.0;
+
+ //computing slopes and center of gravity values from the equidistant points extracted from each substroke
+ for(pointIndex = 0; pointIndex < numSubStrokesPoints; ++pointIndex)
+ {
+ if(!subStrokeVec[pointIndex].penUp)
+ {
+
+ // Compute slope of line joining consecutive points in a substrokes
+ dx = (subStrokeVec[pointIndex + 1].X - subStrokeVec[pointIndex].X);
+ dy = (subStrokeVec[pointIndex + 1].Y - subStrokeVec[pointIndex].Y);
+
+ if( (errorCode = computeSlope(dx,dy,slope)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::extractFeaturesFromSubStroke" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ outSlope.push_back(slope);
+
+ sumOfX += subStrokeVec[pointIndex].X;
+
+ sumOfY += subStrokeVec[pointIndex].Y;
+
+ }
+ else
+ {
+ int div = (NUMBER_OF_SLOPE + 1);
+
+ sumOfX += subStrokeVec[pointIndex].X;
+
+ sumOfY += subStrokeVec[pointIndex].Y;
+
+ sumOfX = sumOfX / (float)div;
+
+ sumOfY = sumOfY / (float)div;
+
+ outCenterOfGravity.push_back(sumOfX);
+
+ outCenterOfGravity.push_back(sumOfY);
+
+ outSlope.push_back(SUBSTROKES_ANGLE_DELIMITER);
+
+ sumOfX = 0.0;
+
+ sumOfY = 0.0;
+
+ }
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::extractFeatureFromSubStroke()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getDirectionCode
+ * DESCRIPTION : quantize the slope
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+ int SubStrokeShapeFeatureExtractor::getDirectionCode(const float inSlope, int& outDirectionCode)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::getDirectionCode()" << endl;
+
+ //Validating inSlope
+ if(inSlope < 0.0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_SLOPE << " : " << getErrorMessage(EINVALID_SLOPE)<<
+ " SubStrokeShapeFeatureExtractor::getDirectionCode" <<endl;
+
+ LTKReturnError(EINVALID_SLOPE);
+ }
+
+ outDirectionCode = 0;
+
+ // return the octant value as slope value
+
+ if((inSlope< ANGLE_HIGHER_LIMIT_1) || (inSlope >= ANGLE_HIGHER_LIMIT_8))
+ {
+ outDirectionCode = DIRECTION_CODE_EAST;
+ }
+
+ else if((inSlope < ANGLE_HIGHER_LIMIT_2) && (inSlope >=ANGLE_HIGHER_LIMIT_1))
+ {
+ outDirectionCode = DIRECTION_CODE_NORTH_EAST;
+ }
+
+ else if(((inSlope >= ANGLE_HIGHER_LIMIT_2) && (inSlope < ANGLE_HIGHER_LIMIT_3)) )
+ {
+ outDirectionCode = DIRECTION_CODE_NORTH;
+ }
+
+ else if( (inSlope < ANGLE_HIGHER_LIMIT_4 ) && (inSlope >= ANGLE_HIGHER_LIMIT_3))
+ {
+ outDirectionCode = DIRECTION_CODE_NORTH_WEST;
+ }
+
+ else if((inSlope >= ANGLE_HIGHER_LIMIT_4) && (inSlope < ANGLE_HIGHER_LIMIT_5))
+ {
+ outDirectionCode = DIRECTION_CODE_WEST;
+ }
+
+ else if((inSlope >= ANGLE_HIGHER_LIMIT_5) && (inSlope < ANGLE_HIGHER_LIMIT_6))
+ {
+ outDirectionCode = DIRECTION_CODE_SOUTH_WEST;
+ }
+
+ else if(((inSlope >= ANGLE_HIGHER_LIMIT_6) && (inSlope < ANGLE_HIGHER_LIMIT_7)))
+ {
+ outDirectionCode = DIRECTION_CODE_SOUTH;
+ }
+
+ else if((inSlope >= ANGLE_HIGHER_LIMIT_7) && (inSlope < ANGLE_HIGHER_LIMIT_8))
+ {
+ outDirectionCode = DIRECTION_CODE_SOUTH_EAST;
+ }
+
+ if(outDirectionCode == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_DIRECTION_CODE << " : " <<
+ getErrorMessage(EINVALID_DIRECTION_CODE)<<
+ " SubStrokeShapeFeatureExtractor::getDirectionCode" <<endl;
+
+ LTKReturnError(EINVALID_DIRECTION_CODE);;
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::getDirectionCode()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : canSegmentStrokes
+ * DESCRIPTION : decision is taken towards dividing a stroke into substroke
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeatureExtractor::canSegmentStrokes(const float inFirstSlope, const float inSecondSlope, bool& outSegment)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::canSegmentStrokes()" << endl;
+
+ //Validating slope values
+ if(inFirstSlope < 0.0 || inSecondSlope < 0.0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EINVALID_SLOPE << " : " << getErrorMessage(EINVALID_SLOPE)<<
+ " SubStrokeShapeFeatureExtractor::canSegmentStrokes" <<endl;
+
+ LTKReturnError(EINVALID_SLOPE);
+ }
+
+ int directionCodeOfFirstSlope = 0;
+ int directionCodeOfSecondSlope = 0;
+
+ outSegment = false;
+
+ int errorCode = -1;
+
+ // Computing octants of hte inFirstSlope and inSecondSlope
+ if( (errorCode = getDirectionCode(inFirstSlope, directionCodeOfFirstSlope)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::canSegmentStrokes" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = getDirectionCode(inSecondSlope, directionCodeOfSecondSlope)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::canSegmentStrokes" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(abs(directionCodeOfSecondSlope - directionCodeOfFirstSlope) <= STROKE_SEGMENT_VALUE )
+ outSegment = false;
+ else
+ outSegment = true;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::canSegmentStrokes()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE : Feb-2009
+ * NAME : getSlopeFromTrace
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int SubStrokeShapeFeatureExtractor::getSlopeFromTrace(const LTKTrace& inTrace, vector<float>& outSlopeVector)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "SubStrokeShapeFeatureExtractor::getSlopeFromTrace()" << endl;
+
+ int dimension = 0; //Stores the number of points in a trace
+
+ dimension = inTrace.getNumberOfPoints();
+
+ if(dimension == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " <<
+ EEMPTY_TRACE << " : " << getErrorMessage(EEMPTY_TRACE)<<
+ " SubStrokeShapeFeatureExtractor::getSlopeFromTrace" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ int pointIndex = 0;
+
+ float dx = 0.0, dy = 0.0; //Variables to store differences in x and y-directions to compute slope
+
+ float slope = 0.0;
+
+ floatVector xVec, yVec;
+
+ int errorCode = -1;
+
+ if( (errorCode = inTrace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: SubStrokeShapeFeatureExtractor::getSlopeFromTrace"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = inTrace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: SubStrokeShapeFeatureExtractor::getSlopeFromTrace"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ outSlopeVector.clear();
+
+ for(pointIndex=0; pointIndex < dimension-1; ++pointIndex)
+ {
+ dx = xVec[pointIndex+1] - xVec[pointIndex];
+
+ dy = yVec[pointIndex+1] - yVec[pointIndex];
+
+ if( (errorCode = computeSlope(dx, dy, slope)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " SubStrokeShapeFeatureExtractor::getSlopeFromTrace" <<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ outSlopeVector.push_back(slope);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "SubStrokeShapeFeatureExtractor::getSlopeFromTrace()" << endl;
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.h
new file mode 100644
index 00000000..7d803727
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/SubStrokeShapeFeatureExtractor.h
@@ -0,0 +1,139 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all
+* copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: $
+ * $Revision: $
+ * $Author: $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Definitions for SubStroke feature extractor module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Tanmay Mondal
+ *
+ * DATE: February 2009
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+#ifndef __SUBSTROKESHAPEFEATUREEXTRACTOR_H
+#define __SUBSTROKESHAPEFEATUREEXTRACTOR_H
+
+#define SUPPORTED_MIN_VERSION "3.0.0"
+
+// delimiter of the slope of extracted substroke
+#define SUBSTROKES_ANGLE_DELIMITER -999.0
+
+#define SUBSTROKES_LENGTH_REJECT_THRESHOLD 0.001
+
+#define STROKE_SEGMENT_VALUE 0
+
+#define SINGLE_SUBSTROKES 1
+
+#define ANGLE_HIGHER_LIMIT_1 22.5
+
+#define ANGLE_HIGHER_LIMIT_2 67.5
+
+#define ANGLE_HIGHER_LIMIT_3 112.5
+
+#define ANGLE_HIGHER_LIMIT_4 157.5
+
+#define ANGLE_HIGHER_LIMIT_5 202.5
+
+#define ANGLE_HIGHER_LIMIT_6 247.5
+
+#define ANGLE_HIGHER_LIMIT_7 292.5
+
+#define ANGLE_HIGHER_LIMIT_8 337.5
+
+#define PI_DEGREE 180.0
+
+#include "LTKShapeFeatureExtractor.h"
+
+class SubStrokeShapeFeatureExtractor : public LTKShapeFeatureExtractor
+{
+
+public:
+ /** @brief Constructor for the SubStroke feature extractor
+ * Gets the cfg file path from the contorInfo
+ * Reads the cfg variables and poputlates the member variables
+ * @param controlInfo: LTKControlInfo : The control information
+ * @return no return value as it is a constructor
+ */
+
+ SubStrokeShapeFeatureExtractor(const LTKControlInfo& controlInfo);
+
+ int extractFeatures(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& outFeatureVec);
+
+ LTKShapeFeaturePtr getShapeFeatureInstance();
+
+private:
+
+ //store extracted sub-strokes
+ struct subStrokePoint
+ {
+ float X; // x point
+ float Y; // y point
+ bool penUp; // If point is penup then penUp = 1 else penUp =0
+ };
+
+ /** extract feature from sub strokes
+ */
+ int extractFeaturesFromSubStroke(const vector<struct subStrokePoint>& inSubStrokeVector,
+ vector<float>& outSlope,
+ vector<float>& outLength,
+ vector<float>& outCenterOfGravity);
+
+ /** extract the sub strokes from the preprocessed trace group
+ */
+ int extractSubStrokesFromInk(const LTKTraceGroup& inTraceGroup, vector<struct subStrokePoint>& outSubStrokeVector);
+
+ /** @brief claculate the angle
+ * inDeltaX,inDeltaY : float : the difference of x[i] and x[i+1] and difference of y[i] and y[i+1] of ink point
+ * float : the angle made with x axis and the point
+ */
+ int computeSlope(const float inDeltaX, const float inDeltaY, float& outSlope);
+
+ /** decide the octant of the point along the ink
+ * slope : float : value of the angle
+ * int : the octant code
+ */
+ int getDirectionCode(const float inSlope, int& outDirectionCode);
+
+ /** break the stroke into substrokes
+ * infirstSlope, insecondSlope : float : value of the slope
+ * int : SUCCESS : FAILURE
+ */
+ int canSegmentStrokes(const float inFirstSlope, const float inSecondSlope, bool& outSegment);
+
+ /** compute the slope of each point present in the tace
+ * inTrace : LTKTrace : value of a trace
+ * int : SUCCESS : FAILURE : errorcode
+ */
+ int getSlopeFromTrace(const LTKTrace& inTrace, vector<float>& outSlopeVector);
+
+};
+
+#endif //#ifndef __SUBSTROKESHAPEFEATUREEXTRACTOR_H
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/substroke.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/substroke.pro
new file mode 100644
index 00000000..804d1f42
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/featureextractor/substroke/substroke.pro
@@ -0,0 +1,22 @@
+LIPILIBS = ltkcommon ltkutil featureextractorcommon
+include(../../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../../util/lib \
+ ../common \
+
+HEADERS += \
+ SubStroke.h \
+ SubStrokeShapeFeature.h \
+ SubStrokeShapeFeatureExtractor.h \
+
+SOURCES += \
+ SubStroke.cpp \
+ SubStrokeShapeFeature.cpp \
+ SubStrokeShapeFeatureExtractor.cpp \
+
+win32 {
+ DEFINES += SUBSTROKE_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = SubStroke.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.cpp
new file mode 100644
index 00000000..ac6cdae5
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.cpp
@@ -0,0 +1,112 @@
+// NEURALNET.cpp : Defines the entry point for the DLL application.
+//
+
+#include "NeuralNet.h"
+#include "LTKShapeRecognizer.h"
+#include "NeuralNetShapeRecognizer.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKOSUtil.h"
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+
+/**********************************************************************************
+* AUTHOR : Saravanan R
+* DATE : 23-Jan-2007
+* NAME : createShapeRecoginizer
+* DESCRIPTION : Creates instance of type NNShaperecongnizer and retuns of type
+ LTKShapeRecognizer. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKShapeRecoginzer.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** ptrObj )
+{
+ try
+ {
+ *ptrObj = new NeuralNetShapeRecognizer(controlInfo);
+ return SUCCESS;
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R
+* DATE : 23-Jan-2007
+* NAME : deleteShapeRecoginzer
+* DESCRIPTION : Destroy the instance by taking the address as its argument.
+* ARGUMENTS : Address of LTKShapeRecognizer instance.
+* RETURNS : Returns 0 on Success
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int deleteShapeRecognizer(LTKShapeRecognizer *obj)
+{
+ try
+ {
+ if (obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR :Tarun Madan
+* DATE :
+* NAME :
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int getTraceGroups(LTKShapeRecognizer *obj, int shapeId,
+ int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ int errorCode = ((NeuralNetShapeRecognizer*)obj)->getTraceGroups(shapeId,
+ numberOfTraceGroups, outTraceGroups);
+
+ if ( errorCode != SUCCESS )
+ {
+ LTKReturnError(errorCode);
+ }
+
+ return SUCCESS;
+} \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.def
new file mode 100644
index 00000000..0a4f75c9
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.def
@@ -0,0 +1,4 @@
+EXPORTS
+ createShapeRecognizer @1
+ deleteShapeRecognizer @2
+ getTraceGroups @3 \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.h
new file mode 100644
index 00000000..bfe4ac02
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNet.h
@@ -0,0 +1,62 @@
+
+#ifndef __NEURALNET_H__
+#define __NEURALNET_H__
+
+
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the NEURALNET_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// NEURALNET_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef NEURALNET_EXPORTS
+#define NEURALNET_API __declspec(dllexport)
+#else
+#define NEURALNET_API __declspec(dllimport)
+#endif //#ifdef NEURALNET_EXPORTS
+#else
+#define NEURALNET_API
+#endif //#ifdef _WIN32
+
+class LTKTraceGroup;
+class LTKShapeRecognizer;
+
+#include "LTKInc.h"
+#include "LTKTypes.h"
+
+/** @defgroup NeuralNetShapeRecognizer NeuralNetShapeRecognizer
+*@brief The NeuralNetShapeRecognizer
+*/
+
+/**
+* @ingroup NeuralNetShapeRecognizer
+* @file NEURALNET.cpp
+*/
+
+/**
+ * Crates instance of type NeuralNetShapeRecognizer and returns of type
+ * LTKShpeRecognizer. (Acts as a Factory Method).
+ *
+ * @param none
+ *
+ * @return LTKShapeRecognizer - an instance of type LTKShapeRecognizer.
+ */
+extern "C" NEURALNET_API int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** pReco );
+
+/**
+ * Destroy the instance by taking the address as its argument.
+ *
+ * @param obj - Address of LTKShapeRecognizer instance.
+ *
+ * @return 0 on Success
+ */
+extern "C" NEURALNET_API int deleteShapeRecognizer(LTKShapeRecognizer *obj);
+
+extern "C" NEURALNET_API int getTraceGroups(LTKShapeRecognizer *obj, int shapeID, int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups);
+
+void unloadDLLs();
+
+#endif //#ifndef __NEURALNET_H__ \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.cpp
new file mode 100644
index 00000000..3c406f68
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.cpp
@@ -0,0 +1,4682 @@
+#include "LTKConfigFileReader.h"
+
+#include "NeuralNetShapeRecognizer.h"
+
+#include "LTKPreprocDefaults.h"
+
+#include "LTKHierarchicalClustering.h"
+
+#include "LTKPreprocessorInterface.h"
+
+#include "LTKShapeFeatureExtractorFactory.h"
+
+#include "LTKShapeFeatureExtractor.h"
+
+#include "LTKShapeFeature.h"
+
+#include "LTKVersionCompatibilityCheck.h"
+
+#include "LTKInkFileWriter.h"
+#include "LTKOSUtil.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKClassifierDefaults.h"
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : assignDefaultValues
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+void NeuralNetShapeRecognizer::assignDefaultValues()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::assignDefaultValues()" << endl;
+
+ m_numShapes = 0;
+ m_neuralnetCfgFilePath = "";
+ m_neuralnetMDTFilePath = "";
+ m_ptrPreproc = NULL;
+ m_projectTypeDynamic=false;
+ m_preProcSeqn=NN_DEF_PREPROC_SEQ;
+ m_ptrFeatureExtractor=NULL;
+ m_featureExtractorName=NN_DEF_FEATURE_EXTRACTOR;
+ m_neuralnetNormalizationFactor=NEURALNET_DEF_NORMALIZE_FACTOR;
+ m_neuralnetRandomNumberSeed=NEURALNET_DEF_RANDOM_NUMBER_SEED;
+ m_neuralnetLearningRate=NEURALNET_DEF_LEARNING_RATE;
+ m_neuralnetMomemtumRate=NEURALNET_DEF_MOMEMTUM_RATE;
+ m_neuralnetTotalError=NEURALNET_DEF_TOTAL_ERROR;
+ m_neuralnetIndividualError=NEURALNET_DEF_INDIVIDUAL_ERROR;
+ m_neuralnetNumHiddenLayers=NEURALNET_DEF_HIDDEN_LAYERS_SIZE;
+ m_layerOutputUnitVec.push_back(0); // for input layer
+ for(int i = 0; i < m_neuralnetNumHiddenLayers; ++i)
+ {
+ m_layerOutputUnitVec.push_back(NEURALNET_DEF_HIDDEN_LAYERS_UNITS); // for hidden layer
+ }
+ m_layerOutputUnitVec.push_back(0); // for output layer
+ m_layerOutputUnitVec.push_back(0);
+ m_isNeuralnetWeightReestimate=false;
+ m_neuralnetMaximumIteration=NEURALNET_DEF_MAX_ITR;
+ m_isCreateTrainingSequence=true;
+ m_rejectThreshold=NN_DEF_REJECT_THRESHOLD;
+ m_deleteLTKLipiPreProcessor=NULL;
+ m_MDTFileOpenMode = NN_MDT_OPEN_MODE_ASCII;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::assignDefaultValues()" << endl;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : NeuralNetShapeRecognizer
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+NeuralNetShapeRecognizer::NeuralNetShapeRecognizer(const LTKControlInfo& controlInfo):
+m_OSUtilPtr(LTKOSUtilFactory::getInstance()),
+m_libHandler(NULL),
+m_libHandlerFE(NULL)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" << endl;
+
+ try
+ {
+ LTKControlInfo tmpControlInfo=controlInfo;
+
+ string strProjectName = "";
+ string strProfileName = "";
+
+
+ if( (tmpControlInfo.projectName).empty() )
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+ if( (tmpControlInfo.lipiRoot).empty() )
+ {
+ throw LTKException(ELIPI_ROOT_PATH_NOT_SET);
+ }
+
+ if( (tmpControlInfo.profileName).empty() )
+ {
+ strProfileName = DEFAULT_PROFILE;
+ tmpControlInfo.profileName = strProfileName;
+ }
+
+ if ( tmpControlInfo.toolkitVersion.empty() )
+ {
+ throw LTKException(ENO_TOOLKIT_VERSION);
+ }
+
+ assignDefaultValues();
+
+ m_lipiRootPath = tmpControlInfo.lipiRoot;
+ m_lipiLibPath = tmpControlInfo.lipiLib;
+ m_currentVersion = tmpControlInfo.toolkitVersion;
+ strProjectName = tmpControlInfo.projectName;
+ strProfileName = tmpControlInfo.profileName;
+
+
+ //Holds the value of Number of Shapes in string format
+ string strNumShapes = "";
+
+ string strProfileDirectory = m_lipiRootPath + PROJECTS_PATH_STRING +
+ strProjectName + PROFILE_PATH_STRING;
+
+ //Holds the path of the Project.cfg
+ string projectCFGPath = strProfileDirectory + PROJECT_CFG_STRING;
+
+ // Config file
+
+ m_neuralnetCfgFilePath = m_lipiRootPath + PROJECTS_PATH_STRING +
+ (tmpControlInfo.projectName) + PROFILE_PATH_STRING +
+ (tmpControlInfo.profileName) + SEPARATOR +
+ NEURALNET + CONFIGFILEEXT;
+
+
+ //Set the path for neuralnet.mdt
+ m_neuralnetMDTFilePath = strProfileDirectory + strProfileName + SEPARATOR + NEURALNET + DATFILEEXT;
+
+ //To find whether the project was dynamic or not andto read read number of shapes from project.cfg
+ int errorCode = m_shapeRecUtil.isProjectDynamic(projectCFGPath,
+ m_numShapes, strNumShapes, m_projectTypeDynamic);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+
+ //Set the NumShapes to the m_headerInfo
+ m_headerInfo[NUMSHAPES] = strNumShapes;
+
+ //Currently preproc cfg also present in NEURALNET
+ tmpControlInfo.cfgFileName = NEURALNET;
+ errorCode = initializePreprocessor(tmpControlInfo,
+ &m_ptrPreproc);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Reading NEURALNET configuration file
+ errorCode = readClassifierConfig();
+
+ if( errorCode != SUCCESS)
+ {
+ cout<<endl<<"Encountered error in readClassifierConfig"<<endl;
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Writing Feature extractor name and version into the header
+ m_headerInfo[FE_NAME] = m_featureExtractorName;
+ m_headerInfo[FE_VER] = SUPPORTED_MIN_VERSION; //FE version
+
+ //Writting mdt file open mode to the mdt header
+ m_headerInfo[MDT_FOPEN_MODE] = m_MDTFileOpenMode;
+
+ errorCode = initializeFeatureExtractorInstance(tmpControlInfo);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ }
+ catch(LTKException e)
+ {
+
+ deletePreprocessor();
+
+ //Unloading the feature Extractor instance
+ deleteFeatureExtractorInstance();
+
+ delete m_OSUtilPtr;
+ throw e;
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::NeuralNetShapeRecognizer()" << endl;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : ~NeuralNetShapeRecognizer
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+NeuralNetShapeRecognizer::~NeuralNetShapeRecognizer()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::~NeuralNetShapeRecognizer()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ //clear the traning set
+ try{
+
+ m_trainSet.clear();
+
+ //clear all the vector nedded for traning
+ m_delW.clear();
+
+ m_previousDelW.clear();
+
+ m_layerOutputUnitVec.clear();
+
+ m_outputLayerContentVec.clear();
+
+ m_targetOutputVec.clear();
+
+ m_connectionWeightVec.clear();
+ }
+ catch(LTKException e)
+ {
+ delete m_OSUtilPtr;
+
+ throw e;
+ }
+
+ returnStatus = deletePreprocessor();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NeuralNetShapeRecognizer::~NeuralNetShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ //Unloading the feature Extractor instance
+ returnStatus = deleteFeatureExtractorInstance();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NeuralNetShapeRecognizer::~NeuralNetShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ delete m_OSUtilPtr;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::~NeuralNetShapeRecognizer()" << endl;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : readClassifierConfig
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::readClassifierConfig()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::readClassifierConfig()" << endl;
+
+ string tempStringVar = "";
+ int tempIntegerVar = 0;
+ float tempFloatVar = 0.0;
+ LTKConfigFileReader *shapeRecognizerProperties = NULL;
+ int errorCode = FAILURE;
+
+ try
+ {
+ shapeRecognizerProperties = new LTKConfigFileReader(m_neuralnetCfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<< "Info: " <<
+ "Config file not found, using default values of the parameters" <<
+ "NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ return FAILURE;
+ }
+
+ //Pre-processing sequence
+ errorCode = shapeRecognizerProperties->getConfigValue(PREPROCSEQUENCE, m_preProcSeqn);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Info: " <<
+ "Using default value of prerocessing sequence: "<< m_preProcSeqn <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ m_preProcSeqn = NN_DEF_PREPROC_SEQ;
+ }
+ else
+ {
+ m_headerInfo[PREPROC_SEQ] = m_preProcSeqn;
+ }
+
+ if((errorCode = mapPreprocFunctions()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<" Error: " << errorCode <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(REJECT_THRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar < 1)
+ {
+ m_rejectThreshold = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ REJECT_THRESHOLD << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << REJECT_THRESHOLD <<
+ " : " << m_rejectThreshold << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(FEATUREEXTRACTOR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_featureExtractorName = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ FEATUREEXTRACTOR << " = "<<tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << FEATUREEXTRACTOR << " : " <<
+ m_featureExtractorName << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MDT_FILE_OPEN_MODE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( tempStringVar == NN_MDT_OPEN_MODE_ASCII ||
+ tempStringVar == NN_MDT_OPEN_MODE_BINARY )
+ {
+ m_MDTFileOpenMode = tempStringVar;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDT_FILE_OPEN_MODE <<
+ " should be ascii or binary" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MDT_FILE_OPEN_MODE <<
+ " : " << m_MDTFileOpenMode << endl;
+ }
+
+ //Rendom number seed
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(RANDOM_NUMBER_SEED,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ m_neuralnetRandomNumberSeed = atoi(tempStringVar.c_str());
+ if(m_neuralnetRandomNumberSeed<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << RANDOM_NUMBER_SEED <<
+ " should be zero or a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << RANDOM_NUMBER_SEED <<
+ " should be zero or a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << RANDOM_NUMBER_SEED <<
+ " : " << m_neuralnetRandomNumberSeed << endl;
+ }
+
+ //Normalised factor
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_NORMALISED_FACTOR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ //Writing normalised factor
+ m_headerInfo[NORMALISED_FACTOR] = tempStringVar;
+
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 )
+ {
+ m_neuralnetNormalizationFactor = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEURALNET_NORMALISED_FACTOR << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_NORMALISED_FACTOR <<
+ " should be a positive real number" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_NORMALISED_FACTOR <<
+ " should be a positive real number" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_NORMALISED_FACTOR <<
+ " : " << m_neuralnetNormalizationFactor << endl;
+ }
+
+ //Learning rate
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_LEARNING_RATE,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ //Writing Learning rate
+ m_headerInfo[LEARNING_RATE] = tempStringVar;
+
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0.0 && tempFloatVar <= 1.0)
+ {
+ m_neuralnetLearningRate = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEURALNET_LEARNING_RATE << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_LEARNING_RATE <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_LEARNING_RATE <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_LEARNING_RATE <<
+ " : " << m_neuralnetLearningRate << endl;
+ }
+
+ //Momemtum rate
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_MOMEMTUM_RATE,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ m_headerInfo[MOMEMTUM_RATE] = tempStringVar;
+
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0.0 && tempFloatVar <= 1.0)
+ {
+ m_neuralnetMomemtumRate = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEURALNET_MOMEMTUM_RATE << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_MOMEMTUM_RATE <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_MOMEMTUM_RATE <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_MOMEMTUM_RATE <<
+ " : " << m_neuralnetMomemtumRate << endl;
+ }
+
+ //Total error
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_TOTAL_ERROR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar < 1)
+ {
+ m_neuralnetTotalError = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEURALNET_TOTAL_ERROR << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_TOTAL_ERROR <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_TOTAL_ERROR <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_TOTAL_ERROR <<
+ " : " << m_neuralnetTotalError << endl;
+ }
+
+ //individual error
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_INDIVIDUAL_ERROR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar < 1)
+ {
+ m_neuralnetIndividualError = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEURALNET_INDIVIDUAL_ERROR << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_INDIVIDUAL_ERROR <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_INDIVIDUAL_ERROR <<
+ " should be in the range (0-1)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_INDIVIDUAL_ERROR <<
+ " : " << m_neuralnetIndividualError << endl;
+ }
+
+ //hidden layer
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_HIDDEN_LAYERS_SIZE,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ //Writing number of hidden layer
+ m_headerInfo[HIDDEN_LAYER] = tempStringVar;
+
+ m_neuralnetNumHiddenLayers = atoi(tempStringVar.c_str());
+ if(m_neuralnetNumHiddenLayers<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_HIDDEN_LAYERS_SIZE <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_HIDDEN_LAYERS_SIZE <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_HIDDEN_LAYERS_SIZE <<
+ " : " << m_neuralnetNumHiddenLayers << endl;
+ }
+
+ //hidden layer unit
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEURALNET_HIDDEN_LAYERS_UNITS,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ stringVector tokens;
+
+ LTKStringUtil::tokenizeString(tempStringVar, HIDDEN_LAYER_UNIT_DELIMITER, tokens);
+
+ if(tokens.size() == m_neuralnetNumHiddenLayers)
+ {
+ m_layerOutputUnitVec.clear();
+
+ m_layerOutputUnitVec.push_back(0); // input layer
+
+ for(int i = 0; i < m_neuralnetNumHiddenLayers; ++i)
+ {
+ if ( LTKStringUtil::isInteger(tokens[i]) )
+ {
+ m_layerOutputUnitVec.push_back(atoi(tokens[i].c_str())); // for hidden layer
+
+ if(m_layerOutputUnitVec[i+1]<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_HIDDEN_LAYERS_UNITS <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_HIDDEN_LAYERS_UNITS <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }// end for
+
+ m_layerOutputUnitVec.push_back(0); // output layer
+
+ m_layerOutputUnitVec.push_back(0); // extra
+
+ tokens.clear();
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_HIDDEN_LAYERS_UNITS <<
+ " should be a positive integer (number of unit should be same with number of hidden layer)" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_HIDDEN_LAYERS_UNITS <<
+ " : " << m_neuralnetNumHiddenLayers << endl;
+
+ m_neuralnetNumHiddenLayers=NEURALNET_DEF_HIDDEN_LAYERS_SIZE;
+ }
+
+ //initialised weight from previously train weight
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(NEURALNET_WEIGHT_REESTIMATION, tempStringVar);
+
+ if(LTKSTRCMP(tempStringVar.c_str(), "true") ==0)
+ {
+ m_isNeuralnetWeightReestimate = true;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Confidence computation method: " << NEURALNET_WEIGHT_REESTIMATION << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_WEIGHT_REESTIMATION << " : " <<
+ m_isNeuralnetWeightReestimate << endl;
+ }
+
+ //number of itaretion
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(NEURALNET_TRAINING_ITERATION, tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ m_neuralnetMaximumIteration = atoi(tempStringVar.c_str());
+
+ if(m_neuralnetMaximumIteration<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_TRAINING_ITERATION <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEURALNET_TRAINING_ITERATION <<
+ " should be a positive integer" <<
+ " NeuralNetShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_TRAINING_ITERATION <<
+ " : " << m_neuralnetMaximumIteration << endl;
+ }
+
+ //prepare traning sequence
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(NEURALNET_TRAINING_SEQUENCE, tempStringVar);
+
+ if(LTKSTRCMP(tempStringVar.c_str(), "false") ==0)
+ {
+ m_isCreateTrainingSequence = false;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Confidence computation method: " << NEURALNET_TRAINING_SEQUENCE << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << NEURALNET_TRAINING_SEQUENCE << " : " <<
+ m_isCreateTrainingSequence << endl;
+ }
+
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_SIZE_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(ASPECTRATIOTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[ASP_RATIO_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DOTTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVERELATIVEYPOSITION,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_REL_Y_POS] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVEASPECTRATIO,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_ASP_RATIO] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[NORM_LN_WID_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(RESAMPLINGMETHOD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[RESAMP_POINT_ALLOC] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SMOOTHFILTERLENGTH,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[SMOOTH_WIND_SIZE] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ LTKStringUtil::convertIntegerToString(m_ptrPreproc->getTraceDimension(),
+ tempStringVar);
+
+ m_headerInfo[TRACE_DIM] = tempStringVar;
+
+ delete shapeRecognizerProperties;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::readClassifierConfig()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : mapPreprocFunctions
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::mapPreprocFunctions()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ stringStringMap preProcSequence;
+
+ stringStringPair tmpPair;
+
+ stringVector moduleFuncNames;
+ stringVector modFuncs;
+ stringVector funcNameTokens;
+
+ string module = "", funName = "", sequence = "";
+ string::size_type indx;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ LTKStringUtil::tokenizeString(m_preProcSeqn, DELEMITER_SEQUENCE, funcNameTokens);
+
+ int numFunctions = funcNameTokens.size();
+
+ if(numFunctions == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Wrong preprocessor sequence in cfg file : " + m_preProcSeqn <<
+ " NeuralNetShapeRecognizer::mapPreprocFunctions()"<<endl;
+
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+
+ for (indx = 0; indx < numFunctions ; indx++)
+ {
+ moduleFuncNames.push_back(funcNameTokens[indx]);
+ }
+
+ int numModuleFunctions = moduleFuncNames.size();
+
+ for(indx=0; indx < numModuleFunctions ; indx++)
+ {
+ sequence = moduleFuncNames[indx];
+
+ LTKStringUtil::tokenizeString(sequence, DELEMITER_FUNC, modFuncs);
+
+ if(modFuncs.size() >= 2)
+ {
+ module = modFuncs.at(0);
+
+ funName = modFuncs.at(1);
+
+ if(!module.compare("CommonPreProc"))
+ {
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+ if(pPreprocFunc!= NULL)
+ {
+ tmpPair.first = module;
+ tmpPair.second = funName;
+ m_preprocSequence.push_back(tmpPair);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " <<funName<<
+ " NeuralNetShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " << module<<
+ " NeuralNetShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : "<<module<<
+ " NeuralNetShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : initializePreprocessor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+
+ FN_PTR_CREATELTKLIPIPREPROCESSOR createLTKLipiPreProcessor = NULL;
+ int errorCode;
+
+ // Load the DLL with path=preprocDLLPath
+ void* functionHandle = NULL;
+
+ int returnVal = m_OSUtilPtr->loadSharedLib(controlInfo.lipiLib, PREPROC, &m_libHandler);
+
+
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ELOAD_PREPROC_DLL << " " <<
+ getErrorMessage(ELOAD_PREPROC_DLL) <<
+ " NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ELOAD_PREPROC_DLL);
+ }
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ CREATEPREPROCINST,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ createLTKLipiPreProcessor = (FN_PTR_CREATELTKLIPIPREPROCESSOR)functionHandle;
+
+ functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ DESTROYPREPROCINST,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ m_deleteLTKLipiPreProcessor = (FN_PTR_DELETELTKLIPIPREPROCESSOR)functionHandle;
+
+ // Create preprocessor instance
+ errorCode = createLTKLipiPreProcessor(controlInfo, preprocInstance);
+
+ if(errorCode!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // Could not create a LTKLipiPreProcessor
+ if(*preprocInstance == NULL)
+ {
+ // Unload the DLL
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ECREATE_PREPROC << " " <<
+ getErrorMessage(ECREATE_PREPROC) <<
+ " NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ECREATE_PREPROC);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::initializePreprocessor()" << endl;
+
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : unloadPreprocessorDLL
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::unloadPreprocessorDLL()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+
+ //Check the preprocessor DLL was loaded already
+ if(m_libHandler != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandler);
+ m_libHandler = NULL;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : initializeFeatureExtractorInstance
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+
+ LTKShapeFeatureExtractorFactory factory;
+ int errorCode = factory.createFeatureExtractor(m_featureExtractorName,
+ m_lipiRootPath,
+ m_lipiLibPath,
+ &m_libHandlerFE,
+ controlInfo,
+ &m_ptrFeatureExtractor);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EFTR_EXTR_NOT_EXIST << " " <<
+ " NeuralNetShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+ LTKReturnError(errorCode);
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : deleteFeatureExtractorInstance
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::deleteFeatureExtractorInstance()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ if (m_ptrFeatureExtractor != NULL)
+ {
+ typedef int (*FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)(LTKShapeFeatureExtractor *obj);
+ FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR deleteFeatureExtractor;
+ void * functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ int returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandlerFE,
+ DELETE_SHAPE_FEATURE_EXTRACTOR,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: "<< EDLL_FUNC_ADDRESS_DELETE_FEATEXT << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_DELETE_FEATEXT) <<
+ " NeuralNetShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_DELETE_FEATEXT);
+ }
+
+ deleteFeatureExtractor = (FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)functionHandle;
+
+ deleteFeatureExtractor(m_ptrFeatureExtractor);
+
+ m_ptrFeatureExtractor = NULL;
+
+ // unload feature extractor dll
+ if(m_libHandlerFE != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandlerFE);
+ m_libHandlerFE = NULL;
+
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : deletePreprocessor
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::deletePreprocessor()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::deletePreprocessor()" << endl;
+
+ //deleting the preprocessor instance
+ if(m_ptrPreproc != NULL)
+ {
+ m_deleteLTKLipiPreProcessor(m_ptrPreproc);
+ m_ptrPreproc = NULL;
+ }
+
+ //Unload the dll
+ int returnStatus = unloadPreprocessorDLL();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::deletePreprocessor()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::deletePreprocessor()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : preprocess
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::preprocess(const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outPreprocessedTraceGroup)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::preprocess()" << endl;
+
+ int indx = 0;
+ int errorCode = -1;
+
+ string module = "";
+ string funName = "" ;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ local_inTraceGroup = inTraceGroup;
+
+ if(m_preprocSequence.size() != 0)
+ {
+ while(indx < m_preprocSequence.size())
+ {
+ module = m_preprocSequence.at(indx).first;
+ funName = m_preprocSequence.at(indx).second;
+
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+
+ if(pPreprocFunc!= NULL)
+ {
+ outPreprocessedTraceGroup.emptyAllTraces();
+
+
+ if((errorCode = (m_ptrPreproc->*(pPreprocFunc))
+ (local_inTraceGroup,outPreprocessedTraceGroup)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::preprocess()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ local_inTraceGroup = outPreprocessedTraceGroup;
+ }
+ indx++;
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting " <<
+ "NeuralNetShapeRecognizer::preprocess()" << endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : getTraceGroups
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::getTraceGroups(int shapeID, int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering NeuralNetShapeRecognizer::getTraceGroups"
+ <<endl;
+
+ //base class function, to be implemented
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NeuralNetShapeRecognizer::getTraceGroups"
+ <<endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : appendNeuralNetDetailsToMDTFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::appendNeuralNetDetailsToMDTFile(const double2DVector& resultVector,
+ const bool isWeight,
+ ofstream & mdtFileHandle)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::appendNeuralNetDetailsToMDTFile()" << endl;
+
+ int index =0;
+
+ double2DVector::const_iterator resultRowIter = resultVector.begin();
+ double2DVector::const_iterator resultRowIterEnd = resultVector.end();
+
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_FILE_HANDLE << " " <<
+ "Invalid file handle for MDT file"<<
+ " NNShapeRecognizer::appendNeuralNetDetailsToMDTFile()" << endl;
+ LTKReturnError(EINVALID_FILE_HANDLE);
+ }
+
+ if( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_BINARY )
+ {
+ int numOfLayer = resultVector.size();
+
+ mdtFileHandle.write((char *)(&numOfLayer), sizeof(int));
+ }
+ else
+ {
+ if(isWeight)
+ mdtFileHandle << "<Weight>" << NEW_LINE_DELIMITER;
+ else
+ mdtFileHandle << "<De_W Previous>" << NEW_LINE_DELIMITER;
+ }
+
+ for(; resultRowIter != resultRowIterEnd; resultRowIter++)
+ {
+ doubleVector::const_iterator colItr = (*resultRowIter).begin();
+ doubleVector::const_iterator colItrEnd = (*resultRowIter).end();
+
+ int numOfNode = (*resultRowIter).size();
+
+ if(numOfNode != 0 && m_MDTFileOpenMode == NN_MDT_OPEN_MODE_BINARY)
+ {
+ mdtFileHandle.write((char *)(&numOfNode), sizeof(int));
+ }
+
+ for(; colItr != colItrEnd; colItr++)
+ {
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_BINARY )
+ {
+ float floatValue = (*colItr);
+ mdtFileHandle.write((char *)(&floatValue), sizeof(float));
+ }
+ else
+ {
+ mdtFileHandle <<scientific <<fixed << (*colItr);
+
+ if(index > 99)
+ {
+ mdtFileHandle << NEW_LINE_DELIMITER;
+
+ index =0;
+ }
+ else
+ {
+ mdtFileHandle << CLASSID_FEATURES_DELIMITER;
+ ++index;
+ }
+ }
+ }
+
+ if(m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII)
+ {
+ mdtFileHandle <<NEW_LINE_DELIMITER;
+ }
+
+ }
+
+ if( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ if(isWeight)
+ mdtFileHandle << "<End Weight>" << NEW_LINE_DELIMITER;
+ else
+ mdtFileHandle << "<End De_W Previous>" << NEW_LINE_DELIMITER;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NeuralNetShapeRecognizer::appendNeuralNetDetailsToMDTFile()"
+ <<endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME :
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::loadModelData()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::loadModelData()" << endl;
+
+ int numofShapes = 0;
+
+ int errorCode = -1;
+
+ // variable for shape Id
+ int classId = -1;
+
+ int layerIndex = 0;
+
+ int nodeValueIndex;
+
+ //Algorithm version
+ string algoVersionReadFromADT = "";
+
+ stringStringMap headerSequence;
+
+ LTKCheckSumGenerate cheSumGen;
+
+ if(errorCode = cheSumGen.readMDTHeader(m_neuralnetMDTFilePath,headerSequence))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // printing the headerseqn
+ stringStringMap::const_iterator iter = headerSequence.begin();
+ stringStringMap::const_iterator endIter = headerSequence.end();
+
+ for(; iter != endIter; iter++)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Info: header seqn"<<
+ iter->first << " : " <<
+ iter->second << endl;
+ }
+
+ string featureExtractor = headerSequence[FE_NAME];
+
+ if(LTKSTRCMP(m_featureExtractorName.c_str(), featureExtractor.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of FeatureExtractor parameter in config file ("<<
+ m_featureExtractorName<<") does not match with the value in MDT file ("<<
+ featureExtractor<<")"<<
+ " NeuralNetShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ string feVersion = headerSequence[FE_VER];
+
+ // comparing the mdt open mode read from cfg file with value in the mdt header
+ string mdtOpenMode = headerSequence[MDT_FOPEN_MODE];
+
+ if (LTKSTRCMP(m_MDTFileOpenMode.c_str(), mdtOpenMode.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of NEURAL_NETMDTFileOpenMode parameter in config file ("<<
+ m_MDTFileOpenMode <<") does not match with the value in MDT file ("<<
+ mdtOpenMode<<")"<<
+ " NeuralNetShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ // validating preproc parameters
+ int iErrorCode = validatePreprocParameters(headerSequence);
+ if (iErrorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Values of NEURAL_NETMDTFileOpenMode parameter in config file does not match with "
+ <<"the values in MDT file " << "NeuralNetShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ iErrorCode = validateNeuralnetArchitectureParameters(headerSequence);
+
+ if (iErrorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Values of NEURAL_NETMDTFileOpenMode parameter in config file does not match with "
+ <<"the values in MDT file " << "NeuralNetShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // Version comparison START
+ algoVersionReadFromADT = headerSequence[RECVERSION].c_str();
+
+ LTKVersionCompatibilityCheck verTempObj;
+ string supportedMinVersion(SUPPORTED_MIN_VERSION);
+ string currentVersionStr(m_currentVersion);
+
+ bool compatibilityResults = verTempObj.checkCompatibility(supportedMinVersion,
+ currentVersionStr,
+ algoVersionReadFromADT);
+
+ if(compatibilityResults == false)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINCOMPATIBLE_VERSION << " " <<
+ " Incompatible version"<<
+ " NeuralNetShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EINCOMPATIBLE_VERSION);
+ }
+ // Version comparison END
+
+ //Input Stream for Model Data file
+ ifstream mdtFileHandle;
+
+ if (m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_neuralnetMDTFilePath.c_str(), ios::in);
+ }
+ else
+ {
+ mdtFileHandle.open(m_neuralnetMDTFilePath.c_str(), ios::in | ios::binary);
+ }
+
+ //If error while opening, return an error
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ " Unable to open model data file : " <<m_neuralnetMDTFilePath<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ mdtFileHandle.seekg(atoi(headerSequence[HEADERLEN].c_str()),ios::beg);
+
+ //Read the number of shapes
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> numofShapes;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &numofShapes,
+ atoi(headerSequence[SIZEOFSHORTINT].c_str()));
+ }
+
+ if(!m_projectTypeDynamic && m_numShapes != numofShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of NumShapes parameter in config file ("<<m_numShapes<<
+ ") does not match with the value in MDT file ("<<numofShapes<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ else
+ {
+ m_numShapes = numofShapes;
+ }
+
+ //set output layer unit
+ if(m_layerOutputUnitVec[(m_layerOutputUnitVec.size() - 2)] != m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of output unit parameter in config file ("<<m_numShapes<<
+ ") does not match with the value in MDT file ("<<numofShapes<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // validating the header values
+
+ string strValue = "";
+
+ //testing for initialisation
+ if(m_connectionWeightVec.size() == 0 || m_previousDelW.size() == 0)
+ {
+ for(int index = 0; index < (m_neuralnetNumHiddenLayers + 2); ++index)
+ {
+ doubleVector tempDoubleVec(((m_layerOutputUnitVec[index] + 1) * m_layerOutputUnitVec[index+1]));
+
+ m_connectionWeightVec.push_back(tempDoubleVec);
+
+ m_previousDelW.push_back(tempDoubleVec);
+
+ tempDoubleVec.clear();
+ }
+ }
+
+ int floatSize = atoi(headerSequence[SIZEOFFLOAT].c_str());
+
+ int intSize = atoi(headerSequence[SIZEOFINT].c_str());
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ while(getline(mdtFileHandle, strValue, NEW_LINE_DELIMITER ))
+ {
+ if(LTKSTRCMP(strValue.c_str(),"<Weight>") == 0)
+ {
+ for (layerIndex = 0; layerIndex < m_neuralnetNumHiddenLayers + 1; layerIndex++)
+ {
+ for (nodeValueIndex =0; nodeValueIndex < (m_layerOutputUnitVec[layerIndex] + 1) * m_layerOutputUnitVec[layerIndex + 1]; nodeValueIndex++)
+ {
+ mdtFileHandle >> strValue;
+
+ float floatValue = LTKStringUtil::convertStringToFloat(strValue);
+
+ m_connectionWeightVec[layerIndex][nodeValueIndex] = (double)floatValue;
+ }
+ }
+
+ }
+ else if(LTKSTRCMP(strValue.c_str(),"<De_W Previous>") == 0)
+ {
+ for (layerIndex = 0; layerIndex < m_neuralnetNumHiddenLayers + 1; layerIndex++)
+ {
+ for (nodeValueIndex = 0; nodeValueIndex < (m_layerOutputUnitVec[layerIndex] + 1) * m_layerOutputUnitVec[layerIndex + 1]; nodeValueIndex++)
+ {
+ mdtFileHandle >> strValue;
+
+ double floatValue = LTKStringUtil::convertStringToFloat(strValue);
+
+ m_previousDelW[layerIndex][nodeValueIndex] = floatValue;
+ }
+ }
+ }
+ } // end while outer
+ }
+ else // for binary mode
+ {
+ int numOfLayer;
+
+ while(!mdtFileHandle.eof())
+ {
+ mdtFileHandle.read((char*) &numOfLayer, intSize);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+
+ if( (numOfLayer - 1) != (m_neuralnetNumHiddenLayers + 1))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of hidden layer parameter in config file ("<<m_neuralnetNumHiddenLayers<<
+ ") does not match with the value in MDT file ("<<(numOfLayer - 2)<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ layerIndex = 0;
+
+ for ( ; layerIndex < (numOfLayer - 1) ; layerIndex++)
+ {
+ nodeValueIndex = 0;
+
+ int numberOfNode;
+
+ mdtFileHandle.read((char*) &numberOfNode, intSize);
+
+ cout<<numberOfNode << "::"<<endl;
+
+ if(numberOfNode !=((m_layerOutputUnitVec[layerIndex] + 1) * m_layerOutputUnitVec[layerIndex + 1]))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of hidden node parameter in config file" <<
+ " does not match with the value in MDT file" <<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ for(; nodeValueIndex < numberOfNode ; nodeValueIndex++)
+ {
+ float nodeValue = 0.0f;
+
+ mdtFileHandle.read((char*) &nodeValue, floatSize);
+
+ m_connectionWeightVec[layerIndex][nodeValueIndex] = nodeValue;
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ } //weight
+
+ numOfLayer = 0;
+
+ mdtFileHandle.read((char*) &numOfLayer, intSize);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+
+ if((numOfLayer - 1) != (m_neuralnetNumHiddenLayers + 1))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of hidden layer parameter in config file ("<<m_neuralnetNumHiddenLayers<<
+ ") does not match with the value in MDT file ("<<(numOfLayer - 2)<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ layerIndex = 0;
+
+ for ( ; layerIndex < (numOfLayer - 1) ; layerIndex++)
+ {
+ int numberOfNode;
+ mdtFileHandle.read((char*) &numberOfNode, intSize);
+
+ if(numberOfNode !=((m_layerOutputUnitVec[layerIndex] + 1) * m_layerOutputUnitVec[layerIndex + 1]))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of hidden node parameter in config file" <<
+ " does not match with the value in MDT file" <<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ nodeValueIndex = 0;
+ for(; nodeValueIndex < numberOfNode ; nodeValueIndex++)
+ {
+ float nodeValue = 0.0f;
+
+ mdtFileHandle.read((char*) &nodeValue, floatSize);
+
+ m_previousDelW[layerIndex][nodeValueIndex] = nodeValue;
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+ }
+
+ }
+ }
+ }
+
+ mdtFileHandle.close();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::loadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : validateNeuralnetArchitectureParameters
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+
+ string headerValue = "";
+ int headerValueInt = 0;
+ float headerValueFloat = 0.0f;
+
+
+ if(LTKSTRCMP((headerSequence[HIDDEN_LAYER]).c_str(), "NA") != 0)
+ {
+ headerValueInt = atoi(headerSequence[HIDDEN_LAYER].c_str());
+
+ if(headerValueInt != m_neuralnetNumHiddenLayers)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of hidden layer in config file ("<<
+ m_neuralnetNumHiddenLayers<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ if(LTKSTRCMP((headerSequence[LEARNING_RATE].c_str()),"NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[LEARNING_RATE].c_str());
+
+ if(headerValueFloat != m_neuralnetLearningRate)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of larning rate in config file ("<<
+ m_neuralnetLearningRate<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+ }
+
+ }
+
+ if(LTKSTRCMP((headerSequence[MOMEMTUM_RATE].c_str()),"NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[MOMEMTUM_RATE].c_str());
+
+ if(headerValueFloat != m_neuralnetMomemtumRate)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of momentum rate in config file ("<<
+ m_neuralnetMomemtumRate<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+ }
+
+ }
+
+ if(LTKSTRCMP((headerSequence[NORMALISED_FACTOR].c_str()),"NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[NORMALISED_FACTOR].c_str());
+
+ if(headerValueFloat != m_neuralnetNormalizationFactor)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of normalised factor in config file ("<<
+ m_neuralnetNormalizationFactor<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ }
+
+ stringVector unitTokens;
+ string mdtHLayerUnit = headerSequence[HIDDENLAYERSUNIT];
+
+ LTKStringUtil::tokenizeString(mdtHLayerUnit,
+ HIDDEN_LAYER_UNIT_DELIMITER, unitTokens);
+
+ if(unitTokens.size() != m_layerOutputUnitVec.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of layer stracture does not match" <<
+ " does not match with the value in MDT file"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ else
+ {
+ int s = m_layerOutputUnitVec.size();
+
+ for(int i = 0 ; i < (s - 1) ; ++i)
+ {
+ if(i == 0)
+ {
+ //set input layer
+ m_layerOutputUnitVec[i] = atoi(unitTokens[i].c_str());
+ }
+ else if( i <= m_neuralnetNumHiddenLayers)
+ {
+ if(m_layerOutputUnitVec[i] != atoi(unitTokens[i].c_str()))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of hidden node does not match" <<
+ " does not match with the value in MDT file"<<
+ " NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+ else
+ {
+ m_layerOutputUnitVec[i] = atoi(unitTokens[i].c_str());
+ }
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::validateNeuralnetArchitectureParameters()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : validatePreprocParameters
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::validatePreprocParameters(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ string tempStrVar = "";
+ string headerValue = "";
+ int headerValueInt = 0;
+ float headerValueFloat = 0.0f;
+ int tempIntegerValue = 0;
+ float tempFloatValue = 0.0f;
+
+ //preproc sequence
+ string mdtPreprocSeqn = headerSequence[PREPROC_SEQ];
+ if(LTKSTRCMP(m_preProcSeqn.c_str(), mdtPreprocSeqn.c_str()) != 0 &&
+ LTKSTRCMP("NA", mdtPreprocSeqn.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preprocSeqn in config file ("<<
+ m_preProcSeqn <<") does not match with the value in MDT file ("<<
+ mdtPreprocSeqn <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ //ResampTraceDimension
+ headerValue = "";
+ if(LTKSTRCMP("NA", headerSequence[TRACE_DIM].c_str()) != 0)
+ {
+ headerValueInt = atoi(headerSequence[TRACE_DIM].c_str());
+ tempIntegerValue = m_ptrPreproc->getTraceDimension();
+
+ if(headerValueInt != tempIntegerValue )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of TraceDimension in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // preserve aspect ratio
+ bool preProcPreserveAspectRatio = m_ptrPreproc->getPreserveAspectRatio();
+ tempStrVar = "false";
+ if (preProcPreserveAspectRatio == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatio in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_ASP_RATIO] <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ //NormPreserveRelativeYPosition
+ bool preProcNormPreserveRelativeYPosition = m_ptrPreproc->getPreserveRealtiveYPosition();
+ tempStrVar = "false";
+ if (preProcNormPreserveRelativeYPosition == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormPreserveRelativeYPosition in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_REL_Y_POS] <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // NormPreserveAspectRatioThreshold
+ tempFloatValue = m_ptrPreproc->getAspectRatioThreshold();
+ if(LTKSTRCMP((headerSequence[ASP_RATIO_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[ASP_RATIO_THRES].c_str());
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatioThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // NormLineWidthThreshold
+ if(LTKSTRCMP((headerSequence[DOT_SIZE_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_SIZE_THRES].c_str());
+ tempFloatValue = m_ptrPreproc->getSizeThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormLineWidthThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // NormDotSizeThreshold
+ if(LTKSTRCMP((headerSequence[DOT_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_THRES].c_str());
+ tempFloatValue = m_ptrPreproc->getDotThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormDotSizeThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+ //ResampPointAllocation
+ tempStrVar = "";
+ tempStrVar = m_ptrPreproc->getResamplingMethod();
+ if(LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcResampPointAllocation in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[RESAMP_POINT_ALLOC] <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ //SmoothWindowSize
+ if(LTKSTRCMP((headerSequence[SMOOTH_WIND_SIZE]).c_str(), "NA") != 0)
+ {
+ headerValueInt = atoi(headerSequence[SMOOTH_WIND_SIZE].c_str());
+ tempIntegerValue = m_ptrPreproc->getFilterLength();
+
+ if(headerValueInt != tempIntegerValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcSmoothWindowSize in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::validatePreprocParameters()" << endl;
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : setDeviceContext
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::setDeviceContext(const LTKCaptureDevice& deviceInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::setDeviceContext()" << endl;
+
+ m_captureDevice = deviceInfo;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::setDeviceContext()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : unloadModelData
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::unloadModelData()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::unloadModelData()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ m_connectionWeightVec.clear();
+
+ m_previousDelW.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::unloadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : writeNeuralNetDetailsToMDTFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::writeNeuralNetDetailsToMDTFile()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ int index = 0;
+
+ int maxIndex;
+
+ double maxVal;
+
+
+ //write the Neural net architecture i.e network and weight
+ ofstream mdtFileHandle;
+
+ double2DVector vecNetworkWeight;
+
+ double2DVector vecNetworkDelW;
+
+ double2DVector::iterator networkWeightIter;
+
+ int connectionWeightSetSize = m_connectionWeightVec.size();
+
+ if(connectionWeightSetSize == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EEMPTY_VECTOR << " " <<
+ "Empty connection weights" <<
+ " NNShapeRecognizer::writeNeuralNetDetailsToMDTFile()"<<endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ double2DVector::iterator networkDelWItr;
+
+ int priviousDelWSetSize = m_previousDelW.size();
+
+ if(priviousDelWSetSize == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EEMPTY_VECTOR << " " <<
+ "Empty privious Del W" <<
+ " NNShapeRecognizer::writeNeuralNetDetailsToMDTFile()"<<endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_neuralnetMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_neuralnetMDTFilePath.c_str(),ios::out|ios::binary);
+ }
+
+ //Throw an error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN)<<
+ " NeuralNetShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ //Write the number of Shapes
+ mdtFileHandle << m_numShapes << endl;
+ }
+ else
+ {
+ mdtFileHandle.write((char*) &m_numShapes, sizeof(unsigned short));
+ }
+
+ networkWeightIter = m_connectionWeightVec.begin();
+
+ int i=0;
+ for (i=0;i<connectionWeightSetSize;i++)
+ {
+ vecNetworkWeight.push_back((*networkWeightIter));
+
+ networkWeightIter++;
+ }
+
+ returnStatus = appendNeuralNetDetailsToMDTFile(vecNetworkWeight,true,mdtFileHandle);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ vecNetworkWeight.clear();
+
+ networkDelWItr = m_previousDelW.begin();
+
+ for (i=0;i<priviousDelWSetSize;i++)
+ {
+ vecNetworkDelW.push_back((*networkDelWItr));
+
+ networkDelWItr++;
+ }
+
+ returnStatus = appendNeuralNetDetailsToMDTFile(vecNetworkDelW,false,mdtFileHandle);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ vecNetworkDelW.clear();
+
+ mdtFileHandle.close();
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ string strModelDataHeaderInfoFile = "";
+ LTKCheckSumGenerate cheSumGen;
+
+ returnStatus = cheSumGen.addHeaderInfo(
+ strModelDataHeaderInfoFile,
+ m_neuralnetMDTFilePath,
+ m_headerInfo
+ );
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::writeNeuralNetDetailsToMDTFile()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : train
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::train()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ if(comment.empty() != true)
+ {
+ m_headerInfo[COMMENT] = comment;
+ }
+
+ if(dataset.empty() != true)
+ {
+ m_headerInfo[DATASET] = dataset;
+ }
+
+ returnStatus = trainNetwork(trainingInputFilePath,
+ mdtHeaderFilePath,
+ trainFileType);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NNShapeRecognizer::train()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::train()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : updateHeaderWithAlgoInfo
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+void NeuralNetShapeRecognizer::updateHeaderWithAlgoInfo()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+ //Set the NumShapes to the m_headerInfo
+ char strVal[80];
+ //itoa function is not available in linux
+ //itoa(m_numShapes,strVal,10);
+ sprintf(strVal,"%d",m_numShapes);
+ string strNumShapes(strVal);
+ m_headerInfo[NUMSHAPES] = strNumShapes;
+
+ ostringstream tempString;
+
+ int size = m_layerOutputUnitVec.size();
+
+ for(int i = 0; i < size; ++i)
+ {
+ tempString << m_layerOutputUnitVec[i] <<HIDDEN_LAYER_UNIT_DELIMITER;
+ }
+
+ string strhLayerUnit = tempString.str();
+
+ m_headerInfo[HIDDENLAYERSUNIT] = strhLayerUnit;
+
+ m_headerInfo[RECVERSION] = m_currentVersion;
+ string algoName = NEURALNET;
+ m_headerInfo[RECNAME] = algoName;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : trainNetwork
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::trainNetwork(const string& trainingInputFilePath,
+ const string &mdtHeaderFilePath,
+ const string& inFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ //Time at the beginning of Train Clustering
+ m_OSUtilPtr->recordStartTime();
+
+ int returnStatus = SUCCESS;
+
+ ///////////////////////////////////////
+ // Calculating feature for all sample and all class
+ if(LTKSTRCMP(inFileType.c_str(), INK_FILE) == 0)
+ {
+ //If the Input file is UNIPEN Ink file
+ returnStatus = trainFromListFile(trainingInputFilePath);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+ }
+ else if(LTKSTRCMP(inFileType.c_str(), FEATURE_FILE) == 0)
+ {
+ //If the Input file is Feature file
+ returnStatus = trainFromFeatureFile(trainingInputFilePath);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ PreprocParametersForFeatureFile(m_headerInfo);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Feature store successfully" <<endl;
+
+ if(m_isCreateTrainingSequence)
+ {
+ //rearrabging the feature for traning of neural net
+ returnStatus = prepareNeuralNetTrainingSequence();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Success fully complete neural net traning sequence" <<endl;
+ }
+
+ //train the network
+ returnStatus = prepareNetworkArchitecture();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Successfully train Network" <<endl;
+
+ //write the weight
+ returnStatus = writeNeuralNetDetailsToMDTFile();
+
+ if( returnStatus != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<returnStatus << " " <<
+ " NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::trainClustering()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ ////////////////////////////////////////
+ //Time at the end of Train Clustering
+ m_OSUtilPtr->recordEndTime();
+
+ string timeTaken = "";
+ m_OSUtilPtr->diffTime(timeTaken);
+
+ cout << "Time Taken = " << timeTaken << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::trainNetwork()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : trainFromListFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::trainFromListFile(const string& listFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+
+ //Count for the no. of samples read for a shape
+ int sampleCount = 0;
+
+ //Count of the no. of shapes read so far
+ int shapeCount = 0;
+
+ //Flag to skip reading a newline in the list file, when a new class starts
+ bool lastshapeIdFlag = false;
+
+ //Ink File Path
+ string path = "";
+
+ //Line from the list file
+ string line = "";
+
+ //Line is split into tokens
+ stringVector tokens;
+
+ //Flag is set when EOF is reached
+ bool eofFlag = false;
+
+ //ID for each shapes
+ int shapeId = -1;
+
+ //classId of the character
+ int prevClassId = -1;
+
+ //Indicates the first class
+ bool initClassFlag = false;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ vector<LTKShapeFeaturePtr> shapeFeature;
+
+ //list file handle
+ ifstream listFileHandle;
+
+ //Opening the train list file for reading mode
+ listFileHandle.open(listFilePath.c_str(), ios::in);
+
+ //Throw an error if unable to open the training list file
+ if(!listFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ETRAINLIST_FILE_OPEN << " " <<
+ getErrorMessage(ETRAINLIST_FILE_OPEN)<<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(ETRAINLIST_FILE_OPEN);
+ }
+
+ int errorCode = SUCCESS;
+ unsigned short numShapes = m_numShapes;
+ while(!listFileHandle.eof())
+ {
+ // Not a sample of a new class
+ if( lastshapeIdFlag == false )
+ {
+ //Get the line from the list file
+ getline(listFileHandle, line, NEW_LINE_DELIMITER);
+
+ path = "";
+
+ //Check if EOF is reached
+ if( listFileHandle.eof() )
+ {
+ eofFlag = true;
+ }
+
+ //Skip commented line
+ if ( line[0] == COMMENTCHAR )
+ {
+ continue;
+ }
+
+ if (eofFlag == false)
+ {
+ //Tokenize the string
+ errorCode = LTKStringUtil::tokenizeString(line, LIST_FILE_DELIMITER, tokens);
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+
+ LTKReturnError(errorCode);
+ }
+
+
+ //Tokens must be of size 2, one is pathname and other is shapeId
+ //If the end of file not reached then continue the looping
+ if( tokens.size() != 2 && eofFlag == false )
+ continue;
+
+ //Tokens[0] indicates the path name
+ path = tokens[0];
+
+ //Tokens[1] indicates the shapeId
+ shapeId = atoi( tokens[1].c_str() );
+
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "The NeuralNetShapeRecognizer requires training file class Ids to be positive integers and listed in the increasing order"<<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_SHAPEID;
+ break;
+ }
+ else if(shapeId < prevClassId)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "Shape IDs in the train list file should be in the increasing order. Please use scripts/validateListFile.pl to generate list files." <<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_ORDER_LISTFILE;
+ break;
+ }
+
+
+ //This condition is used to handle the first sample in the file
+ if( initClassFlag == false )
+ {
+ initClassFlag = true;
+ prevClassId=shapeId;
+ }
+ }
+ }
+ else //Sample of a new class; do not read the next line during this iteration
+ {
+ //flag unset to read next line during the next iteration
+ lastshapeIdFlag = false;
+ }
+
+ // Sample from the same class, extract features, and push the extracted features to shapeSamplesVec
+ if( shapeId == prevClassId && ! path.empty())
+ {
+ if( getShapeFeatureFromInkFile(path, shapeFeature) != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Error extracting features from the ink file: " <<
+ path << ", extracting features from the next sample."<<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+
+ continue;
+ }
+
+ shapeSampleFeatures.setFeatureVector(shapeFeature);
+ shapeSampleFeatures.setClassID(shapeId);
+
+ ++sampleCount;
+
+ shapeFeature.clear();
+
+ //All the samples are pushed to m_trainSet used for neural net training
+ m_trainSet.push_back(shapeSampleFeatures);
+ }
+ // Sample of new class seen, or end of list file reached; train all the samples of previous class ID
+ if( shapeId != prevClassId || eofFlag == true )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Training for class : " << prevClassId << endl;
+
+ //Increase shape count only if there are atleast one sample per class
+ if( sampleCount > 0 )
+ shapeCount++;
+
+ //check that shapecount must not be greater than specified number
+ //of shapes, if projecttype was not dynamic
+ if( !m_projectTypeDynamic && shapeCount > numShapes )
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+ break;
+ }
+
+ if( shapeCount > 0 && sampleCount > 0 )
+ {
+ //number of sample present in the traning shape
+ m_sampleCountVec.push_back(sampleCount);
+
+ //new shape is found
+ //m_numShapes variable value is retreived from config file
+ m_numShapes += 1;
+
+ //Resetting sampleCount for the next class
+ sampleCount = 0;
+
+ //Set the flag so that the already read line of next class in the list file is not lost
+ lastshapeIdFlag = true;
+
+ prevClassId = shapeId;
+
+ }
+ }
+ }//End of while
+
+ //Closing the Train List file
+ listFileHandle.close();
+
+ if(!m_projectTypeDynamic && shapeCount != numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_SHAPES << " " <<
+ getErrorMessage(EINVALID_NUM_OF_SHAPES)<<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ /*else
+ {
+ m_numShapes = shapeCount;
+ }*/
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::trainFromListFile()" << endl;
+
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : prepareNeuralNetTrainingSequence
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::prepareNeuralNetTrainingSequence()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::prepareNeuralNetTraningSequence()" << endl;
+
+ int sizeOfTraningSet = m_trainSet.size();
+
+ if(sizeOfTraningSet == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty traning set) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::prepareNeuralNetTraningSequence()" << endl;
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ vector<LTKShapeSample> shapeSamplesVec;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ intVector countVector;
+
+ intVector initIndexVec;
+
+ int qumulativeIndex = 0;
+
+ int index = 0;
+
+ // store the shape ID which contain the maximum traning sample
+ int patternId = -1;
+
+ int max = -1;
+
+ bool isPrepareTraningSet = false;
+
+ try{
+
+ //if traning set contain unequal number of sample,
+ // then it make the equal number of sample for the traning set
+ for(index = 0; index < m_sampleCountVec.size(); ++index)
+ {
+ if(index == 0)
+ {
+ qumulativeIndex = (m_sampleCountVec[index] - 1);
+
+ max = m_sampleCountVec[index];
+
+ patternId = index;
+
+ initIndexVec.push_back(index);
+ }
+ else
+ {
+ qumulativeIndex = (countVector[index - 1] + m_sampleCountVec[index]);
+
+ initIndexVec.push_back((countVector[index - 1] + 1));
+
+ if(m_sampleCountVec[index] > max)
+ {
+ max = m_sampleCountVec[index];
+
+ patternId = index;
+ }
+ }
+
+ countVector.push_back(qumulativeIndex);
+ }
+
+ index = 0;
+
+ // copy the whole traning set
+ shapeSamplesVec = m_trainSet;
+
+ m_trainSet.clear();
+
+ while(!isPrepareTraningSet)
+ {
+ // currenly pointing the sample of a traning shape
+ int currentIndex = initIndexVec[index];
+
+ if(currentIndex <= countVector[index])
+ {
+ //point the next sample
+ initIndexVec[index] += 1;
+
+ int shapeId = shapeSamplesVec[currentIndex].getClassID();
+
+ m_targetOutputVec.push_back(vector<double>());
+
+ m_targetOutputVec[m_targetOutputVec.size() - 1] = doubleVector(m_numShapes);
+
+ m_targetOutputVec[m_targetOutputVec.size() - 1][shapeId] = 1;
+
+ vector<LTKShapeFeaturePtr> shapeFeature = shapeSamplesVec[currentIndex].getFeatureVector();
+
+ //Normalised feature vector to prepare neural net traning feature lise between (-1 to 1)
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = shapeFeature.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = shapeFeature.end();
+
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+ floatVector floatFeatureVector;
+
+ (*shapeFeatureIter)->toFloatVector(floatFeatureVector);
+
+ int vectorSize = floatFeatureVector.size();
+
+ int i=0;
+ for (i=0; i< vectorSize; i++)
+ {
+ float floatValue = floatFeatureVector[i];
+
+ floatFeatureVector[i] = floatValue;
+ }
+
+ if(floatFeatureVector[(i - 1)] > 0.0)
+ {
+ //for penup and pendown
+ floatFeatureVector[(i - 1)] = 1;
+ }
+
+ //Initialised the neuralnet traning feature
+ (*shapeFeatureIter)->initialize(floatFeatureVector);
+
+ floatFeatureVector.clear();
+
+ }
+
+ shapeSampleFeatures.setFeatureVector(shapeFeature);
+ shapeSampleFeatures.setClassID(shapeId);
+
+ m_trainSet.push_back(shapeSampleFeatures);
+
+ //Initialised the output vector (output node) for nuralne net traning
+ doubleVector tempVector(m_numShapes);
+ m_outputLayerContentVec.push_back(tempVector);
+ tempVector.clear();
+
+ ++index; // for next shape
+ }
+ else
+ {
+ //for putting duplicate copy for same traning
+ if(index != patternId)
+ {
+ if(index == 0)
+ initIndexVec[index] = 0;
+ else
+ initIndexVec[index] = (countVector[index - 1] + 1);
+ }
+ }
+
+ // for back to the first class
+ if(index == m_numShapes)
+ {
+ index = 0;
+
+ if(initIndexVec[patternId] > countVector[patternId])
+ {
+ isPrepareTraningSet = true;
+ }
+ }
+ }
+
+ }//end try
+ catch(LTKException e)
+ {
+ cout<<"Could not produce traning sequence." <<"\nPlease check the traning sequence."<<endl;
+
+ shapeSamplesVec.clear();
+
+ countVector.clear();
+
+ initIndexVec.clear();
+
+ m_trainSet.clear();
+
+ throw e;
+ }
+
+ shapeSamplesVec.clear();
+
+ countVector.clear();
+
+ initIndexVec.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::prepareNeuralNetTraningSequence()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : trainFromFeatureFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::trainFromFeatureFile(const string& featureFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+
+ //TIME NEEDED
+
+ //Count for the no. of samples read for a shape
+ int sampleCount = 0;
+
+ //Count of the no. of shapes read so far
+ int shapeCount = 0;
+
+ //ID for each shapes
+ int shapeId = -1;
+
+ //classId of the character
+ int prevClassId = -1;
+
+ //Flag to skip reading a newline in the list file, when a new class starts
+ bool lastshapeIdFlag = false;
+
+ //Flag is set when EOF is reached
+ bool eofFlag = false;
+
+ //Line from the list file
+ string line = "";
+
+ //Indicates the first class
+ bool initClassFlag = false;
+
+ //Input Stream for feature file
+ ifstream featureFileHandle;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ //Opening the feature file for reading mode
+ featureFileHandle.open(featureFilePath.c_str(), ios::in);
+
+ //Throw an error if unable to open the training list file
+ if(!featureFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EFEATURE_FILE_OPEN << " " <<
+ getErrorMessage(EFEATURE_FILE_OPEN) <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(EFEATURE_FILE_OPEN);
+
+ }
+
+ //Reading feature file header
+ getline(featureFileHandle, line, NEW_LINE_DELIMITER);
+ stringStringMap headerSequence;
+ int errorCode = SUCCESS;
+ errorCode = m_shapeRecUtil.convertHeaderToStringStringMap(line, headerSequence);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ while(!featureFileHandle.eof())
+ {
+ if( lastshapeIdFlag == false )
+ {
+ //Get a line from the feature file
+ getline(featureFileHandle, line, NEW_LINE_DELIMITER);
+
+ if( featureFileHandle.eof() )
+ {
+ eofFlag = true;
+ }
+
+ if((getShapeSampleFromString(line, shapeSampleFeatures) != SUCCESS) && (eofFlag == false) )
+ continue;
+
+ shapeId = shapeSampleFeatures.getClassID();
+
+ if(eofFlag == false)
+ {
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "The NeuralNet Shape recognizer requires training file class Ids to be positive integers and listed in the increasing order" <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ errorCode = EINVALID_SHAPEID;
+ break;
+ }
+ else if(shapeId < prevClassId)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "Shape IDs in the train list file should be in the increasing order. Please use scripts/validateListFile.pl to generate list files." <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ errorCode = EINVALID_ORDER_LISTFILE;
+ break;
+ }
+ }
+
+ if( initClassFlag == false )
+ {
+ initClassFlag = true;
+ prevClassId=shapeId;
+ }
+
+ }
+ else //Do not read next line during this iteration
+ {
+ //flag unset to read next line during the next iteration
+ lastshapeIdFlag = false;
+ }
+ // Sample of the same class seen, keep pushing to the shapeSamplesVec
+ if( shapeId == prevClassId )
+ {
+ //---------------------shapeSamplesVec.push_back(shapeSampleFeatures);
+ ++sampleCount;
+ //All the samples are pushed to trainSet for neuralnet traning
+ m_trainSet.push_back(shapeSampleFeatures);
+
+ shapeSampleFeatures.clearShapeSampleFeatures();
+ }
+ // Sample of a new class seen, or end of feature file reached, train the recognizer on the samples of the previous class
+ if( shapeId != prevClassId || eofFlag == true )
+ {
+ //Increase shape count only if there are atleast one sample per class
+ if( sampleCount > 0 )
+ shapeCount++;
+
+ //check that shapecount must not be greater than specified number
+ //of shapes, if projecttype was not dynamic
+ if( !m_projectTypeDynamic && shapeCount > m_numShapes )
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+ break;
+ }
+
+ if( shapeCount > 0 && sampleCount > 0 )
+ {
+ //Clearing the shapeSampleVector and clusteredShapeSampleVector
+ //---------------clusteredShapeSampleVec.clear();
+ //----------------shapeSamplesVec.clear();
+
+ //number of sample present in the traning shape
+ m_sampleCountVec.push_back(sampleCount);
+
+ //Resetting sampleCount for the next class
+ sampleCount = 0;
+
+ //Set the flag so that the already read line of next class in the list file is not lost
+ lastshapeIdFlag = true;
+
+ prevClassId = shapeId;
+ }
+ }
+ }
+
+ featureFileHandle.close();
+
+ if(!m_projectTypeDynamic && shapeCount != m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_SHAPES << " " <<
+ getErrorMessage(EINVALID_NUM_OF_SHAPES) <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ {
+ m_numShapes = shapeCount;
+ }
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::trainFromFeatureFile()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : getShapeSampleFromString
+ * DESCRIPTION : This method get the Shape Sample Feature from a given line
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::getShapeSampleFromString(const string& inString, LTKShapeSample& outShapeSample)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::getShapeSampleFromString()" << endl;
+
+
+ //Line is split into tokens
+ stringVector tokens;
+
+ //Class Id
+ int classId = -1;
+
+ //Feature Vector string
+ string strFeatureVector = "";
+
+ //Tokenize the string
+ int errorCode = LTKStringUtil::tokenizeString(inString, EMPTY_STRING, tokens);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ //Tokens must be of size 2, one is classId and other is Feature Vector
+ if( tokens.size() != 2)
+ return FAILURE;
+
+ //Tokens[0] indicates the path name
+ classId = atoi(tokens[0].c_str());
+
+ //Tokens[1] indicates the shapeId
+ strFeatureVector = tokens[1];
+
+ errorCode = LTKStringUtil::tokenizeString(strFeatureVector, FEATURE_EXTRACTOR_DELIMITER, tokens);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVector;
+ LTKShapeFeaturePtr shapeFeature;
+
+ for(int i = 0; i < tokens.size(); ++i)
+ {
+ shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+ if(shapeFeature->initialize(tokens[i]) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct" <<
+ " NeuralNetShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+ shapeFeatureVector.push_back(shapeFeature);
+ }
+
+ //Set the feature vector and class id to the shape sample features
+ outShapeSample.setFeatureVector(shapeFeatureVector);
+ outShapeSample.setClassID(classId);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::getShapeSampleFromString()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : PreprocParametersForFeatureFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::PreprocParametersForFeatureFile(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::PreprocParametersForFeatureFile()" << endl;
+
+ //preproc sequence
+ headerSequence[PREPROC_SEQ] = "NA";
+ //ResampTraceDimension
+ headerSequence[TRACE_DIM] = "NA";
+ // preserve aspect ratio
+ headerSequence[PRESER_ASP_RATIO] = "NA";
+ //NormPreserveRelativeYPosition
+ headerSequence[PRESER_REL_Y_POS] = "NA";
+ // NormPreserveAspectRatioThreshold
+ headerSequence[ASP_RATIO_THRES] = "NA";
+ // NormLineWidthThreshold
+ headerSequence[DOT_SIZE_THRES] = "NA";
+ // NormDotSizeThreshold
+ headerSequence[DOT_THRES] = "NA";
+ //ResampPointAllocation
+ headerSequence[RESAMP_POINT_ALLOC] = "NA";
+ //SmoothWindowSize
+ headerSequence[SMOOTH_WIND_SIZE] = "NA";
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::PreprocParametersForFeatureFile()" << endl;
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : getShapeFeatureFromInkFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ if ( inkFilePath.empty() )
+ return FAILURE;
+
+ LTKCaptureDevice captureDevice;
+ LTKScreenContext screenContext;
+
+ LTKTraceGroup inTraceGroup, preprocessedTraceGroup;
+ inTraceGroup.emptyAllTraces();
+
+ int returnVal = m_shapeRecUtil.readInkFromFile(inkFilePath,
+ m_lipiRootPath, inTraceGroup,
+ captureDevice, screenContext);
+
+ if (returnVal!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<returnVal<<
+ " NeuralNetShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(returnVal);
+ }
+
+ m_ptrPreproc->setCaptureDevice(captureDevice);
+ m_ptrPreproc->setScreenContext(screenContext);
+
+ preprocessedTraceGroup.emptyAllTraces();
+
+ //Preprocessing to be done for the trace group that was read
+ int errorCode = preprocess(inTraceGroup, preprocessedTraceGroup);
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Extract feature from the preprocessed trace group
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : computeConfidence
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::computeConfidence()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::computeConfidence()" << endl;
+
+ // Temporary vector to store the recognition results
+ LTKShapeRecoResult outResult;
+
+ int index = 0;
+
+ //itaretor for the recognition result
+ double2DVector::const_iterator outputLayerRowIter = m_outputLayerContentVec.begin();
+
+ double2DVector::const_iterator outputLayerRowIterEnd = m_outputLayerContentVec.end();
+
+ for(; outputLayerRowIter != outputLayerRowIterEnd; outputLayerRowIter++)
+ {
+ doubleVector::const_iterator colItr = (*outputLayerRowIter).begin();
+
+ doubleVector::const_iterator colItrEnd = (*outputLayerRowIter).end();
+
+ for(; colItr != colItrEnd; colItr++)
+ {
+ int classID = index++;
+
+ double confidence = (*colItr);
+
+ outResult.setShapeId(classID);
+
+ outResult.setConfidence(confidence);
+
+ m_vecRecoResult.push_back(outResult);
+ }
+ }
+
+ //Sort the result vector in descending order of confidence
+ sort(m_vecRecoResult.begin(), m_vecRecoResult.end(), sortResultByConfidence);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::computeConfidence()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : sortResultByConfidence
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+bool NeuralNetShapeRecognizer::sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y)
+{
+ return (x.getConfidence()) > (y.getConfidence());
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : recognize
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVector,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::recognize()" << endl;
+
+ // Validating numChoices: valid values: {-1, (0,m_numShapes]}
+ if(numChoices <= 0 && numChoices != NUM_CHOICES_FILTER_OFF)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<")<=0, setting it to off (-1)"<<endl;
+ numChoices = -1;
+ }
+
+ if(!m_projectTypeDynamic && numChoices > m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<") > numShapes ("<<
+ m_numShapes<<"), using numShapes "<<m_numShapes<<" instead"<<endl;
+ numChoices = m_numShapes;
+ }
+
+ int index;
+
+ //store the feature for network
+ double2DVector outptr;
+
+ //initialised the network parameter
+ doubleVector tempVector(m_numShapes);
+
+ m_outputLayerContentVec.push_back(tempVector);
+
+ for( index = 0; index < (m_neuralnetNumHiddenLayers + 2); ++index)
+ {
+ doubleVector tempDoubleV((m_layerOutputUnitVec[index] + 1));
+
+ outptr.push_back(tempDoubleV);
+
+ tempDoubleV.clear();
+ }
+
+ for(index = 0; index < (m_neuralnetNumHiddenLayers + 1); ++index)
+ {
+ outptr[index][m_layerOutputUnitVec[index]] = 1.0;
+ }
+
+ //compute the forward algo for recognition performance
+ int errorCode = feedForward(shapeFeatureVector,outptr,0);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = computeConfidence();
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //copy the recognition result
+ outResultVector = m_vecRecoResult;
+
+ //clear the network parameter
+ m_vecRecoResult.clear();
+ m_outputLayerContentVec.clear();
+ outptr.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : recognize
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::recognize()" << endl;
+
+ if(traceGroup.containsAnyEmptyTrace())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<EEMPTY_TRACE << " " <<
+ " Input trace is empty"<<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+
+ //Contains TraceGroup after Preprocessing is done
+ LTKTraceGroup preprocessedTraceGroup;
+
+
+ //Preprocess the traceGroup
+ int errorCode = preprocess(traceGroup, preprocessedTraceGroup);
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Extract the shapeSample from preprocessedTraceGroup
+ if(!m_ptrFeatureExtractor)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ENULL_POINTER << " " <<
+ " m_ptrFeatureExtractor is NULL"<<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+ LTKReturnError(ENULL_POINTER);
+ }
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVec;
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ // call recognize with featureVector
+
+ if(recognize( shapeFeatureVec, inSubSetOfClasses, confThreshold,
+ numChoices, outResultVector) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " NeuralNetShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : constractNeuralnetLayeredStructure
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()" << endl;
+
+ int sizeOfTraningSet = m_trainSet.size();
+ if(sizeOfTraningSet == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty traning set) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ int outputLayerIndex;
+
+ //Store how many feature extracted from a sample (i.e the number of input node)
+ int inputNodes = 0;
+
+ vector<LTKShapeFeaturePtr> shapeFeature = m_trainSet[0].getFeatureVector();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = shapeFeature.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = shapeFeature.end();
+
+ //itaretor through all the feature vector
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+ int dimention = (*shapeFeatureIter)->getFeatureDimension();
+
+ inputNodes += dimention;
+ }
+
+ if(inputNodes <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_INPUT_NODE << "(Input node must be grater then zero) " <<
+ getErrorMessage(EINVALID_NUM_OF_INPUT_NODE)<<
+ " NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()" << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_INPUT_NODE);
+ }
+
+ // input node
+ m_layerOutputUnitVec[0] = inputNodes;
+
+ outputLayerIndex = (m_layerOutputUnitVec.size() - 2);
+
+ if(m_numShapes <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_OUTPUT_NODE << "(Output node must be grater than zero) " <<
+ getErrorMessage(EINVALID_NUM_OF_OUTPUT_NODE)<<
+ " NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()" << endl;
+
+ LTKReturnError(EINVALID_NUM_OF_OUTPUT_NODE);
+ }
+
+ // output node
+ m_layerOutputUnitVec[outputLayerIndex] = m_numShapes;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::constractNeuralnetLayeredStructure()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : prepareNetworkArchitecture
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::prepareNetworkArchitecture()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::prepareNetworkArchitecture" << endl;
+
+ int index;
+
+ int returnStatus = SUCCESS;
+
+ //Temporary vector for network parameter
+ double2DVector outptr,errptr,target;
+
+ //Store the error value of the network
+ doubleVector ep;
+
+ //Configur the node and layer of the network
+ returnStatus = constractNeuralnetLayeredStructure();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::prepareNetworkArchitecture()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ returnStatus = initialiseNetwork(outptr,errptr);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::prepareNetworkArchitecture()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ //Backpropogate function for creating the network
+ returnStatus = adjustWeightByErrorBackpropagation(outptr,errptr,ep);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::prepareNetworkArchitecture()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting NeuralNetShapeRecognizer::prepareNetworkArchitecture" <<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : initialiseNetwork
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::initialiseNetwork(double2DVector& outptr,double2DVector& errptr)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::initialiseNetwork()" << endl;
+
+ //Chack the total number of layer is correctly specified
+ int numLayer = (m_layerOutputUnitVec.size());
+
+ if((m_neuralnetNumHiddenLayers + 3) != numLayer) // 3 because input layer + output layer + one extra
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NETWORK_LAYER << "(Network layer does not match) " <<
+ getErrorMessage(EINVALID_NETWORK_LAYER)<<
+ " NeuralNetShapeRecognizer::initialiseNetwork()" << endl;
+
+ LTKReturnError(EINVALID_NETWORK_LAYER);
+ }
+
+ int index;
+
+ //initialised all the parameter which are need
+ for(index = 0; index < (m_neuralnetNumHiddenLayers + 2); ++index)
+ {
+ doubleVector tempDoubleVec(((m_layerOutputUnitVec[index] + 1) * m_layerOutputUnitVec[index+1]));
+
+ m_connectionWeightVec.push_back(tempDoubleVec);
+
+ m_delW.push_back(tempDoubleVec);
+
+ m_previousDelW.push_back(tempDoubleVec);
+
+ tempDoubleVec.clear();
+
+ doubleVector tempDoubleV((m_layerOutputUnitVec[index] + 1));
+
+ outptr.push_back(tempDoubleV);
+
+ errptr.push_back(tempDoubleV);
+
+ tempDoubleV.clear();
+ }
+
+ for(index = 0; index < (m_neuralnetNumHiddenLayers + 1); ++index)
+ {
+ outptr[index][m_layerOutputUnitVec[index]] = 1.0;
+ }
+
+ if(!m_isNeuralnetWeightReestimate)
+ {
+ //For randomly initialised the weight of the network
+ srand(m_neuralnetRandomNumberSeed);
+
+ for(index = 0; index < (m_neuralnetNumHiddenLayers + 2); ++index)
+ {
+ for(int i = 0; i < ((m_layerOutputUnitVec[index] + 1) * m_layerOutputUnitVec[index+1]); ++i)
+ {
+ m_connectionWeightVec[index][i] = (double) ((double)rand()/((double)RAND_MAX) - 0.5);
+ m_delW[index][i] = 0.0;
+ m_previousDelW[index][i] = 0.0;
+ }
+ }
+ }
+ else
+ {
+ //Initialised neuralnet from previously train weight
+ cout<<"Loading initial weight and acrhitecture from previously train data"<<endl;
+ int returnStatus = loadModelData();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NeuralNetShapeRecognizer::initialiseNetwork()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting NeuralNetShapeRecognizer::initialiseNetwork()" <<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : feedForward
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::feedForward(const vector<LTKShapeFeaturePtr>& shapeFeature,double2DVector& outptr,const int& currentIndex)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entaring " <<
+ "NeuralNetShapeRecognizer::feedForward" << endl;
+
+ if(shapeFeature.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty traning set) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::feedForward()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ if(m_layerOutputUnitVec.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty network layer) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::feedForward()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ if(m_connectionWeightVec.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty network weights) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::feedForward()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ double normalizationFactor = m_neuralnetNormalizationFactor;
+
+ if(normalizationFactor <= 0.0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENON_POSITIVE_NUM <<"(Normalised factor should be posative)" <<
+ getErrorMessage(ENON_POSITIVE_NUM)<<
+ " NeuralNetShapeRecognizer::feedForward()" << endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+
+ int index;
+
+ int offset;
+
+ int lInddex; //Layer index
+
+ int nodeIndex; // node index
+
+ double net;
+
+ //input level output calculation
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = shapeFeature.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = shapeFeature.end();
+
+ nodeIndex = 0;
+
+ // assign content to input layer
+ //itaretor through all the feature vector
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+ floatVector floatFeatureVector;
+
+ (*shapeFeatureIter)->toFloatVector(floatFeatureVector);
+
+ int vectorSize = floatFeatureVector.size();
+
+ for (int i=0; i< vectorSize; i++)
+ {
+ double floatValue = floatFeatureVector[i];
+
+ // Normalised the feature, so that the feature value lies between 0 to 1
+ floatValue /= normalizationFactor;
+
+ outptr[0][nodeIndex++] = floatValue;
+ }
+ }
+
+ // assign output(activation) value
+ // to each neuron usng sigmoid func
+ //hidden & output layer output calculation
+ for (lInddex = 1; lInddex < m_neuralnetNumHiddenLayers + 2; lInddex++) // For each layer
+ {
+ // For each neuron in current layer
+ for (nodeIndex = 0; nodeIndex < m_layerOutputUnitVec[lInddex]; nodeIndex++)
+ {
+ net=0.0;
+
+ // For input from each neuron in preceeding layer
+ for (index = 0; index < m_layerOutputUnitVec[lInddex - 1]+1; index++)
+ {
+ offset = (m_layerOutputUnitVec[lInddex - 1]+1) * nodeIndex + index;
+
+ // Apply weight to inputs and add to net
+ net += (m_connectionWeightVec[lInddex - 1][offset] * outptr[lInddex - 1][index]);
+ }
+
+ // Apply sigmoid function
+ outptr[lInddex][nodeIndex] = calculateSigmoid(net);
+ }
+
+ }
+
+ // returns currentIndex'th output of the net
+ for (nodeIndex = 0; nodeIndex < m_layerOutputUnitVec[m_neuralnetNumHiddenLayers + 1]; nodeIndex++)
+ {
+ m_outputLayerContentVec[currentIndex][nodeIndex] = outptr[m_neuralnetNumHiddenLayers + 1][nodeIndex];
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::feedForward()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : introspective
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::introspective(const doubleVector& ep, const double currentError, const int& currentItr, int& outConvergeStatus)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entaring " <<
+ "NeuralNetShapeRecognizer::introspective" << endl;
+
+ if(ep.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty individual error set) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::introspective()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ if(currentError < 0.0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENEGATIVE_NUM << "(Current error can't be nagative) " <<
+ getErrorMessage(ENEGATIVE_NUM)<<
+ " NeuralNetShapeRecognizer::introspective()" << endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ if(currentItr < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENEGATIVE_NUM << "(Itaretion can't be nagative) " <<
+ getErrorMessage(ENEGATIVE_NUM)<<
+ " NeuralNetShapeRecognizer::introspective()" << endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ bool isConverge;
+
+ int index;
+
+ int nsnew;
+
+ int traningSetSize = m_trainSet.size();
+
+ // reached max. iteration ?
+ if (currentItr >= m_neuralnetMaximumIteration)
+ {
+ cout<<"Successfully complete traning (Maximum iteration reached)"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Successfully complete traning (Maximum iteration reached) : " <<
+ currentItr << endl;
+
+ outConvergeStatus = (EXIT_FAILURE);
+ }
+ else
+ {
+ // error for each pattern small enough?
+ isConverge = true;
+
+ for (index = 0; (index < traningSetSize) && (isConverge); index++)
+ {
+ if (ep[index] >= m_neuralnetIndividualError)
+ isConverge = false;
+ }
+
+ if(isConverge)
+ {
+ cout<<"Successfully complete traning (individual error suficently small) : "<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Successfully complete traning (Individual error suficently small) : " << endl;
+
+ outConvergeStatus = (EXIT_SUCCESSFULLY);
+ }
+ else
+ {
+ // system total error small enough?
+ if (currentError <= m_neuralnetTotalError)
+ {
+ cout<<"Successfully complete traning (Total error suficently small) : "<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Successfully complete traning (Total error suficently small) : " << endl;
+
+ outConvergeStatus = (EXIT_SUCCESSFULLY);
+ }
+ else
+ {
+ //Continue traning itaretion
+ outConvergeStatus = (CONTINUE);
+ }
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::introspective" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : adjustWeightByErrorBackpropagation
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::adjustWeightByErrorBackpropagation(double2DVector& outptr,double2DVector& errptr,doubleVector& ep)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entaring " <<
+ "NeuralNetShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ if(outptr.size() == 0 || errptr.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ int totalNumberOfSample = m_trainSet.size();
+
+ if(totalNumberOfSample == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_VECTOR << "(Empty traning set) " <<
+ getErrorMessage(EEMPTY_VECTOR)<<
+ " NeuralNetShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ int outResult;
+
+ int nIndex; // node index
+
+ int offset; // offfset index of the vector
+
+ int layerIndex; //Layer index
+
+ int nodeIndex; // node or neuron index
+
+ int sampleIndex;
+
+ int nsold = 0;
+
+ int itaretorIndex = 0; // itaretorIndex
+
+ double actualOutput;
+
+ double currentError;
+
+ ep = doubleVector( totalNumberOfSample ); //errror per sample // individual error
+
+ cout<<"After preparing traning sequence" <<
+ "(made all shape same number of traning sample" <<
+ " as the highest number of sample present in orginal traning list) :"<<
+ totalNumberOfSample << endl;
+
+ /////////////////////////////////////////////////////
+ outResult = CONTINUE;
+
+ do
+ {
+ currentError = 0.0;
+ //for each pattern
+ for(sampleIndex = 0; sampleIndex < totalNumberOfSample; sampleIndex++)
+ {
+
+ vector<LTKShapeFeaturePtr> shapeFeature = m_trainSet[sampleIndex].getFeatureVector();
+ //bottom_up calculation
+ // update output values for each neuron
+ int errorCode = feedForward(shapeFeature,outptr,sampleIndex);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ shapeFeature.clear();
+
+ //top_down error propagation output_level error
+ // find error for output layer
+ for(layerIndex = 0; layerIndex < m_layerOutputUnitVec[ (m_neuralnetNumHiddenLayers + 1) ]; layerIndex++)
+ {
+ actualOutput= outptr[ (m_neuralnetNumHiddenLayers+1)][layerIndex];
+ errptr[(m_neuralnetNumHiddenLayers + 1)][layerIndex] = ((m_targetOutputVec[sampleIndex][layerIndex] - actualOutput) *
+ (1 - actualOutput) * actualOutput);
+ }
+
+ // hidden & input layer errors
+ for(layerIndex = (m_neuralnetNumHiddenLayers+1); layerIndex >= 1; layerIndex--)
+ {
+ for(nodeIndex = 0; nodeIndex < m_layerOutputUnitVec[layerIndex - 1]+1; nodeIndex++)
+ {
+ errptr[layerIndex-1][nodeIndex] = 0.0;
+ for(nIndex = 0; nIndex < m_layerOutputUnitVec[layerIndex]; nIndex++)
+ {
+ offset = (m_layerOutputUnitVec[layerIndex-1]+1) * nIndex + nodeIndex;
+
+ m_delW[layerIndex-1][offset] = m_neuralnetLearningRate * (errptr[layerIndex][nIndex]) *
+ (outptr[layerIndex - 1][nodeIndex]) + m_neuralnetMomemtumRate *
+ (m_previousDelW[layerIndex - 1][offset]);
+
+ errptr[layerIndex-1][nodeIndex] += (errptr[layerIndex][nIndex]) *
+ (m_connectionWeightVec[layerIndex - 1][offset]);
+ }
+
+ (errptr[layerIndex - 1][nodeIndex]) = (errptr[layerIndex - 1][nodeIndex]) *
+ (1- (outptr[layerIndex - 1][nodeIndex])) *
+ (outptr[layerIndex - 1][nodeIndex]);
+ }
+ }
+
+ // connection weight changes
+ // adjust weights usng steepest descent
+ for(layerIndex = 1 ; layerIndex < (m_neuralnetNumHiddenLayers + 2); layerIndex++)
+ {
+ for(nodeIndex = 0; nodeIndex < m_layerOutputUnitVec[layerIndex]; nodeIndex++)
+ {
+ for(nIndex = 0; nIndex < m_layerOutputUnitVec[layerIndex-1]+1; nIndex++)
+ {
+ offset= (m_layerOutputUnitVec[layerIndex - 1] + 1) * nodeIndex + nIndex;
+
+ (m_connectionWeightVec[layerIndex - 1][offset]) += (m_delW[layerIndex - 1][offset]);
+ }
+ }
+ }
+
+ //current modification amount saved
+ for(layerIndex = 1; layerIndex < m_neuralnetNumHiddenLayers + 2; layerIndex++)
+ {
+ for(nodeIndex = 0; nodeIndex < m_layerOutputUnitVec[layerIndex]; nodeIndex++)
+ {
+ for(nIndex = 0; nIndex < m_layerOutputUnitVec[layerIndex - 1] + 1; nIndex++)
+ {
+ offset = (m_layerOutputUnitVec[layerIndex - 1] + 1) * nodeIndex + nIndex;
+
+ (m_previousDelW[layerIndex - 1][offset]) = (m_delW[layerIndex - 1][offset]);
+ }
+ }
+ }
+
+ //update individula error for find mean square error
+ ep[sampleIndex] = 0.0;
+
+ for(layerIndex = 0; layerIndex < m_layerOutputUnitVec[m_neuralnetNumHiddenLayers+1]; layerIndex++)
+ {
+
+ ep[sampleIndex] += fabs((m_targetOutputVec[sampleIndex][layerIndex] -
+ (outptr[m_neuralnetNumHiddenLayers+1][layerIndex])));
+
+ }
+
+ currentError +=ep[sampleIndex] * ep[sampleIndex];
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<sampleIndex <<" ->" <<currentError <<endl;
+
+ }
+
+ //mean square error
+ currentError =0.5 * currentError / (double)( totalNumberOfSample * m_numShapes );
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"itaretion = "<<itaretorIndex<<"||"<<"Mean square error = "<<currentError<<endl;
+
+ cout <<"Itaretion = " << itaretorIndex <<"||"
+ <<"Mean square error = " << currentError << endl;
+
+ itaretorIndex++;
+
+ // check condition for terminating learning
+ int errorCode = introspective(ep,currentError,itaretorIndex,outResult);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ } while (outResult == CONTINUE);
+
+ //update output with changed weights
+ for (sampleIndex = 0; sampleIndex < totalNumberOfSample; sampleIndex++)
+ {
+ vector<LTKShapeFeaturePtr> shapeFeature = m_trainSet[sampleIndex].getFeatureVector();
+
+ int errorCode = feedForward(shapeFeature,outptr,sampleIndex);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ shapeFeature.clear();
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NeuralNetShapeRecognizer::adjustWeightByErrorBackpropagation()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : calculateSigmoid
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+double NeuralNetShapeRecognizer ::calculateSigmoid(double inNet)
+{
+ return (double)(1/(1+exp(-inNet)));
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : addClass
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID)
+{
+ // Should be moved to nnInternal
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::addClass()" << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NeuralNetShapeRecognizer::addClass"<<endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : addSample
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::addSample(const LTKTraceGroup& sampleTraceGroup, int shapeID)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NeuralNetShapeRecognizer::addSample()" << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NeuralNetShapeRecognizer::addSample"<<endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tanmay Mondal
+ * SUPERVISOR : Ujjwal Bhattacharya
+ * OTHER PLP : Kalikinkar Das
+ * ORGANIZATION : Indian Statistical Institute, Kolkata, India
+ * DEPARTMENT : Computer Vision and Pattern Recognition Unit
+ * DATE :
+ * NAME : deleteClass
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : int:
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NeuralNetShapeRecognizer::deleteClass(int shapeID)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering NeuralNetShapeRecognizer::deleteClass" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting NeuralNetShapeRecognizer::deleteClass" <<endl;
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.h
new file mode 100644
index 00000000..6e32002a
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/NeuralNetShapeRecognizer.h
@@ -0,0 +1,1111 @@
+#ifndef __NEURALNETSHAPERECOGNIZER_H
+#define __NEURALNETSHAPERECOGNIZER_H
+
+/** Include files */
+#include "LTKInc.h"
+#include "LTKTypes.h"
+#include "LTKMacros.h"
+#include "LTKShapeRecognizer.h"
+#include "LTKShapeRecoUtil.h"
+#include "LTKShapeSample.h"
+#include "LTKCheckSumGenerate.h"
+
+/** Forward declaration of classes */
+class LTKTraceGroup;
+class LTKPreprocessorInterface;
+class LTKShapeSample;
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+#define SUPPORTED_MIN_VERSION "3.0.0"
+
+typedef int (*FN_PTR_CREATELTKLIPIPREPROCESSOR)(const LTKControlInfo& , LTKPreprocessorInterface** );
+typedef int (*FN_PTR_DELETELTKLIPIPREPROCESSOR)(LTKPreprocessorInterface* );
+
+
+/**
+ * @ingroup NeuralNetShapeRecognizer.h
+ * @brief The Header file for the NeuralNetShapeRecognizer
+ * @class NeuralNetShapeRecognizer
+ *<p> Fully connected feedforward multilayer perceptron
+ * backpropogation algorithm used for its training.
+ *</p>
+ */
+
+class NeuralNetShapeRecognizer: public LTKShapeRecognizer
+{
+
+ /** @name private data members */
+ //@{
+ private:
+
+ FN_PTR_DELETELTKLIPIPREPROCESSOR m_deleteLTKLipiPreProcessor;
+ //Function pointer for deleteLTKLipiPreProcessor
+
+ // preproc lib handle
+ void *m_libHandler;
+
+ // feature extractor lib handle
+ void *m_libHandlerFE;
+
+ unsigned short m_numShapes;
+ /**< @brief Number of shapes
+ * <p>
+ * It Defines the number of shapes to be recognized
+ *
+ * DEFAULT: 0
+ *
+ * Note: If the project is dynamic, then this numShapes is set to 0
+ * If the project is not dynamic, then the numShapes is read from project configuration file
+ * </p>
+ */
+
+ string m_featureExtractorName;
+ /**< @brief The Feature Extractor
+ * <p>
+ *
+ * DEFAULT:PointFloat
+ *
+ * </p>
+ */
+
+ bool m_projectTypeDynamic;
+ /**< @brief Project Dynamic
+ * <p>
+ * if projectTypeDynamic = true, then the project is dynamic i.e., the numShapes can take any number of value(s)
+ * = false, then the project is not dynamic i.e., the numShapes take value from project.cfg file
+ *
+ * DEFAULT: false
+ * </p>
+ */
+
+ LTKPreprocessorInterface *m_ptrPreproc;
+ /**< @brief Pointer to preprocessor instance
+ * <p>
+ * Instance which is used to call the preprocessing methods before recognition
+ *
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_neuralnetCfgFilePath;
+ /**< @brief Full path of NeuralNet configuration file
+ * <p>
+ * Assigned value in the NeuralNetShapeRecognizer::initialize function
+ * </p>
+ */
+
+ string m_neuralnetMDTFilePath;
+ /**< @brief Full path of Model data file
+ * <p>
+ * Assigned value in the NeuralNetShapeRecognizer::initialize function
+ * </p>
+ */
+
+ stringStringMap m_headerInfo;
+ /**< @brief Header Information
+ * <p>
+ * </p>
+ */
+
+ LTKShapeRecoUtil m_shapeRecUtil;
+ /**< @brief Pointer to LTKShapeRecoUtil class
+ * <p>
+ * Instance used to call Shape Recognizer Utility functions
+ *
+ * DEFAULT: NULL
+ */
+
+ string m_lipiRootPath;
+ /**< @brief Path of the Lipi Root
+ * <p>
+ * DEFAULT: LipiEngine::getLipiPath()
+ * </p>
+ */
+
+ string m_lipiLibPath;
+ /**< @brief Path of the Lipi Libraries
+ * <p>
+ * DEFAULT: LipiEngine::getLipiPath()
+ * </p>
+ */
+
+ LTKShapeFeatureExtractor *m_ptrFeatureExtractor;
+ /**< @brief Pointer to LTKShapeFeatureExtractor class
+ * <p>
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_preProcSeqn;
+ /**< @brief Preprocessor Sequence
+ * <p>
+ * This string holds the sequence of preprocessor methods
+ * </p>
+ */
+
+ vector<stringStringPair> m_preprocSequence;
+ /**< @brief Preprocessor Sequence vector
+ * <p>
+ * This vector of string holds the sequence of preprocessor methods
+ * </p>
+ */
+
+ vector<LTKShapeRecoResult> m_vecRecoResult;
+ /**< @brief Store Recognize results
+ * <p>
+ * This vector hold shape ID and its confidance value
+ * </p>
+ */
+
+ int m_neuralnetRandomNumberSeed;
+ /**< @brief Store seed value for random number generator
+ *
+ * <p>
+ * This integer variable hold the seed value of random number generator for initialization of network weights
+ *
+ * DEFAULT : NEURALNET_DEF_RANDOM_NUMBER_SEED
+ * </p>
+ */
+
+ float m_neuralnetNormalizationFactor;
+ /**< @brief Store the normalisation factor to normalise the input feature component value between (-1 to +1)
+ * It is used during genaration of training / testing feature vector
+ * <p>
+ *
+ * DEFAULT : NEURALNET_DEF_NORMALIZE_FACTOR
+ * </p>
+ */
+
+ float m_neuralnetLearningRate;
+ /**< @brief Learning rate of backpropagation algorithm
+ *
+ * <p>
+ *
+ * DEFAULT : NEURALNET_DEF_LEARNING_RATE
+ * </p>
+ */
+
+ float m_neuralnetMomemtumRate;
+ /**< @brief Momentum rate of backpropagation algorithm
+ *
+ * <p>
+ *
+ * DEFAULT : NEURALNET_DEF_MOMEMTUM_RATE
+ * </p>
+ */
+
+ double m_neuralnetTotalError;
+ /**< @brief Store the threshold value of the system error
+ * (i.e total error of network response during an epoch)
+ *
+ * <p>
+ * Used for training convergence criterion
+ *
+ * DEFAULT : NEURALNET_DEF_TOTAL_ERROR
+ * </p>
+ */
+
+ double m_neuralnetIndividualError;
+ /**< @brief Store the threshold value of the network response error per
+ * inidividual sample
+ *
+ * <p>
+ * Used for training convergence criterion
+ *
+ * DEFAULT : NEURALNET_DEF_INDIVIDUAL_ERROR
+ * </p>
+ */
+
+ int m_neuralnetNumHiddenLayers;
+ /**< @brief Number of hidden layers of the neural net
+ *
+ * <p>
+ *
+ * DEFAULT : NEURALNET_DEF_HIDDEN_LAYERS_SIZE
+ * </p>
+ */
+
+ int m_neuralnetMaximumIteration;
+ /**< @brief Number of iteration
+ *
+ * <p>
+ * Used for upper bound of traning iteration
+ *
+ * DEFAULT : NEURALNET_DEF_MAX_ITR
+ * </p>
+ */
+
+ bool m_isCreateTrainingSequence;
+ /**< @brief If true generate input sequence of feature vectors for training
+ *
+ * <p>
+ *
+ * DEFAULT : true
+ * </p>
+ */
+
+ double2DVector m_connectionWeightVec;
+ /**< @brief Store network connection weight
+ * <p>
+ *
+ * </p>
+ */
+
+ double2DVector m_delW;
+ /**< @brief Store error derivatives with respect to network weights
+ * <p>
+ *
+ * </p>
+ */
+
+ double2DVector m_previousDelW;
+ /**< @brief Store values of m_delW during last but one iteration
+ * <p>
+ *
+ * </p>
+ */
+
+ double2DVector m_outputLayerContentVec;
+ /**< @brief Store values of output layer node
+ * <p>
+ *
+ * </p>
+ */
+
+ double2DVector m_targetOutputVec;
+ /**< @brief Store values of target output vactor components for each training sample
+ * <p>
+ *
+ * </p>
+ */
+
+ intVector m_layerOutputUnitVec;
+ /**< @brief Stores numbere of nodes at different layers of the network
+ * <p>
+ *
+ * </p>
+ */
+
+ bool m_isNeuralnetWeightReestimate;
+ /**< @brief If true the neural net is initialised using a previously trained network information
+ * this information is obtained from neuralnet.mdt file
+ * <p>
+ *
+ * </p>
+ */
+
+ float m_rejectThreshold;
+ /**< @brief Threshold on the confidence to declare a test sample rejected
+ * <p>
+ * DEFAULT : 0.01
+ * </p>
+ */
+
+ intVector m_sampleCountVec;
+ /**< @brief Number of training samples present in each category
+ * <p>
+ *
+ * </p>
+ */
+
+ LTKCaptureDevice m_captureDevice;
+
+ LTKOSUtil* m_OSUtilPtr;
+ /**< @brief Pointer to LTKOSUtil interface
+ * <p>
+ *
+ * </p>
+ */
+
+ vector<LTKShapeSample> m_trainSet;
+ /**< @brief Store ShapeSampleFeatures for all training samples
+ * Used during neuralnet training
+ * <p>
+ *
+ * DEFAULT : 0.01
+ * </p>
+ */
+
+ string m_MDTFileOpenMode;
+ /**< @brief Store the neuralnet.mdt file open mode (Ascii or Binary)
+ * <p>
+ * Used during open neuralnet.mdt file
+ *
+ * DEFAULT : Ascii
+ * </p>
+ */
+
+ //@}
+
+ string m_currentVersion;
+
+ public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ NeuralNetShapeRecognizer(const LTKControlInfo& controlInfo);
+
+ /**
+ * Destructor
+ */
+ ~NeuralNetShapeRecognizer();
+
+ //@}
+
+ /**
+ * This method initializes the NeuralNet shape recognizer
+ * <p>
+ * Semantics
+ * - Set the project name in NeuralNetShapeRecognizer::headerInfo with the parameter passed <br>
+ * m_headerInfo[PROJNAME] = strProjectName;
+ *
+ * - Initialize NeuralNetShapeRecognizer::m_neuralnetCfgFilePath <br>
+ * m_neuralnetCfgFilePath = NeuralNetShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::NEURALNET + LTKInc::CONFIGFILEEXT;
+ *
+ * - Initializes NeuralNetShapeRecognizer::m_neuralnetMDTFilePath <br>
+ * m_neuralnetMDTFilePath = NeuralNetShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::NEURALNET + LTKInc::DATFILEEXT;
+ *
+ * - Initializes NeuralNetShapeRecognizer::m_projectTypeDynamic with the value returned from LTKShapeRecoUtil::isProjectDynamic
+ *
+ * - Initialize the preprocessor using LTKShapeRecoUtil::initializePreprocessor and assign
+ * default values for
+ * -# Normalised size
+ * -# Threshold size
+ * -# Aspect ratio
+ * -# Dot threshold
+ *
+ * - Initialize the instance variables of neuralnet recognizer with the values given in classifier config file
+ *
+ * </p>
+ * @param strProjectName : string : Holds the name of the Project
+ * @param strProfileName : string : Holds the name of the Profile
+ *
+ * @return int : LTKInc::SUCCESS if initialization done successfully
+ * errorValues if initialization has some errors
+ *
+ * @exception LTKErrorList::ECONFIG_FILE_OPEN Could not open project.cfg
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES Negative value for number of shapes
+ * @exception LTKErrorList::ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+
+ /**
+ * This method calls the train method of the NeuralNet classifier
+ *
+ */
+ int train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType=INK_FILE) ;
+
+ /**
+ * This method loads the Training Data of the NeuralNet classifier
+ * @param
+ * @return LTKInc::SUCCESS : if the model data was loaded successfully
+ * @exception
+ */
+ int loadModelData();
+
+ /**
+ * This method unloads all the training data
+ * @param none
+ * @return LTKInc::SUCCESS : if the model data was unloaded successfully
+ * @exception none
+ */
+ int unloadModelData();
+
+ /**
+ * This method sets the device context for the recognition
+ *
+ * @param deviceInfo parameter to be set
+ * @return
+ * @exception
+ */
+ int setDeviceContext(const LTKCaptureDevice& deviceInfo);
+
+ /**
+ * Populates a vector of LTKShapeRecoResult consisting of top classes with their confidences
+ *
+ * Semantics
+ *
+ * - Validate the input arguments
+ * - Extract the features from traceGroup
+ * - Compute the confidences of the classes, call computeConfidence()
+ * - Check if the first element of resultVector has confidence less than m_rejectThreshold, if so,
+ empty the resultVector (reject the sample), log and return.
+ * - If the confThreshold value was specified by the user (not equal to -1),
+ delete the entries from resultVector with confidence values less than confThreshold
+ * - If the numChoices value was specified by the user (not equal to -1),
+ update the resultVector with top numChoices entries, delete other values
+ *
+ * @param traceGroup The co-ordinates of the shape which is to be recognized
+ * @param screenContext Contains information about the input sample whether it is written inside a preprinted box
+ * or unconstrained continuous writing
+ * @param subSetOfClasses A subset of the entire class space which is to be used for
+ * recognizing the input shape.
+ * @param confThreshold Classes with confidence below this threshold are not returned,
+ * valid range of confThreshold: (0,1)
+ * @param numOfChoices Number of top choices to be returned in the result structure
+ * @param resultVector The result of recognition
+ *
+ * @return SUCCESS: resultVector populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector);
+
+
+ /* Overloaded the above function to take vector<LTKShapeFeaturePtr> as
+ * input
+ */
+ int recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVec,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& resultVector);
+
+ /**
+ * This method add Class
+ *
+ * Semantics
+ *
+ *
+ * @param sampleTraceGroup : LTKTraceGroup : Holds TraceGroup of sample to add
+ * @param shapeID : int : Holds shapeID of new Class
+ *
+ * @return SUCCESS:Shape Class added successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID);
+
+ /**
+ * This method add Sample Class for adapt
+ *
+ * Semantics
+ *
+ *
+ * @param sampleTraceGroup : LTKTraceGroup : Holds TraceGroup of sample to Add
+ * @param shapeID : int : Holds shapeID of new Class
+ *
+ * @return SUCCESS:Shape Class added successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int addSample(const LTKTraceGroup& sampleTraceGroup, int shapeID);
+
+ /**
+ * This method delete Class
+ *
+ * Semantics
+ *
+ * @param shapeID : int : Holds shapeID of Shape to be deleted
+ *
+ * @return SUCCESS: Shape Class deleted successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int deleteClass(int shapeID);
+
+ /**
+ * This method converts features to TraceGroup
+ *
+ * Semantics
+ *
+ *
+ * @param shapeID : int : Holds shapeID
+ * @param numberOfTraceGroups : int : Maximum number of Trace Groups to populate
+ * @param outTraceGroups : vector<LTKTraceGroup> : TraceGroup
+ *
+ * @return SUCCESS:
+ * FAILURE:
+ * @exception none
+ */
+ int getTraceGroups(int shapeID, int numberOfTraceGroups, vector<LTKTraceGroup> &outTraceGroups);
+
+
+ private:
+ /**
+ * This function is the method for generation of network architecture,
+ * creation of training samples and learning of network weights
+ *
+ *
+ * Semantics
+ *
+ * - Note the start time for computation of execution time
+ *
+ * - Call train method depending on the inFileType
+ * - NeuralNetShapeRecognizer::trainFromListFile() if inFileType = LTKMacros::INK_FILE
+ * - NeuralNetShapeRecognizer::trainFromFeatureFile() if inFileType = LTKMacros ::FEATURE_FILE
+ *
+ * - Call prepareNeuralNetTrainingSequence method depending on the m_isCreateTratningSequence
+ * - NeuralNetShapeRecognizer::prepareNeuralNetTrainingSequence() if m_isCreateTrainingSequence = true
+ *
+ * - Call NeuralNetShapeRecognizer::prepareNetworkArchitecture()
+ *
+ * - Update the headerInfo with algorithm version and name using NeuralNetShapeRecognizer::updateHeaderWithAlgoInfo() method
+ *
+ * - Calculate the checksum.
+ *
+ * - Call NeuralNetShapeRecognizer::writePrototypeSetToMDTFile()
+ *
+ * - Note the termination time for execution time computation
+ *
+ *
+ * @param inputFilePath :string : Path of trainListFile / featureFile
+ * @param strModelDataHeaderInfoFile : string : Holds the Header information of Model Data File
+ * @param inFileType : string : Possible values ink / featureFile
+ *
+ * @return LTKInc::SUCCESS : if the training done successfully
+ * @return errorCode : if it contains some error training fails
+ */
+ int trainNetwork(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string& trainFileType);
+
+
+ /**
+ * This method maps between the module names and respective function names from the cfg file
+ *
+ * Semantics
+ *
+ * - Read the Preprocess Sequence from the neuralnet.cfg file
+ *
+ * - Split the sequence into tokens with delimiter LTKMacros::DELEMITER_SEQUENCE using LTKStringUtil::tokenizeString
+ *
+ * - Split each token with delimiter LTKMacrosDELEMITER_FUNC using LTKStringUtil::tokenizeString
+ * to get the Module name and Function name
+ *
+ * - Store the Module name and the Function name into a structure
+ *
+ *
+ * @param none
+ * @return LTKInc::SUCCESS : if functions are successfully mapped,
+ * @return errorCodes : if contains any error
+ * @exception none
+ */
+ int mapPreprocFunctions();
+
+ /**
+ * This method will assign default values to the members
+ *
+ * Semantics
+ *
+ * - Assign Default values to all the data members
+ *
+ *
+ * @param none
+ *
+ * @return none
+ */
+ void assignDefaultValues();
+
+ /** Reads the NeuralNet.cfg and initializes the instance variable of the classifier with the user defined
+ * values.
+ *
+ * Semantics
+ *
+ * - Open the NeuralNet.cfg using LTKConfigFileReader
+ *
+ * - In case of file open failure (NeuralNet.cfg), default values of the classifier parameters are used
+ *
+ * - The valid values of the classifier parameters are cached into the class data members
+ * LTKConfigFileReader::getConfigValue is used to get the value for a key defined in the config file
+ *
+ * - Exception is thrown if the user has specified an invalid value for a parameter
+ *
+ *
+ * @param none
+ * @return SUCCESS : If the Config file is read successfully
+ * @return errorCode : If it contains some error
+ * @exception LTKErrorList::ECONFIG_FILE_RANGE The config file variable is not within the correct range
+ */
+ int readClassifierConfig();
+
+ /**
+ * This method creates a custom feature extractor instance and stores it's address in
+ *
+ * Semantics
+ *
+ *
+ * - Intialize the NeuralNetShapeRecognizer::m_ptrFeatureExtractor with address of the feature extractor instance created
+ * using LTKShapeFeatureExtractorFactory::createFeatureExtractor
+ *
+ * @param none
+ *
+ * @return 0 on LTKInc::SUCCESS and 1 on LTKInc::FAILURE
+ *
+ * @exception none
+ */
+ int initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo);
+
+ /**
+ * This method trains the classifier from the file containing train list whose path is passed as a paramater
+ *
+ * Semantics
+ *
+ * - Open the trainListFile for reading
+ *
+ * - Open the mdt file for writing
+ *
+ * - Write header information to the mdt file
+ * - NeuralNetShapeRecognizer::m_numShapes
+ * - NeuralNetShapeRecognizer::m_traceDimension
+ * - NeuralNetShapeRecognizer::m_flexibilityIndex
+ *
+ * - Get a valid line from the train list file
+ * - Skip commented lines
+ * - Skip lines where number_of_tokens != 2
+ * - Throw error LTKErrorList::EINITSHAPE_NONZERO, if the first shape in the list file is not zero
+ * - Throw error LTKErrorList::EINVALID_ORDER_LISTFILE if the shapes are not in sequential order
+ *
+ * - For every valid line get the ShapeSample from the ink file using NeuralNetShapeRecognizer::getShapeSampleFromInkFile
+ * - Read ink from UNIPEN ink file
+ * - Skip if the trace group is empty
+ * - Pre process the trace group read from the ink file
+ * - Extract features
+ *
+ * - Push all the ShapeSamples corresponding to a shape into a vector of ShapeSample ShapeSamplesVec
+ *
+ *
+ * @param listFilePath : string : Holds the path for train list file
+ *
+ * @return none
+ *
+ * @exception LTKErrorList::EFILE_OPEN_ERROR : Error in Opening a file (may be mdt file or list file)
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES : Invalid value for number of shapes
+ * @exception LTKErrorList::EINVALID_ORDER_LISTFILE: Invalid order of shapeId in List file
+ * @exception LTKErrorList::EINITSHAPE_NONZERO : Initial shapeId must not be zero
+ */
+ int trainFromListFile(const string& listFilePath);
+
+ /**
+ * This method trains the classifier from the feature file whose path is passed as paramater
+ *
+ * Semantics
+ *
+ *
+ * @param featureFilePath : string : Holds the path of Feature file
+ *
+ * @return none
+ */
+ int trainFromFeatureFile(const string& featureFilePath);
+
+ /**
+ * This method is used to store the preprocess parameter for header of the .mdt file
+ *
+ * Semantics
+ *
+ *
+ * @param headerSequence : stringStringMap : Holds header value of .mdt file
+ *
+ * @return none
+ */
+ int PreprocParametersForFeatureFile(stringStringMap& headerSequence);
+
+ /**
+ * This method returns the ShapeSample by using the ink file path as input
+ *
+ * Semantics
+ *
+ * - Call the LTKShapeRecoUtil::readInkFromFile() method (Utility Method) to read the ink file
+ * By reading this file, an inTraceGroup is generated
+ *
+ * - Preprocess the inTraceGroup and get the preprocessed trace group
+ * LTKTraceGroup preprocessedTraceGroup
+ *
+ * - Extract features from the preprocessed trace group to get the ShapeSamples.
+ *
+ *
+ * @param path : string : The path for Ink file
+ * @param ShapeSample : ShapeSample : The ShapeSample generated after feature extraction
+ *
+ * @return SUCCESS : If the ShapeSample is generated successfully
+ * @return FAILURE : Empty traces group detected for current shape
+ *
+ * @exception LTKErrorList::EINKFILE_EMPTY : Ink file is empty
+ * @exception LTKErrorList::EINK_FILE_OPEN : Unable to open unipen ink file
+ * @exception LTKErrorList::EINKFILE_CORRUPTED : Incorrect or corrupted unipen ink file
+ * @exception LTKErrorList::EEMPTY_TRACE : Number of points in the trace is zero
+ * @exception LTKErrorList::EEMPTY_TRACE_GROUP : Number of traces in the trace group is zero
+ */
+ int getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec);
+
+ /**
+ * This method will Update the Header information for the MDT file
+ *
+ * Semantics
+ *
+ * - Copy the version number to a string
+ *
+ * - Update the version info and algoName to NeuralNetShapeRecognizer::m_headerInfo, which specifies the
+ * header information for MDT file
+ *
+ *
+ * @param none
+ *
+ * @return none
+
+ * @exception none
+ */
+ void updateHeaderWithAlgoInfo();
+
+ /**
+ * This method do preprocessing for input trace group
+ *
+ * Semantics
+ *
+ * @param inTraceGroup : LTKTraceGroup : Store unipen ink file
+ outPreprocessedTraceGroup : LTKTraceGroup : Store preprocess ink of input ink
+ * @return
+ * @exception
+ */
+ int preprocess (const LTKTraceGroup& inTraceGroup, LTKTraceGroup& outPreprocessedTraceGroup);
+
+ /**
+ * This method write training results to the mdt file
+ *
+ * Semantics
+ *
+ * - If mdt file open mode is ASCII
+ * - Write the number of Shape
+ * - Write the connection weight
+ * - Write the derivative of connection weight
+ *
+ * - If mdt file open mode is BINARY
+ * - Write the number of Shape
+ * - Write the connection weight
+ * - Write the connection weight vector size
+ * - Write the derivative of connection weight
+ *
+ * @param none
+ * @return
+ * @exception
+ */
+ int writeNeuralNetDetailsToMDTFile();
+
+ /**
+ * This method will writes training results to the mdt file
+ *
+ * Semantics
+ *
+ * - If mdt file open mode is ASCII
+ * - Write the number of Shape
+ * - Write the connection weight
+ * - Write the derivative of connection weight
+ *
+ * - If mdt file open mode is BINARY
+ * - Write the number of Shape
+ * - Write the connection weight
+ * - Write the connection weight and derivative of connection weight vectors size
+ * - Write the derivative of connection weight
+ *
+ *
+ * @param resultVector : double2DVector : A vector of weight or weight derivative created as a result of training
+ * mdtFileHandle : ofstream : Specifies the outut stream
+ * isWeight : bool : If true then resultVector contain weight, if false then resultVector contain weight derivative
+ *
+ * @return none
+ *
+ * @exception none
+ */
+ int appendNeuralNetDetailsToMDTFile(const double2DVector& resultVector, const bool isWeight, ofstream & mdtFileHandle);
+
+ int deleteFeatureExtractorInstance();
+
+ /**
+ * This method computes the confidences for underlying classes of a test sample
+ *
+ * Semantics
+ *
+ * - Compute the confidence based on the values of m_outputLayerContentVec (output layer value of each node)
+ * - Populate the resultVector
+ * - Sort the resultVector
+ *
+ * @param none
+ *
+ * @return SUCCESS: resultVector populated
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int computeConfidence();
+
+ /**
+ * The comparison function object of STL's sort() method, overloaded for class LTKShapeRecoResult, used to sort the vector of LTKShapeRecoResult based on the member variable confidence
+ *
+ * Semantics
+ *
+ * - Compare the values of two objects
+ * - Return true or false
+ * -
+ *
+ * @param x : LTKShapeRecoResult : First object for comparison
+ * @param y : LTKShapeRecoResult : Second object for comparison
+ *
+ * @return true: If x.confidence > y.confidence
+ * false: If x.confidence <= y.confidence
+ * @exception none
+ */
+ static bool sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y);
+
+ /** This method is used to initialize the PreProcessor
+ *
+ * Semantics
+ *
+ * - Load the preprocessor DLL using LTKLoadDLL().
+ *
+ * - Get the proc address for creating and deleting the preprocessor instance.
+ *
+ * - Create preprocessor instance.
+ *
+ * - Start the logging for the preprocessor module.
+ *
+ * @param preprocDLLPath : string : Holds the Path of the Preprocessor DLL,
+ * @param errorStatus : int : Holds SUCCESS or Error Values, if occurs
+ * @return preprocessor instance
+ *
+ * @exception ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+ int initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance);
+
+
+ /** This method is used to delete the PreProcessor instance
+ *
+ * Semantics
+ *
+ * - Call deleteLTKPreprocInst from the preproc.dll.
+ *
+ * - Unload the preprocessor DLL.
+ *
+ * @param ptrPreprocInstance : Holds the pointer to the LTKPreprocessorInterface
+ * @return none
+ * @exception none
+ */
+
+ int deletePreprocessor();
+
+ /** This method is used to unload the preprocessor DLL.
+ *
+ * Semantics
+ *
+ * - If m_libHandler != NULL, unload the DLL
+ * LTKUnloadDLL(m_libHandler);
+ * m_libHandler = NULL;
+ *
+ * @param none
+ * @return none
+ * @exception none
+ */
+ int unloadPreprocessorDLL();
+
+ /** This method is used to check the preprocess parameter are specified correcty in cfg file
+ *
+ * Semantics
+ *
+ *
+ * @param headerSequence : stringStringMap :
+ * @return
+ * @exception
+ */
+ int validatePreprocParameters(stringStringMap& headerSequence);
+
+ /**
+ * MLP is trained by backpropagation algorithm. Training samples (feature vector representation) from underlying
+ * classes are presented in an alternative sequence. Error for each such pattern is calculated at the output layer
+ * Error is propagated backward for top-to-bottom layer weight adjustments
+ *
+ * Semantics
+ *
+ * - Call feedForward method for bottom-to-top propagation of training feature
+ *
+ * - Calculate the error at output layer for each nuron
+ *
+ * - Calculate weight adjustment amount for each sample presented
+ *
+ * @param : outptr : double2DVector : Hold the conteint of each node after forward propagation of a sample
+ * errptr : double2DVector : Hold intermediate error values used for computation of error derivatives
+ * at hidden & output layer
+ * ep : doubleVector : Hold output layer absolute error for individual samples
+ *
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ *
+ * @exception LTKErrorList::EEMPTY_VECTOR Vector which are used in this method is empty
+ */
+ int adjustWeightByErrorBackpropagation(double2DVector& outptr,double2DVector& errptr,doubleVector& ep);
+
+ /** This method is used to arrange training samples in an alternate sequence required for effective application of backpropagation algorithm
+ *
+ * Semantics
+ *
+ * - If the number of training samples for each class is unequal, then it repeats samples of those classes
+ * which have fewer samples in the training set
+ *
+ * - If m_trainSet is empty it returns error and stop training process.
+ *
+ * @param none
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ * @exception
+ */
+ int prepareNeuralNetTrainingSequence();
+
+ /** This method is used to prepare architecture of neural network
+ *
+ * Semantics
+ *
+ * - Call constractNeuralnetLayeredStructure method
+ * - For creating input, hidden, and output layer structure
+ *
+ * - Call initialiseNetwork method.
+ *
+ * - Call adjustWeightByErrorBackpropagation method.
+ * - For neuralnet training
+ *
+ * @param none
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int prepareNetworkArchitecture();
+
+ /** This method is used to initialise neuralnet parameters
+ *
+ * Semantics
+ *
+ * - Check specified network architecture during reestimation of network weights
+ *
+ * - Generally the network weights are initialised by random numbers
+ *
+ * - During reestimation of network (weights, prevDelW) neuralnet parameters are initialised by previously
+ * train network
+ * - Call loadModelData method
+ *
+ *
+ * @param
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ *
+ * @exception LTKErrorList::EINVALID_NETWORK_LAYER Network layer are not specified correctly
+ */
+ int initialiseNetwork(double2DVector& outptr,double2DVector& errptr);
+
+ /**
+ * Feedforward input training sample
+ * Bottom up calculation of response at each node of network for a specific input pattern
+ *
+ * Semantics
+ *
+ * - It checks whether necessary vectors are empty
+ *
+ * - Normalise the featurte vector so that each feature component should be in the range 0 to 1
+ *
+ * - Calculate hidden and output layer node activation values using
+ * calculateSigmoid method
+ *
+ * - Call NeuralNetShapeRecognizer::calculateSigmoid() method for sigmoid units, the output varies
+ * continuously but not linearly as the input changes <br>
+ * Sigmoid units bear a greater resemblance to real neurones than do linear or threshold units <br>
+ * Also, sigmoidal transfer function being derivable, it is
+ * useful for calculation of the error derivatives in backpropagation algorithm
+ *
+ * @param : shapeFeature : vector<LTKShapeFeaturePtr> : Hold feature representation of input sample
+ outptr : double2DVector : Hold the output layer content
+ * currentIndex : const int : Hold index of current sample
+ *
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ *
+ * @exception LTKErrorList::EEMPTY_VECTOR Vector which is used in this method is empty
+ * LTKErrorList::ENON_POSITIVE_NUM Normalised factor should be positive
+ */
+ int feedForward(const vector<LTKShapeFeaturePtr>& shapeFeature,double2DVector& outptr,const int& currentIndex);
+
+ /** This method is used to take dissection for terminating training process if network converge or maximum itaretion reach
+ *
+ * Semantics
+ *
+ * - Check if individual error set for each neuron are empty
+ *
+ * - Check if current error is negative
+ *
+ * - Check if training iteration is negative
+ *
+ * - If criteria for convergence or maximum training iteration is reached
+ * - terminate else training process continue
+ *
+ * @param ep : const doubleVector : Hold output layer absolute error for individual neuron
+ * currentError : const double : Hold the current error
+ * currentItr : const int : Itaretion number
+ * outConvergeStatus : int : Status of iterative learning after each iteration
+ *
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ *
+ * @exception LTKErrorList::EEMPTY_VECTOR Empty individual error set
+ * @exception LTKErrorList::ENEGATIVE_NUM Current error can't be nagative
+ * @exception LTKErrorList::ENEGATIVE_NUM Itaretion can't be nagative
+ */
+ int introspective(const doubleVector& ep, const double currentError,const int& currentItr, int& outConvergeStatus);
+
+ /** This method is used to construct the layered structure of network.
+ *
+ * Semantics
+ *
+ * - It initialise input layer and output layer nodes
+ *
+ * @param none
+ * @return SUCCESS: successfully complete
+ *
+ * @exception LTKErrorList::EEMPTY_VECTOR If the feature set is empty
+ * LTKErrorList::EINVALID_NUM_OF_INPUT_NODE If input layer nodes are not correctly specified
+ * LTKErrorList::EINVALID_NUM_OF_OUTPUT_NODE If output layer nodes are not correctly specified
+ */
+ int constractNeuralnetLayeredStructure();
+
+ /** This method is used to check if the network architecture parameters are specified correctly or not
+ *
+ * Semantics
+ *
+ * - Check network cofig parameters
+ *
+ * @param none
+ * @return SUCCESS: successfully complete
+ * FAILURE: return ErrorCode
+ * @exception
+ */
+ int validateNeuralnetArchitectureParameters(stringStringMap& headerSequence);
+
+ /** This method is used to calculate sigmoid value of input value to a node
+ *
+ * Semantics
+ *
+ * @param
+ * @return
+ * @exception
+ */
+ double calculateSigmoid(double inNet);
+
+ int getShapeSampleFromString(const string& inString, LTKShapeSample& outShapeSample);
+};
+
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.cfg b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.cfg
new file mode 100644
index 00000000..e52d3147
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.cfg
@@ -0,0 +1,407 @@
+#------------------------------------------------------------------------------
+# neuralnet.cfg
+#
+# Configuration file for Neural Net Classification Method for
+# Lipi Toolkit 4.0.0
+#------------------------------------------------------------------------------
+
+#------------------------------------------------------------------------------
+# The standard format for the configuration entries is the name of the
+# configuration parameter seperated by an equal to sign and then the value of
+# the configuration parameter. For example:
+# ConfigurationEntryName = value
+#
+# Lines starting with a # are commnet lines
+#
+# A cfg entry is strictly a key value pair and leaving the key without the
+# value or specification of a value out of the range is not permitted
+#
+# If a cfg entry is not specified at all, then default values are used by the
+# recognizer
+#------------------------------------------------------------------------------
+
+#-------------------------------
+# PREPROCESSING
+#-------------------------------
+
+#-------------------------------------------------------------------------------
+# ResampTraceDimension
+#
+# Description: The number of target points for resampling. In other words,
+# each character will be resampled to this number of points. In case of
+# multistroke characters, this number of points will be distributed between
+# the strokes in proportion to their lengths in proportion to their initial
+# number of points.
+#
+# Valid values: Any integer > 0
+# Units: Points
+# Default value: 60
+# Typical value: Average number of points per character in the training data set.
+#-------------------------------------------------------------------------------
+ResampTraceDimension = 60
+
+
+#-------------------------------------------------------------------------------
+# ResampPointAllocation
+#
+# Description: Method to be used for point allocation among different strokes
+# during resampling. Two schemes have been implemented lengthbased and point
+# based. In lengthbased allocation scheme, the number of points allocated to
+# each stroke is proportional to the length of the stroke. Length of a stroke
+# is calculated as the sum of the distances between each point in the stroke.
+# In the pointbased allocation scheme, the target stroke point allocation is
+# proportional to the number of points in the initial stroke. In the
+# interpointdistbased scheme, the distance between consecutive points is fixed
+# resulting in variable number based on the length of the trajectory.
+#
+# Valid value: [lengthbased | pointbased | interpointdistbased]
+# Default value: lengthbased
+#-------------------------------------------------------------------------------
+ResampPointAllocation = lengthbased
+
+#-------------------------------------------------------------------------------
+# NormDotSizeThreshold
+#
+# Description: This threshold is used to determine whether a character is a dot.
+# It is expressed in real length terms (inches) and converted internally to
+# points using knowledge of the device’s spatial resolution. If the width
+# and height are both less than this threshold, then all the points are replaced
+# with the center of the of the normalized character, basically to represent it
+# as a dot
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormDotSizeThreshold = 0.00001
+
+#-------------------------------------------------------------------------------
+# NormLineWidthThreshold
+#
+# Description: This threshold is used to detect whether the character is a
+# vertical or horizontal line. If only the height is less than this threshold
+# then the character is detected as a horizontal line and if only the width is
+# less than this threshold then the character is detected as a vertical line.
+# Assuming the height is along the y-dimension and width is along the x-
+# dimension, during normalization of a horizontal line only the x-coordinates
+# are scaled and the y-coordinates are translated to the center of the character,
+# with out scaling. Similarly for the vertical line only the y-coordinates are
+# normalized and the x-coordinates are translated to the center with out scaling
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormLineWidthThreshold = 0.01
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatio
+#
+# Description: This parameter is used to indicate whether the aspect ratio
+# has to be preserved during normalization. The aspect ratio is the calculated
+# as maximum of (height/width , width/height). The aspect ratio is preserved only
+# if the calculated aspect ratio is greater than the threshold value specified
+# through NormPreserveAspectRatioThreshold and this configuration variable is
+# set to true. If this configuration variable is set to false the aspect ratio
+# is not preserved during normalization.
+#
+# Valid value: [true | false]
+# Default value: true
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatio = true
+
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatioThreshold
+#
+# Description: Aspect ratio is preserved during normalization if the computed
+# aspect ratio (max(height/width, width/height)) is greater than this threshold
+# and the configuration value NormPreserveAspectRatio is set to true. During
+# aspect ratio preserving normalization, the larger of the two dimensions is
+# normalized to the standard size and the other dimension is normalized
+# proportional to the initial height and width ratio, so that the initial
+# aspect ratio is maintained.
+#
+# Valid values: Any real number >= 1
+# Default value: 3
+# Typical value: >= 1.5
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatioThreshold = 3
+
+#-------------------------------------------------------------------------------
+# NormPreserveRelativeYPosition
+#
+# Description: The relative Y position is the mean of the y-coordinates in the
+# input character. During normalization if this parameter is set to true, each
+# y-coordinate of the character point is translated by the initial y-mean value,
+# so that the mean of the y-coordinates remains the same before and after
+# normalization. This is typically used in the word recognition context where
+# each stroke of the character has to be normalized separately and the relative
+# position of the strokes should be maintained even after normalization.
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+NormPreserveRelativeYPosition = false
+
+#-------------------------------------------------------------------------------
+# SmoothWindowSize
+#
+# Description: The configuration value specifies the length of the moving
+# average filter (size of the window) for smoothing the character image.
+# If this value is set to N, then each point in the input character is replaced
+# by the average of value of this point, (N-1)/2 points on the right and (N-1)/2
+# on the left of this point.
+#
+# Valid value: Any integer > 0
+# Units: Points
+# Typical value: 5
+# Default value: 3
+#-------------------------------------------------------------------------------
+SmoothWindowSize = 3
+
+#-------------------------------------------------------------------------------
+# PreprocSequence
+#
+# Description: This variable is used to specify the sequence of preprocessing
+# operations to be carried out on the input character sample before extracting
+# the features. A valid preprocessing sequence can consist of combination of one
+# or more of the functions selected from the valid values set mentioned below.
+# The CommonPreProc prefix is used specify the default preprocessing module of
+# LipiTk. The user can add his own preprocessing functions in other modules and
+# specify them in the preprocessing sequence.
+#
+# Valid values: Any sequence formed from the following set
+# CommonPreProc::normalizeSize;
+# CommonPreProc::removeDuplicatePoints;
+# CommonPreProc::smoothenTraceGroup;
+# CommonPreProc::dehookTraces;
+# CommonPreProc::normalizeOrientation;
+# CommonPreProc::resampleTraceGroup;
+# Default value: {CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+#-------------------------------------------------------------------------------
+PreprocSequence={CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+
+#---------------------------------------
+# TRAINING
+#---------------------------------------
+
+#-------------------------------------------------------------------------------
+# SeedValueForRandomNumberGenaretor
+#
+# Description: The generation of pseudo-random numbers is a common task in computer
+# simulations. Computational algorithms (pseudorandom number generators) producing
+# pseudo-random numbers (sequences of apparently random numbers), are in fact
+# completely determined by a shorter initial value, called a seed or key. Any integer
+# value can be used for this seed. Different values of seed should produce different
+# sequences of pseudo-random numbers depending upon the periodicity of the generating
+# algorithm. This quantity is used to initialise the random number generator. Random
+# numbers are used to initialize connection weights of the network. Different seed
+# values should produce different sequences of pseudo-random numbers depending upon
+# the periodicity of the generating algorithm.
+#
+# Valid value: [Any integer > 0]
+# Default value: 426
+#-------------------------------------------------------------------------------
+SeedValueForRandomNumberGenaretor = 456
+
+#-------------------------------------------------------------------------------
+# NormalizationFactor
+#
+# Description: Input feature components are divided by this quatity because present
+# implementation of BackPropagation algorithm needs input feature vector components
+# in the range 0 to 1. Usually, this quantity is greater than or equal to the possible
+# maximum value of input feature components.
+#
+# Valid value: [Any real number grater then 0.0]
+# Default value: 10.0
+#-------------------------------------------------------------------------------
+NeuralNetNormalizationFactor = 10.0
+
+#-------------------------------------------------------------------------------
+# NeuralNetLearningRate
+#
+# Description: This is the parameter of the learning algorithm that controls step size along
+# the steepest descent in the error (system error) surface. Connection weights are adjusted
+# by adding the weight increment multiplied by this quantity to the previous weight. The
+# learning rate indicates how far in the direction of steepest descent the network weights are
+# shifted at each iteration. For example, if this value is 1.0, the shift amount will be equal
+# to the value of the resultant gradient. For parctical problem in which the error surface is
+# generally nonlinear, a smaller learning rate must be used to slowly and smoothly guide the
+# descent towards the optimum weights; therefore, this value is normally between 0 and 1, and
+# indicates the proportion of the gradient length that will be traversed in the direction of the
+# steepest descent.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.005
+#-------------------------------------------------------------------------------
+NeuralNetLearningRate = 0.005
+
+#-------------------------------------------------------------------------------
+# NeuralNetMomemtumRate
+#
+# Description: A quantity involving momentum rate was introduced in the weight modification
+# rule of BackPropagation algorithm for incorporating influence of the past iterations during
+# current updation of the connection weights. The momentum introduces a "damping" effect on
+# the search procedure, thus avoiding possible oscillations on the error surface by averaging
+# gradient components with opposite sign and accelerating the convergence in long flat areas.
+# Also, in situations of falling into local minima, it possibly helps to certain limit to avoid
+# the same. Momentum may be considered as an approximation to a second-order method, as it uses
+# information from the previous iterations.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.0025
+#-------------------------------------------------------------------------------
+NeuralNetMomemtumRate = 0.0025
+
+#-------------------------------------------------------------------------------
+# NeuralNetTotalError
+#
+# Description: After presentation of the complete set of training samples to the network
+# during training, the network computes the total error corresponding to this whole set. A
+# threshold for this error is set to decide when the training should be terminated.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.00001
+#-------------------------------------------------------------------------------
+NeuralNetTotalError = 0.00001
+
+#-------------------------------------------------------------------------------
+# NeuralNetIndividualError
+#
+# Description: After each presentation of a training sample to the network during its
+# training the system calculates the error value for the particular sample. A threshold
+# for this error is set to decide when the training should be terminated.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.00001
+#-------------------------------------------------------------------------------
+NeuralNetIndividualError = 0.00001
+
+#-------------------------------------------------------------------------------
+# NeuralNetHiddenLayersSize
+#
+# Description: In a full-connected, feed-forward, perceptron neural network the values
+#only move from input to hidden to output layers. All neural networks have an input layer
+#and an output layer, but the number of hidden layers may vary. When there is more than
+#one hidden layer, the output from one hidden layer is fed into the next hidden layer
+#and separate weights are applied to the sum going into each layer. For nearly all problems,
+#one hidden layer is sufficient. Two hidden layers may be helpful in a few cases such as
+#modeling data with discontinuities, e.g., a saw tooth wave pattern. Using two hidden layers
+#rarely improves the model, and it may introduce a greater risk of converging to a local
+#minima. There is no theoretical reason for using more than two hidden layers. Three layer
+#models with one hidden layer are recommended.
+#
+# Valid value: [any integer from 1-50]
+# Default value: 1
+#-------------------------------------------------------------------------------
+NeuralNetHiddenLayersSize = 1
+
+#-------------------------------------------------------------------------------
+# NeuralNetHiddenLayersUnitSize
+#
+# Description: One of the important issues of a MLP network is the choice of number of neurons
+# in the hidden layer(s). An inadequate number of neurons causes failure to model complex data,
+# and the final result is bound to be poor. If too many neurons are used, the training time may
+# become excessively long, and, worse, the network may over fit the data. When overfitting occurs,
+# the network will begin to model random noise in the data. Use of a validation set helps to
+# detect overfitting. There are several approaches in the literature for automatic selection of the
+# optimal number of neurons in the hidden layer. A better approach is to build models using varying
+# numbers of hidden neurons and measure the quality of training using cross validation or hold-out
+# data not used for training. This is a highly effective method for finding the optimal number of
+# neurons, but it is computationally expensive, because many models must be built, and each model
+# has to be validated.
+#
+# Valid value: [any integer]
+# Default value: 175:
+#-------------------------------------------------------------------------------
+NeuralNetHiddenLayersUnitSize = 175:
+
+#-------------------------------------------------------------------------------
+# ReestimateNeuralnetConnectionWeights
+#
+# Description: Training of MLP may be done in repeated sessions. For example, during the initial
+# session one may continue training for 100 iterations (presentation of the whole set of training
+# samples to the network). Check the network performance on the validation or test set. In the next
+# session the trained network may be further trained for some more iterations
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+ReestimateNeuralnetConnectionWeights = false
+
+#-------------------------------------------------------------------------------
+# NeuralnetTraningIteration
+#
+# Description: The number of training iterations is another important factor and it is
+# required to be chosen suitably to get best possible performance from the network. If
+# too many iterations are performed, the training time may become excessively long, and,
+# worse, the network may overfit the data. When overfitting occurs, the network will begin
+# to model random noise in the data. Use of a validation set helps to detect overfitting.
+#
+# Valid value: [any integer]
+# Default value: 600
+#-------------------------------------------------------------------------------
+NeuralnetTrainingIteration = 600
+
+#-------------------------------------------------------------------------------
+# PrepareTraningSequence
+#
+# Description:
+#
+# Valid value: [true | false]
+# Default value: true
+#-------------------------------------------------------------------------------
+PrepareTrainingSequence = true
+
+#-----------------------------------------
+# FEATURE EXTRACTION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# FeatureExtractor
+#
+# Description: The configuration value is used to specify the feature extraction
+# module to be used for feature extraction. The point float feature extraction
+# module extracts the x,y,cosine and sine angle features at every point of the
+# character.
+#
+# Valid value: [PointFloatShapeFeatureExtractor|L7ShapeFeatureExtractor|
+# NPenShapeFeatureExtractor|SubStrokeShapeFeatureExtractor]
+# Default value: PointFloatShapeFeatureExtractor
+#-------------------------------------------------------------------------------
+FeatureExtractor=PointFloatShapeFeatureExtractor
+
+#-----------------------------------------
+# RECOGNITION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNRecoRejectThreshold
+#
+# Description: Threshold to reject the test sample. If the confidence obtained
+# for the recognition of test sample is less than this threshold then the test
+# sample is rejected.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.001
+#-------------------------------------------------------------------------------
+NNRecoRejectThreshold =0.001
+
+#--------------------------------------------
+# COMMON FOR TRAINING AND RECOGNITION
+#--------------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNDTWBandingRadius
+#
+# Description: This configuration parameter specifies the mode for
+# opening the mdt file.
+#
+# Valid values: ascii, binary
+# Default Value: ascii
+#-------------------------------------------------------------------------------
+
+NNMDTFileOpenMode=ascii
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.pro
new file mode 100644
index 00000000..8359a4f3
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/neuralnet/neuralnet.pro
@@ -0,0 +1,21 @@
+LIPILIBS = shaperecommon ltkcommon ltkutil featureextractorcommon
+include(../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../featureextractor/common \
+ ../common \
+
+HEADERS += \
+ NeuralNet.h \
+ NeuralNetShapeRecognizer.h \
+
+SOURCES += \
+ NeuralNet.cpp \
+ NeuralNetShapeRecognizer.cpp \
+
+win32 {
+ DEFINES += NEURALNET_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = NeuralNet.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.cpp
new file mode 100644
index 00000000..167e7fed
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.cpp
@@ -0,0 +1,142 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-01-18 15:41:43 +0530 (Tue, 18 Jan 2011) $
+ * $Revision: 829 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+// NN.cpp : Defines the entry point for the DLL application.
+//
+
+#include "NN.h"
+#include "LTKShapeRecognizer.h"
+#include "NNShapeRecognizer.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKOSUtil.h"
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+
+/**********************************************************************************
+* AUTHOR : Saravanan R
+* DATE : 23-Jan-2007
+* NAME : createShapeRecoginizer
+* DESCRIPTION : Creates instance of type NNShaperecongnizer and retuns of type
+ LTKShapeRecognizer. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKShapeRecoginzer.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+*************************************************************************************/
+int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** ptrObj )
+{
+ try
+ {
+ *ptrObj = new NNShapeRecognizer(controlInfo);
+ return SUCCESS;
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+}
+
+/**********************************************************************************
+* AUTHOR : Saravanan R
+* DATE : 23-Jan-2007
+* NAME : deleteShapeRecoginzer
+* DESCRIPTION : Destroy the instance by taking the address as its argument.
+* ARGUMENTS : Address of LTKShapeRecognizer instance.
+* RETURNS : Returns 0 on Success
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description
+* Balaji MNA 18th Jan 2010 Receiving LTKShapeRecognizer as single pointer
+* instead of double pointer in deleteShapeRecognizer
+*************************************************************************************/
+int deleteShapeRecognizer(LTKShapeRecognizer *obj)
+{
+ try
+ {
+ if (obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR :Tarun Madan
+* DATE :
+* NAME :
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int getTraceGroups(LTKShapeRecognizer *obj, int shapeId,
+ int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ int errorCode = ((NNShapeRecognizer*)obj)->getTraceGroups(shapeId,
+ numberOfTraceGroups, outTraceGroups);
+
+ if ( errorCode != SUCCESS )
+ {
+ LTKReturnError(errorCode);
+ }
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.def
new file mode 100644
index 00000000..0a4f75c9
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.def
@@ -0,0 +1,4 @@
+EXPORTS
+ createShapeRecognizer @1
+ deleteShapeRecognizer @2
+ getTraceGroups @3 \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.h
new file mode 100644
index 00000000..0241eb21
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NN.h
@@ -0,0 +1,100 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-01-18 15:41:43 +0530 (Tue, 18 Jan 2011) $
+ * $Revision: 829 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+
+/************************************************************************
+ * FILE DESCR: Definitions for NN dll exporting functions.
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Vijayakumara M.
+ *
+ * DATE: 28-July-2005
+ * CHANGE HISTORY:
+ * Author Date Description
+ ************************************************************************/
+#ifndef __NN_H__
+#define __NN_H__
+
+
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the NN_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// NN_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef _WIN32
+#ifdef NN_EXPORTS
+#define NN_API __declspec(dllexport)
+#else
+#define NN_API __declspec(dllimport)
+#endif //#ifdef NN_EXPORTS
+#else
+#define NN_API
+#endif //#ifdef _WIN32
+
+class LTKTraceGroup;
+class LTKShapeRecognizer;
+
+#include "LTKInc.h"
+#include "LTKTypes.h"
+
+/** @defgroup NNShapeRecognizer NNShapeRecognizer
+*@brief The NNShapeRecognizer
+*/
+
+/**
+* @ingroup NNShapeRecognizer
+* @file NN.cpp
+*/
+
+/**
+ * Crates instance of type NNShapeRecognizer and returns of type
+ * LTKShpeRecognizer. (Acts as a Factory Method).
+ *
+ * @param none
+ *
+ * @return LTKShapeRecognizer - an instance of type LTKShapeRecognizer.
+ */
+extern "C" NN_API int createShapeRecognizer(const LTKControlInfo& controlInfo,
+ LTKShapeRecognizer** pReco );
+
+/**
+ * Destroy the instance by taking the address as its argument.
+ *
+ * @param obj - Address of LTKShapeRecognizer instance.
+ *
+ * @return 0 on Success
+ */
+extern "C" NN_API int deleteShapeRecognizer(LTKShapeRecognizer *obj);
+
+extern "C" NN_API int getTraceGroups(LTKShapeRecognizer *obj, int shapeID, int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups);
+
+void unloadDLLs();
+
+#endif //#ifndef __NN_H__
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.cpp
new file mode 100644
index 00000000..7e57252b
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.cpp
@@ -0,0 +1,370 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2007-06-01 11:16:10 +0530 (Fri, 01 Jun 2007) $
+ * $Revision: 105 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+
+#include "NNShapeRecognizer.h"
+#include "NNAdapt.h"
+#include "LTKLoggerUtil.h"
+#include "LTKConfigFileReader.h"
+#include "LTKErrors.h"
+#include "LTKErrorsList.h"
+#include "LTKPreprocDefaults.h"
+
+#define ALPHA_MORPH -0.1
+
+LTKAdapt* LTKAdapt::adaptInstance = NULL;
+int LTKAdapt::m_count = 0;
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : Constructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt::LTKAdapt(NNShapeRecognizer* ptrNNShapeReco)
+{
+ m_nnShapeRecognizer = ptrNNShapeReco;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << "Exit LTKAdapt::LTKAdapt()"<<endl;
+
+ //Assign Default Values
+ m_adaptSchemeName = NAME_ADD_LVQ_ADAPT_SCHEME;
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : Destructor
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt::~LTKAdapt()
+{
+
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 8-Oct-2007
+* NAME : deleteInstance
+* DESCRIPTION : delete AdaptInstance
+* ARGUMENTS :
+* RETURNS : None
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+void LTKAdapt::deleteInstance()
+{
+ m_count = 0;
+ if(adaptInstance)
+ {
+ delete adaptInstance;
+ adaptInstance = NULL;
+ }
+}
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : getInstance
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+LTKAdapt* LTKAdapt::getInstance(NNShapeRecognizer* ptrNNShapeReco)
+{
+ if(adaptInstance == NULL)
+ {
+ adaptInstance = new LTKAdapt(ptrNNShapeReco);
+ }
+
+ return adaptInstance;
+
+}
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : Process
+* DESCRIPTION : Performs adaptation
+* ARGUMENTS :
+* RETURNS : Success : If completed successfully
+* Failure : Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int LTKAdapt::adapt(int shapeId)
+{
+ int iErrorCode;
+ if(m_count==0)
+ {
+ m_count = 1;
+
+ iErrorCode = readAdaptConfig();
+ if(iErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during LTKAdapt::readAdaptConfig()"<<endl;
+ LTKReturnError(FAILURE);
+ }
+ }
+
+ if(LTKSTRCMP(m_adaptSchemeName.c_str(),NAME_ADD_LVQ_ADAPT_SCHEME)==0)
+ {
+ iErrorCode = adaptAddLVQ(shapeId);
+ if(iErrorCode!=SUCCESS)
+ {
+ LTKReturnError(iErrorCode);
+ }
+ }
+ else
+ {
+ //Adapt Scheme not supported
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"AdaptScheme not supported: " <<m_adaptSchemeName
+ <<endl;
+ LTKReturnError(EADAPTSCHEME_NOT_SUPPORTED);
+ }
+
+ return(SUCCESS);
+}
+
+/******************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 07-06-2007
+* NAME : AdaptADDLVQ
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS : Success
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int LTKAdapt::adaptAddLVQ(int shapeId)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"Enter NNShapeRecognizer::adaptAddLVQ"
+ <<endl;
+ int errorCode;
+ try
+ {
+
+ //Check if Cached variables are valid
+ if(m_nnShapeRecognizer->m_neighborInfoVec.size()==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"DistanceIndexPair is empty"<<endl;
+
+ LTKReturnError(ENEIGHBOR_INFO_VECTOR_EMPTY );
+ }
+
+ //Check if Cached variables are valid
+ //Comment to allow addition/adaptation if Resultvec is empty as sample rejected
+ /*if(m_nnShapeRecognizer->m_vecRecoResult.size()==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Result Vector is empty"<<endl;
+
+ LTKReturnError(ERECO_RESULT_EMPTY);
+ }*/
+
+ if(m_nnShapeRecognizer->m_cachedShapeSampleFeatures.getFeatureVector().size()>0)
+ {
+ m_nnShapeRecognizer->m_cachedShapeSampleFeatures.setClassID(shapeId);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Features of input TraceGroup is empty"<<endl;
+
+ LTKReturnError(ESHAPE_SAMPLE_FEATURES_EMPTY);
+ }
+
+
+ //If mismatch,then add, else Morph with 0.1
+ double alpha = ALPHA_MORPH;
+ if(m_nnShapeRecognizer->m_vecRecoResult.size()==0 ||
+ m_nnShapeRecognizer->m_vecRecoResult.at(0).getShapeId()
+ != shapeId ||
+ m_nnShapeRecognizer->m_shapeIDNumPrototypesMap[shapeId]
+ < m_minNumberSamplesPerClass)
+ {
+ m_nnShapeRecognizer->insertSampleToPrototypeSet(
+ m_nnShapeRecognizer->m_cachedShapeSampleFeatures
+ );
+ //Update m_shapeIDNumPrototypesMap
+ m_nnShapeRecognizer->m_shapeIDNumPrototypesMap[shapeId]=
+ m_nnShapeRecognizer->m_shapeIDNumPrototypesMap[shapeId] + 1;
+ }
+ else
+ {
+ LTKShapeSample recognizedClassNearestSample;
+ int nearestSampleIndex = 0;
+ NNShapeRecognizer::NeighborInfo distindexPairObj;
+
+ // Morph with Nearest Sample of Recognized Class
+ for(int index =0;index <m_nnShapeRecognizer->m_neighborInfoVec.size();index++)
+ {
+ distindexPairObj = m_nnShapeRecognizer->m_neighborInfoVec.at(index);
+ if(distindexPairObj.classId ==m_nnShapeRecognizer->m_vecRecoResult.at(0).getShapeId())
+ {
+ nearestSampleIndex = distindexPairObj.prototypeSetIndex;
+ recognizedClassNearestSample = m_nnShapeRecognizer->m_prototypeSet.at(nearestSampleIndex);
+ break;
+ }
+ }
+ errorCode = m_nnShapeRecognizer->morphVector(
+ m_nnShapeRecognizer->m_cachedShapeSampleFeatures,
+ alpha,
+ recognizedClassNearestSample);
+ if(errorCode!=0)
+ {
+ return(errorCode);
+ }
+
+ //Update PrototypeSet with Morph Vector
+ const vector<LTKShapeFeaturePtr>& tempFeatVec = recognizedClassNearestSample.getFeatureVector();
+ m_nnShapeRecognizer->m_prototypeSet.at(nearestSampleIndex).setFeatureVector(tempFeatVec);
+ }
+ //Update MDT File
+ m_nnShapeRecognizer->writePrototypeSetToMDTFile();
+
+ }
+ catch(...)
+ {
+// return FALSE;
+ return false;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"Exit NNShapeRecognizer::adaptAddLVQ"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 11-06-2007
+* NAME : readAdaptConfig
+* DESCRIPTION :
+*
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int LTKAdapt::readAdaptConfig()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Enter Adapt::readAdaptConfig"
+ <<endl;
+
+ LTKConfigFileReader *adaptConfigReader = NULL;
+
+ adaptConfigReader = new LTKConfigFileReader(m_nnShapeRecognizer->m_nnCfgFilePath);
+
+ //Don't throw Error as ShapeRecognizer might not support ADAPT
+ string tempStringVar = "";
+
+ int errorCode = adaptConfigReader->getConfigValue(ADAPT_SCHEME,tempStringVar);
+ if(errorCode == SUCCESS)
+ m_adaptSchemeName = tempStringVar;
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "AdaptScheme not specified. Assuming default(AddLVQ) " <<endl;
+ }
+
+ int tempIntegerVar = 0;
+
+ errorCode =
+ adaptConfigReader->getConfigValue(ADAPT_MIN_NUMBER_SAMPLES_PER_CLASS,tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+ if(tempIntegerVar > 0)
+ {
+ m_minNumberSamplesPerClass = tempIntegerVar;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< "Error: " << ECONFIG_FILE_RANGE
+ <<ADAPT_MIN_NUMBER_SAMPLES_PER_CLASS << " is out of permitted range"
+ << " LTKAdapt::readAdaptConfig()"<<endl;
+
+ delete adaptConfigReader;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< "Error: " << ECONFIG_FILE_RANGE
+ << ADAPT_MIN_NUMBER_SAMPLES_PER_CLASS << " is out of permitted range"
+ << " LTKAdapt::readAdaptConfig()"<<endl;
+
+ delete adaptConfigReader;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ m_minNumberSamplesPerClass = ADAPT_DEF_MIN_NUMBER_SAMPLES_PER_CLASS;
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Info: " <<
+ "Using default value of MinimumNumerOfSamplesPerClass: "<<
+ m_minNumberSamplesPerClass <<
+ " LTKAdapt::readAdaptConfig()"<<endl;
+ }
+
+ if(adaptConfigReader)
+ delete adaptConfigReader;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exit Adapt::readAdaptConfig"
+ <<endl;
+
+ return SUCCESS;
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.h
new file mode 100644
index 00000000..2b78be50
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNAdapt.h
@@ -0,0 +1,110 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2007-06-01 11:16:10 +0530 (Fri, 01 Jun 2007) $
+ * $Revision: 105 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+
+/************************************************************************
+ * FILE DESCR: Implements NNShapeRecognizer::Adapt
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Tarun Madan
+ *
+ * DATE: 30-Aug-2007
+ * CHANGE HISTORY:
+ * Author Date Description
+ ************************************************************************/
+
+class LTKAdapt
+{
+private:
+ LTKAdapt(NNShapeRecognizer* ptrNNShapeReco);
+ static LTKAdapt* adaptInstance;
+ static int m_count;
+
+public:
+ static LTKAdapt* getInstance(NNShapeRecognizer* ptrNNShapeReco);
+ int adapt(int shapeId);
+ ~LTKAdapt();
+ void deleteInstance();
+
+private:
+ /**< @brief Pointer to NNShapeRecognizer
+ * <p>
+ *
+ * </p>
+ */
+ NNShapeRecognizer* m_nnShapeRecognizer;
+
+ /**< @brief Adapt Scheme name
+ * <p>
+ *
+ * </p>
+ */
+ string m_adaptSchemeName;
+
+ /**< @brief Minimum number of samples required per class
+ * <p>
+ *
+ * </p>
+ */
+
+ int m_minNumberSamplesPerClass;
+
+
+ /**
+ * This method reads Config variables related to Adapt from CFG
+ *
+ * Semantics
+ *
+ *
+ * @param none
+ *
+ * @return SUCCESS:
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int readAdaptConfig();
+
+ /**
+ * This method implements AddLVQ scheme of Adaptation
+ *
+ * Semantics
+ * - if wrong recognition or new style,
+ * then
+ * ADD
+ * else
+ * Morph
+ * - Update Prototypeset and Update MDT File
+ *
+ * @param shapeId : int : Holds shapeId of adaptSampleTrace
+ *
+ * @return SUCCESS: return 0
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int adaptAddLVQ(int shapeId);
+};
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.cpp
new file mode 100644
index 00000000..78b09e47
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.cpp
@@ -0,0 +1,5432 @@
+/*****************************************************************************************
+ * Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+ * Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-02-08 16:57:52 +0530 (Tue, 08 Feb 2011) $
+ * $Revision: 834 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation for NN Shape Recognition module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Saravanan R.
+ *
+ w
+ * DATE: January 23, 2004
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKConfigFileReader.h"
+
+#include "NNShapeRecognizer.h"
+
+#include "LTKPreprocDefaults.h"
+
+#include "LTKHierarchicalClustering.h"
+
+#include "LTKPreprocessorInterface.h"
+
+#include "LTKShapeFeatureExtractorFactory.h"
+
+#include "LTKShapeFeatureExtractor.h"
+
+#include "LTKShapeFeature.h"
+
+#include "LTKVersionCompatibilityCheck.h"
+
+#include "LTKInkFileWriter.h"
+#include "LTKOSUtil.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKClassifierDefaults.h"
+#include "NNAdapt.h"
+#include "LTKLoggerUtil.h"
+#include "LTKShapeRecoUtil.h"
+#include "LTKTraceGroup.h"
+#include "LTKErrors.h"
+#include "LTKShapeSample.h"
+#include "LTKException.h"
+#include "LTKErrorsList.h"
+#include "LTKStringUtil.h"
+#include "LTKDynamicTimeWarping.h"
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : NNShapeRecognizer
+ * DESCRIPTION : Default Constructor that initializes all data members
+ * ARGUMENTS : none
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+
+void NNShapeRecognizer::assignDefaultValues()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::assignDefaultValues()" << endl;
+
+ m_numShapes = 0;
+ m_nnCfgFilePath = "";
+ m_nnMDTFilePath = "";
+ m_ptrPreproc = NULL;
+ m_projectTypeDynamic=false;
+ m_prototypeSelection=NN_DEF_PROTOTYPESELECTION;
+ m_prototypeReductionFactor=NN_DEF_PROTOTYPEREDUCTIONFACTOR;
+ m_prototypeDistance=NN_DEF_PROTOTYPEDISTANCE;
+ m_nearestNeighbors=NN_DEF_NEARESTNEIGHBORS;
+ m_dtwBanding=NN_DEF_BANDING;
+ m_dtwEuclideanFilter=NN_DEF_DTWEUCLIDEANFILTER;
+ m_preProcSeqn=NN_DEF_PREPROC_SEQ;
+ m_ptrFeatureExtractor=NULL;
+ m_featureExtractorName=NN_DEF_FEATURE_EXTRACTOR;
+ m_numClusters=NN_NUM_CLUST_INITIAL; // just to check that this is not what is mentioned by the user
+ m_MDTUpdateFreq=NN_DEF_MDT_UPDATE_FREQ;
+ m_prototypeSetModifyCount=0;
+ m_rejectThreshold=NN_DEF_REJECT_THRESHOLD;
+ m_adaptivekNN=false;
+ m_deleteLTKLipiPreProcessor=NULL;
+ m_MDTFileOpenMode = NN_MDT_OPEN_MODE_ASCII;
+ m_LVQIterationScale=NN_DEF_LVQITERATIONSCALE;
+ m_LVQInitialAlpha=NN_DEF_LVQINITIALALPHA;
+ m_LVQDistanceMeasure=NN_DEF_LVQDISTANCEMEASURE;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::assignDefaultValues()" << endl;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : initialize
+ * DESCRIPTION : This method initializes the NN shape recognizer
+ * ARGUMENTS : string Holds the Project Name
+ * string Holds the Profile Name
+ * RETURNS : integer Holds error value if occurs
+ * Holds SUCCESS if no erros
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+NNShapeRecognizer::NNShapeRecognizer(const LTKControlInfo& controlInfo):
+m_OSUtilPtr(LTKOSUtilFactory::getInstance()),
+m_libHandler(NULL),
+m_libHandlerFE(NULL)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" << endl;
+
+ try
+ {
+ LTKControlInfo tmpControlInfo=controlInfo;
+
+ string strProjectName = "";
+ string strProfileName = "";
+
+
+ if( (tmpControlInfo.projectName).empty() )
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+ if( (tmpControlInfo.lipiRoot).empty() )
+ {
+ throw LTKException(ELIPI_ROOT_PATH_NOT_SET);
+ }
+
+ if( (tmpControlInfo.profileName).empty() )
+ {
+ strProfileName = DEFAULT_PROFILE;
+ tmpControlInfo.profileName = strProfileName;
+ }
+
+ if ( tmpControlInfo.toolkitVersion.empty() )
+ {
+ throw LTKException(ENO_TOOLKIT_VERSION);
+ }
+
+ assignDefaultValues();
+
+ m_lipiRootPath = tmpControlInfo.lipiRoot;
+ m_lipiLibPath = tmpControlInfo.lipiLib;
+ m_currentVersion = tmpControlInfo.toolkitVersion;
+ strProjectName = tmpControlInfo.projectName;
+ strProfileName = tmpControlInfo.profileName;
+
+
+ //Model Data file Header Information
+ m_headerInfo[PROJNAME] = strProjectName;
+
+ //Holds the value of Number of Shapes in string format
+ string strNumShapes = "";
+
+ string strProfileDirectory = m_lipiRootPath + PROJECTS_PATH_STRING +
+ strProjectName + PROFILE_PATH_STRING;
+
+ //Holds the path of the Project.cfg
+ string projectCFGPath = strProfileDirectory + PROJECT_CFG_STRING;
+
+ // Config file
+
+ m_nnCfgFilePath = m_lipiRootPath + PROJECTS_PATH_STRING +
+ (tmpControlInfo.projectName) + PROFILE_PATH_STRING +
+ (tmpControlInfo.profileName) + SEPARATOR +
+ NN + CONFIGFILEEXT;
+
+
+ //Set the path for nn.mdt
+ m_nnMDTFilePath = strProfileDirectory + strProfileName + SEPARATOR + NN + DATFILEEXT;
+
+
+ //To find whether the project was dynamic or not andto read read number of shapes from project.cfg
+ int errorCode = m_shapeRecUtil.isProjectDynamic(projectCFGPath,
+ m_numShapes, strNumShapes, m_projectTypeDynamic);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+
+ //Set the NumShapes to the m_headerInfo
+ m_headerInfo[NUMSHAPES] = strNumShapes;
+
+ //Currently preproc cfg also present in NN
+ tmpControlInfo.cfgFileName = NN;
+ errorCode = initializePreprocessor(tmpControlInfo,
+ &m_ptrPreproc);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Reading NN configuration file
+ errorCode = readClassifierConfig();
+
+ if( errorCode != SUCCESS)
+ {
+ cout<<endl<<"Encountered error in readClassifierConfig"<<endl;
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ //Writing Feature extractor name and version into the header
+ m_headerInfo[FE_NAME] = m_featureExtractorName;
+ m_headerInfo[FE_VER] = SUPPORTED_MIN_VERSION; //FE version
+
+ //Writting mdt file open mode to the mdt header
+ m_headerInfo[MDT_FOPEN_MODE] = m_MDTFileOpenMode;
+
+ errorCode = initializeFeatureExtractorInstance(tmpControlInfo);
+
+ if( errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" <<endl;
+ throw LTKException(errorCode);
+ }
+
+ }
+ catch(LTKException e)
+ {
+
+ deletePreprocessor();
+ m_prototypeSet.clear();
+
+ m_cachedShapeSampleFeatures.clearShapeSampleFeatures();
+
+ //Unloading the feature Extractor instance
+ deleteFeatureExtractorInstance();
+
+ delete m_OSUtilPtr;
+ throw e;
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::NNShapeRecognizer()" << endl;
+
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : readClassifierConfig
+ * DESCRIPTION : Reads the NN.cfg and initializes the data members of the class
+ * ARGUMENTS : none
+ * RETURNS : SUCCESS - If config file read successfully
+ * errorCode - If failure
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::readClassifierConfig()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::readClassifierConfig()" << endl;
+ string tempStringVar = "";
+ int tempIntegerVar = 0;
+ float tempFloatVar = 0.0;
+ LTKConfigFileReader *shapeRecognizerProperties = NULL;
+ int errorCode = FAILURE;
+
+ try
+ {
+ shapeRecognizerProperties = new LTKConfigFileReader(m_nnCfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<< "Info: " <<
+ "Config file not found, using default values of the parameters" <<
+ "NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ return FAILURE;
+ }
+
+ //Pre-processing sequence
+ errorCode = shapeRecognizerProperties->getConfigValue(PREPROCSEQUENCE, m_preProcSeqn);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Info: " <<
+ "Using default value of prerocessing sequence: "<< m_preProcSeqn <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ m_preProcSeqn = NN_DEF_PREPROC_SEQ;
+ }
+
+ m_headerInfo[PREPROC_SEQ] = m_preProcSeqn;
+
+
+ if((errorCode = mapPreprocFunctions()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<" Error: " << errorCode <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PROTOTYPESELECTION,
+ tempStringVar);
+
+ if (errorCode == SUCCESS)
+ {
+ if( (LTKSTRCMP(tempStringVar.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0) || (LTKSTRCMP(tempStringVar.c_str(), PROTOTYPE_SELECTION_LVQ) == 0))
+ {
+ m_prototypeSelection = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ PROTOTYPESELECTION << " = " << tempStringVar <<
+ "NNShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " " <<
+ PROTOTYPESELECTION << " : " << tempStringVar
+ << " method is not supported" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << PROTOTYPESELECTION << " : " <<
+ m_prototypeSelection <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PROTOREDFACTOR,
+ tempStringVar);
+
+ string tempStringVar1 = "";
+ int errorCode1 = shapeRecognizerProperties->getConfigValue(NUMCLUSTERS,
+ tempStringVar1);
+
+ if(errorCode1 == SUCCESS && errorCode == SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ << " Cannot use both config parameters " <<
+ PROTOREDFACTOR << " and " << NUMCLUSTERS << " at the same time "<<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ if(tempStringVar != "")
+ {
+ if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_AUTOMATIC)==0)
+ {
+ //DEFINE MACRO DEF_PROTO_RED_FACTOR
+ m_prototypeReductionFactor = -1;
+ }
+ else if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_NONE)==0)
+ {
+ m_prototypeReductionFactor = 0;
+ }
+ else if(LTKSTRCMP(tempStringVar.c_str(), PROTO_RED_FACTOR_COMPLETE) == 0)
+ {
+ m_prototypeReductionFactor = 100;
+ }
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+ if(tempIntegerVar >= 0 && tempIntegerVar <=100)
+ {
+ m_prototypeReductionFactor = tempIntegerVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ << PROTOREDFACTOR << " is =" << tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ PROTOREDFACTOR << " is out of permitted range " <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ PROTOREDFACTOR << " is out of permitted range"<<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ }
+ }
+ else if(tempStringVar1 != "")
+ {
+ if(LTKSTRCMP(tempStringVar1.c_str(), PROTO_RED_FACTOR_AUTOMATIC) == 0)
+ {
+ m_prototypeReductionFactor = -1;
+ }
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar1) )
+ {
+ tempIntegerVar = atoi((tempStringVar1).c_str());
+ if(tempIntegerVar > 0)
+ {
+ m_numClusters = tempIntegerVar;
+
+ // m_numClusters is used in this case
+ m_prototypeReductionFactor = NN_NUM_CLUST_INITIAL;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NUMCLUSTERS << " is = " << tempStringVar << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ NUMCLUSTERS << " is out of permitted range "<<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ " Error: " << ECONFIG_FILE_RANGE <<
+ NUMCLUSTERS << " is out of permitted range"<<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Assuming default value of " NUMCLUSTERS << " : " <<
+ m_numClusters << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PROTOTYPEDISTANCE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS )
+ {
+ if((LTKSTRCMP(tempStringVar.c_str(), EUCLIDEAN_DISTANCE) == 0) ||
+ (LTKSTRCMP(tempStringVar.c_str(), DTW_DISTANCE) == 0))
+ {
+ m_prototypeDistance = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Prototype Distance Method = " <<tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << " " <<
+ PROTOTYPEDISTANCE << " : " << tempStringVar <<
+ " is not supported" <<
+ "NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " PROTOTYPEDISTANCE " : " <<
+ m_prototypeDistance << endl;
+ }
+
+ tempStringVar = "";
+ shapeRecognizerProperties->getConfigValue(ADAPTIVE_kNN, tempStringVar);
+ if(LTKSTRCMP(tempStringVar.c_str(), "true") ==0)
+ {
+ m_adaptivekNN = true;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Confidence computation method: " << ADAPTIVE_kNN << endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << ADAPTIVE_kNN << " : " <<
+ m_adaptivekNN << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(NEARESTNEIGHBORS,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ //Valid values of nearest neighbors: 1 or greater than MIN_NEARESTNEIGHBORS
+ if(tempIntegerVar > 0)
+ {
+ // If the value of NearestNeighbors = 1, NN recognizer is used
+ if(tempIntegerVar == 1)
+ {
+ m_adaptivekNN = false;
+ }
+
+ // If AdaptivekNN is set to false, simply assign the value to m_nearestNeighbors
+ // If AdaptivekNN is set, NearestNeighbors should be greater than than the
+ // minimum no.of nearest neighbors allowed (MIN_NEARESTNEIGHBORS defined as macro)
+ if(!m_adaptivekNN || (m_adaptivekNN && tempIntegerVar >= MIN_NEARESTNEIGHBORS))
+ {
+ m_nearestNeighbors = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ NEARESTNEIGHBORS << " = " <<m_nearestNeighbors<<endl;
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEARESTNEIGHBORS <<
+ " is out of permitted range" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << NEARESTNEIGHBORS <<
+ " is out of permitted range" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Debug: " << "Using default value for " << NEARESTNEIGHBORS <<
+ " : " << m_nearestNeighbors << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(REJECT_THRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar < 1)
+ {
+ m_rejectThreshold = tempFloatVar;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ REJECT_THRESHOLD << " = " <<tempStringVar <<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << REJECT_THRESHOLD <<
+ " should be in the range (0-1)" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << REJECT_THRESHOLD <<
+ " : " << m_rejectThreshold << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DTWBANDING,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ tempFloatVar = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if(tempFloatVar > 0 && tempFloatVar <= 1)
+ {
+ m_dtwBanding = tempFloatVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ DTWBANDING << " = " <<m_dtwBanding<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE << DTWBANDING <<
+ " is out of permitted range" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: "<< ECONFIG_FILE_RANGE <<
+ " DTWBANDING is out of permitted range" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << DTWBANDING << " : " <<
+ m_dtwBanding << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DTWEUCLIDEANFILTER,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ if(LTKSTRCMP(tempStringVar.c_str(), DTW_EU_FILTER_ALL) == 0)
+ {
+ m_dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ }
+ else
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ tempIntegerVar = atoi((tempStringVar).c_str());
+
+ if(tempIntegerVar > 0 && tempIntegerVar <= 100)
+ {
+ m_dtwEuclideanFilter = tempIntegerVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ DTWEUCLIDEANFILTER << " is = "<<
+ m_dtwEuclideanFilter<<endl;
+
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ DTWEUCLIDEANFILTER << " is out of permitted range " <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << DTWEUCLIDEANFILTER <<
+ " is out of permitted range"<<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << DTWEUCLIDEANFILTER <<
+ " : " << m_dtwEuclideanFilter << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(FEATUREEXTRACTOR,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_featureExtractorName = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ FEATUREEXTRACTOR << " = "<<tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << FEATUREEXTRACTOR << " : " <<
+ m_featureExtractorName << endl;
+ }
+ //LVQ Paramaters
+ //LVQ Iteration Scale
+ errorCode = shapeRecognizerProperties->getConfigValue(LVQITERATIONSCALE,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_LVQIterationScale=atoi((tempStringVar).c_str());
+
+ if(!((m_LVQIterationScale>0)&& LTKStringUtil::isInteger(tempStringVar)))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ LVQITERATIONSCALE << " should be a positive integer " <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ m_LVQIterationScale = NN_DEF_LVQITERATIONSCALE;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Using default value for LVQIterationScale: " << m_LVQIterationScale <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ }
+ //LVQ Initial Alpha
+ tempStringVar="";
+ errorCode = shapeRecognizerProperties->getConfigValue(LVQINITIALALPHA,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_LVQInitialAlpha = LTKStringUtil::convertStringToFloat(tempStringVar);
+
+ if((m_LVQInitialAlpha>1)||(m_LVQInitialAlpha<0))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ LVQINITIALALPHA << " is out of permitted range " <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ }
+ else
+ {
+ m_LVQInitialAlpha = NN_DEF_LVQINITIALALPHA ;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Using default value for LVQInitialAlpha: " << m_LVQInitialAlpha <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+ }
+ //LVQ Distance Measure
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(LVQDISTANCEMEASURE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS )
+ {
+ if((LTKSTRCMP(tempStringVar.c_str(), EUCLIDEAN_DISTANCE) == 0) ||
+ (LTKSTRCMP(tempStringVar.c_str(), DTW_DISTANCE) == 0))
+ {
+ m_LVQDistanceMeasure = tempStringVar;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "LVQ Prototype Distance Method = " <<tempStringVar<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << " " <<
+ LVQDISTANCEMEASURE << " : " << tempStringVar <<
+ " is not supported" <<
+ "NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " LVQDISTANCEMEASURE " : " <<
+ m_prototypeDistance << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MDT_UPDATE_FREQUENCY,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ m_MDTUpdateFreq = atoi(tempStringVar.c_str());
+ if(m_MDTUpdateFreq<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDT_UPDATE_FREQUENCY <<
+ " should be zero or a positive integer" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDT_UPDATE_FREQUENCY <<
+ " should be zero or a positive integer" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MDT_UPDATE_FREQUENCY <<
+ " : " << m_MDTUpdateFreq << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(MDT_FILE_OPEN_MODE,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ if ( tempStringVar == NN_MDT_OPEN_MODE_ASCII ||
+ tempStringVar == NN_MDT_OPEN_MODE_BINARY )
+ {
+ m_MDTFileOpenMode = tempStringVar;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE << MDT_FILE_OPEN_MODE <<
+ " should be ascii or binary" <<
+ " NNShapeRecognizer::readClassifierConfig()"<<endl;
+
+ delete shapeRecognizerProperties;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Using default value for " << MDT_FILE_OPEN_MODE <<
+ " : " << m_MDTFileOpenMode << endl;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_SIZE_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(ASPECTRATIOTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[ASP_RATIO_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(DOTTHRESHOLD,
+ tempStringVar);
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[DOT_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVERELATIVEYPOSITION,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_REL_Y_POS] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(PRESERVEASPECTRATIO,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[PRESER_ASP_RATIO] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[NORM_LN_WID_THRES] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(RESAMPLINGMETHOD,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[RESAMP_POINT_ALLOC] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ errorCode = shapeRecognizerProperties->getConfigValue(SMOOTHFILTERLENGTH,
+ tempStringVar);
+
+ if(errorCode == SUCCESS)
+ {
+ m_headerInfo[SMOOTH_WIND_SIZE] = tempStringVar;
+ }
+
+ tempStringVar = "";
+ LTKStringUtil::convertIntegerToString(m_ptrPreproc->getTraceDimension(),
+ tempStringVar);
+
+ m_headerInfo[TRACE_DIM] = tempStringVar;
+
+ delete shapeRecognizerProperties;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::readClassifierConfig()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R
+ * DATE : 23-Jan-2007
+ * NAME : mapPreprocFunctions
+ * DESCRIPTION : Maps the module name and its function names in the preprocessing
+ sequence.
+ * ARGUMENTS : none
+ * RETURNS : SUCCESS on successful,
+ * errorNumbers on Failure.
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::mapPreprocFunctions()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ stringStringMap preProcSequence;
+
+ stringStringPair tmpPair;
+
+ stringVector moduleFuncNames;
+ stringVector modFuncs;
+ stringVector funcNameTokens;
+
+ string module = "", funName = "", sequence = "";
+ string::size_type indx;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ LTKStringUtil::tokenizeString(m_preProcSeqn, DELEMITER_SEQUENCE, funcNameTokens);
+
+ int numFunctions = funcNameTokens.size();
+
+ if(numFunctions == 0)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Wrong preprocessor sequence in cfg file : " + m_preProcSeqn <<
+ " NNShapeRecognizer::mapPreprocFunctions()"<<endl;
+
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+
+ for (indx = 0; indx < numFunctions ; indx++)
+ {
+ moduleFuncNames.push_back(funcNameTokens[indx]);
+ }
+
+ int numModuleFunctions = moduleFuncNames.size();
+
+ for(indx=0; indx < numModuleFunctions ; indx++)
+ {
+ sequence = moduleFuncNames[indx];
+
+ LTKStringUtil::tokenizeString(sequence, DELEMITER_FUNC, modFuncs);
+
+ if(modFuncs.size() >= 2)
+ {
+ module = modFuncs.at(0);
+
+ funName = modFuncs.at(1);
+
+ if(!module.compare("CommonPreProc"))
+ {
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+ if(pPreprocFunc!= NULL)
+ {
+ tmpPair.first = module;
+ tmpPair.second = funName;
+ m_preprocSequence.push_back(tmpPair);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " <<funName<<
+ " NNShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : " << module<<
+ " NNShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_PREPROC_SEQUENCE << " " <<
+ "Wrong preprocessor sequence entry in cfg file : "<<module<<
+ " NNShapeRecognizer::mapPreprocFunctions()"<<endl;
+ LTKReturnError(EINVALID_PREPROC_SEQUENCE);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::mapPreprocFunctions()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2004
+ * NAME : ~NNShapeRecognizer
+ * DESCRIPTION : destructor
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+NNShapeRecognizer::~NNShapeRecognizer()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::~NNShapeRecognizer()" << endl;
+
+ deleteAdaptInstance();
+
+ int returnStatus = SUCCESS;
+ //To update MDT File
+ if(m_prototypeSetModifyCount >0)
+ {
+ m_prototypeSetModifyCount = m_MDTUpdateFreq-1;
+
+ returnStatus = writePrototypeSetToMDTFile();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::~NNShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+
+ }
+ }
+
+ m_neighborInfoVec.clear();
+
+ returnStatus = deletePreprocessor();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::~NNShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ m_prototypeSet.clear();
+
+ m_cachedShapeSampleFeatures.clearShapeSampleFeatures();
+
+ //Unloading the feature Extractor instance
+ returnStatus = deleteFeatureExtractorInstance();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::~NNShapeRecognizer()" << endl;
+ throw LTKException(returnStatus);
+ }
+
+ delete m_OSUtilPtr;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::~NNShapeRecognizer()" << endl;
+
+
+}
+
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 25-Jan-2004
+ * NAME : train
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::train()" << endl;
+
+ int returnStatus = SUCCESS;
+
+
+ if(comment.empty() != true)
+ {
+ m_headerInfo[COMMENT] = comment;
+ }
+
+ if(dataset.empty() != true)
+ {
+ m_headerInfo[DATASET] = dataset;
+ }
+
+ //Check the prototype Selection method and call accordingly
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_LVQ) == 0)
+ {
+ returnStatus = trainLVQ(trainingInputFilePath, mdtHeaderFilePath, trainFileType);
+
+ if(returnStatus != SUCCESS)
+ {
+ LTKReturnError(returnStatus);
+ }
+
+ }
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0)
+ {
+ returnStatus = trainClustering(trainingInputFilePath,
+ mdtHeaderFilePath,
+ trainFileType);
+
+ if(returnStatus != SUCCESS)
+ {
+ LTKReturnError(returnStatus);
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::train()" << endl;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : trainClustering
+ * DESCRIPTION : This function is the train method using Clustering prototype
+ * selection technique.
+ * ARGUMENTS :
+ * RETURNS : SUCCESS : if training done successfully
+ * errorCode : if traininhas some errors
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::trainClustering(const string& trainingInputFilePath,
+ const string &mdtHeaderFilePath,
+ const string& inFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::trainClustering()" << endl;
+
+ //Time at the beginning of Train Clustering
+ m_OSUtilPtr->recordStartTime();
+
+ int returnStatus = SUCCESS;
+
+ if(LTKSTRCMP(inFileType.c_str(), INK_FILE) == 0)
+ {
+ //If the Input file is UNIPEN Ink file
+ returnStatus = trainFromListFile(trainingInputFilePath);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NNShapeRecognizer::trainClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+ }
+ else if(LTKSTRCMP(inFileType.c_str(), FEATURE_FILE) == 0)
+ {
+ //If the Input file is Feature file
+ returnStatus = trainFromFeatureFile(trainingInputFilePath);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NNShapeRecognizer::trainClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ PreprocParametersForFeatureFile(m_headerInfo);
+ }
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ LTKCheckSumGenerate cheSumGen;
+
+ returnStatus = cheSumGen.addHeaderInfo(mdtHeaderFilePath,
+ m_nnMDTFilePath,
+ m_headerInfo);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NNShapeRecognizer::trainClustering()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ //Time at the end of Train Clustering
+ m_OSUtilPtr->recordEndTime();
+
+ string timeTaken = "";
+ m_OSUtilPtr->diffTime(timeTaken);
+
+ cout << "Time Taken = " << timeTaken << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::trainClustering()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : appendPrototypesToMDTFile
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::appendPrototypesToMDTFile(const vector<LTKShapeSample>& prototypeVec,
+ ofstream & mdtFileHandle)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::appendPrototypesToMDTFile()" << endl;
+
+ //iterators to iterate through the result vector
+ vector<LTKShapeSample>::const_iterator sampleFeatureIter = prototypeVec.begin();
+ vector<LTKShapeSample>::const_iterator sampleFeatureIterEnd = prototypeVec.end();
+
+ string strFeature = "";
+
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_FILE_HANDLE << " " <<
+ "Invalid file handle for MDT file"<<
+ " NNShapeRecognizer::appendPrototypesToMDTFile()" << endl;
+ LTKReturnError(EINVALID_FILE_HANDLE);
+ }
+
+
+ for(; sampleFeatureIter != sampleFeatureIterEnd; sampleFeatureIter++)
+ {
+ //Write the class Id
+ int classId = (*sampleFeatureIter).getClassID();
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle << classId << " ";
+ }
+ else
+ {
+ mdtFileHandle.write((char*) &classId,sizeof(int));
+ }
+
+ const vector<LTKShapeFeaturePtr>& shapeFeatureVector = (*sampleFeatureIter).getFeatureVector();
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_BINARY )
+ {
+ int numberOfFeatures = shapeFeatureVector.size();
+ int featureDimension = shapeFeatureVector[0]->getFeatureDimension();
+
+ mdtFileHandle.write((char *)(&numberOfFeatures), sizeof(int));
+ mdtFileHandle.write((char *)(&featureDimension), sizeof(int));
+
+ floatVector floatFeatureVector;
+ m_shapeRecUtil.shapeFeatureVectorToFloatVector(shapeFeatureVector,
+ floatFeatureVector);
+
+ int vectorSize = floatFeatureVector.size();
+
+ for (int i=0; i< vectorSize; i++)
+ {
+ float floatValue = floatFeatureVector[i];
+ mdtFileHandle.write((char *)(&floatValue), sizeof(float));
+ }
+ }
+ else
+ {
+
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIter = shapeFeatureVector.begin();
+ vector<LTKShapeFeaturePtr>::const_iterator shapeFeatureIterEnd = shapeFeatureVector.end();
+
+ for(; shapeFeatureIter != shapeFeatureIterEnd; ++shapeFeatureIter)
+ {
+ (*shapeFeatureIter)->toString(strFeature);
+ mdtFileHandle << strFeature << FEATURE_EXTRACTOR_DELIMITER;
+ }
+
+ mdtFileHandle << "\n";
+ }
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::appendPrototypesToMDTFile()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : preprocess
+ * DESCRIPTION : calls the required pre-processing functions from the LTKPreprocessor library
+ * ARGUMENTS : inTraceGroup - reference to the input trace group
+ * outPreprocessedTraceGroup - pre-processed inTraceGroup
+ * RETURNS : SUCCESS on successful pre-processing operation
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::preprocess (const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outPreprocessedTraceGroup)
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::preprocess()" << endl;
+
+ int indx = 0;
+
+ string module = "";
+ string funName = "" ;
+
+ LTKTraceGroup local_inTraceGroup;
+
+ local_inTraceGroup = inTraceGroup;
+
+ if(m_preprocSequence.size() != 0)
+ {
+ while(indx < m_preprocSequence.size())
+ {
+ module = m_preprocSequence.at(indx).first;
+ funName = m_preprocSequence.at(indx).second;
+
+ FN_PTR_PREPROCESSOR pPreprocFunc = NULL;
+ pPreprocFunc = m_ptrPreproc->getPreprocptr(funName);
+
+ if(pPreprocFunc!= NULL)
+ {
+ outPreprocessedTraceGroup.emptyAllTraces();
+
+
+ if((errorCode = (m_ptrPreproc->*(pPreprocFunc))
+ (local_inTraceGroup,outPreprocessedTraceGroup)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::preprocess()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ local_inTraceGroup = outPreprocessedTraceGroup;
+ }
+ indx++;
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting NNShapeRecognizer::preprocess()"<<endl;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : calculateMedian
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+
+int NNShapeRecognizer::calculateMedian(const int2DVector& clusteringResult,
+ const float2DVector& distanceMatrix, vector<int>& outMedianIndexVec)
+
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::calculateMedian()" << endl;
+
+
+
+
+ int clusteringResultSize = clusteringResult.size();
+
+ for (int clusterID = 0; clusterID < clusteringResultSize ; clusterID++)
+ {
+ double minDist = FLT_MAX;
+ int medianIndex = -1;
+ for (int clusMem = 0; clusMem < clusteringResult[clusterID].size(); clusMem++)// for each element of the cluster
+ {
+ double dist = 0;
+ for(int otherClusMem = 0; otherClusMem < clusteringResult[clusterID].size(); otherClusMem++)
+ {
+ if(clusteringResult[clusterID][clusMem] != clusteringResult[clusterID][otherClusMem])
+ {
+ if(clusteringResult[clusterID][otherClusMem] > clusteringResult[clusterID][clusMem])
+ {
+ int tempi = clusteringResult[clusterID][clusMem];
+ int tempj = clusteringResult[clusterID][otherClusMem];
+ dist += distanceMatrix[tempi][tempj-tempi-1];
+ }
+ else
+ {
+ int tempi = clusteringResult[clusterID][otherClusMem];
+ int tempj = clusteringResult[clusterID][clusMem];
+ dist += distanceMatrix[tempi][tempj-tempi-1];
+ }
+ }
+ }
+ if(dist < minDist)
+ {
+ minDist = dist;
+ medianIndex = clusteringResult[clusterID][clusMem];
+
+ }
+
+ }
+ outMedianIndexVec.push_back(medianIndex);
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::calculateMedian()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Ramnath. K
+ * DATE : 19-05-2005
+ * NAME : computerDTWDistanceClusteringWrapper
+ * DESCRIPTION : Wrapper function to the function whichcomputes DTW distance between
+ two characters
+ * ARGUMENTS : train character, test character
+ * RETURNS : DTWDistance
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::computeDTWDistance(
+ const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outDTWDistance)
+
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::computeDTWDistance()" << endl;
+
+ const vector<LTKShapeFeaturePtr>& firstFeatureVec = inFirstShapeSampleFeatures.getFeatureVector();
+ const vector<LTKShapeFeaturePtr>& secondFeatureVec = inSecondShapeSampleFeatures.getFeatureVector();
+
+ int errorCode = m_dtwObj.computeDTW(firstFeatureVec, secondFeatureVec, getDistance,outDTWDistance,
+ m_dtwBanding, FLT_MAX, FLT_MAX);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "DTWDistance: " <<
+ outDTWDistance << endl;
+
+ if (errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: "<<
+ getErrorMessage(errorCode) <<
+ " NNShapeRecognizer::computeDTWDistance()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::computeDTWDistance()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+ * AUTHOR : Sridhar Krishna
+ * DATE : 24-04-2006
+ * NAME : computeEuclideanDistance
+ * DESCRIPTION : computes euclidean distance between two characters
+ * ARGUMENTS : LTKShapeFeaturePtrtor - 2
+ * RETURNS : euclidean distance
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::computeEuclideanDistance(
+ const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outEuclideanDistance)
+{
+ const vector<LTKShapeFeaturePtr>& firstFeatureVec = inFirstShapeSampleFeatures.getFeatureVector();
+ const vector<LTKShapeFeaturePtr>& secondFeatureVec = inSecondShapeSampleFeatures.getFeatureVector();
+
+ int firstFeatureVectorSize = firstFeatureVec.size();
+ int secondFeatureVectorSize = secondFeatureVec.size();
+
+ if(firstFeatureVectorSize != secondFeatureVectorSize)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EUNEQUAL_LENGTH_VECTORS << " " <<
+ getErrorMessage(EUNEQUAL_LENGTH_VECTORS) <<
+ " NNShapeRecognizer::computeEuclideanDistance()" << endl;
+
+ LTKReturnError(EUNEQUAL_LENGTH_VECTORS);
+ }
+
+ for(int i = 0; i < firstFeatureVectorSize; ++i)
+ {
+ float tempDistance = 0.0f;
+ getDistance(firstFeatureVec[i],
+ secondFeatureVec[i],
+ tempDistance);
+ outEuclideanDistance += tempDistance;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::computeEuclideanDistance()" << endl;
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 23-01-2007
+ * NAME : loadModelData
+ * DESCRIPTION : loads the reference model file into memory
+ * ARGUMENTS :
+ * RETURNS : SUCCESS on successful loading of the reference model file
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::loadModelData()
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::loadModelData()" << endl;
+
+ int numofShapes = 0;
+
+ // variable for shape Id
+ int classId = -1;
+
+ //Algorithm version
+ string algoVersionReadFromMDT = "";
+
+// int iMajor, iMinor, iBugfix = 0;
+
+ stringStringMap headerSequence;
+ LTKCheckSumGenerate cheSumGen;
+
+ if(errorCode = cheSumGen.readMDTHeader(m_nnMDTFilePath,headerSequence))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // printing the headerseqn
+ stringStringMap::const_iterator iter = headerSequence.begin();
+ stringStringMap::const_iterator endIter = headerSequence.end();
+
+ for(; iter != endIter; iter++)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Debug: header seqn"<<
+ iter->first << " : " <<
+ iter->second << endl;
+ }
+
+ string featureExtractor = headerSequence[FE_NAME];
+
+ if(LTKSTRCMP(m_featureExtractorName.c_str(), featureExtractor.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of FeatureExtractor parameter in config file ("<<
+ m_featureExtractorName<<") does not match with the value in MDT file ("<<
+ featureExtractor<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ string feVersion = headerSequence[FE_VER];
+
+ // comparing the mdt open mode read from cfg file with value in the mdt header
+ string mdtOpenMode = headerSequence[MDT_FOPEN_MODE];
+
+ if (LTKSTRCMP(m_MDTFileOpenMode.c_str(), mdtOpenMode.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of NNMDTFileOpenMode parameter in config file ("<<
+ m_MDTFileOpenMode <<") does not match with the value in MDT file ("<<
+ mdtOpenMode<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ // validating preproc parameters
+ int iErrorCode = validatePreprocParameters(headerSequence);
+ if (iErrorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Values of NNMDTFileOpenMode parameter in config file does not match with "
+ <<"the values in MDT file " << "NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // Version comparison START
+ algoVersionReadFromMDT = headerSequence[RECVERSION].c_str();
+
+ LTKVersionCompatibilityCheck verTempObj;
+ string supportedMinVersion(SUPPORTED_MIN_VERSION);
+ string currentVersionStr(m_currentVersion);
+
+ bool compatibilityResults = verTempObj.checkCompatibility(supportedMinVersion,
+ currentVersionStr,
+ algoVersionReadFromMDT);
+
+ if(compatibilityResults == false)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINCOMPATIBLE_VERSION << " " <<
+ " Incompatible version"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EINCOMPATIBLE_VERSION);
+ }
+ // Version comparison END
+
+ //Input Stream for Model Data file
+ ifstream mdtFileHandle;
+
+ if (m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::in);
+ }
+ else
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::in | ios::binary);
+ }
+
+ //If error while opening, return an error
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ " Unable to open model data file : " <<m_nnMDTFilePath<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ mdtFileHandle.seekg(atoi(headerSequence[HEADERLEN].c_str()),ios::beg);
+
+ //Read the number of shapes
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle >> numofShapes;
+ }
+ else
+ {
+ mdtFileHandle.read((char*) &numofShapes,
+ atoi(headerSequence[SIZEOFSHORTINT].c_str()));
+ }
+
+ if(!m_projectTypeDynamic && m_numShapes != numofShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
+ " Value of NumShapes parameter in config file ("<<m_numShapes<<
+ ") does not match with the value in MDT file ("<<numofShapes<<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ if(m_projectTypeDynamic)
+ {
+ m_numShapes = numofShapes;
+ }
+
+ // validating the header values
+
+ stringVector tokens;
+ stringVector classToken;
+
+ string strFeatureVector = "";
+
+ LTKShapeSample shapeSampleFeatures;
+
+ int floatSize = atoi(headerSequence[SIZEOFFLOAT].c_str());
+
+ int intSize = atoi(headerSequence[SIZEOFINT].c_str());
+
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ while(getline(mdtFileHandle, strFeatureVector, NEW_LINE_DELIMITER ))
+ {
+ LTKStringUtil::tokenizeString(strFeatureVector,
+ CLASSID_FEATURES_DELIMITER, classToken);
+
+ if(classToken.size() != 2)
+ continue;
+
+ classId = atoi((classToken[0]).c_str());
+
+ if(classId == -1)
+ continue;
+
+ LTKStringUtil::tokenizeString(classToken[1], FEATURE_EXTRACTOR_DELIMITER, tokens);
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVector;
+ LTKShapeFeaturePtr shapeFeature;
+
+ for(int i = 0; i < tokens.size(); ++i)
+ {
+ shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+
+ if (shapeFeature->initialize(tokens[i]) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+
+ shapeFeatureVector.push_back(shapeFeature);
+ }
+ //Set the feature vector and class id to the shape sample features
+ shapeSampleFeatures.setFeatureVector(shapeFeatureVector);
+ shapeSampleFeatures.setClassID(classId);
+
+ //cout << "load mdt class id :" << classId << endl;
+ //Adding all shape sample feature to the prototypeset
+ m_prototypeSet.push_back(shapeSampleFeatures);
+ //Add to Map
+ if( m_shapeIDNumPrototypesMap.find(classId)==m_shapeIDNumPrototypesMap.end())
+ {
+ m_shapeIDNumPrototypesMap[classId] = 1;
+ }
+ else
+ {
+ ++(m_shapeIDNumPrototypesMap[classId]);
+ }
+
+
+ //Clearing the vectors
+ shapeFeatureVector.clear();
+ tokens.clear();
+ classToken.clear();
+ classId = -1;
+ strFeatureVector = "";
+
+
+ }
+ }
+
+ else
+ {
+ floatVector floatFeatureVectorBuffer;
+
+ while(!mdtFileHandle.eof())
+ {
+ mdtFileHandle.read((char*) &classId, intSize);
+
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+
+ int numberOfFeatures;
+ int featureDimension;
+
+ mdtFileHandle.read((char*) &numberOfFeatures, intSize);
+ mdtFileHandle.read((char*) &featureDimension, intSize);
+
+ m_prototypeSet.push_back(shapeSampleFeatures);
+ LTKShapeSample &shapeSampleFeaturesRef = m_prototypeSet.back();
+ shapeSampleFeaturesRef.setClassID(classId);
+
+ // Read all features in one batch
+ size_t floatFeatureVectorElementCount = numberOfFeatures * featureDimension;
+ floatFeatureVectorBuffer.resize(floatFeatureVectorElementCount);
+ mdtFileHandle.read((char*) &floatFeatureVectorBuffer.front(), floatFeatureVectorElementCount * floatSize);
+ if ( mdtFileHandle.fail() )
+ {
+ break;
+ }
+
+ int featureIndex = 0;
+
+ vector<LTKShapeFeaturePtr>& shapeFeatureVector = shapeSampleFeaturesRef.getFeatureVectorRef();
+ shapeFeatureVector.reserve(numberOfFeatures);
+ floatVector::const_pointer floatFeatureVectorData = floatFeatureVectorBuffer.data();
+ LTKShapeFeaturePtr shapeFeature;
+
+ for ( ; featureIndex < numberOfFeatures ; featureIndex++)
+ {
+
+ shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+
+ if (shapeFeature->initialize(floatFeatureVectorData + featureIndex * featureDimension, featureDimension) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+
+ shapeFeatureVector.push_back(shapeFeature);
+
+ }
+
+ //Add to Map
+ intIntMap::iterator mapEntry;
+ if( (mapEntry = m_shapeIDNumPrototypesMap.find(classId))==m_shapeIDNumPrototypesMap.end())
+ {
+ m_shapeIDNumPrototypesMap[classId] = 1;
+ }
+ else
+ {
+ ++mapEntry->second;
+ }
+ }
+ }
+
+ mdtFileHandle.close();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::loadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 2-Mar-2007
+ * NAME : sortDist
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+bool NNShapeRecognizer::sortDist(const NeighborInfo& x, const NeighborInfo& y)
+{
+ return (x.distance) < (y.distance);
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 23-01-2007
+ * NAME : recognize
+ * DESCRIPTION : recognizes the incoming tracegroup
+ * ARGUMENTS : inTraceGroup - trace group to be recognized
+ * screenContext - screen context
+ * subSetOfClasses - subset of classes whose samples will be compared with traceGroup
+ * confThreshold - classes with confidence below this threshold are not returned, valid range of confThreshold: (0,1)
+ * numChoices - maximum number of choices to be returned
+ * outResultVector - result of recognition
+ * RETURNS : SUCCESS on successful running of the code
+ * NOTES :
+ * CHANGE HISTROY
+ * Author : Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::recognize()" << endl;
+
+
+ //Check for empty traces in traceGroup
+
+ if(traceGroup.containsAnyEmptyTrace())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<EEMPTY_TRACE << " " <<
+ " Input trace is empty"<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+
+ //Contains TraceGroup after Preprocessing is done
+ LTKTraceGroup preprocessedTraceGroup;
+
+
+ //Preprocess the traceGroup
+ if( preprocess(traceGroup, preprocessedTraceGroup) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Extract the shapeSample from preprocessedTraceGroup
+ if(!m_ptrFeatureExtractor)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ENULL_POINTER << " " <<
+ " m_ptrFeatureExtractor is NULL"<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(ENULL_POINTER);
+ }
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVec;
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ // call recognize with featureVector
+
+ if(recognize( shapeFeatureVec, inSubSetOfClasses, confThreshold,
+ numChoices, outResultVector) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ getErrorMessage(errorCode)<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+
+
+int NNShapeRecognizer::recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVector,
+ const vector<int>& inSubSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector)
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::recognize()" << endl;
+
+ m_cancelRecognition = false;
+
+ m_cachedShapeSampleFeatures.setFeatureVector(shapeFeatureVector);
+
+ //Creating a local copy of input inSubSetOfClasses, as it is const, STL's unique function modifies it!!!
+ vector<int> subSetOfClasses = inSubSetOfClasses;
+
+ int numPrototypes = m_prototypeSet.size();
+
+ /*********Validation for m_prototypeSet ***************************/
+ if ( numPrototypes == 0 )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROTOTYPE_SET_EMPTY << " " <<
+ " getErrorMessage(EPROTOTYPE_SET_EMPTY) "<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(EPROTOTYPE_SET_EMPTY); //modify
+ }
+
+ int dtwEuclideanFilter = (m_dtwEuclideanFilter == EUCLIDEAN_FILTER_OFF)?
+ EUCLIDEAN_FILTER_OFF : (int)((m_dtwEuclideanFilter * numPrototypes) / 100);
+
+ if(dtwEuclideanFilter == 0)
+ dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+
+ if( dtwEuclideanFilter != EUCLIDEAN_FILTER_OFF && dtwEuclideanFilter < m_nearestNeighbors)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ DTWEUCLIDEANFILTER << " is out of permitted range " <<
+ " NNShapeRecognizer::recognize()"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ // dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ }
+
+ /******************************************************************/
+ /*******************VALIDATING INPUT ARGUMENTS*********************/
+ /******************************************************************/
+
+ // Validating numChoices: valid values: {-1, (0,m_numShapes]}
+ if(numChoices <= 0 && numChoices != NUM_CHOICES_FILTER_OFF)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<")<=0, setting it to off (-1)"<<endl;
+ numChoices = -1;
+ }
+
+ if(!m_projectTypeDynamic && numChoices > m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "numChoices ("<<numChoices<<") > numShapes ("<<
+ m_numShapes<<"), using numShapes "<<m_numShapes<<" instead"<<endl;
+ numChoices = m_numShapes;
+ }
+
+
+ //Validating confThreshold: valid values: [0,1]
+ if(confThreshold > 1 || confThreshold < 0)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<
+ "Invalid value of confThreshold, valid values are: [0,1]"<<endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+
+
+ /*****************************************************************************************/
+ /*********************** DECLARING IMPORTANT LOCAL VARIABLES *****************************/
+ /*****************************************************************************************/
+
+ //Variable to store the DTW distance.
+ float dtwDistance = 0.0f;
+
+ //Variable to store the Euclidean distance.
+ float euclideanDistance = 0.0f;
+
+
+ // begin and end iterators for m_prototypeSet
+ vector<LTKShapeSample>::iterator prototypeSetIter = m_prototypeSet.begin();
+ vector<LTKShapeSample>::iterator prototypeSetIterEnd = m_prototypeSet.end();
+
+ //iterator for iterating the input shape subset vector
+
+ vector<int>::iterator subSetOfClassesIter;
+
+ int prototypeIndexOffset=0;
+
+ int numPrototypesForSubset=0;
+
+ if(subSetOfClasses.size()>0)
+ {
+ sort(subSetOfClasses.begin(),subSetOfClasses.end());
+ subSetOfClasses.erase(unique(subSetOfClasses.begin(),subSetOfClasses.end()),subSetOfClasses.end());
+ }
+
+ // Clearing cached Variables
+ m_vecRecoResult.clear();
+ m_neighborInfoVec.clear();
+
+ //Temporary variable to be used to populate distIndexPairVector
+ struct NeighborInfo tempPair;
+
+
+ /***************End of declarations and initializations of variables**************/
+
+
+
+ /***************************************************************/
+ /*************** Computation of Distance ***********************/
+ /***************************************************************/
+
+
+ if(subSetOfClasses.size()>0)
+ {
+ vector<int>::iterator tempSubsetIter = subSetOfClasses.begin();
+ vector<int>::iterator tempSubsetIterEnd = subSetOfClasses.end();
+
+ for(; tempSubsetIter!= tempSubsetIterEnd; ++tempSubsetIter)
+ {
+ if(m_shapeIDNumPrototypesMap.find(*tempSubsetIter)==m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ "Invalid class ID in the shape subset vector:"<<(*tempSubsetIter)<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+ else
+ {
+ numPrototypesForSubset = numPrototypesForSubset + m_shapeIDNumPrototypesMap[*tempSubsetIter];
+ }
+ }
+
+ if(dtwEuclideanFilter!= EUCLIDEAN_FILTER_OFF)
+ {
+ if(numPrototypesForSubset < dtwEuclideanFilter)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Number of prototypes corresponding to subset of classes asked for is less than Euclidean filter size; switching Euclidean filter off" << endl;
+ dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ }
+ }
+
+ subSetOfClassesIter=subSetOfClasses.begin();
+ }
+ // If Euclidean filter size >= size of the m_prototypeSet, do not use twEuclideanFilter
+ else if(subSetOfClasses.size()==0 && dtwEuclideanFilter >= m_prototypeSet.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "dtwEuclideanFilter >= m_prototypeSet.size(), switching Euclidean filter off" << endl;
+ dtwEuclideanFilter = EUCLIDEAN_FILTER_OFF;
+ }
+
+ // If the distance metric is Euclidean, compute the distances of test sample to all the samples in the prototype set
+ if(LTKSTRCMP(m_prototypeDistance.c_str(), EUCLIDEAN_DISTANCE) == 0)
+ {
+ for (int j = 0; prototypeSetIter != prototypeSetIterEnd; )
+ {
+
+ if(subSetOfClasses.size()>0)
+ {
+ if((*prototypeSetIter).getClassID()<(*subSetOfClassesIter))
+ {
+ j=j + m_shapeIDNumPrototypesMap[(*prototypeSetIter).getClassID()];
+ prototypeSetIter=prototypeSetIter +
+ m_shapeIDNumPrototypesMap[(*prototypeSetIter).getClassID()];
+
+ continue;
+ }
+
+
+ }
+ if(subSetOfClasses.size()==0 || (*prototypeSetIter).getClassID()==(*subSetOfClassesIter))
+ {
+ while(subSetOfClasses.size()==0 || (*prototypeSetIter).getClassID()==(*subSetOfClassesIter))
+ {
+ euclideanDistance = 0.0f;
+ errorCode = computeEuclideanDistance(*prototypeSetIter,
+ m_cachedShapeSampleFeatures,
+ euclideanDistance);
+
+ if(errorCode == SUCCESS && m_cancelRecognition)
+ return SUCCESS;
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ tempPair.distance = euclideanDistance;
+ tempPair.classId = (*prototypeSetIter).getClassID();
+ tempPair.prototypeSetIndex = j;
+
+ m_neighborInfoVec.push_back(tempPair);
+ ++prototypeSetIter;
+ ++j;
+
+ if(prototypeSetIter==m_prototypeSet.end())
+ {
+ break;
+ }
+ }
+
+ if(subSetOfClasses.size()>0)
+ {
+ ++subSetOfClassesIter;
+ if(subSetOfClassesIter==subSetOfClasses.end())
+ {
+ break;
+ }
+ }
+ }
+ }
+ }
+ // If the distance metric is DTW
+ else if(LTKSTRCMP(m_prototypeDistance.c_str(), DTW_DISTANCE) == 0)
+ {
+ vector<bool> filterVector(m_prototypeSet.size(), true);
+
+ // If Euclidean Filter is specified, find Euclidean distance to all the samples in the prototypeset,
+ // choose the top dtwEuclideanFilter number of prototypes, to which the DTW distance will be computed.
+ if(dtwEuclideanFilter != EUCLIDEAN_FILTER_OFF)
+ {
+ vector <struct NeighborInfo> eucDistIndexPairVector;
+
+ filterVector.assign(m_prototypeSet.size(), false);
+
+
+ for (int j = 0; prototypeSetIter != prototypeSetIterEnd;)
+ {
+ if(subSetOfClasses.size()>0)
+ {
+ if((*prototypeSetIter).getClassID()<(*subSetOfClassesIter))
+ {
+
+ j=j + m_shapeIDNumPrototypesMap[(*prototypeSetIter).getClassID()];
+ prototypeSetIter = prototypeSetIter + m_shapeIDNumPrototypesMap
+ [(*prototypeSetIter).getClassID()];
+
+ continue;
+ }
+ }
+ if(subSetOfClasses.size()==0 || (*prototypeSetIter).getClassID()==(*subSetOfClassesIter))
+ {
+ while(subSetOfClasses.size()==0 ||
+ (*prototypeSetIter).getClassID()==(*subSetOfClassesIter))
+ {
+ euclideanDistance = 0.0f;
+ errorCode = computeEuclideanDistance(*prototypeSetIter,
+ m_cachedShapeSampleFeatures,
+ euclideanDistance);
+
+ if(errorCode == SUCCESS && m_cancelRecognition)
+ return SUCCESS;
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ tempPair.distance = euclideanDistance;
+ tempPair.classId = (*prototypeSetIter).getClassID();
+ tempPair.prototypeSetIndex = j;
+
+ eucDistIndexPairVector.push_back(tempPair);
+ ++prototypeSetIter;
+ ++j;
+
+ if(prototypeSetIter==m_prototypeSet.end())
+ {
+ break;
+ }
+ }
+
+ if(subSetOfClasses.size()>0)
+ {
+ ++subSetOfClassesIter;
+ if(subSetOfClassesIter==subSetOfClasses.end())
+ {
+ break;
+ }
+ }
+ }
+ }
+
+ //Sort the eucDistIndexPairVector in ascending order of distance, and used only top dtwEuclideanFilter for DTW distance computation
+ sort(eucDistIndexPairVector.begin(), eucDistIndexPairVector.end(), sortDist);
+
+ for (int z = 0; z < dtwEuclideanFilter; ++z )
+ {
+ int prototypeSetIndex = eucDistIndexPairVector[z].prototypeSetIndex ;
+ filterVector[prototypeSetIndex] = true;
+ }
+ }
+ else
+ {
+ if(subSetOfClasses.size()>0)
+ {
+ filterVector.assign(m_prototypeSet.size(), false);
+
+ for(map<int,int>::iterator shapeIDNumPrototypesMapIter=m_shapeIDNumPrototypesMap.begin();
+ shapeIDNumPrototypesMapIter!=m_shapeIDNumPrototypesMap.end();)
+ {
+ if(shapeIDNumPrototypesMapIter->first<(*subSetOfClassesIter))
+ {
+
+ prototypeIndexOffset=prototypeIndexOffset +
+ shapeIDNumPrototypesMapIter->second;
+
+ ++shapeIDNumPrototypesMapIter;
+
+ continue;
+ }
+ else if(shapeIDNumPrototypesMapIter->first==(*subSetOfClassesIter))
+ {
+ while(m_prototypeSet[prototypeIndexOffset].getClassID()==
+ (*subSetOfClassesIter))
+ {
+ filterVector[prototypeIndexOffset]=true;
+ ++prototypeIndexOffset;
+ if( prototypeIndexOffset == m_prototypeSet.size()) break; }
+ if(subSetOfClassesIter==subSetOfClasses.end()) { break; } //filterVector.assign(filterVector.begin()+prototypeIndexOffset,filterVector.begin()+prototypeIndexOffset+shapeIDNumPrototypesMapIter->second,true);
+ ++shapeIDNumPrototypesMapIter;
+ ++subSetOfClassesIter;
+ if(subSetOfClassesIter==subSetOfClasses.end())
+ {
+ break;
+ }
+
+ }
+ }
+ }
+ }
+
+
+ //Iterate through all the prototypes, and compute DTW distance to the prototypes for which corresponding entry in filterVector is true
+ for (int i = 0 ; i < m_prototypeSet.size(); ++i )
+ {
+
+ if(filterVector[i])
+ {
+ dtwDistance = 0.0f;
+ errorCode = computeDTWDistance(m_prototypeSet[i],
+ m_cachedShapeSampleFeatures,
+ dtwDistance);
+
+ if(errorCode == SUCCESS && m_cancelRecognition)
+ return SUCCESS;
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::recognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ tempPair.distance = dtwDistance;
+ tempPair.classId = (m_prototypeSet[i]).getClassID();
+ tempPair.prototypeSetIndex = i;
+ m_neighborInfoVec.push_back(tempPair);
+ }
+ }
+
+ filterVector.clear();
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_FILE_RANGE << " " <<
+ "The selected prototype distance method \""<<
+ m_prototypeDistance<<"\" is not supported "<<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+
+ //Sort the distIndexPairVector based on distances, in ascending order.
+ sort(m_neighborInfoVec.begin(), m_neighborInfoVec.end(), sortDist);
+
+ //Reject the sample if the similarity of the nearest sample is lower than m_rejectThreshold specified by the user.
+ if(SIMILARITY(m_neighborInfoVec[0].distance) <= m_rejectThreshold)
+ {
+
+ m_vecRecoResult.clear();
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)<<"Test sample too distinct, rejecting the sample"<<endl;
+ return SUCCESS;
+ }
+
+ //Compute the confidences of the classes appearing in distIndexPairVector
+ //outResultVector is an output argument, populated in computeConfidence()
+ if((errorCode = computeConfidence()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::recognize()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // Temporary result vector to store the results based on confThreshold and numChoices specified by the user.
+ vector<LTKShapeRecoResult> tempResultVector;
+
+ //If confThreshold is specified, get the entries from resultVector with confidence >= confThreshold
+ if(confThreshold != CONF_THRESHOLD_FILTER_OFF)
+ {
+ for(int i = 0 ; i < m_vecRecoResult.size() ; i++)
+ {
+ if( m_vecRecoResult[i].getConfidence() >= confThreshold)
+ {
+ tempResultVector.push_back(m_vecRecoResult[i]);
+ }
+ }
+ m_vecRecoResult.clear();
+ m_vecRecoResult = tempResultVector;
+ tempResultVector.clear();
+ }
+ //Check if outResultVector is empty, if so, log
+ if(m_vecRecoResult.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) <<
+ "Size of the result vector is empty, could not satisfy confThreshold criteria"<<endl;
+ }
+
+ //If numChoices is specified, get the top numChoices entries from outResultVector
+ if(numChoices != NUM_CHOICES_FILTER_OFF)
+ {
+ //Get the entries from outResultVector only if size of resultVector > numChoices
+ if(m_vecRecoResult.size() > numChoices)
+ {
+ for( int i = 0 ; i < numChoices ; ++i)
+ tempResultVector.push_back(m_vecRecoResult[i]);
+ m_vecRecoResult.clear();
+ m_vecRecoResult = tempResultVector;
+ tempResultVector.clear();
+ }
+
+ }
+
+ if(m_cancelRecognition)
+ m_vecRecoResult.clear();
+
+ outResultVector = m_vecRecoResult;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::recognize()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 23-Jan-2007
+ * NAME : unloadModelData
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : SUCCESS
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::unloadModelData()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::unloadModelData()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ //Update MDT file with any modification, if available in memory
+ if(m_prototypeSetModifyCount >0)
+ {
+ m_prototypeSetModifyCount = m_MDTUpdateFreq-1;
+
+ returnStatus = writePrototypeSetToMDTFile();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::unloadModelData()" << endl;
+ }
+ m_prototypeSetModifyCount = 0;
+ }
+
+ //Clearing the prototypSet
+ m_prototypeSet.clear();
+ m_shapeIDNumPrototypesMap.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::unloadModelData()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 27-Feb-2007
+ * NAME : setDeviceContext
+ * DESCRIPTION : New Function - Not yet added
+ * ARGUMENTS :
+ * RETURNS : SUCCESS
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::setDeviceContext(const LTKCaptureDevice& deviceInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::setDeviceContext()" << endl;
+
+ if(m_ptrPreproc == NULL)
+ {
+ int returnStatus = ECREATE_PREPROC;
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::setDeviceContext()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ m_ptrPreproc->setCaptureDevice(deviceInfo);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::setDeviceContext()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Nidhi sharma
+ * DATE : 22-02-2007
+ * NAME : peformClustering
+ * DESCRIPTION : This method will do Custering for the given ShapeSamples
+ * ARGUMENTS :
+ * RETURNS : medianIndex
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::performClustering(const vector<LTKShapeSample> & shapeSamplesVec,
+ vector<LTKShapeSample>& outClusteredShapeSampleVec)
+
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::performClustering()" << endl;
+
+ intVector tempVec;
+ int2DVector outputVector;
+ float2DVector distanceMatrix;
+ int sampleCount=shapeSamplesVec.size();
+ int returnStatus = SUCCESS;
+
+ if(m_prototypeReductionFactor == -1)
+ {
+ //find number of clusters automatically
+ //this is done when either of NumClusters or PrototypeReducrion factor is set
+ //to automatic
+ LTKHierarchicalClustering<LTKShapeSample,NNShapeRecognizer> hc(shapeSamplesVec,AVERAGE_LINKAGE,AVG_SIL);
+ if(LTKSTRCMP(m_prototypeDistance.c_str(), DTW_DISTANCE) == 0)
+ {
+ returnStatus = hc.cluster(this,&NNShapeRecognizer::computeDTWDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+ }
+ else if(LTKSTRCMP(m_prototypeDistance.c_str(), EUCLIDEAN_DISTANCE) == 0)
+ {
+ returnStatus = hc.cluster(this,&NNShapeRecognizer::computeEuclideanDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+ }
+
+ //Cluster results are populated in an outputVector
+ hc.getClusterResult(outputVector);
+ distanceMatrix = hc.getProximityMatrix();
+
+ }
+ else if(m_prototypeReductionFactor == 0|| m_numClusters >= sampleCount)
+ {
+ //case where clustering is not required every sample is a cluster by itself
+ outClusteredShapeSampleVec = shapeSamplesVec;
+ }
+ else
+ {
+ //clustering has to be performed
+ int numClusters;
+ if(m_numClusters == NN_NUM_CLUST_INITIAL)
+ {
+ numClusters = (100-m_prototypeReductionFactor)*sampleCount/100;
+ if(numClusters == 0)
+ {
+ numClusters = 1;
+ }
+ }
+ else if(m_prototypeReductionFactor == NN_NUM_CLUST_INITIAL)
+ {
+ numClusters = m_numClusters;
+ }
+
+ try
+ {
+ LTKHierarchicalClustering<LTKShapeSample,NNShapeRecognizer>
+ hc(shapeSamplesVec,numClusters, AVERAGE_LINKAGE);
+
+
+ if(numClusters == 1)
+ {
+ int tempVar;
+ if(LTKSTRCMP(m_prototypeDistance.c_str(), DTW_DISTANCE) == 0)
+ {
+ hc.computeProximityMatrix(this, &NNShapeRecognizer::computeDTWDistance);
+ }
+ else if(LTKSTRCMP(m_prototypeDistance.c_str(), EUCLIDEAN_DISTANCE) == 0)
+ {
+ hc.computeProximityMatrix(this, &NNShapeRecognizer::computeEuclideanDistance);
+ }
+
+ for(tempVar=0;tempVar<shapeSamplesVec.size();tempVar++)
+ {
+ tempVec.push_back(tempVar);
+ }
+
+ outputVector.push_back(tempVec);
+ tempVec.clear();
+ }
+ else
+ {
+ if(LTKSTRCMP(m_prototypeDistance.c_str(), DTW_DISTANCE) == 0)
+ {
+ returnStatus = hc.cluster(this,&NNShapeRecognizer::computeDTWDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ }
+ else if(LTKSTRCMP(m_prototypeDistance.c_str(), EUCLIDEAN_DISTANCE) == 0)
+ {
+ returnStatus = hc.cluster(this,&NNShapeRecognizer::computeEuclideanDistance);
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << returnStatus << " " <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+
+ }
+
+ //Cluster results are populated in an outputVector
+ hc.getClusterResult(outputVector);
+ }
+ distanceMatrix = hc.getProximityMatrix();
+ }
+ catch(LTKException e)
+ {
+ errorCode = e.getErrorCode();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(errorCode);
+ }
+ }
+
+ if((m_prototypeReductionFactor != 0 && m_prototypeReductionFactor != NN_NUM_CLUST_INITIAL)||
+ (m_numClusters>0 && m_numClusters<sampleCount))
+ {
+
+ vector<int> medianIndexVec;
+
+ errorCode = calculateMedian(outputVector, distanceMatrix, medianIndexVec);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+ for(int numMedians = 0 ; numMedians < medianIndexVec.size() ; numMedians++)
+ {
+ outClusteredShapeSampleVec.push_back(shapeSamplesVec[medianIndexVec[numMedians]]);
+ }
+ /*
+ int medianIndex = 0;
+ for (int clusNum = 0; clusNum < outputVector.size(); clusNum++)
+ {
+
+ errorCode = calculateMedian(outputVector, distanceMatrix, clusNum,medianIndex);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Error computing median, calculateMedian()" <<
+ " NNShapeRecognizer::performClustering()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+ outClusteredShapeSampleVec.push_back(shapeSamplesVec[medianIndex]);
+ }
+ */
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::performClustering()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Nidhi sharma
+ * DATE : 22-02-2007
+ * NAME : getShapeSampleFromInkFile
+ * DESCRIPTION : This method will get the ShapeSample by giving the ink
+ * file path as input
+ * ARGUMENTS :
+ * RETURNS : SUCCESS
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec)
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ if ( inkFilePath.empty() )
+ return FAILURE;
+
+ LTKCaptureDevice captureDevice;
+ LTKScreenContext screenContext;
+
+ LTKTraceGroup inTraceGroup, preprocessedTraceGroup;
+ inTraceGroup.emptyAllTraces();
+
+ int returnVal = m_shapeRecUtil.readInkFromFile(inkFilePath,
+ m_lipiRootPath, inTraceGroup,
+ captureDevice, screenContext);
+
+ if (returnVal!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<returnVal<<
+ " NNShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(returnVal);
+ }
+
+ m_ptrPreproc->setCaptureDevice(captureDevice);
+ m_ptrPreproc->setScreenContext(screenContext);
+
+ preprocessedTraceGroup.emptyAllTraces();
+
+ //Preprocessing to be done for the trace group that was read
+ if( preprocess(inTraceGroup, preprocessedTraceGroup) != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ shapeFeatureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::getShapeFeatureFromInkFile()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Saravanan
+ * DATE : 22-02-2007
+ * NAME : trainFromListFile
+ * DESCRIPTION : This method will do the training by giving the Train List
+ * file as input
+ * ARGUMENTS :
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::trainFromListFile(const string& listFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::trainFromListFile()" << endl;
+
+
+ //Count for the no. of samples read for a shape
+ int sampleCount = 0;
+
+ //Count of the no. of shapes read so far
+ int shapeCount = 0;
+
+ //Flag to skip reading a newline in the list file, when a new class starts
+ bool lastshapeIdFlag = false;
+
+ //Ink File Path
+ string path = "";
+
+ //Line from the list file
+ string line = "";
+
+ //Line is split into tokens
+ stringVector tokens;
+
+ //Flag is set when EOF is reached
+ bool eofFlag = false;
+
+ //ID for each shapes
+ int shapeId = -1;
+
+ //classId of the character
+ int prevClassId = -1;
+
+ //Indicates the first class
+ bool initClassFlag = false;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ vector<LTKShapeSample> shapeSamplesVec;
+
+ vector<LTKShapeSample> clusteredShapeSampleVec;
+
+ ofstream mdtFileHandle;
+ ifstream listFileHandle;
+
+ vector<LTKShapeFeaturePtr> shapeFeature;
+
+ //Get the Instance of LTKShapeFeatureExtractor
+ //initializeFeatureExtractorInstance();
+
+ //Opening the train list file for reading mode
+ listFileHandle.open(listFilePath.c_str(), ios::in);
+
+ //Throw an error if unable to open the training list file
+ if(!listFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ETRAINLIST_FILE_OPEN << " " <<
+ getErrorMessage(ETRAINLIST_FILE_OPEN)<<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(ETRAINLIST_FILE_OPEN);
+ }
+
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(),ios::out|ios::binary);
+ }
+
+ //Throw an error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ listFileHandle.close();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN)<<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ //Write the number of Shapes
+ mdtFileHandle << m_numShapes << endl;
+ }
+ else
+ {
+ mdtFileHandle.write((char*) &m_numShapes, sizeof(unsigned short));
+ }
+
+ int errorCode = SUCCESS;
+ while(!listFileHandle.eof())
+ {
+ // Not a sample of a new class
+ if( lastshapeIdFlag == false )
+ {
+ //Get the line from the list file
+ getline(listFileHandle, line, NEW_LINE_DELIMITER);
+
+ path = "";
+
+ //Check if EOF is reached
+ if( listFileHandle.eof() )
+ {
+ eofFlag = true;
+ }
+
+ //Skip commented line
+ if ( line[0] == COMMENTCHAR )
+ {
+ continue;
+ }
+
+ if (eofFlag == false)
+ {
+ //Tokenize the string
+ errorCode = LTKStringUtil::tokenizeString(line, LIST_FILE_DELIMITER, tokens);
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+ mdtFileHandle.close();
+
+ LTKReturnError(errorCode);
+ }
+
+
+ //Tokens must be of size 2, one is pathname and other is shapeId
+ //If the end of file not reached then continue the looping
+ if( tokens.size() != 2 && eofFlag == false )
+ continue;
+
+ //Tokens[0] indicates the path name
+ path = tokens[0];
+
+ //Tokens[1] indicates the shapeId
+ shapeId = atoi( tokens[1].c_str() );
+
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "The NNShapeRecognizer requires training file class Ids to be positive integers and listed in the increasing order"<<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_SHAPEID;
+ break;
+ }
+ else if(shapeId < prevClassId)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "Shape IDs in the train list file should be in the increasing order. Please use scripts/validateListFile.pl to generate list files." <<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ errorCode = EINVALID_ORDER_LISTFILE;
+ break;
+ }
+
+
+ //This condition is used to handle the first sample in the file
+ if( initClassFlag == false )
+ {
+ initClassFlag = true;
+ prevClassId=shapeId;
+ }
+ }
+ }
+ else //Sample of a new class; do not read the next line during this iteration
+ {
+ //flag unset to read next line during the next iteration
+ lastshapeIdFlag = false;
+ }
+
+ // Sample from the same class, extract features, and push the extracted features to shapeSamplesVec
+ if( shapeId == prevClassId && ! path.empty())
+ {
+ if( getShapeFeatureFromInkFile(path, shapeFeature) != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
+ "Error extracting features from the ink file: " <<
+ path << ", extracting features from the next sample."<<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ continue;
+ }
+
+ shapeSampleFeatures.setFeatureVector(shapeFeature);
+ shapeSampleFeatures.setClassID(shapeId);
+
+ ++sampleCount;
+ shapeSamplesVec.push_back(shapeSampleFeatures);
+
+ shapeFeature.clear();
+
+ //All the samples are pushed to m_trainSet used only for trainLVQ
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_LVQ)
+ == 0 && m_prototypeReductionFactor != 0)
+ m_trainSet.push_back(shapeSampleFeatures);
+ }
+
+ // Sample of new class seen, or end of list file reached; train all the samples of previous class ID
+ if( shapeId != prevClassId || eofFlag == true )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Training for class : " << prevClassId << endl;
+
+ //Increase shape count only if there are atleast one sample per class
+ if( sampleCount > 0 )
+ shapeCount++;
+
+ //check that shapecount must not be greater than specified number
+ //of shapes, if projecttype was not dynamic
+ if( !m_projectTypeDynamic && shapeCount > m_numShapes )
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+ break;
+ }
+
+ if( shapeCount > 0 && sampleCount > 0 )
+ {
+ // No LVQ training being done?
+ errorCode = performClustering(shapeSamplesVec,
+ clusteredShapeSampleVec);
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+ mdtFileHandle.close();
+ LTKReturnError(errorCode);
+ }
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_LVQ) == 0)
+ {
+ //Push all the samples after clustering into prototypeSet
+ for( int i = 0; i < clusteredShapeSampleVec.size(); ++i )
+ {
+ m_prototypeSet.push_back(clusteredShapeSampleVec[i]);
+ }
+ }
+ else if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0)
+ {
+ //Writing results to the MDT file
+ errorCode = appendPrototypesToMDTFile(clusteredShapeSampleVec, mdtFileHandle);
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<errorCode << " " <<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+
+ listFileHandle.close();
+ mdtFileHandle.close();
+ LTKReturnError(errorCode);
+ }
+
+ }
+
+ //Clearing the shapeSampleVector and clusteredShapeSampleVector
+ clusteredShapeSampleVec.clear();
+ shapeSamplesVec.clear();
+
+ //Resetting sampleCount for the next class
+ sampleCount = 0;
+
+ //Set the flag so that the already read line of next class in the list file is not lost
+ lastshapeIdFlag = true;
+
+ prevClassId = shapeId;
+
+ }
+ }
+ }//End of while
+
+ //Closing the Train List file and Model Data file
+ listFileHandle.close();
+ mdtFileHandle.close();
+
+ if(!m_projectTypeDynamic && shapeCount != m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_SHAPES << " " <<
+ getErrorMessage(EINVALID_NUM_OF_SHAPES)<<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromListFile()" << endl;
+ LTKReturnError(errorCode);
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::trainFromListFile()" << endl;
+
+ return SUCCESS;
+
+}
+
+
+/******************************************************************************
+* AUTHOR : Saravanan
+* DATE : 23-03-2007
+* NAME : getShapeSampleFromString
+* DESCRIPTION : This method get the Shape Sample Feature from a given line
+* ARGUMENTS :
+* RETURNS : none
+* NOTES : w
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int NNShapeRecognizer::getShapeSampleFromString(const string& inString, LTKShapeSample& outShapeSample)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::getShapeSampleFromString()" << endl;
+
+
+ //Line is split into tokens
+ stringVector tokens;
+
+ //Class Id
+ int classId = -1;
+
+ //Feature Vector string
+ string strFeatureVector = "";
+
+ //Tokenize the string
+ int errorCode = LTKStringUtil::tokenizeString(inString, EMPTY_STRING, tokens);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ //Tokens must be of size 2, one is classId and other is Feature Vector
+ if( tokens.size() != 2)
+ return FAILURE;
+
+ //Tokens[0] indicates the path name
+ classId = atoi(tokens[0].c_str());
+
+ //Tokens[1] indicates the shapeId
+ strFeatureVector = tokens[1];
+
+ errorCode = LTKStringUtil::tokenizeString(strFeatureVector, FEATURE_EXTRACTOR_DELIMITER, tokens);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+
+ vector<LTKShapeFeaturePtr> shapeFeatureVector;
+ LTKShapeFeaturePtr shapeFeature;
+
+ for(int i = 0; i < tokens.size(); ++i)
+ {
+ shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();
+ if(shapeFeature->initialize(tokens[i]) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
+ "Number of features extracted from a trace is not correct" <<
+ " NNShapeRecognizer::getShapeSampleFromString()" << endl;
+ LTKReturnError(EINVALID_INPUT_FORMAT);
+ }
+ shapeFeatureVector.push_back(shapeFeature);
+ }
+
+ //Set the feature vector and class id to the shape sample features
+ outShapeSample.setFeatureVector(shapeFeatureVector);
+ outShapeSample.setClassID(classId);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::getShapeSampleFromString()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : Saravanan
+* DATE : 22-02-2007
+* NAME : initializeFeatureExtractorInstance
+* DESCRIPTION : This method get the Instance of the Feature Extractor
+* from LTKShapeFeatureExtractorFactory
+* ARGUMENTS :
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int NNShapeRecognizer::initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+
+ LTKShapeFeatureExtractorFactory factory;
+ int errorCode = factory.createFeatureExtractor(m_featureExtractorName,
+ m_lipiRootPath,
+ m_lipiLibPath,
+ &m_libHandlerFE,
+ controlInfo,
+ &m_ptrFeatureExtractor);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EFTR_EXTR_NOT_EXIST << " " <<
+ " NNShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+ LTKReturnError(errorCode);
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::initializeFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : Saravanan
+* DATE : 26-03-2007
+* NAME : deleteFeatureExtractorInstance
+* DESCRIPTION : This method unloads the Feature extractor instance
+* ARGUMENTS : none
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int NNShapeRecognizer::deleteFeatureExtractorInstance()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ if (m_ptrFeatureExtractor != NULL)
+ {
+ typedef int (*FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)(LTKShapeFeatureExtractor *obj);
+ FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR deleteFeatureExtractor;
+ void * functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ int returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandlerFE,
+ DELETE_SHAPE_FEATURE_EXTRACTOR,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: "<< EDLL_FUNC_ADDRESS_DELETE_FEATEXT << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_DELETE_FEATEXT) <<
+ " NNShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_DELETE_FEATEXT);
+ }
+
+ deleteFeatureExtractor = (FN_PTR_DELETE_SHAPE_FEATURE_EXTRACTOR)functionHandle;
+
+ deleteFeatureExtractor(m_ptrFeatureExtractor);
+
+ m_ptrFeatureExtractor = NULL;
+
+ // unload feature extractor dll
+ if(m_libHandlerFE != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandlerFE);
+ m_libHandlerFE = NULL;
+
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::deleteFeatureExtractorInstance()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+* AUTHOR : Saravanan
+* DATE : 22-02-2007
+* NAME : updateHeaderWithAlgoInfo
+* DESCRIPTION : This method will Update the Header information for the MDT file
+* ARGUMENTS :
+* RETURNS : none
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+void NNShapeRecognizer::updateHeaderWithAlgoInfo()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+ m_headerInfo[RECVERSION] = m_currentVersion;
+ string algoName = NN;
+ m_headerInfo[RECNAME] = algoName;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::updateHeaderWithAlgoInfo()" << endl;
+
+}
+
+
+/******************************************************************************
+* AUTHOR : Saravanan
+* DATE : 19-03-2007
+* NAME : getDistance
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+void NNShapeRecognizer::getDistance(const LTKShapeFeaturePtr& f1,
+ const LTKShapeFeaturePtr& f2,
+ float& distance)
+{
+ f1->getDistance(f2, distance);
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 11-06-2007
+ * NAME : getFeaturesFromTraceGroup
+ * DESCRIPTION : 1. PreProcess 2. Extract Features 3.Add to PrototypeSet
+ * 4. Add to MDT
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::extractFeatVecFromTraceGroup(const LTKTraceGroup& inTraceGroup,
+ vector<LTKShapeFeaturePtr>& featureVec)
+{
+ int errorCode;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+
+ LTKTraceGroup preprocessedTraceGroup; //TraceGroup after Preprocessing
+
+ //Check for empty traces in inTraceGroup
+ if(inTraceGroup.containsAnyEmptyTrace())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EEMPTY_TRACE << " " <<
+ getErrorMessage(EEMPTY_TRACE) <<
+ " NNShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ //Preprocess the inTraceGroup
+ if(preprocess(inTraceGroup, preprocessedTraceGroup) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = m_ptrFeatureExtractor->extractFeatures(preprocessedTraceGroup,
+ featureVec);
+
+ if (errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NNShapeRecognizer::extractFeatVecFromTraceGroup()" << endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 07-06-2007
+ * NAME : addClass
+ * DESCRIPTION : 1. PreProcess 2. Extract Features 3.Add to PrototypeSet
+ * 4. Add to MDT
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID)
+{
+ // Should be moved to nnInternal
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::addClass()" << endl;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ if(!m_projectTypeDynamic)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROJ_NOT_DYNAMIC << " " <<
+ "Not allowed to ADD shapes to a project with fixed number of shapes"<<
+ " NNShapeRecognizer::addClass()" << endl;
+
+ LTKReturnError(EPROJ_NOT_DYNAMIC);
+ }
+
+ //Compute ClassID
+ int tempShapeID;
+ if(m_shapeIDNumPrototypesMap.size()>0)
+ {
+ map<int,int>::reverse_iterator m_shapeIDNumPrototypesMapIter;
+ m_shapeIDNumPrototypesMapIter = m_shapeIDNumPrototypesMap.rbegin();
+ tempShapeID = m_shapeIDNumPrototypesMapIter->first;
+ shapeID = tempShapeID+1;
+ }
+ else
+ {
+ shapeID = LTK_START_SHAPEID;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "New ShapeID = "<<shapeID<<endl;
+ //Calculate Features
+ int errorCode = SUCCESS;
+ vector<LTKShapeFeaturePtr> tempFeatureVec;
+
+ errorCode = extractFeatVecFromTraceGroup(sampleTraceGroup,tempFeatureVec);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addClass()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ shapeSampleFeatures.setFeatureVector(tempFeatureVec);
+
+ shapeSampleFeatures.setClassID(shapeID);
+
+ //Update m_prototypeSet
+ errorCode = insertSampleToPrototypeSet(shapeSampleFeatures);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addClass()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Update m_shapeIDNumPrototypesMap
+ m_shapeIDNumPrototypesMap[shapeID]= 1;
+
+
+ //Update MDT File
+ errorCode = writePrototypeSetToMDTFile();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addClass()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NNShapeRecognizer::addClass"<<endl;
+ return SUCCESS;
+}
+/******************************************************************************
+* AUTHOR : Anish Kumar
+* DATE : 07-06-2007
+* NAME : addSample
+* DESCRIPTION : Add Sample to given class
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+******************************************************************************/
+int NNShapeRecognizer::addSample(const LTKTraceGroup& sampleTraceGroup, int shapeID)
+{
+ // Should be moved to nnInternal
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::addSample()" << endl;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ if(!m_projectTypeDynamic)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROJ_NOT_DYNAMIC << " " <<
+ "Not allowed to ADD shapes to a project with fixed number of shapes"<<
+ " NNShapeRecognizer::addSample()" << endl;
+
+ LTKReturnError(EPROJ_NOT_DYNAMIC);
+ }
+
+ //Calculate Features
+ int errorCode = SUCCESS;
+ vector<LTKShapeFeaturePtr> tempFeatureVec;
+
+ errorCode = extractFeatVecFromTraceGroup(sampleTraceGroup,tempFeatureVec);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addSample()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ shapeSampleFeatures.setFeatureVector(tempFeatureVec);
+
+ shapeSampleFeatures.setClassID(shapeID);
+
+ //Update m_prototypeSet
+ errorCode = insertSampleToPrototypeSet(shapeSampleFeatures);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addSample()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Update m_shapeIDNumPrototypesMap
+ int currentNum = m_shapeIDNumPrototypesMap[shapeID];
+ m_shapeIDNumPrototypesMap[shapeID]= currentNum+1;
+
+ //Update MDT File
+ errorCode = writePrototypeSetToMDTFile();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::addSample()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NNShapeRecognizer::addSample"<<endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 07-06-2007
+ * NAME : deleteClass
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::deleteClass(int shapeID)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering NNShapeRecognizer::deleteClass" <<endl;
+
+ LTKShapeSample shapeSampleFeatures;
+ vector<LTKShapeSample>::iterator prototypeSetIter;
+
+ int prototypeSetSize = m_prototypeSet.size();
+
+ if(!m_projectTypeDynamic)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EPROJ_NOT_DYNAMIC << " " <<
+ "Not allowed to delete shapes to a project with fixed number of Shapes"<<
+ " NNShapeRecognizer::deleteClass()" << endl;
+
+ LTKReturnError(EPROJ_NOT_DYNAMIC);
+ }
+
+ //Validate Input Parameters - shapeID
+ if(m_shapeIDNumPrototypesMap.find(shapeID) ==m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_SHAPEID << " " <<
+ "shapeID is not valid"<<
+ " NNShapeRecognizer::deleteClass()" << endl;
+
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ //Update m_prototypeSet
+ int k =0;
+ for (int i=0;i<prototypeSetSize;i++)
+ {
+ prototypeSetIter = m_prototypeSet.begin() + k;
+ int classId = (*prototypeSetIter).getClassID();
+
+ if(classId == shapeID)
+ {
+ m_prototypeSet.erase(prototypeSetIter);
+ continue;
+ }
+ k++;
+ prototypeSetIter++;
+ }
+ //Update m_shapeIDNumPrototypesMap
+ m_shapeIDNumPrototypesMap.erase(shapeID);
+
+ //Update MDT File
+ int returnStatus = writePrototypeSetToMDTFile();
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: " << returnStatus << " " <<
+ "Exiting NNShapeRecognizer::deleteClass" <<endl;
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting NNShapeRecognizer::deleteClass" <<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 09-06-2007
+ * NAME : writePrototypeSetToMDTFile
+ * DESCRIPTION : Creates a MDTFile with updated m_prototypeSet
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::writePrototypeSetToMDTFile()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::writePrototypeSetToMDTFile()" << endl;
+
+ int returnStatus = SUCCESS;
+
+ //Flush to MDT only after m_MDTUpdateFreq modifications
+ m_prototypeSetModifyCount++;
+ if(m_prototypeSetModifyCount == m_MDTUpdateFreq)
+ {
+ m_prototypeSetModifyCount = 0;
+
+ ofstream mdtFileHandle;
+ vector<LTKShapeSample> vecShapeSampleFeatures;
+ LTKShapeSample shapeSampleFeatures;
+
+ vector<LTKShapeSample>::iterator prototypeSetIter;
+
+ int prototypeSetSize = m_prototypeSet.size();
+
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(),ios::out|ios::binary);
+ }
+
+
+ //Throw an error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN) <<
+ " NNShapeRecognizer::writePrototypeSetToMDTFile()" << endl;
+
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ //Write the number of Shapes
+ mdtFileHandle << 0 << endl; //Representing Dynamic
+ }
+ else
+ {
+ int numShapes = 0;
+ mdtFileHandle.write((char*) &numShapes, sizeof(unsigned short));
+ }
+ prototypeSetIter = m_prototypeSet.begin();
+
+ for (int i=0;i<prototypeSetSize;i++)
+ {
+ int classId = (*prototypeSetIter).getClassID();
+ shapeSampleFeatures.setClassID(classId);
+ shapeSampleFeatures.setFeatureVector((*prototypeSetIter).getFeatureVector());
+
+ vecShapeSampleFeatures.push_back(shapeSampleFeatures);
+ prototypeSetIter++;
+ }
+
+ returnStatus = appendPrototypesToMDTFile(vecShapeSampleFeatures,mdtFileHandle);
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::writePrototypeSetToMDTFile()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ mdtFileHandle.close();
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ string strModelDataHeaderInfoFile = "";
+ LTKCheckSumGenerate cheSumGen;
+
+ returnStatus = cheSumGen.addHeaderInfo(
+ strModelDataHeaderInfoFile,
+ m_nnMDTFilePath,
+ m_headerInfo
+ );
+
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< returnStatus << " " <<
+ " NNShapeRecognizer::writePrototypeSetToMDTFile()" << endl;
+
+ LTKReturnError(returnStatus);
+ }
+
+ vecShapeSampleFeatures.clear();
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NNShapeRecognizer::writePrototypeSetToMDTFile"<<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 09-06-2007
+ * NAME : Add Sample to m_prototypeSet
+ * DESCRIPTION : Add LTKShapeSample to m_prototypeSet
+ *
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::insertSampleToPrototypeSet(const LTKShapeSample &shapeSampleFeatures)
+{
+ //Error??
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering NNShapeRecognizer::insertSampleToPrototypeSet"<<endl;
+
+ vector<LTKShapeSample>::iterator prototypeSetIter;
+ int classID = shapeSampleFeatures.getClassID();
+ int maxClassID;
+
+ int prototypeSize = m_prototypeSet.size();
+ if(prototypeSize > 0)
+ {
+ maxClassID = m_prototypeSet.at(prototypeSize-1).getClassID();
+ }
+ else
+ {
+ maxClassID = LTK_START_SHAPEID;
+ }
+
+ prototypeSetIter = m_prototypeSet.begin();
+
+ if(classID >= maxClassID)
+ {
+ m_prototypeSet.push_back(shapeSampleFeatures);
+ }
+ else
+ {
+ for(;prototypeSetIter!=m_prototypeSet.end();)
+ {
+ int currentClassId = (*prototypeSetIter).getClassID();
+
+ if(currentClassId >= classID)
+ {
+ m_prototypeSet.insert(prototypeSetIter,shapeSampleFeatures);
+ break;
+ }
+ int count = m_shapeIDNumPrototypesMap[currentClassId];
+ prototypeSetIter = prototypeSetIter + count; //To point to first sample of next classID
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting NNShapeRecognizer::insertSampleToPrototypeSet"<<endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Vandana Roy
+ * DATE : 05-07-2007
+ * NAME : computeConfidence
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::computeConfidence()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::computeConfidence()" << endl;
+
+ /******************************************************************/
+ /*******************VALIDATING INPUT ARGUMENTS*********************/
+ /******************************************************************/
+ if(m_neighborInfoVec.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ENEIGHBOR_INFO_VECTOR_EMPTY << " " <<
+ getErrorMessage(ENEIGHBOR_INFO_VECTOR_EMPTY) <<
+ " NNShapeRecognizer::computeConfidence()" << endl;
+
+ LTKReturnError(ENEIGHBOR_INFO_VECTOR_EMPTY);
+ }
+ // Temporary vector to store the recognition results
+ LTKShapeRecoResult outResult;
+ vector<pair<int,float> > classIdSimilarityPairVec;
+ pair<int, float> classIdSimilarityPair;
+
+ // Temporary vector to store the distinct classes appearing in distIndexPairVector
+ intVector distinctClassVector;
+ intVector::iterator distinctClassVectorIter;
+
+ vector <LTKShapeRecoResult>::iterator resultVectorIter = m_vecRecoResult.begin();
+ vector <LTKShapeRecoResult>::iterator resultVectorIterEnd = m_vecRecoResult.end();
+
+ // Variable to store sum of distances to all the prototypes in distIndexPairVector
+ float similaritySum = 0.0f;
+ // Temporary variable to store the confidence value.
+ float confidence = 0.0f;
+
+ // Confidence computation for the NN (1-NN) Classifier
+ if(m_nearestNeighbors == 1)
+ {
+ vector <struct NeighborInfo>::iterator distIndexPairIter = m_neighborInfoVec.begin();
+ vector <struct NeighborInfo>::iterator distIndexPairIterEnd = m_neighborInfoVec.end();
+
+
+ for(; distIndexPairIter != distIndexPairIterEnd; ++distIndexPairIter)
+ {
+ //Check if the class is already present in distinctClassVector
+ //The complexity of STL's find() is linear, with atmost last-first comparisons for equality
+ distinctClassVectorIter = find(distinctClassVector.begin(), distinctClassVector.end(), (*distIndexPairIter).classId);
+
+ //The distinctClassVectorIter will point to distinctClassVector.end() if the class is not present in distinctClassVector
+ if(distinctClassVectorIter == distinctClassVector.end())
+ {
+ //outResult.setShapeId( (*distIndexPairIter).classId );
+ classIdSimilarityPair.first = (*distIndexPairIter).classId ;
+ float similarityValue = SIMILARITY((*distIndexPairIter).distance);
+ //outResult.setConfidence(similarityValue);
+ classIdSimilarityPair.second = similarityValue;
+ similaritySum += similarityValue;
+ //m_vecRecoResult.push_back(outResult);
+ classIdSimilarityPairVec.push_back(classIdSimilarityPair);
+ distinctClassVector.push_back((*distIndexPairIter).classId);
+ }
+ }
+
+ int classIdSimilarityPairVecSize = classIdSimilarityPairVec.size();
+ for( int i = 0 ; i < classIdSimilarityPairVecSize ; ++i)
+ {
+ int classID = classIdSimilarityPairVec[i].first;
+ confidence = classIdSimilarityPairVec[i].second;
+ confidence /= similaritySum;
+ outResult.setConfidence(confidence);
+ outResult.setShapeId(classID);
+ if(confidence > 0)
+ m_vecRecoResult.push_back(outResult);
+
+ }
+ classIdSimilarityPairVec.clear();
+
+ }
+ // Computing confidence for k-NN classifier, implementation of the confidence measure described in paper (cite)
+ else
+ {
+ if(m_nearestNeighbors >= m_neighborInfoVec.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "m_nearestNeighbors >= m_prototypeSet.size(), using distIndexPairVector.size() for m_nearestNeighbors instead" << endl;
+ m_nearestNeighbors = m_neighborInfoVec.size();
+ }
+// vector<pair<int,float> > classIdSimilarityPairVec;
+ // pair<int, float> classIdSimilarityPair;
+
+ // Variable to store the maximum of the number of samples per class.
+ int maxClassSize = (max_element(m_shapeIDNumPrototypesMap.begin(), m_shapeIDNumPrototypesMap.end(), &compareMap))->second;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "maxClassSize: " <<maxClassSize<< endl;
+
+ // Vector to store the cumulative similarity values
+ vector<float> cumulativeSimilaritySum;
+
+ // Populate the values in cumulativeSimilaritySum vector for the top m_nearestNeighbors prototypes
+ // Assumption is m_nearestNeighbors >= MIN_NEARESTNEIGHBORS and
+ // m_nearestNeighbors < dtwEuclideanFilter, validation done in recognize()
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Displaying cumulativeSimilaritySum..." << endl;
+ int i = 0;
+ for( i = 0 ; i < m_nearestNeighbors ; ++i)
+ {
+ //outResult.setShapeId(m_neighborInfoVec[i].classId);
+ classIdSimilarityPair.first = m_neighborInfoVec[i].classId;
+ float similarityValue = SIMILARITY((m_neighborInfoVec[i]).distance);
+// outResult.setConfidence(similarityValue);
+ classIdSimilarityPair.second = similarityValue;
+// classIdSimilarityPairVector.push_back(outResult);
+ classIdSimilarityPairVec.push_back(classIdSimilarityPair);
+ similaritySum += similarityValue;
+ cumulativeSimilaritySum.push_back(similaritySum);
+
+ // Logging the cumulative similarity values for debugging
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "classID:" <<
+ m_neighborInfoVec[i].classId << " confidence:" <<
+ similarityValue << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << i << ": " << similaritySum << endl;
+ }
+
+// for(i = 0 ; i < classIdSimilarityPairVector.size() ; ++i)
+ for(i = 0 ; i < classIdSimilarityPairVec.size() ; ++i)
+ {
+// int classID = classIdSimilarityPairVector[i].getShapeId();
+ int classID = classIdSimilarityPairVec[i].first;
+
+ int finalNearestNeighbors = 0;
+
+ //Check if the class is already present in distinctClassVector
+ distinctClassVectorIter = find(distinctClassVector.begin(), distinctClassVector.end(), classID);
+
+ //The distinctClassVectorIter will point to distinctClassVector.end() if the class is not present in distinctClassVector
+ if(distinctClassVectorIter == distinctClassVector.end())
+ {
+ distinctClassVector.push_back(classID);
+ confidence = 0.0f;
+
+ //If the confidence is based on Adaptive k-NN scheme,
+ //Computing number of nearest neighbours for the class to be used for computation of confidence
+ if(m_adaptivekNN == true )
+ {
+
+ int sizeProportion = (int)ceil(1.0*m_nearestNeighbors*m_shapeIDNumPrototypesMap[classID]/maxClassSize);
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"sizeProportion of class " <<classID<<" is "<<sizeProportion<<endl;
+
+ // Computing min(sizeProportion, m_shapeIDNumPrototypesMap[classID])
+ int upperBound = (sizeProportion < m_shapeIDNumPrototypesMap[classID]) ? sizeProportion:m_shapeIDNumPrototypesMap[classID];
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"upperBound: " <<upperBound<<endl;
+
+ // Computing max(upperBound, MIN_NEARESTNEIGHBORS)
+ finalNearestNeighbors = (MIN_NEARESTNEIGHBORS > upperBound) ? MIN_NEARESTNEIGHBORS:upperBound;
+ }
+ //Else, compute kNN based confidence
+ else if(m_adaptivekNN == false)
+ {
+ finalNearestNeighbors = m_nearestNeighbors;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Error: " << ECONFIG_FILE_RANGE << " " <<
+ "m_adaptivekNN should be true or false" <<
+ " NNShapeRecognizer::computeConfidence()" << endl;
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"finalNearestNeighbors: " <<finalNearestNeighbors<<endl;
+
+ for( int j = 0 ; j < finalNearestNeighbors ; ++j)
+ {
+ if(classID == classIdSimilarityPairVec[j].first)
+ {
+ confidence += classIdSimilarityPairVec[j].second;
+ }
+ }
+ confidence /= cumulativeSimilaritySum[finalNearestNeighbors-1];
+
+ outResult.setShapeId(classID);
+ outResult.setConfidence(confidence);
+
+ if(confidence > 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"classId: " <<classID<<" confidence: "<<confidence<<endl;
+
+ m_vecRecoResult.push_back(outResult);
+ }
+ }
+ }
+ classIdSimilarityPairVec.clear();
+ }
+
+ //Sort the result vector in descending order of confidence
+ sort(m_vecRecoResult.begin(), m_vecRecoResult.end(), sortResultByConfidence);
+
+ //Logging the results at info level
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Printing the Classes and respective Confidences" <<endl;
+
+ for( int i=0; i < m_vecRecoResult.size() ; i++)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Class ID: " <<m_vecRecoResult[i].getShapeId()
+ <<" Confidence: "<<m_vecRecoResult[i].getConfidence()
+ <<endl;
+ }
+
+ distinctClassVector.clear();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::computeConfidence()" << endl;
+
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : Vandana Roy
+ * DATE : 05-07-2007
+ * NAME : sortResultByConfidence
+ * DESCRIPTION : Sort the LTKShapeRecoResult vector based on the Confidence value
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+bool NNShapeRecognizer::sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y)
+{
+ return (x.getConfidence()) > (y.getConfidence());
+}
+/******************************************************************************
+ * AUTHOR : Vandana Roy
+ * DATE : 05-07-2007
+ * NAME : compareMap
+ * DESCRIPTION : Sort the STL's map based on the 'value'(second) field
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+bool NNShapeRecognizer::compareMap( const map<int, int>::value_type& lhs, const map<int, int>::value_type& rhs )
+{
+ return lhs.second < rhs.second;
+}
+
+/******************************************************************************
+ * AUTHOR : Tarun Madan
+ * DATE : 08-07-2007
+ * NAME : getTraceGroup
+ * DESCRIPTION :
+ *
+ * ARGUMENTS :
+ * RETURNS :
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int NNShapeRecognizer::getTraceGroups(int shapeID, int numberOfTraceGroups,
+ vector<LTKTraceGroup> &outTraceGroups)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering NNShapeRecognizer::getTraceGroups"
+ <<endl;
+
+ if(m_shapeIDNumPrototypesMap.find(shapeID) == m_shapeIDNumPrototypesMap.end())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_SHAPEID << " " <<
+ getErrorMessage(EINVALID_SHAPEID) <<
+ " NNShapeRecognizer::getTraceGroups()" << endl;
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ if(m_shapeIDNumPrototypesMap[shapeID] < numberOfTraceGroups)
+ {
+ numberOfTraceGroups = m_shapeIDNumPrototypesMap[shapeID];
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Number of TraceGroup in PrototypeSet is less than specified."
+ << "Returning all TraceGroups :"
+ << numberOfTraceGroups <<endl;
+ }
+
+ vector<LTKShapeSample>::iterator prototypeSetIter = m_prototypeSet.begin();
+ int counter =0;
+ for(;prototypeSetIter!=m_prototypeSet.end();)
+ {
+ int currentShapeId = (*prototypeSetIter).getClassID();
+
+ if(currentShapeId == shapeID)
+ {
+ LTKTraceGroup traceGroup;
+
+ int errorCode = m_ptrFeatureExtractor->convertFeatVecToTraceGroup(
+ (*prototypeSetIter).getFeatureVector(),
+ traceGroup);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::getTraceGroups()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ outTraceGroups.push_back(traceGroup);
+
+ counter++;
+ if(counter==numberOfTraceGroups)
+ break;
+
+ prototypeSetIter++;
+ }
+ else
+ {
+ //To point to first sample of next classID
+ int offset = m_shapeIDNumPrototypesMap[currentShapeId];
+ prototypeSetIter = prototypeSetIter + offset;
+ }
+
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting NNShapeRecognizer::getTraceGroups"
+ <<endl;
+ return SUCCESS;
+}
+
+/***********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 19-01-2007
+ * NAME : initializePreprocessor
+ * DESCRIPTION : This method is used to initialize the PreProcessor
+ * ARGUMENTS : preprocDLLPath : string : Holds the Path of the Preprocessor DLL,
+ * returnStatus : int : Holds SUCCESS or Error Values, if occurs
+ * RETURNS : preprocessor instance
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::initializePreprocessor()" << endl;
+
+ FN_PTR_CREATELTKLIPIPREPROCESSOR createLTKLipiPreProcessor = NULL;
+ int errorCode;
+
+ // Load the DLL with path=preprocDLLPath
+ void* functionHandle = NULL;
+
+ int returnVal = m_OSUtilPtr->loadSharedLib(controlInfo.lipiLib, PREPROC, &m_libHandler);
+
+
+ if(returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ELOAD_PREPROC_DLL << " " <<
+ getErrorMessage(ELOAD_PREPROC_DLL) <<
+ " NNShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ELOAD_PREPROC_DLL);
+ }
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ CREATEPREPROCINST,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " NNShapeRecognizer::initializePreprocessor()" << endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ createLTKLipiPreProcessor = (FN_PTR_CREATELTKLIPIPREPROCESSOR)functionHandle;
+
+ functionHandle = NULL;
+
+ // Map createpreprocessor and deletePreprocessor functions
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_libHandler,
+ DESTROYPREPROCINST,
+ &functionHandle);
+ // Could not map the createLipiPreprocessor function from the DLL
+ if(returnVal != SUCCESS)
+ {
+ //Unload the dll
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EDLL_FUNC_ADDRESS_CREATE << " " <<
+ getErrorMessage(EDLL_FUNC_ADDRESS_CREATE) <<
+ " NNShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(EDLL_FUNC_ADDRESS_CREATE);
+ }
+
+ m_deleteLTKLipiPreProcessor = (FN_PTR_DELETELTKLIPIPREPROCESSOR)functionHandle;
+
+ // Create preprocessor instance
+ errorCode = createLTKLipiPreProcessor(controlInfo, preprocInstance);
+
+ if(errorCode!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ // Could not create a LTKLipiPreProcessor
+ if(*preprocInstance == NULL)
+ {
+ // Unload the DLL
+ unloadPreprocessorDLL();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< ECREATE_PREPROC << " " <<
+ getErrorMessage(ECREATE_PREPROC) <<
+ " NNShapeRecognizer::initializePreprocessor()" << endl;
+ LTKReturnError(ECREATE_PREPROC);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::initializePreprocessor()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+ * AUTHOR : Saravanan R.
+ * DATE : 23-Jan-2007
+ * NAME : trainLvq
+ * DESCRIPTION : This function is the train method using LVQ
+ * ARGUMENTS :
+ * RETURNS : SUCCESS : if training done successfully
+ * errorCode : if traininhas some errors
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Naveen Sundar G Date Description
+ * Balaji MNA 13th Jan, 2011 Prototype set must be emptied before
+ * returning from call to LVQ train
+ *************************************************************************************/
+int NNShapeRecognizer::trainLVQ(const string& inputFilePath,
+ const string &strModelDataHeaderInfoFile,
+ const string& inFileType)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::trainLVQ()" << endl;
+ //Time calculation requirements
+
+ int errorCode = SUCCESS;
+ m_OSUtilPtr->recordStartTime();
+
+ //Time at the beginning of Train LVQ
+ if(LTKSTRCMP(inFileType.c_str(), INK_FILE) == 0)
+ {
+ //If the Input file is UNIPEN Ink file
+ errorCode = trainFromListFile(inputFilePath);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainLVQ()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+ else if(LTKSTRCMP(inFileType.c_str(), FEATURE_FILE) == 0)
+ {
+ //If the Input file is Feature file
+ errorCode = trainFromFeatureFile(inputFilePath);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainLVQ()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ PreprocParametersForFeatureFile(m_headerInfo);
+
+ }
+
+ // Now the Clustered ShapeSamples are stored in "prototypeSet"
+ // Already computed "trainVec" contains all of the training data
+
+ //Learning Part
+ if(m_prototypeReductionFactor != 0)
+ {
+ errorCode = processPrototypeSetForLVQ();
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainLVQ()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+
+ ofstream mdtFileHandle;
+
+ //Open the model data file
+ if (m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::app);
+ }
+ else
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::app | ios::binary);
+ }
+
+ //If file not opened throw an exception
+ if(!mdtFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ " Unable to open model data file : " <<m_nnMDTFilePath<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+ //Writing results to the Model Data file
+ errorCode = appendPrototypesToMDTFile(m_prototypeSet,mdtFileHandle);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainLVQ()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //Close the Model Data file
+ mdtFileHandle.close();
+
+ //Updating the Header Information
+ updateHeaderWithAlgoInfo();
+
+ //Adding header information and checksum generation
+ LTKCheckSumGenerate cheSumGen;
+ errorCode = cheSumGen.addHeaderInfo(strModelDataHeaderInfoFile, m_nnMDTFilePath, m_headerInfo);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainLVQ()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //Time at the end of LVQ training
+ m_OSUtilPtr->recordEndTime();
+
+ m_prototypeSet.clear();
+
+ string timeTaken = "";
+ m_OSUtilPtr->diffTime(timeTaken);
+
+ cout << "Time Taken = " << timeTaken << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::trainLVQ()" << endl;
+ return SUCCESS;
+}
+/******************************************************************************
+ * AUTHOR : Saravanan
+ * DATE : 22-02-2007
+ * NAME : processPrototypeSetForLVQ
+ * DESCRIPTION :
+ * ARGUMENTS :
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Naveen Sundar G. Date 11-Oct-2007 Description
+ ******************************************************************************/
+int NNShapeRecognizer::processPrototypeSetForLVQ()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::processPrototypeSetForLVQ()" << endl;
+ //Reference : http://www.cis.hut.fi/research/lvq_pak/lvq_doc.txt
+ LTKShapeSample bestShapeSample;
+
+ int codeVecIndex = 5;
+ int trainSize = m_trainSet.size() ;
+ int train_index = 0;
+
+ //Number of iterations for LVQ
+ long length = m_prototypeSet.size() * m_LVQIterationScale;
+ long iter ;
+ long index;
+ // learning parameter
+ double c_alpha=m_LVQInitialAlpha;
+
+ int errorCode = SUCCESS;
+
+ // initialize random seed
+ unsigned int randSeedVal ;
+
+ #ifdef WINCE
+ char szTime[10] ;
+ SYSTEMTIME st ;
+ GetLocalTime(&st) ;
+ sprintf(szTime, "%d%d%d", st.wHour, st.wMinute, st.wSecond) ;
+ randSeedVal = atoi(szTime);
+ #else
+ randSeedVal = time(NULL);
+ #endif
+ srand(randSeedVal) ;
+
+ for (iter=0; iter < length; ++iter )
+ {
+
+
+ cout<<"\n Amount of LVQ Training Completed = "<<(double)iter*100/length<<" %\n\n Current Value of Alpha \t = "<<c_alpha<<"\n";
+ //To take the train vector at a random index
+ index = rand()%trainSize;
+ errorCode = trainRecognize(m_trainSet.at(index), bestShapeSample, codeVecIndex);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ if(bestShapeSample.getClassID() == m_trainSet.at(index).getClassID())
+ {
+ //Move the codeVec closer (Match)
+ c_alpha = linearAlpha(iter,length,m_LVQInitialAlpha,c_alpha,+1);
+ errorCode = morphVector(m_trainSet.at(index), -c_alpha, bestShapeSample);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+ else
+ {
+ //Move the codeVec away (No Match)
+ c_alpha = linearAlpha(iter,length,m_LVQInitialAlpha,c_alpha,-1);
+ errorCode = morphVector(m_trainSet.at(index), c_alpha, bestShapeSample);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+
+ //Now update the prototypeSet with the morphed vector
+
+ const vector<LTKShapeFeaturePtr>& tempFeatVec = (bestShapeSample).getFeatureVector();
+ m_prototypeSet.at(codeVecIndex).setFeatureVector(tempFeatVec);
+ }
+
+ m_trainSet.clear();
+
+ cout<<"\n Amount of LVQ Training Completed = "<<(double) 100<<" %\n\n Current Value of Alpha \t = "<<c_alpha<<"\n\n\n";
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::processPrototypeSetForLVQ()" << endl;
+ return SUCCESS;
+}
+
+/******************************************************************************
+ * AUTHOR : N. Sridhar Krishna
+ * DATE : 24-03-2006
+ * NAME : linearAlpha
+ * DESCRIPTION : this function is called from trainLVQ - linearly decreasing learning parameter in learing vector quantization
+ * ARGUMENTS :
+ * RETURNS : learning parameter (alpha)
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Naveen Sundar G. Date 11-Oct-2007 Description
+ ******************************************************************************/
+float NNShapeRecognizer:: linearAlpha(long iter, long length, double& initialAlpha, double lastAlpha,int correctDecision)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::linearAlpha()" << endl;
+ // return ( (initialAlpha * ( ( (double) (length - iter)) / (double) length )));
+ // return (alpha *( (double ) 1/iter));
+
+ // Reference : http://www.cis.hut.fi/research/lvq_pak/lvq_doc.txt
+
+ float currentAlpha;
+ currentAlpha=lastAlpha/(1+correctDecision*lastAlpha);
+
+ if (currentAlpha >initialAlpha)
+ currentAlpha=initialAlpha;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::linearAlpha()" << endl;
+
+ return currentAlpha;
+
+}
+
+/**********************************************************************************
+* AUTHOR : N. Sridhar Krishna
+* DATE : 24-03-2006
+* NAME : morphVector
+* DESCRIPTION : This function does the reshaping of prototype vector (called from trainLVQ)
+* ARGUMENTS : The input parameters are the code vector, data vector (learning example in the context of LVQ), and alpha (learning parameter)
+* @param bestcodeVec is the character which we are trying to morph
+* the function modifies the character bestcodeVec
+* RETURNS : SUCCESS on successful training
+* NOTES :
+* CHANGE HISTROY
+* Author Naveen Sundar G. Date Description
+*************************************************************************************/
+int NNShapeRecognizer::morphVector(const LTKShapeSample& dataShapeSample,
+ double talpha, LTKShapeSample& bestShapeSample)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Enter NNShapeRecognizer::morphVector"<<endl;
+
+ vector<LTKShapeFeaturePtr> bestFeatureVector = bestShapeSample.getFeatureVector();
+ const vector<LTKShapeFeaturePtr>& dataFeatureVector = dataShapeSample.getFeatureVector();
+
+ int index=0;
+ int bestFVSize = bestFeatureVector.size();
+ int dataFVSize = dataFeatureVector.size();
+
+ int errorCode = SUCCESS;
+
+ if(bestFVSize !=dataFVSize)
+ {
+ LTKReturnError(EMORPH_FVEC_SIZE_MISMATCH);
+ }
+
+ float temp1 = 0;
+
+
+
+ for(index=0; index < bestFVSize ; ++index)
+ {
+ LTKShapeFeaturePtr temp1;
+ LTKShapeFeaturePtr temp2;
+ LTKShapeFeaturePtr temp3;
+
+
+ errorCode = bestFeatureVector[index]->subtractFeature(dataFeatureVector[index],temp1);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = temp1->scaleFeature(talpha,temp2);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ errorCode = bestFeatureVector[index]->addFeature(temp2,temp3);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::morphVector()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ bestFeatureVector[index] = temp3;
+
+ }
+
+ bestShapeSample.setFeatureVector(bestFeatureVector);
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exit NNShapeRecognizer::morphVector"<<endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+ * AUTHOR : N. Sridhar Krishna
+ * DATE : 23-03-2006
+ * NAME : trainRecognize (overloaded with 4 args)
+ * DESCRIPTION : This function does the recognition function required for training phase (called from trainLVQ)
+ * ARGUMENTS : The input parameter are the inFeatureVector, which is compared with the existing set of prototypes and then the matched code vector and along with its index (and also the shape id) is returned
+ * @param inFeatureVector is the character which we are trying to recognise.
+ * @param returnshapeID is the value of the matched character which is returned, codeCharacter is the matched prototype (code vector) vector, and codeVecIndex is the matched prototype (code vector) index
+ * RETURNS : SUCCESS on successful reading of the allocation statistics
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+int NNShapeRecognizer::trainRecognize(LTKShapeSample& inShapeSample,
+ LTKShapeSample& bestShapeSample,int& codeVecIndex)
+
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::trainRecognize()" << endl;
+ //Variable to store the Euclidean distance.
+ float localDistance = 0.0;
+
+ //Iterator for prototypeSet
+ vector <LTKShapeSample>::const_iterator prototypeSetIter = m_prototypeSet.begin();
+ vector <LTKShapeSample>::const_iterator prototypeSetIterEnd = m_prototypeSet.end();
+
+ //The top choice index
+ int bestIndex = 0;
+
+ //The top choice distance (FLT_MAX indicates the maximum value for float)
+ float bestMinDist = FLT_MAX;
+
+ int errorCode = SUCCESS;
+
+ for(int j = 0; prototypeSetIter != prototypeSetIterEnd; ++prototypeSetIter, j++)
+ {
+ localDistance=0;
+ if(LTKSTRCMP(m_LVQDistanceMeasure.c_str(), EUCLIDEAN_DISTANCE) == 0)
+ {
+ errorCode = computeEuclideanDistance(*prototypeSetIter,
+ inShapeSample,
+ localDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::trainRecognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+ if(LTKSTRCMP(m_LVQDistanceMeasure.c_str(), DTW_DISTANCE) == 0)
+ {
+ errorCode = computeDTWDistance(*prototypeSetIter,
+ inShapeSample,
+ localDistance);
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << errorCode << " " <<
+ " NNShapeRecognizer::trainRecognize()" << endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+
+ //BestSofar Value for BSF computation using Euclidean distance
+ if(bestMinDist > localDistance )
+ {
+ //bestMinDist is the Minimum Distance
+ bestMinDist = localDistance;
+ //bestIndex is the best match for the given character
+ bestIndex = j;
+ }
+ }
+
+ //Get the shape id of the best match from the prototypeSet
+ bestShapeSample.setClassID((m_prototypeSet.at(bestIndex)).getClassID());
+
+ //Get the Feature vector of the best match from the prototypeSet
+ const vector<LTKShapeFeaturePtr>& tempFeatureVector =
+ (m_prototypeSet.at(bestIndex)).getFeatureVector();
+ bestShapeSample.setFeatureVector(tempFeatureVector);
+
+ codeVecIndex = bestIndex ;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::trainRecognize()" << endl;
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+ * AUTHOR : Saravanan. R
+ * DATE : 25-01-2007
+ * NAME : deletePreprocessor
+ * DESCRIPTION : This method is used to deletes the PreProcessor instance
+ * ARGUMENTS : ptrPreprocInstance : Holds the pointer to the LTKPreprocessorInterface
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ *************************************************************************************/
+
+//int NNShapeRecognizer::deletePreprocessor(LTKPreprocessorInterface *ptrPreprocInstance)
+int NNShapeRecognizer::deletePreprocessor()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::deletePreprocessor()" << endl;
+
+ //deleting the preprocessor instance
+ if(m_ptrPreproc != NULL)
+ {
+ m_deleteLTKLipiPreProcessor(m_ptrPreproc);
+ m_ptrPreproc = NULL;
+ }
+
+ //Unload the dll
+ int returnStatus = unloadPreprocessorDLL();
+ if(returnStatus != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Error: " <<
+ getErrorMessage(returnStatus) <<
+ " NNShapeRecognizer::deletePreprocessor()" << endl;
+ LTKReturnError(returnStatus);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::deletePreprocessor()" << endl;
+
+ return SUCCESS;
+}
+
+/**************************************************************************
+ * AUTHOR : Nidhi Sharma
+ * DATE : 29-01-2007
+ * NAME : unloadPreprocessorDLL
+ * DESCRIPTION : This method is used to Unloads the preprocessor DLL.
+ * ARGUMENTS : none
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ****************************************************************************/
+int NNShapeRecognizer::unloadPreprocessorDLL()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+
+ //Check the preprocessor DLL was loaded already
+ if(m_libHandler != NULL)
+ {
+ //Unload the DLL
+ m_OSUtilPtr->unloadSharedLib(m_libHandler);
+ m_libHandler = NULL;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::unloadPreprocessorDLL()" << endl;
+
+ return SUCCESS;
+}
+
+/**************************************************************************
+ * AUTHOR : Srinivasa Vithal, Ch
+ * DATE : 20-06-2008
+ * NAME : validatePreprocParameters
+ * DESCRIPTION : This method is used to validate the preproc parameters with
+ * mdt header values
+ * ARGUMENTS : none
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ****************************************************************************/
+int NNShapeRecognizer::validatePreprocParameters(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::validatePreprocParameters()" << endl;
+ string tempStrVar = "";
+ string headerValue = "";
+ int headerValueInt = 0;
+ float headerValueFloat = 0.0f;
+ int tempIntegerValue = 0;
+ float tempFloatValue = 0.0f;
+
+ //preproc sequence
+ string mdtPreprocSeqn = headerSequence[PREPROC_SEQ];
+ if(LTKSTRCMP(m_preProcSeqn.c_str(), mdtPreprocSeqn.c_str()) != 0 &&
+ LTKSTRCMP("NA", mdtPreprocSeqn.c_str()) != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preprocSeqn in config file ("<<
+ m_preProcSeqn <<") does not match with the value in MDT file ("<<
+ mdtPreprocSeqn <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ //ResampTraceDimension
+ headerValue = "";
+ if(LTKSTRCMP("NA", headerSequence[TRACE_DIM].c_str()) != 0)
+ {
+ headerValueInt = atoi(headerSequence[TRACE_DIM].c_str());
+ tempIntegerValue = m_ptrPreproc->getTraceDimension();
+
+ if(headerValueInt != tempIntegerValue )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of TraceDimension in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // preserve aspect ratio
+ bool preProcPreserveAspectRatio = m_ptrPreproc->getPreserveAspectRatio();
+ tempStrVar = "false";
+ if (preProcPreserveAspectRatio == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_ASP_RATIO]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatio in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_ASP_RATIO] <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ //NormPreserveRelativeYPosition
+ bool preProcNormPreserveRelativeYPosition = m_ptrPreproc->getPreserveRealtiveYPosition();
+ tempStrVar = "false";
+ if (preProcNormPreserveRelativeYPosition == true)
+ {
+ tempStrVar = "true";
+ }
+
+ if(LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[PRESER_REL_Y_POS]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormPreserveRelativeYPosition in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[PRESER_REL_Y_POS] <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+ // NormPreserveAspectRatioThreshold
+ tempFloatValue = m_ptrPreproc->getAspectRatioThreshold();
+ if(LTKSTRCMP((headerSequence[ASP_RATIO_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[ASP_RATIO_THRES]);
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcPreserveAspectRatioThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // NormLineWidthThreshold
+ if(LTKSTRCMP((headerSequence[DOT_SIZE_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_SIZE_THRES]);
+ tempFloatValue = m_ptrPreproc->getSizeThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormLineWidthThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+
+ // NormDotSizeThreshold
+ if(LTKSTRCMP((headerSequence[DOT_THRES]).c_str(), "NA") != 0)
+ {
+ headerValueFloat = LTKStringUtil::convertStringToFloat(headerSequence[DOT_THRES]);
+ tempFloatValue = m_ptrPreproc->getDotThreshold();
+
+ if(headerValueFloat != tempFloatValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcNormDotSizeThreshold in config file ("<<
+ tempFloatValue<<") does not match with the value in MDT file ("<<
+ headerValueFloat <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+ //ResampPointAllocation
+ tempStrVar = "";
+ tempStrVar = m_ptrPreproc->getResamplingMethod();
+ if(LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), tempStrVar.c_str()) != 0 &&
+ LTKSTRCMP((headerSequence[RESAMP_POINT_ALLOC]).c_str(), "NA") != 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcResampPointAllocation in config file ("<<
+ tempStrVar<<") does not match with the value in MDT file ("<<
+ headerSequence[RESAMP_POINT_ALLOC] <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+
+
+ //SmoothWindowSize
+ if(LTKSTRCMP((headerSequence[SMOOTH_WIND_SIZE]).c_str(), "NA") != 0)
+ {
+ headerValueInt = atoi(headerSequence[SMOOTH_WIND_SIZE].c_str());
+ tempIntegerValue = m_ptrPreproc->getFilterLength();
+
+ if(headerValueInt != tempIntegerValue)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< ECONFIG_MDT_MISMATCH << " " <<
+ "Value of preProcSmoothWindowSize in config file ("<<
+ tempIntegerValue<<") does not match with the value in MDT file ("<<
+ headerValueInt <<")"<<
+ " NNShapeRecognizer::loadModelData()" << endl;
+ LTKReturnError(ECONFIG_MDT_MISMATCH);
+ }
+ }
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::validatePreprocParameters()" << endl;
+ return SUCCESS;
+
+}
+/******************************************************************************
+ * AUTHOR : Saravanan
+ * DATE : 22-02-2007
+ * NAME : trainFromFeatureFile
+ * DESCRIPTION : This method will do the training by giving the Feature
+ * file as input
+ * ARGUMENTS :
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+
+int NNShapeRecognizer::trainFromFeatureFile(const string& featureFilePath)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::trainFromFeatureFile()" << endl;
+
+ //Count for the no. of samples read for a shape
+ int sampleCount = 0;
+
+ //Count of the no. of shapes read so far
+ int shapeCount = 0;
+
+ //ID for each shapes
+ int shapeId = -1;
+
+ //classId of the character
+ int prevClassId = -1;
+
+ //Flag to skip reading a newline in the list file, when a new class starts
+ bool lastshapeIdFlag = false;
+
+ //Flag is set when EOF is reached
+ bool eofFlag = false;
+
+ //Line from the list file
+ string line = "";
+
+ //Indicates the first class
+ bool initClassFlag = false;
+
+ //Output Stream for MDT file
+ ofstream mdtFileHandle;
+
+ //Input Stream for feature file
+ ifstream featureFileHandle;
+
+ LTKShapeSample shapeSampleFeatures;
+
+ vector<LTKShapeSample> shapeSamplesVec;
+
+ vector<LTKShapeSample> clusteredShapeSampleVec;
+
+
+ //Opening the feature file for reading mode
+ featureFileHandle.open(featureFilePath.c_str(), ios::in);
+
+ //Throw an error if unable to open the training list file
+ if(!featureFileHandle)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EFEATURE_FILE_OPEN << " " <<
+ getErrorMessage(EFEATURE_FILE_OPEN) <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(EFEATURE_FILE_OPEN);
+
+ }
+ //Open the Model data file for writing mode
+ if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::out);
+ }
+ else
+ {
+ mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::out|ios::binary);
+ }
+
+ //Return error if unable to open the Model data file
+ if(!mdtFileHandle)
+ {
+ featureFileHandle.close();
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
+ getErrorMessage(EMODEL_DATA_FILE_OPEN) <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(EMODEL_DATA_FILE_OPEN);
+ }
+
+ //Reading feature file header
+ getline(featureFileHandle, line, NEW_LINE_DELIMITER);
+ stringStringMap headerSequence;
+ int errorCode = SUCCESS;
+ errorCode = m_shapeRecUtil.convertHeaderToStringStringMap(line, headerSequence);
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+
+ //Write the number of Shapes
+ mdtFileHandle << m_numShapes << endl;
+
+ //write Trace Dimension of input vector into the file
+ // mdtFileHandle << m_traceDimension << endl;
+
+
+ while(!featureFileHandle.eof())
+ {
+ if( lastshapeIdFlag == false )
+ {
+ //Get a line from the feature file
+ getline(featureFileHandle, line, NEW_LINE_DELIMITER);
+
+ if( featureFileHandle.eof() )
+ {
+ eofFlag = true;
+ }
+
+ if((getShapeSampleFromString(line, shapeSampleFeatures) != SUCCESS) && (eofFlag == false) )
+ continue;
+
+ shapeId = shapeSampleFeatures.getClassID();
+
+ if(eofFlag == false)
+ {
+ if(shapeId < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "The NN Shape recognizer requires training file class Ids to be positive integers and listed in the increasing order" <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ errorCode = EINVALID_SHAPEID;
+ break;
+ }
+ else if(shapeId < prevClassId)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<<
+ "Shape IDs in the train list file should be in the increasing order. Please use scripts/validateListFile.pl to generate list files." <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ errorCode = EINVALID_ORDER_LISTFILE;
+ break;
+ }
+ }
+
+ if( initClassFlag == false )
+ {
+ initClassFlag = true;
+ prevClassId=shapeId;
+ }
+
+ }
+ else //Do not read next line during this iteration
+ {
+ //flag unset to read next line during the next iteration
+ lastshapeIdFlag = false;
+ }
+ // Sample of the same class seen, keep pushing to the shapeSamplesVec
+ if( shapeId == prevClassId )
+ {
+ shapeSamplesVec.push_back(shapeSampleFeatures);
+ ++sampleCount;
+ //All the samples are pushed to trainSet used only for trainLVQ
+ //trainSet was NULL for Clustering and not NULL for LVQ
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_LVQ)
+ == 0 && m_prototypeReductionFactor != 0)
+ m_trainSet.push_back(shapeSampleFeatures);
+
+ shapeSampleFeatures.clearShapeSampleFeatures();
+ }
+ // Sample of a new class seen, or end of feature file reached, train the recognizer on the samples of the previous class
+ if( shapeId != prevClassId || eofFlag == true )
+ {
+ //Increase shape count only if there are atleast one sample per class
+ if( sampleCount > 0 )
+ shapeCount++;
+
+ //check that shapecount must not be greater than specified number
+ //of shapes, if projecttype was not dynamic
+ if( !m_projectTypeDynamic && shapeCount > m_numShapes )
+ {
+ errorCode = EINVALID_NUM_OF_SHAPES;
+ break;
+ }
+
+ if( shapeCount > 0 && sampleCount > 0 )
+ {
+ errorCode = performClustering(shapeSamplesVec, clusteredShapeSampleVec);
+
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_LVQ) == 0)
+ {
+ //Push all the samples after clustering into prototypeSet
+ for( int i = 0; i < clusteredShapeSampleVec.size(); ++i )
+ {
+ m_prototypeSet.push_back(clusteredShapeSampleVec[i]);
+ }
+ }
+ else if(LTKSTRCMP(m_prototypeSelection.c_str(), PROTOTYPE_SELECTION_CLUSTERING) == 0)
+ {
+ //Writing results to the MDT file
+ errorCode = appendPrototypesToMDTFile(clusteredShapeSampleVec, mdtFileHandle);
+ if( errorCode != SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+ }
+
+ //Clearing the shapeSampleVector and clusteredShapeSampleVector
+
+ clusteredShapeSampleVec.clear();
+ shapeSamplesVec.clear();
+ //Resetting sampleCount for the next class
+ sampleCount = 0;
+
+ //Set the flag so that the already read line of next class in the list file is not lost
+ lastshapeIdFlag = true;
+
+ prevClassId = shapeId;
+ }
+ }
+ }
+
+ featureFileHandle.close();
+ mdtFileHandle.close();
+
+ if(!m_projectTypeDynamic && shapeCount != m_numShapes)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< EINVALID_NUM_OF_SHAPES << " " <<
+ getErrorMessage(EINVALID_NUM_OF_SHAPES) <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(EINVALID_NUM_OF_SHAPES);
+ }
+
+ if(errorCode != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "<< errorCode << " " <<
+ " NNShapeRecognizer::trainFromFeatureFile()" << endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::trainFromFeatureFile()" << endl;
+
+ return SUCCESS;
+}
+
+/**************************************************************************
+ * AUTHOR : Balaji MNA
+ * DATE : 01-DEC-2008
+ * NAME : validatePreprocParameters
+ * DESCRIPTION : This method is used to update the preproc parameters for
+ * featurefile
+ * ARGUMENTS : none
+ * RETURNS : none
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ****************************************************************************/
+int NNShapeRecognizer::PreprocParametersForFeatureFile(stringStringMap& headerSequence)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
+ "NNShapeRecognizer::PreprocParametersForFeatureFile()" << endl;
+
+ //preproc sequence
+ headerSequence[PREPROC_SEQ] = "NA";
+ //ResampTraceDimension
+ headerSequence[TRACE_DIM] = "NA";
+ // preserve aspect ratio
+ headerSequence[PRESER_ASP_RATIO] = "NA";
+ //NormPreserveRelativeYPosition
+ headerSequence[PRESER_REL_Y_POS] = "NA";
+ // NormPreserveAspectRatioThreshold
+ headerSequence[ASP_RATIO_THRES] = "NA";
+ // NormLineWidthThreshold
+ headerSequence[DOT_SIZE_THRES] = "NA";
+ // NormDotSizeThreshold
+ headerSequence[DOT_THRES] = "NA";
+ //ResampPointAllocation
+ headerSequence[RESAMP_POINT_ALLOC] = "NA";
+ //SmoothWindowSize
+ headerSequence[SMOOTH_WIND_SIZE] = "NA";
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
+ "NNShapeRecognizer::PreprocParametersForFeatureFile()" << endl;
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : adapt
+* DESCRIPTION : adapt recent recognized sample
+* ARGUMENTS : shapeID : True shapeID of sample
+* RETURNS : Success : If sample was adapted successfully
+* Failure : Returns Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int NNShapeRecognizer::adapt(int shapeId)
+{
+ try{
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Enter NNShapeRecognizer::adapt()"<<endl;
+
+ //Validate shapeID
+ map<int,int>::iterator m_shapeIDNumPrototypesMapIter;
+ if(m_shapeIDNumPrototypesMap.find(shapeId) == m_shapeIDNumPrototypesMap.end())
+ {
+ LTKReturnError(EINVALID_SHAPEID);
+ }
+
+ //Adaptation Code
+ LTKAdapt* adaptObj = LTKAdapt::getInstance(this);
+
+ int nErrorCode;
+ nErrorCode = adaptObj->adapt(shapeId);
+ if(nErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during NNShapeRecognizer::adapt()"<<endl;
+ LTKReturnError(nErrorCode);
+ }
+
+ //Clear Variables cached
+ m_neighborInfoVec.clear();
+ m_vecRecoResult.clear();
+
+ }
+ catch(...)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during NNShapeRecognizer::adapt()"<<endl;
+ return FAILURE;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Exit NNShapeRecognizer::adapt()"<<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 30-Aug-2007
+* NAME : adapt
+* DESCRIPTION : adapt sample passed as argument
+* ARGUMENTS : sampleTraceGroup : TraceGroup of sample to be adapted
+* shapeID : True shapeID of sample
+* RETURNS : Success : If sample was adapted successfully
+* Failure : Returns Error Code
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int NNShapeRecognizer::adapt(const LTKTraceGroup& sampleTraceGroup, int shapeId )
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Enter NNShapeRecognizer::Adapt()"<<endl;
+
+ vector<int> vecSubSet;
+ vector<LTKShapeRecoResult> vecRecoResult;
+ LTKScreenContext objScreenContext;
+ int nErrorCode;
+ nErrorCode = recognize(
+ sampleTraceGroup,
+ objScreenContext,
+ vecSubSet,
+ CONF_THRESHOLD_FILTER_OFF,
+ NN_DEF_RECO_NUM_CHOICES,
+ vecRecoResult
+ );
+
+ if(nErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during call to recognize in NNShapeRecognizer::Adapt()"<<endl;
+ LTKReturnError(nErrorCode);
+ }
+
+ nErrorCode = adapt(shapeId);
+ if(nErrorCode !=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ << "Error during NNShapeRecognizer::Adapt()"<<endl;
+ LTKReturnError(nErrorCode);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Exit NNShapeRecognizer::Adapt()"<<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Tarun Madan
+* DATE : 8-Oct-2007
+* NAME : deleteAdaptInstance
+* DESCRIPTION : delete AdaptInstance
+* ARGUMENTS :
+* RETURNS : None
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description
+*************************************************************************************/
+int NNShapeRecognizer::deleteAdaptInstance()
+{
+ //Implemented as deleteAdaptInstance is called by ~NNShapeRecognizer
+ //and adaptObj object is not available in NN.cpp
+
+ LTKAdapt *adaptInstance = LTKAdapt::getInstance(this);
+ if(adaptInstance)
+ {
+ adaptInstance->deleteInstance();
+ }
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.h
new file mode 100644
index 00000000..cce1baf0
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/NNShapeRecognizer.h
@@ -0,0 +1,1178 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-08-23 13:31:44 +0530 (Tue, 23 Aug 2011) $
+ * $Revision: 865 $
+ * $Author: jitender $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Definitions for NN Shape Recognition module
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Saravanan R.
+ *
+ * DATE: January 23, 2007
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#ifndef __NNSHAPERECOGNIZER_H
+#define __NNSHAPERECOGNIZER_H
+
+/** Include files */
+#include "LTKInc.h"
+#include "LTKTypes.h"
+#include "LTKTrace.h"
+#include "LTKMacros.h"
+#include "LTKShapeRecognizer.h"
+#include "LTKShapeRecoUtil.h"
+#include "LTKShapeSample.h"
+#include "LTKCheckSumGenerate.h"
+#include "LTKDynamicTimeWarping.h"
+
+/** Forward declaration of classes */
+class LTKTraceGroup;
+class LTKPreprocessorInterface;
+class LTKShapeSample;
+class LTKShapeFeatureExtractor;
+class LTKShapeFeature;
+
+#define SIMILARITY(distance) (1 / (distance + EPS ))
+#define SUPPORTED_MIN_VERSION "3.0.0"
+
+class LTKAdapt;
+
+typedef int (*FN_PTR_LOCAL_DISTANCE)(LTKShapeFeaturePtr, LTKShapeFeaturePtr,float&);
+typedef int (*FN_PTR_CREATELTKLIPIPREPROCESSOR)(const LTKControlInfo& , LTKPreprocessorInterface** );
+typedef int (*FN_PTR_DELETELTKLIPIPREPROCESSOR)(LTKPreprocessorInterface* );
+
+
+/**
+ * @ingroup NNShapeRecognizer.h
+ * @brief The Header file for the NNShapeRecognizer
+ * @class NNShapeRecognizer
+ *<p> <p>
+ */
+
+class NNShapeRecognizer: public LTKShapeRecognizer
+{
+
+ public:
+ friend class LTKAdapt;
+ int adapt(int shapeID );
+ int adapt(const LTKTraceGroup& sampleTraceGroup, int shapeID );
+
+ private:
+
+ int deleteAdaptInstance();
+
+
+ /** @name private data members */
+ //@{
+ private:
+
+ FN_PTR_DELETELTKLIPIPREPROCESSOR m_deleteLTKLipiPreProcessor;
+ //Function pointer for deleteLTKLipiPreProcessor
+
+ // preproc lin handle
+ void *m_libHandler;
+
+ // feature extractor lin handle
+ void *m_libHandlerFE;
+
+ unsigned short m_numShapes;
+ /**< @brief Number of shapes
+ * <p>
+ * It Defines the number of shapes to be recognized
+ *
+ * DEFAULT: 0
+ *
+ * Note: If the project is dynamic, then this numShapes was set to 0
+ * If the project is not dynamic, then the numShapes was read from project configuration file
+ * </p>
+ */
+
+ string m_prototypeSelection;
+ /**< @brief The Prototype Selection
+ * <p>
+ * if Prototype Selection = clustering, the training method used was clustering
+ * = lvq, the training method used was LVQ
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_PROTOTYPESELECTION
+ * Possible values are "clustering" and "lvq"
+ * </p>
+ */
+
+ int m_prototypeReductionFactor;
+ /**< @brief The prototype Reduction factor
+ * <p>
+ * if PrototypeReductionFactor = 0 every training sample is cluster on its own
+ * = 100 all training samples are represented by one prototype
+ * = 80 then all samples are represented by 20% of the training samples
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_PROTOTYPEREDUCTIONFACTOR
+ * RANGE: 0 TO 100
+ * </p>
+ */
+
+ int m_numClusters;
+ /**< @brief The number of clusters
+ * <p>
+ * if NumClusters = k, then k clusters are found from the training samples
+ *
+ *
+ *
+ * DEFAULT: There is no default as this and prototype reduction factor are dependent
+ * RANGE:
+ * </p>
+ */
+
+
+ string m_prototypeDistance;
+ /**< @brief The Prototype Distance
+ * <p>
+ * if PrototypeDistance = eu, then the distance between the samples can be calculated using the Euclidean distance method
+ * = dtw, then the distance between the samples can be calculated using the DTW method
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_PROTOTYPEDISTANCE
+ * Possible values are LTKMacros::DTW_DISTANCE and LTKMacros::EUCLIDEAN_DISTANCE.
+ * </p>
+ */
+
+ int m_nearestNeighbors;
+ /**< @brief Nearest Neighbors
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_NEARESTNEIGHBORS
+ * </p>
+ */
+
+
+// int m_dtwBanding;
+ float m_dtwBanding;
+ /**< @brief DTW Banding
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_BANDING
+ * </p>
+ */
+
+ int m_dtwEuclideanFilter;
+ /**< @brief DTW Euclidean Filter
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_DTWEUCLIDEANFILTER
+ * </p>
+ */
+
+ string m_featureExtractorName;
+ /**< @brief The Feature Extractor
+ * <p>
+ *
+ * DEFAULT:
+ *
+ * </p>
+ */
+
+ bool m_projectTypeDynamic;
+ /**< @brief Project Dynamic
+ * <p>
+ * if projectTypeDynamic = true, then the project is dynamic ie, the numShapes can take any number of value
+ * = false, then the project is not dynamic ie, the numShape can take value specified in project.cfg file
+ *
+ * DEFAULT: false
+ * </p>
+ */
+
+ LTKPreprocessorInterface *m_ptrPreproc;
+ /**< @brief Pointer to preprocessor instance
+ * <p>
+ * Instance which is used to call the preprocessing methods before recognition
+ *
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_nnCfgFilePath;
+ /**< @brief Full path of NN configuration file
+ * <p>
+ * Assigned value in the NNShapeRecognizer::initialize function
+ * </p>
+ */
+
+ string m_nnMDTFilePath;
+ /**< @brief Full path of Model data file
+ * <p>
+ * Assigned value in the NNShapeRecognizer::initialize function
+ * </p>
+ */
+
+ stringStringMap m_headerInfo;
+ /**< @brief Header Information
+ * <p>
+ * </p>
+ */
+
+ LTKShapeRecoUtil m_shapeRecUtil;
+ /**< @brief Pointer to LTKShapeRecoUtil class
+ * <p>
+ * Instance which used to call Shape Recognizer Utility functions
+ *
+ * DEFAULT: NULL
+ */
+
+ string m_lipiRootPath;
+ /**< @brief Path of the Lipi Root
+ * <p>
+ * DEFAULT: LipiEngine::getLipiPath()
+ * </p>
+ */
+
+ string m_lipiLibPath;
+ /**< @brief Path of the Lipi Libraries
+ * <p>
+ * DEFAULT: LipiEngine::getLipiLibPath()
+ * </p>
+ */
+
+ LTKShapeFeatureExtractor *m_ptrFeatureExtractor;
+ /**< @brief Pointer to LTKShapeFeatureExtractor class
+ * <p>
+ * DEFAULT: NULL
+ * </p>
+ */
+
+ string m_preProcSeqn;
+ /**< @brief Preprocessor Sequence
+ * <p>
+ * This string will holds what sequence the preprocessor methods to be executed
+ * </p>
+ */
+
+ vector<LTKShapeSample> m_prototypeSet;
+ /**< @brief Prototype Set for LVQ
+ * <p>
+ * It contains the Vector of Clustered ShapeSamples
+ * </p>
+ */
+
+ LTKCaptureDevice m_captureDevice;
+
+ struct NeighborInfo
+ {
+ int classId;
+ float distance;
+ int prototypeSetIndex;
+ };
+
+ /*
+ struct MapModFunc
+ {
+ string moduleName;
+ string funcName;
+ };
+ */
+
+ vector<stringStringPair> m_preprocSequence;
+
+ intIntMap m_shapeIDNumPrototypesMap;
+ /**< @brief Map of shapeID and Number of Samples per shape
+ * <p>
+ *
+ * </p>
+ */
+
+ int m_prototypeSetModifyCount;
+ /**< @brief
+ * <p>
+ * Used to count number of modifications done to m_prototypeSet.
+ * Write to MDT after m_prototypeModifyCntCFG such modifications or at Exit.
+ * </p>
+ */
+
+ int m_MDTUpdateFreq;
+ /**< @brief Update MDT after a specified number of modifications to m_prototypeSet
+ * <p>
+ * Specified in NN.cfg
+ *
+ * </p>
+ */
+
+ //Cache Parameters used by Adapt
+ vector<LTKShapeRecoResult> m_vecRecoResult;
+ /**< @brief Store Recognize results
+ * used by subsequent call to Adapt
+ * <p>
+ *
+ *
+ * </p>
+ */
+
+
+ vector <struct NeighborInfo> m_neighborInfoVec;
+ /**< @brief Vector to store the distances of test sample to each of the samples in prototypeSet,
+ * classIDs and indices within the prototypeset
+ * Used during subsequent call to Adapt
+ * <p>
+ *
+ *
+ * </p>
+ */
+
+ LTKShapeSample m_cachedShapeSampleFeatures;
+ /**< @brief Store ShapeSampleFeatures of the last inTraceGroup to Recognize
+ * Used during subsequent call to Adapt
+ * <p>
+ *
+ *
+ * </p>
+ */
+
+ float m_rejectThreshold;
+ /**< @brief Threshold on the confidence to reject a test sample
+ * <p>
+ *
+ * </p>
+ */
+
+ bool m_adaptivekNN;
+ /**< @brief Adaptive kNN method to compute confidence
+ * <p>
+ * If m_adaptivekNN = true, the adaptive kNN method is used for confidence computation
+ * false, NN or kNN method is used, based on the value of m_nearestNeighbors
+ * </p>
+ */
+
+ //@}
+
+ string m_currentVersion;
+
+ string m_MDTFileOpenMode;
+
+ DynamicTimeWarping<LTKShapeFeaturePtr, float> m_dtwObj;
+
+ public:
+
+ /** @name Constructors and Destructor */
+ //@{
+
+ NNShapeRecognizer(const LTKControlInfo& controlInfo);
+
+ /**
+ * Destructor
+ */
+ ~NNShapeRecognizer();
+
+ //@}
+
+ /**
+ * This method initializes the NN shape recognizer
+ * <p>
+ * Semantics
+ * - Set the project name in NNShapeRecognizer::headerInfo with the parameter passed.<br>
+ * m_headerInfo[PROJNAME] = strProjectName;
+ *
+ * - Initialize NNShapeRecognizer::m_nnCfgFilePath <br>
+ * m_nnCfgFilePath = NNShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::NN + LTKInc::CONFIGFILEEXT;
+ *
+ * - Initializes NNShapeRecognizer::m_nnMDTFilePath <br>
+ * m_nnMDTFilePath = NNShapeRecognizer::m_lipiRootPath + LTKMacros::PROJECTS_PATH_STRING +
+ * strProjectName + LTKMacros::PROFILE_PATH_STRING + strProfileName +
+ * LTKInc::SEPARATOR + LTKInc::NN + LTKInc::DATFILEEXT;
+ *
+ * - Initializes NNShapeRecognizer::m_projectTypeDynamic with the value returned from LTKShapeRecoUtil::isProjectDynamic
+ *
+ * - Initialize the preprocessor using LTKShapeRecoUtil::initializePreprocessor and assign
+ * default values for
+ * -# Normalised size
+ * -# Threshold size
+ * -# Aspect ratio
+ * -# Dot threshold
+ *
+ * - Initialize the recognizers instance variables with the values given in classifier config file.
+ *
+ * </p>
+ * @param strProjectName : string : Holds the name of the Project
+ * @param strProfileName : string : Holds the name of the Profile
+ *
+ * @return int : LTKInc::SUCCESS if initialization done successfully
+ * errorValues if initialization has some errors
+ *
+ * @exception LTKErrorList::ECONFIG_FILE_OPEN Could not open project.cfg
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES Negative value for number of shapes
+ * @exception LTKErrorList::ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception LTKErrorList::EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+
+ /**
+ * This method calls the train method of the NN classifier.
+ *
+ */
+ int train(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string &comment,const string &dataset,
+ const string &trainFileType=INK_FILE) ;
+
+ /**
+ * This method loads the Training Data of the NN classifier.
+ * @param
+ * @return LTKInc::SUCCESS : if the model data was loaded successfully
+ * @exception
+ */
+ int loadModelData();
+
+ /**
+ * This method unloads all the training data
+ * @param none
+ * @return LTKInc::SUCCESS : if the model data was unloaded successfully
+ * @exception none
+ */
+ int unloadModelData();
+
+ /**
+ * This method sets the device context for the recognition
+ *
+ * @param deviceInfo The parameter to be set
+ * @return
+ * @exception
+ */
+ int setDeviceContext(const LTKCaptureDevice& deviceInfo);
+
+ /**
+ * Populates a vector of LTKShapeRecoResult consisting of top classes with their confidences.
+ *
+ * Semantics
+ *
+ * - Validate the input arguments
+ * - Extract the features from traceGroup
+ * - If the distance method (m_prototypeDistance) is Euclidean (EUCLIDEAN_DISTANCE),
+ * populate the distIndexPairVector with the distance of the test sample to all the
+ samples in the prototype set
+ * - If the distance method is DTW, compute the DTW distance of the test sample to the
+ samples in the prototype set which passed the Euclidean filter. Populate the
+ distIndexPairVector
+ * - Sort the distIndexPairVector based on the distances in ascending order
+ * - Compute the confidences of the classes appearing in distIndexPairVector, call computeConfidence()
+ * - Check if the first element of resultVector has confidence less than m_rejectThreshold, if so,
+ empty the resultVector (reject the sample), log and return.
+ * - If the confThreshold value was specified by the user (not equal to -1),
+ delete the entries from resultVector with confidence values less than confThreshold.
+ * - If the numChoices value was specified by the user (not equal to -1),
+ update the resultVector with top numChoices entries, delete the other values.
+ *
+ * @param traceGroup The co-ordinates of the shape which is to be recognized
+ * @param screenContext Contains information about the input field like whether it is boxed input
+ * or continuous writing
+ * @param subSetOfClasses A subset of the entire class space which is to be used for
+ * recognizing the input shape.
+ * @param confThreshold Classes with confidence below this threshold are not returned,
+ * valid range of confThreshold: (0,1)
+ * @param numOfChoices Number of top choices to be returned in the result structure
+ * @param resultVector The result of recognition
+ *
+ * @return SUCCESS: resultVector populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int recognize(const LTKTraceGroup& traceGroup,
+ const LTKScreenContext& screenContext,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& outResultVector);
+
+
+ /* Overloaded the above function to take vector<LTKShapeFeaturePtr> as
+ * input
+ */
+ int recognize(const vector<LTKShapeFeaturePtr>& shapeFeatureVec,
+ const vector<int>& subSetOfClasses,
+ float confThreshold,
+ int numChoices,
+ vector<LTKShapeRecoResult>& resultVector);
+
+ /**
+ * This method add Class
+ *
+ * Semantics
+ *
+ * - Check if project is Dynamic, if not return ErrorCode
+ * - Calculate Features
+ * - Update PrototypeSet
+ * - Update MDTFile
+ * - return shapeID of new class added
+ *
+ * @param sampleTraceGroup : LTKTraceGroup : Holds TraceGroup of sample to Add
+ * @param shapeID : int : Holds shapeID of new Class
+ * shapeID = m_prototypeSet.at(prototypeSetSize-1).getClassID()+1
+ *
+ * @return SUCCESS:Shape Class added successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int addClass(const LTKTraceGroup& sampleTraceGroup, int& shapeID);
+
+ /**
+ * This method add Sample Class for adapt
+ *
+ * Semantics
+ *
+ * - Check if project is Dynamic, if not return ErrorCode
+ * - Calculate Features
+ * - Update PrototypeSet
+ * - Update MDTFile
+ * - return shapeID of new class added
+ *
+ * @param sampleTraceGroup : LTKTraceGroup : Holds TraceGroup of sample to Add
+ * @param shapeID : int : Holds shapeID of new Class
+ * shapeID = m_prototypeSet.at(prototypeSetSize-1).getClassID()+1
+ *
+ * @return SUCCESS:Shape Class added successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int addSample(const LTKTraceGroup& sampleTraceGroup, int shapeID);
+
+ /**
+ * This method delete Class
+ *
+ * Semantics
+ *
+ * - Check if shapeID is valid, if not return error code
+ * - Check if project is Dynamic, if not return ErrorCode
+ * - Update PrototypeSet
+ * - Update MDTFile
+ *
+ * @param shapeID : int : Holds shapeID of Shape to be deleted
+ *
+ * @return SUCCESS: Shape Class deleted successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int deleteClass(int shapeID);
+
+ /**
+ * This method converts features to TraceGroup
+ *
+ * Semantics
+ *
+ * - Check if shapeID is valid, if not return error code
+ * - Check if project is Dynamic, if not return ErrorCode
+ * - Update PrototypeSet
+ * - Update MDTFile
+ *
+ * @param shapeID : int : Holds shapeID
+ * @param numberOfTraceGroups : int : Maximum number of Trace Groups to populate
+ * @param outTraceGroups : vector<LTKTraceGroup> : TraceGroup
+ *
+ * @return SUCCESS: TraceGroup is populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int getTraceGroups(int shapeID, int numberOfTraceGroups, vector<LTKTraceGroup> &outTraceGroups);
+
+ /**
+ * This function does the recognition function required for training phase (called from trainLVQ)
+ * The input parameter are the incharacter, which is compared with the existing
+ * set of prototypes and then the matched code vector and along with its index (and also the shape id) is returned
+ * @param incharacter is the character which we are trying to recognise.
+ * @param returnshapeID is the value of the matched character which is returned, codeCharacter is the matched prototype (code vector) vector, and codeVecIndex is the matched prototype (code vector) index
+ */
+ int trainRecognize(LTKShapeSample& inShapeSample, LTKShapeSample& bestShapeSample, int& codeVecIndex);
+
+ private:
+ /**
+ * This function is the train method using Clustering prototype selection technique.
+ *
+ *
+ * Semantics
+ *
+ * - Note the start time for time calculations.
+ *
+ * - Create an instance of the feature extractor using NNShapeRecognizer::initializeFeatureExtractorInstance() method
+ *
+ * - Call train method depending on the inFileType
+ * - NNShapeRecognizer::trainFromListFile() if inFileType = LTKMacros::INK_FILE
+ * - NNShapeRecognizer::trainFromFeatureFile() if inFileType = LTKMacros ::FEATURE_FILE
+ *
+ * - Update the headerInfo with algorithm version and name using NNShapeRecognizer::updateHeaderWithAlgoInfo() method
+ *
+ * - Calculate the checksum.
+ *
+ * - Note the finish time for time calculations.
+ *
+ *
+ * @param inputFilePath :string : Path of trainListFile / featureFile
+ * @param strModelDataHeaderInfoFile : string : Holds the Header information of Model Data File
+ * @param inFileType : string : Possible values ink / featureFile
+ *
+ * @return LTKInc::SUCCESS : if the training done successfully
+ * @return errorCode : if it contains some errors
+ */
+ int trainClustering(const string& trainingInputFilePath,
+ const string& mdtHeaderFilePath,
+ const string& trainFileType);
+
+
+ /**
+ * This method do the map between the module name and function names from the cfg file
+ *
+ * Semantics
+ *
+ * - Read the Preprocess Sequence from the nn.cfg
+ *
+ * - Split the sequence into tokens with delimiter LTKMacros::DELEMITER_SEQUENCE using LTKStringUtil::tokenizeString
+ *
+ * - Split each token with delimiter LTKMacrosDELEMITER_FUNC using LTKStringUtil::tokenizeString
+ * to get the Module name and Function name
+ *
+ * - Store the Module name and the Function name into a structure
+ *
+ *
+ * @param none
+ * @return LTKInc::SUCCESS : if functions are successfully mapped,
+ * @return errorCodes : if contains any errors
+ * @exception none
+ */
+ int mapPreprocFunctions();
+
+ /**
+ * This method will assign default values to the members
+ *
+ * Semantics
+ *
+ * - Assign Default values to all the data members
+ *
+ *
+ * @param none
+ *
+ * @return none
+ */
+ void assignDefaultValues();
+
+ /** Reads the NN.cfg and initializes the instance variable of the classifier with the user defined
+ * values.
+ *
+ * Semantics
+ *
+ * - Open the nn.cfg using LTKConfigFileReader
+ *
+ * - Incase of file open failure (nn.cfg), default values of the classifier parameters are used.
+ *
+ * - The valid values of the classifier parameters are cached in to the class data members.
+ * LTKConfigFileReader::getConfigValue is used to get the value fora key defined in the config file
+ *
+ * - Exception is thrown if the user has specified an invalid valid for a parameter
+ *
+ *
+ * @param none
+ * @return SUCCESS : If the Config file read successfully
+ * @return errorCode : If it contains some errors
+ * @exception LTKErrorList::ECONFIG_FILE_RANGE The config file variable is not within the correct range
+ */
+ int readClassifierConfig();
+
+ /**
+ * This function serves as wrapper function to the Dtw distance computation function
+ * (for use by clustering prototype selection)
+ * @param train This is an input parameter and corresponds to the training character.
+ * @param test This is an input parameter and corresponds to the testing character.
+ */
+ int computeDTWDistance(const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outDTWDistance);
+
+
+
+
+ /**
+ * This function computes the eucildean distance between the two points.
+ * @param train X and Y coordinate of the first point.
+ * @param test X and Y coordinate of the second point.
+ */
+
+ /*int computeEuclideanDistance(const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outEuclideanDistance);*/
+
+ int computeEuclideanDistance(const LTKShapeSample& inFirstShapeSampleFeatures,
+ const LTKShapeSample& inSecondShapeSampleFeatures,
+ float& outEuclideanDistance);
+
+ int calculateMedian(const int2DVector& clusteringResult,
+ const float2DVector& distanceMatrix, vector<int>& outMedianIndexVec);
+
+
+
+ /**
+ * This method creates a custom feature extractor instance and stores it's address in
+ * NNShapeRecognizer::m_ltkFE. The local distance function pointer is also initialized.
+ *
+ * Semantics
+ *
+ *
+ * - Intialize the NNShapeRecognizer::m_ptrFeatureExtractor with address of the feature extractor instance created
+ * using LTKShapeFeatureExtractorFactory::createFeatureExtractor
+ *
+ * - Cache the address of LTKShapeFeatureExtractor::getLocalDistance() in an instance variable
+ *
+ * @param none
+ *
+ * @return 0 on LTKInc::SUCCESS and 1 on LTKInc::FAILURE
+ *
+ * @exception none
+ */
+ int initializeFeatureExtractorInstance(const LTKControlInfo& controlInfo);
+
+ /**
+ * This method trains the classifier from the train list file whose path is passed as paramater.
+ *
+ * Semantics
+ *
+ * - Open the trainListFile for reading.
+ *
+ * - Open the mdt file for writing.
+ *
+ * - Write header information to the mdt file
+ * - NNShapeRecognizer::m_numShapes
+ * - NNShapeRecognizer::m_traceDimension
+ * - NNShapeRecognizer::m_flexibilityIndex
+ *
+ * - Get a valid line from the train list file
+ * - Skip commented lines
+ * - Skip lines where number_of_tokens != 2
+ * - Throw error LTKErrorList::EINITSHAPE_NONZERO, if the first shape in the list file is not zero
+ * - Throw error LTKErrorList::EINVALID_ORDER_LISTFILE if the shapes are not in sequential order
+ *
+ * - For every valid line get the ShapeSample from the ink file using NNShapeRecognizer::getShapeSampleFromInkFile
+ * - Read ink from UNIPEN ink file
+ * - Skip if the trace group is empty
+ * - Pre process the trace group read from the ink file
+ * - Extract features
+ *
+ * - Push all the ShapeSamples corresponding to a shape into a vector of ShapeSample ShapeSamplesVec.
+ *
+ * - When all the ShapeSamples corresponding to a Shape have been collected, cluster them using NNShapeRecognizer::performClustering
+ *
+ * - performClustering results in vector of clustered ShapeSamples.
+ *
+ * - Append these clustered vector<ShapeSample> to the mdt file.
+ *
+ *
+ * @param listFilePath : string : Holds the path for train list file
+ *
+ * @return none
+ *
+ * @exception LTKErrorList::EFILE_OPEN_ERROR : Error in Opening a file (may be mdt file or list file)
+ * @exception LTKErrorList::EINVALID_NUM_OF_SHAPES : Invalid value for number of shapes
+ * @exception LTKErrorList::EINVALID_ORDER_LISTFILE: Invalid order of shapeId in List file
+ * @exception LTKErrorList::EINITSHAPE_NONZERO : Initial shapeId must not be zero
+ */
+ int trainFromListFile(const string& listFilePath);
+
+ /**
+ * This method trains the classifier from the feature file whose path is passed as paramater
+ *
+ * Semantics
+ *
+ *
+ * @param featureFilePath : string : Holds the path of Feature file
+ *
+ * @return none
+ */
+ int trainFromFeatureFile(const string& featureFilePath);
+
+ int PreprocParametersForFeatureFile(stringStringMap& headerSequence);
+
+ /**
+ * This method will get the ShapeSample by giving the ink file path as input
+ *
+ * Semantics
+ *
+ * - Call the LTKShapeRecoUtil::readInkFromFile() method (Utility Method) to read the ink file
+ * By reading this file, an inTraceGroup was generated
+ *
+ * - Preprocess the inTraceGroup and get the preprocessed trace group
+ * LTKTraceGroup preprocessedTraceGroup
+ *
+ * - Extract features from the preprocessed trace group to get the ShapeSamples.
+ *
+ *
+ * @param path : string : The path for Ink file
+ * @param ShapeSample : ShapeSample : The ShapeSample generated after feature extraction
+ *
+ * @return SUCCESS : If the ShapeSample was got successfully
+ * @return FAILURE : Empty traces group detected for current shape
+ *
+ * @exception LTKErrorList::EINKFILE_EMPTY : Ink file is empty
+ * @exception LTKErrorList::EINK_FILE_OPEN : Unable to open unipen ink file
+ * @exception LTKErrorList::EINKFILE_CORRUPTED : Incorrect or corrupted unipen ink file.
+ * @exception LTKErrorList::EEMPTY_TRACE : Number of points in the trace is zero
+ * @exception LTKErrorList::EEMPTY_TRACE_GROUP : Number of traces in the trace group is zero
+ */
+ int getShapeFeatureFromInkFile(const string& inkFilePath,
+ vector<LTKShapeFeaturePtr>& shapeFeatureVec);
+
+ /**
+ * This method will do Custering for the given ShapeSamples
+ *
+ * Semantics
+ *
+ * - If the NNShapeRecognizer::m_prototypeReductionFactor is -1 means Automatic clustering could be done
+ *
+ * - If the NNShapeRecognizer::m_prototypeReductionFactor is 0 means No clustering was needed
+ *
+ * - Otherwise clustering is needed based on the value of NNShapeRecognizer::m_prototypeReductionFactor
+ *
+ * - Calculate Median if NNShapeRecognizer::m_prototypeReductionFactor is not equal to zero
+ *
+ *
+ * @param ShapeSamplesVec : ShapeSampleVector : Holds all the ShapeSample for a single class
+ * @param resultVector : ShapeSampleVector : Holds all the ShapeSample after clustering
+ * @param sampleCount : int : Holds the number of shapes for a sample
+ *
+ * @return none
+ * @exception none
+ */
+ int performClustering(const vector<LTKShapeSample> & shapeSamplesVec,
+ vector<LTKShapeSample>& outClusteredShapeSampleVec);
+
+ /**
+ * This method will Update the Header information for the MDT file
+ *
+ * Semantics
+ *
+ * - Copy the version number to a string
+ *
+ * - Update the version info and algoName to NNShapeRecognizer::m_headerInfo, which specifies the
+ * header information for MDT file
+ *
+ *
+ * @param none
+ *
+ * @return none
+
+ * @exception none
+ */
+ void updateHeaderWithAlgoInfo();
+
+ int preprocess (const LTKTraceGroup& inTraceGroup, LTKTraceGroup& outPreprocessedTraceGroup);
+
+ /**
+ * This method will writes training results to the mdt file
+ *
+ * Semantics
+ *
+ * - If the feature representation was float then
+ * - Iterate through the shape model
+ * - Write the feature Dimension
+ * - Write the feature vector size
+ * - Write all the feature vector
+ * - Write the class ID
+ *
+ * - If the feature representation was custom then
+ * - Iterate through the shape model
+ * - Write the feature Size
+ * - Call the writeFeatureVector() to write all the feature vector
+ * - Write the class ID
+ *
+ *
+ * @param resultVector : ShapeSampleVector : A vector of ShapeSamples created as a result of training
+ * mdtFileHandle : ofstream : Specifies the outut stream
+ *
+ * @return none
+ *
+ * @exception none
+ */
+
+ int appendPrototypesToMDTFile(const vector<LTKShapeSample>& prototypeVec, ofstream & mdtFileHandle);
+
+ static bool sortDist(const NeighborInfo& x, const NeighborInfo& y);
+
+ static void getDistance(const LTKShapeFeaturePtr& f1,const LTKShapeFeaturePtr& f2, float& distance);
+
+ int getShapeSampleFromString(const string& inString, LTKShapeSample& outShapeSample);
+
+ int mapFeatureExtractor();
+
+ int deleteFeatureExtractorInstance();
+ /**
+ * This method extracts shape features from given TraceGroup
+ *
+ * Semantics
+ *
+ * - PreProcess tracegroup
+ * - Extract Features
+ *
+ * @param inTraceGroup : LTKTraceGroup : Holds TraceGroup of sample
+ *
+ * @return SUCCESS: if shapeFeatures is populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int extractFeatVecFromTraceGroup(const LTKTraceGroup& traceGroup,
+ vector<LTKShapeFeaturePtr>& featureVec);
+
+ /**
+ * This method create MDTFile
+ *
+ * Semantics
+ *
+ *
+ * @param None
+ *
+ * @return None
+ *
+ * @exception none
+ */
+ int writePrototypeSetToMDTFile();
+
+ /**
+ * This method adds Sample To Prototype
+ *
+ * Semantics
+ *
+ * - Add data in ascending order to ShapeID
+ * -
+ *
+ * @param shapeSampleFeatures : LTKShapeSample : Holds features of sample to be added to PrototypeSet
+ *
+ * @return SUCCESS: if shapeSampleFeatures is populated successfully
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+ int insertSampleToPrototypeSet(const LTKShapeSample &shapeSampleFeatures);
+
+ /**
+ * This method computes the confidences of test sample belonging to various classes
+ *
+ * Semantics
+ *
+ * - Compute the confidence based on the values of m_nearestNeighbors and m_adaptiveKNN
+ * - Populate the resultVector
+ * - Sort the resultVector
+ * -
+ *
+ * @param distIndexPairVector : vector<struct NeighborInfo>: Holds the samples, classIDs and distances to the test sample
+ * @param resultVector : vector<LTKShapeRecoResult> : Holds the classIDs and the respective confidences
+ *
+ * @return SUCCESS: resultVector populated
+ * FAILURE: return ErrorCode
+ * @exception none
+ */
+
+ int computeConfidence();
+
+ /**
+ * The comparison function object of STL's sort() method, overloaded for class LTKShapeRecoResult, used to sort the vector of LTKShapeRecoResult based on the member variable confidence
+ *
+ * Semantics
+ *
+ * - Check if the first object's confidence value is greater than the second object's confidence value
+ * - Return true or false
+ * -
+ *
+ * @param x : LTKShapeRecoResult : First object for comparison
+ * @param y : LTKShapeRecoResult : Second object for comparison
+ *
+ * @return true: If x.confidence > y.confidence
+ * false: If x.confidence <= y.confidence
+ * @exception none
+ */
+ static bool sortResultByConfidence(const LTKShapeRecoResult& x, const LTKShapeRecoResult& y);
+
+ /**
+ * The comparison function object of STL's max_element() method, overloaded for the map<int, int>, used to retrieve the maximum of the value field (second element) of map
+ *
+ * Semantics
+ *
+ * - Check if the first object's second value is greater than the second object's second value
+ * - Return true or false
+ * -
+ *
+ * @param lhs : map<int, int>::value_type : First object for comparison
+ * @param rhs : map<int, int>::value_type : Second object for comparison
+ *
+ * @return true: If lhs.second > rhs.second
+ * false: If lhs.second <= rhs.second
+ * @exception none
+ */
+
+ static bool compareMap( const map<int, int>::value_type& lhs, const map<int, int>::value_type& rhs );
+
+ /** This method is used to initialize the PreProcessor
+ *
+ * Semantics
+ *
+ * - Load the preprocessor DLL using LTKLoadDLL().
+ *
+ * - Get the proc address for creating and deleting the preprocessor instance.
+ *
+ * - Create preprocessor instance.
+ *
+ * - Start the logging for the preprocessor module.
+ *
+ * @param preprocDLLPath : string : Holds the Path of the Preprocessor DLL,
+ * @param errorStatus : int : Holds SUCCESS or Error Values, if occurs
+ * @return preprocessor instance
+ *
+ * @exception ELOAD_PREPROC_DLL Could not load preprocessor DLL
+ * @exception EDLL_FUNC_ADDRESS_CREATE Could not map createPreprocInst
+ * @exception EDLL_FUNC_ADDRESS_DELETE Could not map destroyPreprocInst
+ */
+ int initializePreprocessor(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocInstance);
+
+
+ /** This method is used to deletes the PreProcessor instance
+ *
+ * Semantics
+ *
+ * - Call deleteLTKPreprocInst from the preproc.dll.
+ *
+ * - Unload the preprocessor DLL.
+ *
+ * @param ptrPreprocInstance : Holds the pointer to the LTKPreprocessorInterface
+ * @return none
+ * @exception none
+ */
+
+ int deletePreprocessor();
+
+ /** This method is used to Unloads the preprocessor DLL.
+ *
+ * Semantics
+ *
+ * - If m_libHandler != NULL, unload the DLL
+ * LTKUnloadDLL(m_libHandler);
+ * m_libHandler = NULL;
+ *
+ * @param none
+ * @return none
+ * @exception none
+ */
+ int unloadPreprocessorDLL();
+
+ /**
+ * This function is the train method using LVQ
+ *
+ * Semantics
+ *
+ * - Note the start time for time calculations.
+ *
+ * - Create an instance of the feature extractor using NNShapeRecognizer::initializeFeatureExtractorInstance() method
+ *
+ * - Call train method depending on the inFileType
+ * - NNShapeRecognizer::trainFromListFile if inFileType() = LTKMacros::INK_FILE
+ * - tNNShapeRecognizer::rainFromFeatureFile if inFileType() = LTKMacros::FEATURE_FILE
+ *
+ * NOTE :
+ * The NNShapeRecognizer::trainFromListFile populates the following data structures
+ *
+ * - NNShapeRecognizer::m_prototypeSet : Vector of clustered ShapeSample and
+ *
+ * - Process the prototype set using NNShapeRecognizer::processPrototypeSetForLVQ()
+ *
+ * - Update the headerInfo with algorithm version and name using NNShapeRecognizer::updateHeaderWithAlgoInfo()
+ *
+ * - Calculate the checksum.
+ *
+ * - Note the finish time for time calculations.
+ *
+ *
+ * @param inputFilePath :string : Path of trainListFile / featureFile
+ * @param strModelDataHeaderInfoFile : string : Holds the Header information of Model Data File
+ * @param inFileType : string : Possible values ink / featureFile
+ *
+ * @return LTKInc::SUCCESS : if the training done successfully
+ * @return errorCode : if it contains some errors
+ */
+ int trainLVQ(const string& inputFilePath,
+ const string& mdtHeaderFilePath,
+ const string& inFileType);
+
+ /**
+ * This function is used to compute the learning parameter that is used in Learning Vector Quantization (called from trainLVQ)
+ * The input parameters are the iteration number, number of iterations, and the start value of the learning parameter (alpha)
+ * the function returns the value of the learning parameter (linearly decreasing)
+ */
+ float linearAlpha(long iter, long length, double& initialAlpha,
+ double lastAlpha,int correctDecision);
+
+ /**
+ * This function does the reshaping of prototype vector (called from trainLVQ)
+ * The input parameters are the code vector, data vector (learning example in the context of LVQ), and alpha (learning parameter)
+ * @param bestcodeVec is the character which we are trying to morph
+ * the function modifies the character bestcodeVec
+ */
+ int morphVector(const LTKShapeSample& dataShapeSample,
+ double talpha, LTKShapeSample& bestShapeSample);
+
+ int processPrototypeSetForLVQ();
+
+ int validatePreprocParameters(stringStringMap& headerSequence);
+
+
+ /**< @brief LVQ Iteration Scale
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_LVQITERATIONSCALE
+ * </p>
+ */
+ int m_LVQIterationScale;
+
+ /**< @brief LVQ Initial Alpha
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_LVQINITIALALPHA
+ * </p>
+ */
+ double m_LVQInitialAlpha;
+
+ /**< @brief LVQ Distance Measure
+ * <p>
+ *
+ * DEFAULT: LTKPreprocDefaults::NN_DEF_LVQDISTANCEMEASURE
+ * </p>
+ */
+ string m_LVQDistanceMeasure;
+
+ /**< @brief Pointer to LTKOSUtil interface
+ * <p>
+ *
+ * </p>
+ */
+ LTKOSUtil* m_OSUtilPtr;
+
+ vector<LTKShapeSample> m_trainSet;
+
+};
+
+
+#endif
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.cfg b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.cfg
new file mode 100644
index 00000000..c20803b7
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.cfg
@@ -0,0 +1,362 @@
+#------------------------------------------------------------------------------
+# nn.cfg
+#
+# Configuration file for Nearest Neighbor Classification Method for
+# Lipi Toolkit 4.0.0
+#------------------------------------------------------------------------------
+
+#------------------------------------------------------------------------------
+# The standard format for the configuration entries is the name of the
+# configuration parameter seperated by an equal to sign and then the value of
+# the configuration parameter. For example:
+# ConfigurationEntryName = value
+#
+# Lines starting with a # are commnet lines
+#
+# A cfg entry is strictly a key value pair and leaving the key without the
+# value or specification of a value out of the range is not permitted
+#
+# If a cfg entry is not specified at all, then default values are used by the
+# recognizer
+#------------------------------------------------------------------------------
+
+#-------------------------------
+# PREPROCESSING
+#-------------------------------
+
+#-------------------------------------------------------------------------------
+# ResampTraceDimension
+#
+# Description: The number of target points for resampling. In other words,
+# each character will be resampled to this number of points. In case of
+# multistroke characters, this number of points will be distributed between
+# the strokes in proportion to their lengths in proportion to their initial
+# number of points.
+#
+# Valid values: Any integer > 0
+# Units: Points
+# Default value: 60
+# Typical value: Average number of points per character in the training data set.
+#-------------------------------------------------------------------------------
+ResampTraceDimension = 60
+
+
+
+#-------------------------------------------------------------------------------
+# ResampPointAllocation
+#
+# Description: Method to be used for point allocation among different strokes
+# during resampling. Two schemes have been implemented lengthbased and point
+# based. In lengthbased allocation scheme, the number of points allocated to
+# each stroke is proportional to the length of the stroke. Length of a stroke
+# is calculated as the sum of the distances between each point in the stroke.
+# In the pointbased allocation scheme, the target stroke point allocation is
+# proportional to the number of points in the initial stroke. In the
+# interpointdistbased scheme, the distance between consecutive points is fixed
+# resulting in variable number based on the length of the trajectory.
+#
+# Valid value: [lengthbased | pointbased | interpointdistbased]
+# Default value: lengthbased
+#-------------------------------------------------------------------------------
+ResampPointAllocation = lengthbased
+
+
+#-------------------------------------------------------------------------------
+# NormDotSizeThreshold
+#
+# Description: This threshold is used to determine whether a character is a dot.
+# It is expressed in real length terms (inches) and converted internally to
+# points using knowledge of the device’s spatial resolution. If the width
+# and height are both less than this threshold, then all the points are replaced
+# with the center of the of the normalized character, basically to represent it
+# as a dot
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormDotSizeThreshold = 0.01
+
+#-------------------------------------------------------------------------------
+# NormLineWidthThreshold
+#
+# Description: This threshold is used to detect whether the character is a
+# vertical or horizontal line. If only the height is less than this threshold
+# then the character is detected as a horizontal line and if only the width is
+# less than this threshold then the character is detected as a vertical line.
+# Assuming the height is along the y-dimension and width is along the x-
+# dimension, during normalization of a horizontal line only the x-coordinates
+# are scaled and the y-coordinates are translated to the center of the character,
+# with out scaling. Similarly for the vertical line only the y-coordinates are
+# normalized and the x-coordinates are translated to the center with out scaling
+#
+# Valid values: Any real number > 0
+# Units: inches
+# Default value: 0.01
+# Typical value: < 0.1
+#-------------------------------------------------------------------------------
+NormLineWidthThreshold = 0.01
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatio
+#
+# Description: This parameter is used to indicate whether the aspect ratio
+# has to be preserved during normalization. The aspect ratio is the calculated
+# as maximum of (height/width , width/height). The aspect ratio is preserved only
+# if the calculated aspect ratio is greater than the threshold value specified
+# through NormPreserveAspectRatioThreshold and this configuration variable is
+# set to true. If this configuration variable is set to false the aspect ratio
+# is not preserved during normalization.
+#
+# Valid value: [true | false]
+# Default value: true
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatio = true
+
+
+#-------------------------------------------------------------------------------
+# NormPreserveAspectRatioThreshold
+#
+# Description: Aspect ratio is preserved during normalization if the computed
+# aspect ratio (max(height/width, width/height)) is greater than this threshold
+# and the configuration value NormPreserveAspectRatio is set to true. During
+# aspect ratio preserving normalization, the larger of the two dimensions is
+# normalized to the standard size and the other dimension is normalized
+# proportional to the initial height and width ratio, so that the initial
+# aspect ratio is maintained.
+#
+# Valid values: Any real number >= 1
+# Default value: 3
+# Typical value: >= 1.5
+#-------------------------------------------------------------------------------
+NormPreserveAspectRatioThreshold = 3
+
+#-------------------------------------------------------------------------------
+# NormPreserveRelativeYPosition
+#
+# Description: The relative Y position is the mean of the y-coordinates in the
+# input character. During normalization if this parameter is set to true, each
+# y-coordinate of the character point is translated by the initial y-mean value,
+# so that the mean of the y-coordinates remains the same before and after
+# normalization. This is typically used in the word recognition context where
+# each stroke of the character has to be normalized separately and the relative
+# position of the strokes should be maintained even after normalization.
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+NormPreserveRelativeYPosition = false
+
+#-------------------------------------------------------------------------------
+# SmoothWindowSize
+#
+# Description: The configuration value specifies the length of the moving
+# average filter (size of the window) for smoothing the character image.
+# If this value is set to N, then each point in the input character is replaced
+# by the average of value of this point, (N-1)/2 points on the right and (N-1)/2
+# on the left of this point.
+#
+# Valid value: Any integer > 0
+# Units: Points
+# Typical value: 5
+# Default value: 3
+#-------------------------------------------------------------------------------
+SmoothWindowSize = 3
+
+#-------------------------------------------------------------------------------
+# PreprocSequence
+#
+# Description: This variable is used to specify the sequence of preprocessing
+# operations to be carried out on the input character sample before extracting
+# the features. A valid preprocessing sequence can consist of combination of one
+# or more of the functions selected from the valid values set mentioned below.
+# The CommonPreProc prefix is used specify the default preprocessing module of
+# LipiTk. The user can add his own preprocessing functions in other modules and
+# specify them in the preprocessing sequence.
+#
+# Valid values: Any sequence formed from the following set
+# CommonPreProc::normalizeSize;
+# CommonPreProc::removeDuplicatePoints;
+# CommonPreProc::smoothenTraceGroup;
+# CommonPreProc::dehookTraces;
+# CommonPreProc::normalizeOrientation;
+# CommonPreProc::resampleTraceGroup;
+# Default value: {CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+#-------------------------------------------------------------------------------
+PreprocSequence={CommonPreProc::normalizeSize,CommonPreProc::resampleTraceGroup,CommonPreProc::normalizeSize}
+
+#---------------------------------------
+# TRAINING
+#---------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNTrainPrototypeSelectionMethod
+#
+# Description: This is used to specify the prototype selection method to be used
+# while training the shape recognizer. When set to hier-clustering, the
+# prototypes are selected using hierarchical clustering method.
+#
+# Valid value: [hier-clustering]
+# Default value: hier-clustering
+#-------------------------------------------------------------------------------
+NNTrainPrototypeSelectionMethod=hier-clustering
+
+
+#-------------------------------------------------------------------------------
+# NNTrainPrototypeReductionFactorPerClass
+#
+# Description: This config parameter is used only when the prototype selection
+# is clustering. This config parameter is used to specify the amount of the
+# initial prototypes to be excluded during prototype selection.
+# Set it to automatic if the number of clusters is to be determined
+# automatically. Set it to none if no prototype selection is required. If the
+# value of this parameter is set to a number between 1-100, say 25, then 75%
+# (i.e 100-25) of the initial training data are retained as prototypes.
+# This parameter can be specified only if the NNTrainNumPrototypesPerClass
+# is not specified.
+#
+# Valid value: [automatic | none | any real number from 0-100]
+# Default value: automatic
+#-------------------------------------------------------------------------------
+NNTrainPrototypeReductionFactorPerClass = none
+
+#-------------------------------------------------------------------------------
+# NNTrainNumPrototypesPerClass
+#
+# Description: This config parameter is used only when the prototype selection
+# is clustering. This is used to specify the number of prototypes to be selected
+# from the training data. This parameter can be specified only if
+# PrototypeReductionFactor is not specified. This config entry is commented as
+# only one of NNTrainPrototypeReductionFactorPerClass or
+# NNTrainNumPrototypesPerClass can be active in a valid cfg file.
+#
+# Valid value: [automatic | none | any integer from 1-N]
+# (N is the number of samples # per class)
+# Default value: automatic
+#-------------------------------------------------------------------------------
+#NNTrainNumPrototypesPerClass=automatic
+
+# Note: Only one of either PrototypeReductionFactor or NumClusters can be
+# enabled at any particular instance
+
+#-----------------------------------------
+# FEATURE EXTRACTION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# FeatureExtractor
+#
+# Description: The configuration value is used to specify the feature extraction
+# module to be used for feature extraction. The point float feature extraction
+# module extracts the x,y,cosine and sine angle features at every point of the
+# character.
+#
+# Valid value: [PointFloatShapeFeatureExtractor]
+# Default value: PointFloatShapeFeatureExtractor
+#-------------------------------------------------------------------------------
+FeatureExtractor=PointFloatShapeFeatureExtractor
+
+#-----------------------------------------
+# RECOGNITION
+#-----------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNRecoDTWEuFilterOutputSize
+#
+# Description: This config parameter is used to set the number of nearest
+# neighbours (filtered based on euclidean distance)to be considered for
+# calculating dtw distance. The value is specified as fraction of total number
+# of prototypes.
+# Set to all if all samples are to be considered for
+# calculating dtw distance. This is mainly used to increase the speed of
+# recognition.
+#
+# Valid value: [all| any integer from 1-100]
+# Default Value: all
+#-------------------------------------------------------------------------------
+NNRecoDTWEuFilterOutputSize = all
+
+#-------------------------------------------------------------------------------
+# NNRecoRejectThreshold
+#
+# Description: Threshold to reject the test sample. If the confidence obtained
+# for the recognition of test sample is less than this threshold then the test
+# sample is rejected.
+#
+# Valid value: Any real number from 0-1
+# Default value: 0.001
+#-------------------------------------------------------------------------------
+NNRecoRejectThreshold = 0.001
+
+#-------------------------------------------------------------------------------
+# NNRecoNumNearestNeighbors
+#
+# Description: Number of nearest neighbors to be considered during recognition
+# and computation of confidence. If the value is set to 1, nearest neighbor
+# classifier is used, otherwise k-nearest neighbor or Adaptive k-nearest
+# neighbor classifiers are used. By default, nearest neighbor classifier is used.
+#
+# Valid value: Any integer >= 1
+# Default value: 1
+#-------------------------------------------------------------------------------
+NNRecoNumNearestNeighbors = 1
+
+#-------------------------------------------------------------------------------
+# NNRecoUseAdaptiveKNN
+#
+# Description: This parameter is used to specify whether Adaptive k-nearest
+# neighbor recognizer (A-kNN) is to be used. If set to true, A-kNN recognizer is
+# used, otherwise kNN recognizer is used. The A-kNN recognizer automatically
+# determines the number of nearest neighbors to be considered for recognition in
+# each class. If NNRecoNumNearestNeighbors is set to 1, this parameter is
+# automatically set to false and the manually set value will not be considered.
+# The confidence values obtained do not add to 1 for all classes when
+# Adaptive-kNN is used.
+#
+# Valid value: [true | false]
+# Default value: false
+#-------------------------------------------------------------------------------
+NNRecoUseAdaptiveKNN = false
+
+#--------------------------------------------
+# COMMON FOR TRAINING AND RECOGNITION
+#--------------------------------------------
+
+#-------------------------------------------------------------------------------
+# NNPrototypeDistanceMeasure
+#
+# Description: This configuration parameter is used to specify the distance
+# measure to be used in clustering and recognition. DTW or Euclidean distance
+# measures can be used.
+#
+# Valid value [dtw | eu]
+# Default value: dtw
+#-------------------------------------------------------------------------------
+NNPrototypeDistanceMeasure = dtw
+
+#-------------------------------------------------------------------------------
+# NNDTWBandingRadius
+#
+# Description: This configuration parameter specifies the banding radius
+# to be used for DTW computation. This is used to speed up the computation
+# process. If this value is zero no banding is done. The value is specified as
+# fraction of ResampTraceDimension to be used while computing the DTW
+# distance.
+#
+# Valid values: Any real number > 0 and <= 1
+# Default Value: 0.33
+#-------------------------------------------------------------------------------
+NNDTWBandingRadius=0.33
+
+#-------------------------------------------------------------------------------
+# NNDTWBandingRadius
+#
+# Description: This configuration parameter specifies the mode for
+# opening the mdt file.
+#
+# Valid values: ascii, binary
+# Default Value: ascii
+#-------------------------------------------------------------------------------
+
+NNMDTFileOpenMode=ascii
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.pro
new file mode 100644
index 00000000..0b7046db
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/nn/nn.pro
@@ -0,0 +1,23 @@
+LIPILIBS = shaperecommon ltkcommon ltkutil featureextractorcommon
+include(../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../featureextractor/common \
+ ../common \
+
+HEADERS += \
+ NN.h \
+ NNAdapt.h \
+ NNShapeRecognizer.h \
+
+SOURCES += \
+ NN.cpp \
+ NNAdapt.cpp \
+ NNShapeRecognizer.cpp \
+
+win32 {
+ DEFINES += NN_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = NN.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/LTKPreprocessor.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/LTKPreprocessor.cpp
new file mode 100644
index 00000000..a3eae6cd
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/LTKPreprocessor.cpp
@@ -0,0 +1,3353 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-02-08 11:00:11 +0530 (Tue, 08 Feb 2011) $
+ * $Revision: 832 $
+ * $Author: dineshm $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKPreprocessor which is a library of standard pre-processing functions
+ *
+ * CONTENTS:
+ * LTKPreprocessor
+ * ~LTKPreprocessor
+ * normalizeSize
+ * normalizeOrientation
+ * resampleTrace
+ * smoothenTraceGroup
+ * setFilterLength
+ * centerTraces
+ * dehookTraces
+ * orderTraces
+ * reverseTrace
+ * duplicatePoints
+ * getNormalizedSize
+ * getSizeThreshold
+ * getLoopThreshold
+ * getAspectRatioThreshold
+ * getDotThreshold
+ * setNormalizedSize
+ * setSizeThreshold
+ * setLoopThreshold
+ * setAspectRatioThreshold
+ * setDotThreshold
+ * setHookLengthThreshold1
+ * setHookLengthThreshold2
+ * setHookAngleThreshold
+ * calculateSlope
+ * calculateEuclidDist
+ * getQuantisedSlope
+ * determineDominantPoints
+ * computeTraceLength
+ * removeDuplicatePoints
+ * calculateSweptAngle
+ * initFunAddrMap
+ * getPreprocptr
+ * setPreProcAttributes
+ * initPreprocFactoryDefaults
+ *
+ * AUTHOR: Balaji R.
+ *
+ * DATE: December 23, 2004
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "LTKTypes.h"
+
+#include "LTKPreprocessor.h"
+
+#include "LTKStringUtil.h"
+
+#include "LTKLoggerUtil.h"
+
+#include "LTKPreprocDefaults.h"
+
+#include "LTKTraceGroup.h"
+
+#include "LTKShapeRecoConfig.h"
+
+#include "LTKInkUtils.h"
+
+#include "LTKTrace.h"
+
+#include "LTKErrors.h"
+
+#include "LTKErrorsList.h"
+
+#include "LTKConfigFileReader.h"
+
+#include "LTKException.h"
+
+#include "LTKChannel.h"
+
+#include "LTKClassifierDefaults.h"
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : LTKPreprocessor
+* DESCRIPTION : Copy Constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKPreprocessor:: LTKPreprocessor(const LTKPreprocessor& preprocessor)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered copy constructor of LTKPreprocessor" <<endl;
+
+ initFunAddrMap();
+ initPreprocFactoryDefaults();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting copy constructor of LTKPreprocessor" <<endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : ~LTKPreprocessor
+* DESCRIPTION : destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKPreprocessor:: ~LTKPreprocessor()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered destructor of LTKPreprocessor" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting destructor of LTKPreprocessor" <<endl;
+}
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 13-Oct-2006
+* NAME : getCaptureDevice
+* DESCRIPTION : get the value of the member variable m_captureDevice
+* ARGUMENTS :
+* RETURNS : returns m_captureDevice
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+const LTKCaptureDevice& LTKPreprocessor::getCaptureDevice() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<"Entered getCaptureDevice" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting getCaptureDevice" <<endl;
+
+ return m_captureDevice;
+
+}
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 13-Oct-2006
+* NAME : getScreenContext
+* DESCRIPTION : get the value of the member variable m_screenContext
+* ARGUMENTS :
+* RETURNS : returns m_screenContext
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const LTKScreenContext& LTKPreprocessor::getScreenContext() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered getScreenContext" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting getScreenContext" <<endl;
+
+ return m_screenContext;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 13-Oct-2006
+* NAME : setCaptureDevice
+* DESCRIPTION : sets the member variable m_captureDevice
+* ARGUMENTS :
+*
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKPreprocessor::setCaptureDevice(const LTKCaptureDevice& captureDevice)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered setCaptureDevice" <<endl;
+
+ m_captureDevice = captureDevice;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting setCaptureDevice" <<endl;
+
+}
+
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 13-Oct-2006
+* NAME : setScreenContext
+* DESCRIPTION : sets the member variable m_screenContext
+* ARGUMENTS :
+*
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+void LTKPreprocessor::setScreenContext(const LTKScreenContext& screenContext)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered setScreenContext" <<endl;
+
+ m_screenContext = screenContext;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting setScreenContext" <<endl;
+
+}
+
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 24-Aug-2006
+* NAME : normalizeSize
+* DESCRIPTION : normalizes the size of the incoming trace group
+* ARGUMENTS : inTraceGroup - incoming tracegroup which is to be size normalized
+* outTraceGroup - size noramlized inTraceGroup
+* RETURNS : SUCCESS on successful size normalization
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::normalizeSize(const LTKTraceGroup& inTraceGroup, LTKTraceGroup& outTraceGroup)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::normalizeSize" <<endl;
+
+ float xScale; // scale factor along the x direction
+
+ float yScale; // scale factor along the y direction
+
+ float aspectRatio; // aspect ratio of the trace group
+
+ vector<LTKTrace> normalizedTracesVec; // holds the normalized traces
+
+ LTKTrace trace; // a trace of the trace group
+
+ floatVector xVec; // x channel values of a trace
+
+ floatVector yVec; // y channel values of a trace
+
+ floatVector normalizedXVec; // normalized x channel values of a trace
+
+ floatVector normalizedYVec; // normalized y channel values of a trace
+
+ float scaleX, scaleY, offsetX, offsetY;
+
+ float xMin,yMin,xMax,yMax;
+
+ int errorCode;
+
+ // getting the bounding box information of the input trace group
+
+ if( (errorCode = inTraceGroup.getBoundingBox(xMin,yMin,xMax,yMax)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeSize"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ outTraceGroup = inTraceGroup;
+
+
+ // width of the bounding box at scalefactor = 1
+
+ xScale = ((float)fabs(xMax - xMin))/inTraceGroup.getXScaleFactor();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "xScale = " << xScale <<endl;
+
+ // height of the bounding box at scalefactor = 1
+
+ yScale = ((float)fabs(yMax - yMin))/inTraceGroup.getYScaleFactor();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "yScale = " << yScale <<endl;
+
+ if(m_preserveAspectRatio)
+ {
+ if(yScale > xScale)
+ {
+ aspectRatio = (xScale > EPS) ? (yScale/xScale) : m_aspectRatioThreshold + EPS;
+ }
+ else
+ {
+ aspectRatio = (yScale > EPS) ? (xScale/yScale) : m_aspectRatioThreshold + EPS;
+ }
+ if(aspectRatio > m_aspectRatioThreshold)
+ {
+ if(yScale > xScale)
+ xScale = yScale;
+ else
+ yScale = xScale;
+ }
+ }
+
+
+ offsetY = 0.0f;
+ if(m_preserveRelativeYPosition )
+ {
+ offsetY = (yMin+yMax)/2.0f;
+ }
+
+ if(xScale <= (m_dotThreshold * m_captureDevice.getXDPI()) && yScale <= (m_dotThreshold * m_captureDevice.getYDPI()))
+ {
+
+ offsetX = PREPROC_DEF_NORMALIZEDSIZE/2;
+ offsetY += PREPROC_DEF_NORMALIZEDSIZE/2;
+
+ outTraceGroup.emptyAllTraces();
+
+ for(int traceIndex=0;traceIndex<inTraceGroup.getNumTraces();++traceIndex)
+ {
+ LTKTrace tempTrace;
+
+ inTraceGroup.getTraceAt(traceIndex,tempTrace);
+
+ vector<float> newXChannel(tempTrace.getNumberOfPoints(),offsetX);
+ vector<float> newYChannel(tempTrace.getNumberOfPoints(),offsetY);
+
+ tempTrace.reassignChannelValues(X_CHANNEL_NAME, newXChannel);
+ tempTrace.reassignChannelValues(Y_CHANNEL_NAME, newYChannel);
+
+ outTraceGroup.addTrace(tempTrace);
+
+ }
+
+ return SUCCESS;
+ }
+
+
+ // finding the final scale and offset values for the x channel
+ if((!m_preserveAspectRatio )&&(xScale < (m_sizeThreshold*m_captureDevice.getXDPI())))
+ {
+ scaleX = 1.0f;
+ offsetX = PREPROC_DEF_NORMALIZEDSIZE/2.0 ;
+ }
+ else
+ {
+ scaleX = PREPROC_DEF_NORMALIZEDSIZE / xScale ;
+ offsetX = 0.0;
+ }
+
+ // finding the final scale and offset values for the y channel
+
+
+
+ if((!m_preserveAspectRatio )&&(yScale < (m_sizeThreshold*m_captureDevice.getYDPI())))
+ {
+ offsetY += PREPROC_DEF_NORMALIZEDSIZE/2;
+ scaleY = 1.0f;
+ }
+ else
+ {
+ scaleY = PREPROC_DEF_NORMALIZEDSIZE / yScale ;
+ }
+
+
+ //scaling the copy of the inTraceGroup in outTraceGroup according to new scale factors
+ //and translating xmin_ymin of the trace group bounding box to the point (offsetX,offsetY).
+ //Even though absolute location has to be specified for translateToX and translateToY,
+ //since offsetX and offsetY are computed with respect to origin, they serve as absolute values
+
+ if( (errorCode = outTraceGroup.affineTransform(scaleX,scaleY,offsetX,offsetY,XMIN_YMIN)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeSize"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : normalizeOrientation
+* DESCRIPTION : normalizes the orientation of the incoming trace group
+* ARGUMENTS : inTraceGroup - incoming tracegroup which is to be orientation normalized
+* outTraceGroup - orientation noramlized inTraceGroup
+* RETURNS : SUCCESS on successful orientation normalization
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::normalizeOrientation(const LTKTraceGroup& inTraceGroup, LTKTraceGroup& outTraceGroup)
+{
+ int traceIndex;
+
+ int numTraces;
+
+ float bboxDiagonalLength;
+
+ float initialXCoord, finalXCoord;
+
+ float initialYCoord, finalYCoord;
+
+ float deltaX;
+
+ float deltaY;
+
+ float sweptAngle;
+
+ int errorCode;
+
+ vector<LTKTrace> tracesVec;
+
+ tracesVec = inTraceGroup.getAllTraces();
+
+ numTraces = tracesVec.size();
+
+ vector<string> channelNames;
+
+ channelNames.push_back(X_CHANNEL_NAME);
+
+ channelNames.push_back(Y_CHANNEL_NAME);
+
+ floatVector maxValues, minValues;
+
+ vector<LTKTrace> tempTraceVector;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "numTraces = " << numTraces <<endl;
+
+ for(traceIndex=0; traceIndex < numTraces; ++traceIndex)
+ {
+ const LTKTrace& trace = tracesVec.at(traceIndex);
+
+ if( (errorCode = LTKInkUtils::computeChannelMaxMin(trace, channelNames, maxValues, minValues)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ bboxDiagonalLength = calculateEuclidDist(minValues[0], maxValues[0], minValues[1], maxValues[1]);
+
+ minValues.clear();
+
+ maxValues.clear();
+
+ if(bboxDiagonalLength == 0)
+ {
+ tempTraceVector.push_back(trace);
+ continue;
+ }
+
+ floatVector xVec, yVec;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if(xVec.size()==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_VECTOR <<":"<< getErrorMessage(EEMPTY_VECTOR)
+ <<"LTKPreprocessor::normalizeOrientation" <<endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ if(yVec.size()==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_VECTOR <<":"<< getErrorMessage(EEMPTY_VECTOR)
+ <<"LTKPreprocessor::normalizeOrientation" <<endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+
+ initialXCoord = xVec[0];
+
+ finalXCoord = xVec[xVec.size() - 1];
+
+ initialYCoord = yVec[0];
+
+ finalYCoord = yVec[yVec.size() - 1];
+
+ deltaX = fabs((finalXCoord - initialXCoord) / bboxDiagonalLength);
+
+ deltaY = fabs((finalYCoord - initialYCoord) / bboxDiagonalLength);
+
+ if( (errorCode = calculateSweptAngle(trace, sweptAngle)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if((deltaX > m_loopThreshold && deltaY < m_loopThreshold && finalXCoord < initialXCoord) ||
+ (deltaY > m_loopThreshold && deltaX < m_loopThreshold && finalYCoord < initialYCoord) ||
+ (deltaX > m_loopThreshold && deltaY > m_loopThreshold && finalYCoord < initialYCoord) )
+ {
+
+ LTKTrace revTrace;
+
+ if( (errorCode = reverseTrace(trace, revTrace)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ tempTraceVector.push_back(revTrace);
+ }
+ else if(sweptAngle < 0.0)
+ {
+ LTKTrace revTrace;
+
+ if( (errorCode = reverseTrace(trace, revTrace)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::normalizeOrientation"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ tempTraceVector.push_back(revTrace);
+ }
+ else
+ {
+ tempTraceVector.push_back(trace);
+ }
+ }
+ outTraceGroup.setAllTraces(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : resampleTrace
+* DESCRIPTION : spatially resamples the given trace to a given number of points
+* ARGUMENTS : inTrace - trace to be resampled
+* resamplePoints - number of points required after resampling
+* outTrace - resampled trace
+* RETURNS : SUCCESS on successful resample operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::resampleTrace(const LTKTrace& inTrace, int resamplePoints, LTKTrace& outTrace)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::resampleTrace" <<endl;
+
+ int pointIndex; // a variable to loop over the points of a trace
+
+ int currentPointIndex =0; // index of the current point
+
+ float xSum = 0.0f; // sum of the x coordinate values
+
+ float ySum = 0.0f; // sum of the y coordinate values
+
+ int numTracePoints; // number of points in a trace
+
+ int ptIndex = 0; // index of point in a trace
+
+ float x; // an x coord value
+
+ float y; // an y coord value
+
+ float xDiff; // differenc in x direction
+
+ float yDiff; // diference in y direction
+
+ float xTemp; // temp x storage
+
+ float yTemp; // temp y storage
+
+ float unitLength = 0; // estimated length of each segment after resampling
+
+ float pointDistance;
+
+ float balanceDistance = 0; // distance between the last resampled point and
+ // the next raw sample point
+
+ float measuredDistance;
+
+ float m1,m2;
+
+ int errorCode;
+
+ floatVector xVec, yVec;
+
+ floatVector resampledXVec;
+
+ floatVector resampledYVec;
+
+ floatVector distanceVec;
+
+ numTracePoints = inTrace.getNumberOfPoints();
+
+ if(numTracePoints==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_TRACE <<":"<< getErrorMessage(EEMPTY_TRACE)
+ <<"LTKPreprocessor::resampleTrace" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE);
+ }
+
+ if( (errorCode = inTrace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = inTrace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "resamplePoints = " << resamplePoints <<endl;
+
+ if(resamplePoints < 1)
+ {
+ resamplePoints = 1;
+ }
+
+ if(resamplePoints == 1)
+ {
+ xSum = accumulate(xVec.begin(), xVec.end(), 0.0f);
+ ySum = accumulate(yVec.begin(), yVec.end(), 0.0f);
+
+ x = xSum/ numTracePoints; //As only 1 point is required, this ratio is computed.
+
+ y = ySum/ numTracePoints;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "x mean = " << x <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "y mean = " << y <<endl;
+
+ resampledXVec.push_back(x);
+
+ resampledYVec.push_back(y);
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(resampledXVec);
+ allChannelValuesVec.push_back(resampledYVec);
+
+ if( (errorCode = outTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ /*if( (errorCode = outTrace.setChannelValues(X_CHANNEL_NAME, resampledXVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+ if( (errorCode = outTrace.setChannelValues(Y_CHANNEL_NAME, resampledYVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }*/
+
+ }
+ else if(numTracePoints <= 1)
+ {
+ x = xVec.at(0);
+
+ y = yVec.at(0);
+
+ for(pointIndex = 0; pointIndex < resamplePoints; ++pointIndex)
+ {
+ resampledXVec.push_back(x);
+
+ resampledYVec.push_back(y);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "resampled point " << x << y <<endl;
+ }
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(resampledXVec);
+ allChannelValuesVec.push_back(resampledYVec);
+
+ if( (errorCode = outTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ /*if( (errorCode = outTrace.setChannelValues(X_CHANNEL_NAME, resampledXVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+ if( (errorCode = outTrace.setChannelValues(Y_CHANNEL_NAME, resampledYVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }*/
+ }
+ else
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Point distances" <<endl;
+
+ for( pointIndex = 0; pointIndex < (numTracePoints-1); ++pointIndex)
+ {
+ xDiff = xVec.at(pointIndex) - xVec.at(pointIndex+1);
+
+ yDiff = yVec.at(pointIndex) - yVec.at(pointIndex+1);
+
+ pointDistance = (float) (sqrt(xDiff*xDiff + yDiff*yDiff)); //distance between 2 points.
+
+ unitLength += pointDistance; // finding the length of trace.
+
+ distanceVec.push_back(pointDistance); //storing distances between every 2 consecutive points.
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "point distance: " << pointDistance <<endl;
+ }
+
+ unitLength /= (resamplePoints -1);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "unitLength = " << unitLength <<endl;
+
+ x = xVec.at(0); // adding x of first point;
+
+ y = yVec.at(0); // adding y of first point;
+
+ resampledXVec.push_back(x);
+
+ resampledYVec.push_back(y);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "resampled point " << x << y <<endl;
+
+ for(pointIndex = 1; pointIndex < (resamplePoints-1); ++pointIndex)
+ {
+ measuredDistance = balanceDistance;
+
+ while(measuredDistance < unitLength)
+ {
+ measuredDistance += distanceVec.at(ptIndex++);
+
+ if(ptIndex == 1)
+ {
+ currentPointIndex = 1;
+ }
+ else
+ {
+ currentPointIndex++;
+ }
+ }
+
+ if(ptIndex < 1) ptIndex = 1;
+
+ m2 = measuredDistance - unitLength;
+
+ m1 = distanceVec.at(ptIndex -1) - m2;
+
+ if( fabs(m1+m2) > EPS)
+ {
+ xTemp = (m1* xVec.at(currentPointIndex) + m2* xVec.at(currentPointIndex -1))/(m1+m2);
+
+ yTemp = (m1* yVec.at(currentPointIndex) + m2* yVec.at(currentPointIndex -1))/(m1+m2);
+ }
+ else
+ {
+ xTemp = xVec.at(currentPointIndex);
+
+ yTemp = yVec.at(currentPointIndex);
+ }
+
+ resampledXVec.push_back(xTemp);
+
+ resampledYVec.push_back(yTemp);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "resampled point " << xTemp << yTemp <<endl;
+
+ balanceDistance = m2;
+ }
+
+ x = xVec.at(xVec.size() - 1); // adding x of last point;
+
+ y = yVec.at(yVec.size() - 1); // adding y of last point;
+
+ resampledXVec.push_back(x);
+
+ resampledYVec.push_back(y);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "resampled point " << x << y <<endl;
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(resampledXVec);
+ allChannelValuesVec.push_back(resampledYVec);
+
+ if( (errorCode = outTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ /*if( (errorCode = outTrace.setChannelValues(X_CHANNEL_NAME, resampledXVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+ if( (errorCode = outTrace.setChannelValues(Y_CHANNEL_NAME, resampledYVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTrace"<<endl;
+ LTKReturnError(errorCode);
+ }*/
+
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::resampleTrace" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Mehul Patel
+* DATE : 04-APR-2005
+* NAME : smoothenTraceGroup
+* DESCRIPTION : smoothens the given tracegroup using moving average
+* ARGUMENTS : inTraceGroup - tracegroup to be smoothened
+* m_filterLength - configurable parameter used for filtering
+* outTraceGroup - smoothened TraceGroup
+* RETURNS : SUCCESS on successful smoothening operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::smoothenTraceGroup(const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ int errorCode;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entered LTKPreprocessor::smoothenTrace" << endl;
+
+ int loopIndex; // Index used for looping
+
+ int pointIndex; // Index over all the points in the trace
+
+ int traceIndex; // Index over all the traces of a tracegroup
+
+ int numTraces = inTraceGroup.getNumTraces();
+
+ int actualIndex; //
+
+ float sumX, sumY; //partial sum
+
+ vector<LTKTrace> tempTraceVector;
+
+
+ for(traceIndex = 0; traceIndex < numTraces; ++traceIndex)
+ {
+
+ LTKTrace inTrace;
+ inTraceGroup.getTraceAt(traceIndex, inTrace);
+
+ int numPoints = inTrace.getNumberOfPoints(); // total number of points in the trace
+
+ floatVector newXChannel, newYChannel; // temp vector to store the channelValues of outTrace
+
+ //Retrieving the channels
+
+ floatVector xChannel, yChannel;
+
+ if( (errorCode = inTrace.getChannelValues(X_CHANNEL_NAME, xChannel))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::smoothenTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = inTrace.getChannelValues(Y_CHANNEL_NAME, yChannel)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::smoothenTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ //iterating through the points
+
+ for(pointIndex = 0; pointIndex < numPoints ; ++pointIndex)
+ {
+ sumX = sumY = 0;
+
+ for(loopIndex = 0; loopIndex < m_filterLength; ++loopIndex)
+ {
+ actualIndex = (pointIndex-loopIndex);
+
+ //checking for bounding conditions
+ if (actualIndex <0 )
+ {
+ actualIndex = 0;
+ }
+ else if (actualIndex >= numPoints )
+ {
+ actualIndex = numPoints -1;
+ }
+
+ //accumulating values
+ sumX += xChannel[actualIndex];
+ sumY += yChannel[actualIndex];
+ }
+
+ //calculating average value
+ sumX /= m_filterLength;
+ sumY /= m_filterLength;
+
+
+ //adding the values to the pre processed channels
+ newXChannel.push_back(sumX);
+ newYChannel.push_back(sumY);
+ }
+
+ /*outTrace.reassignChannelValues(X_CHANNEL_NAME, newXChannel);
+ outTrace.reassignChannelValues(Y_CHANNEL_NAME, newYChannel);*/
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(newXChannel);
+ allChannelValuesVec.push_back(newYChannel);
+
+ LTKTrace outTrace;
+ if( (errorCode = outTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::removeDuplicatePoints"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ //adding the smoothed trace to the output trace group
+
+ tempTraceVector.push_back(outTrace);
+ } //traceIndex
+
+
+ outTraceGroup.setAllTraces(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::smoothenTrace" <<endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : centerTraces
+* DESCRIPTION : centers the traces of a trace group to the center of its bounding box
+* ARGUMENTS : inTraceGroup - trace group whose traces are to be centered
+* outTraceGroup - trace group after its traces are centered
+* RETURNS : SUCCESS on successful centering operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::centerTraces (const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entered LTKPreprocessor::centerTraces" <<endl;
+
+ int traceIndex; // a variable to loop over the traces of the trace group
+
+ int pointIndex; // a variable to loop over the points of a trace
+
+ int numTraces; // number of traces in the trace group
+
+ int numTracePoints; // number of points in a trace
+
+ LTKTrace trace; // a trace of the trace group
+
+ vector<LTKTrace> centeredTracesVec; // centered traces of the trace group
+
+ float xAvg,yAvg; // average x and y co-ordinate values
+
+ floatVector xVec; // x coords of a trace
+
+ floatVector yVec; // y coords of a trace
+
+ int errorCode;
+
+ vector<LTKTrace> tempTraceVector;
+
+ /* calculating the average x and y coordinate values and
+ using them to center the traces of the trace group */
+
+ numTraces = inTraceGroup.getNumTraces();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "numTraces = " << numTraces <<endl;
+
+ for(traceIndex=0; traceIndex< numTraces; traceIndex++)
+ {
+ inTraceGroup.getTraceAt(traceIndex, trace);
+
+ numTracePoints = trace.getNumberOfPoints();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "numTracePoints = " << numTracePoints <<endl;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ for(pointIndex=0; pointIndex< numTracePoints; pointIndex++)
+ {
+ xAvg += xVec.at(pointIndex);
+
+ yAvg += yVec.at(pointIndex);
+ }
+
+ xAvg /= numTracePoints;
+
+ yAvg /= numTracePoints;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "xAvg = " << xAvg <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "yAvg = " << yAvg <<endl;
+
+ for(pointIndex=0; pointIndex< numTracePoints; pointIndex++)
+ {
+ xVec.at(pointIndex) -= xAvg;
+
+ yVec.at(pointIndex) -= yAvg;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "centered point " << xVec.at(pointIndex) << yVec.at(pointIndex) <<endl;
+ }
+
+ if( (errorCode = trace.reassignChannelValues(X_CHANNEL_NAME,xVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+ if( (errorCode = trace.reassignChannelValues(Y_CHANNEL_NAME,yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ tempTraceVector.push_back(trace);
+ }
+
+ outTraceGroup.setAllTraces(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::centerTraces" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : dehookTraces
+* DESCRIPTION : dehooks the traces of the tracegroup
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful dehooking operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::dehookTraces(const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ int traceIndex;
+
+ float numTraces;
+
+ float dPX1, dPY1;
+
+ float dPX2, dPY2;
+
+ float dPX3, dPY3;
+
+ float dPX4, dPY4;
+
+ float L0;
+
+ float angle;
+
+ int firstPoint, lastPoint;
+
+ int numDominantPoints;
+
+ vector<int> quantizedSlopes;
+
+ vector<int> dominantPoints;
+
+ vector<string> channelNames;
+
+ channelNames.push_back(X_CHANNEL_NAME);
+
+ channelNames.push_back(Y_CHANNEL_NAME);
+
+ floatVector maxValues, minValues;
+
+ float scale;
+
+ int errorCode;
+
+ numTraces = inTraceGroup.getNumTraces();
+
+ vector<LTKTrace> tempTraceVector;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "numTraces = " << numTraces <<endl;
+
+ for(traceIndex=0; traceIndex< numTraces; traceIndex++)
+ {
+ LTKTrace trace;
+
+ inTraceGroup.getTraceAt(traceIndex, trace);
+
+ if( (errorCode = LTKInkUtils::computeChannelMaxMin(trace, channelNames, maxValues, minValues)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = computeTraceLength(trace, 0, trace.getNumberOfPoints() - 1,scale)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ floatVector xVec, yVec;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = getQuantisedSlope(trace, quantizedSlopes)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = determineDominantPoints(quantizedSlopes, 3, dominantPoints)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ numDominantPoints = dominantPoints.size();
+
+ if(numDominantPoints > 2)
+ {
+
+ dPX1 = xVec[dominantPoints[0]];
+
+ dPY1 = yVec[dominantPoints[0]];
+
+ dPX2 = xVec[dominantPoints[1]];
+
+ dPY2 = yVec[dominantPoints[1]];
+
+ dPX3 = xVec[dominantPoints[1] + 1];
+
+ dPY3 = yVec[dominantPoints[1] + 1];
+
+ dPX4 = xVec[dominantPoints[1] - 1];
+
+ dPY4 = yVec[dominantPoints[1] - 1];
+
+ if( (errorCode = computeTraceLength(trace, dominantPoints[0], dominantPoints[1],L0))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ angle = ( acos(((dPX1 - dPX2) * (dPX3 - dPX2) + (dPY1 - dPY2) * (dPY3 - dPY2)) /
+ (calculateEuclidDist(dPX2, dPX1, dPY2, dPY1) * calculateEuclidDist(dPX2, dPX3, dPY2, dPY3))) ) * 180 / 3.14;
+
+ if((L0/scale) < this->m_hookLengthThreshold1 || (((L0/scale) < this->m_hookLengthThreshold2) &&
+ (angle < this->m_hookAngleThreshold)))
+ {
+ firstPoint = dominantPoints[1];
+ }
+ else
+ {
+ firstPoint = dominantPoints[0];
+ }
+
+ dPX1 = xVec[dominantPoints[numDominantPoints - 1]];
+
+ dPY1 = yVec[dominantPoints[numDominantPoints - 1]];
+
+ dPX2 = xVec[dominantPoints[numDominantPoints - 2]];
+
+ dPY2 = yVec[dominantPoints[numDominantPoints - 2]];
+
+ dPX3 = xVec[dominantPoints[numDominantPoints - 2] - 1];
+
+ dPY3 = yVec[dominantPoints[numDominantPoints - 2] - 1];
+
+ dPX4 = xVec[dominantPoints[numDominantPoints - 2] + 1];
+
+ dPY4 = yVec[dominantPoints[numDominantPoints - 2] + 1];
+
+ if( (errorCode = computeTraceLength(trace, dominantPoints[numDominantPoints - 2], dominantPoints[numDominantPoints - 1],L0))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ angle = (acos(((dPX1 - dPX2) * (dPX3 - dPX2) + (dPY1 - dPY2) * (dPY3 - dPY2)) /
+ (calculateEuclidDist(dPX2, dPX1, dPY2, dPY1) * calculateEuclidDist(dPX2, dPX3, dPY2, dPY3)))) * 180 / 3.14;
+
+ if((L0/scale) < this->m_hookLengthThreshold1 || (((L0/scale) < this->m_hookLengthThreshold2) &&
+ (angle < this->m_hookAngleThreshold)))
+ {
+ lastPoint = dominantPoints[numDominantPoints - 2];
+ }
+ else
+ {
+ lastPoint = dominantPoints[numDominantPoints - 1];
+ }
+
+ floatVector newXVec(xVec.begin() + firstPoint, xVec.begin() + lastPoint + 1);
+
+ floatVector newYVec(yVec.begin() + firstPoint, yVec.begin() + lastPoint + 1);
+
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(newXVec);
+ allChannelValuesVec.push_back(newYVec);
+
+ LTKTrace newTrace;
+ if( (errorCode = newTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ tempTraceVector.push_back(newTrace);
+
+ }
+ else
+ {
+ tempTraceVector.push_back(trace);
+
+ /*
+ if( (errorCode = outTraceGroup.addTrace(trace)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::dehookTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+ */
+ }
+
+ outTraceGroup.setAllTraces(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+
+ quantizedSlopes.clear();
+
+ dominantPoints.clear();
+
+ maxValues.clear();
+
+ minValues.clear();
+
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : orderTraces
+* DESCRIPTION : reorders the traces to a pre-defined empirical order
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful reordering operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::orderTraces (const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entered LTKPreprocessor::orderTraces" <<endl;
+
+ // yet to be implemented
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKPreprocessor::orderTraces" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : reorientTraces
+* DESCRIPTION : reorients the traces to a pre-defined empirical direction
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful reorientation operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::reverseTrace(const LTKTrace& inTrace, LTKTrace& outTrace)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::reverseTrace" <<endl;
+
+ int pointIndex;
+
+ floatVector revXVec, revYVec;
+
+ floatVector xVec, yVec;
+
+ int errorCode;
+
+ if( (errorCode = inTrace.getChannelValues(X_CHANNEL_NAME, xVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::reverseTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = inTrace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::reverseTrace"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ // reversing the trace
+
+ for(pointIndex = xVec.size() - 1; pointIndex >= 0 ; --pointIndex)
+ {
+ revXVec.push_back(xVec[pointIndex]);
+
+ revYVec.push_back(yVec[pointIndex]);
+ }
+
+
+ outTrace = inTrace;
+
+ outTrace.reassignChannelValues(X_CHANNEL_NAME, revXVec);
+ outTrace.reassignChannelValues(Y_CHANNEL_NAME, revYVec);
+
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::reverseTrace" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : duplicatePoints
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful duplication of points operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::duplicatePoints (const LTKTraceGroup& traceGroup, int traceDimension)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::duplicatePoints" <<endl;
+
+ // yet to be implemented
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)<< "LTKPreprocessor::duplicatePoints - method not implemented" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::duplicatePoints" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 24-Aug-2006
+* NAME : getPreserveAspectRatio
+* DESCRIPTION : gets the value of the m_preserveAspectRatio member variable
+* ARGUMENTS :
+* RETURNS : true or false
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+bool LTKPreprocessor::getPreserveAspectRatio() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getPreserveAspectRatio" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getPreserveAspectRatio with return value " << m_preserveAspectRatio <<endl;
+
+ return m_preserveAspectRatio;
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 24-Aug-2006
+* NAME : getPreserveRealtiveYPosition
+* DESCRIPTION : gets the value of the m_preserveAspectRatio member variable
+* ARGUMENTS :
+* RETURNS : true or false
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+bool LTKPreprocessor::getPreserveRealtiveYPosition() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getPreserveRealtiveYPosition" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getPreserveRealtiveYPosition with return value " << m_preserveRelativeYPosition <<endl;
+
+ return m_preserveRelativeYPosition;
+}
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getSizeThreshold
+* DESCRIPTION : gets the size threshold below which traces will not be rescaled
+* ARGUMENTS :
+* RETURNS : size threshold below which traces will not be rescaled
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::getSizeThreshold () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getSizeThreshold" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getSizeThreshold with return value " << m_sizeThreshold <<endl;
+
+ return m_sizeThreshold;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getLoopThreshold
+* DESCRIPTION : gets the threshold below which the trace would considered a loop
+* ARGUMENTS :
+* RETURNS : threshold below which the trace would considered a loop
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::getLoopThreshold () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getLoopThreshold" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getLoopThreshold with return value " << m_loopThreshold <<endl;
+
+ return m_loopThreshold;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getAspectRatioThreshold
+* DESCRIPTION : returns threshold below which aspect ration will be maintained
+* ARGUMENTS :
+* RETURNS : threshold below which aspect ration will be maintained
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::getAspectRatioThreshold () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getAspectRatioThreshold" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getAspectRatioThreshold with return value " << m_aspectRatioThreshold <<endl;
+
+ return m_aspectRatioThreshold;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : getDotThreshold
+* DESCRIPTION : returns threshold to detect dots
+* ARGUMENTS :
+* RETURNS : threshold to detect dots
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::getDotThreshold () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getDotThreshold" <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getDotThreshold with return value " << m_dotThreshold <<endl;
+
+ return m_dotThreshold;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 31-May-2007
+* NAME : getQuantizationStep
+* DESCRIPTION : returns the value of the quantization step used in resampling
+* ARGUMENTS :
+* RETURNS : return the m_quantizationStep of the preprocessor
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::getQuantizationStep() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::getQuantizationStep" <<endl;
+
+ return m_quantizationStep;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::getQuantizationStep with return value " << m_quantizationStep <<endl;
+
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 31-May-2007
+* NAME : getResamplingMethod
+* DESCRIPTION : returns the type of resampling method being used in preprocessing
+* ARGUMENTS :
+* RETURNS : the m_resamplingMethod value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+string LTKPreprocessor::getResamplingMethod() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Entered LTKPreprocessor::getResamplingMethod" <<endl;
+
+ return m_resamplingMethod;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Exiting LTKPreprocessor::getResamplingMethod" <<endl;
+}
+/**********************************************************************************
+* AUTHOR : Srinivasa Vithal, Ch.
+* DATE : 18-Jun-2008
+* NAME : getTraceDimension
+* DESCRIPTION : returns the value of resamplingTraceDimension
+* ARGUMENTS :
+* RETURNS : the m_traceDimension value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const int LTKPreprocessor::getTraceDimension() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Entered LTKPreprocessor::getTraceDimension" <<endl;
+
+ return m_traceDimension;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Exiting LTKPreprocessor::getTraceDimension" <<endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Srinivasa Vithal, Ch.
+* DATE : 18-Jun-2008
+* NAME : getFilterLength
+* DESCRIPTION : returns the value of m_filterLength
+* ARGUMENTS :
+* RETURNS : the m_filterLength value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const int LTKPreprocessor::getFilterLength() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Entered LTKPreprocessor::getFilterLength" <<endl;
+
+ return m_filterLength;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_INFO)<< "Exiting LTKPreprocessor::getFilterLength" <<endl;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 24-AUG-2006
+* NAME : setPreserveAspectRatio
+* DESCRIPTION : sets the m_preserveAspectRatio member variable to the given flag
+* ARGUMENTS : flag - true or false
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+void LTKPreprocessor::setPreserveAspectRatio(bool flag)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setPreserveAspectRatio" <<endl;
+
+ this->m_preserveAspectRatio = flag;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_preserveAspectRatio = " << m_preserveAspectRatio <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setPreserveAspectRatio" <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 24-AUG-2006
+* NAME : setPreserveRelativeYPosition
+* DESCRIPTION : sets the m_preserveRelativeYPosition member variable to the given flag
+* ARGUMENTS : flag - true or false
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+void LTKPreprocessor::setPreserveRelativeYPosition(bool flag)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setPreserveRelativeYPosition" <<endl;
+
+ this->m_preserveRelativeYPosition = flag;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_preserveRelativeYPosition = " << m_preserveRelativeYPosition <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setPreserveRelativeYPosition" <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setSizeThreshold
+* DESCRIPTION : sets the size threshold below which traces will not be rescaled
+* ARGUMENTS : sizeThreshold - size threshold below which traces will not be rescaled
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Nidhi Sharma 13-Sept-2007 Added check on input parameter
+*************************************************************************************/
+
+int LTKPreprocessor::setSizeThreshold (float sizeThreshold)
+{
+ if(sizeThreshold < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<"LTKPreprocessor::setNormalizedSize" <<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ if(sizeThreshold > PREPROC_DEF_NORMALIZEDSIZE/100)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECONFIG_FILE_RANGE <<":"<< getErrorMessage(ECONFIG_FILE_RANGE)
+ <<"LTKPreprocessor::setNormalizedSize" <<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ this->m_sizeThreshold = sizeThreshold;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setLoopThreshold
+* DESCRIPTION : sets the threshold below which the trace would considered a loop
+* ARGUMENTS : loopThreshold - the threshold below which the trace would considered a loop
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::setLoopThreshold (float loopThreshold)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setLoopThreshold" <<endl;
+
+ this->m_loopThreshold = loopThreshold;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_loopThreshold = " << m_loopThreshold <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setLoopThreshold" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setAspectRatioThreshold
+* DESCRIPTION : sets the threshold below which aspect ratio will be maintained
+* ARGUMENTS : aspectRatioThreshold - threshold below which aspect ratio will be maintained
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Nidhi Sharma 13-Sept-2007 Added check on input parameter
+*************************************************************************************/
+
+int LTKPreprocessor::setAspectRatioThreshold (float aspectRatioThreshold)
+{
+ if(aspectRatioThreshold < 1)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<"LTKPreprocessor::setAspectRatioThreshold" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+
+ this->m_aspectRatioThreshold = aspectRatioThreshold;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setDotThreshold
+* DESCRIPTION : sets the threshold to detect dots
+* ARGUMENTS : dotThreshold - threshold to detect dots
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Nidhi Sharma 13-Sept-2007 Added a check on input parameter
+*************************************************************************************/
+
+int LTKPreprocessor::setDotThreshold (float dotThreshold)
+{
+ if(dotThreshold <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<"LTKPreprocessor::setDotThreshold" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+ this->m_dotThreshold = dotThreshold;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Vijayakumara M.
+* DATE : 25-OCT-2005
+* NAME : setFilterLength
+* DESCRIPTION : sets the fileter length
+* ARGUMENTS : filterLength - filter Length
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::setFilterLength (int filterLength)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setFilterLength" <<endl;
+
+ if(filterLength <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<"LTKPreprocessor::setFilterLength" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+ this->m_filterLength = filterLength;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_filterLength = " + m_filterLength <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setFilterLength" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setHookLengthThreshold1
+* DESCRIPTION : sets the length threshold to detect hooks
+* ARGUMENTS : hookLengthThreshold1 - length threshold to detect hooks
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::setHookLengthThreshold1(float hookLengthThreshold1)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setHookLengthThreshold1" <<endl;
+
+ if(hookLengthThreshold1 < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<"LTKPreprocessor::setHookLengthThreshold1" <<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ this->m_hookLengthThreshold1 = hookLengthThreshold1;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_hookLengthThreshold1 = " << m_hookLengthThreshold1 <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setHookLengthThreshold1" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setHookLengthThreshold2
+* DESCRIPTION : sets the length threshold to detect hooks
+* ARGUMENTS : hookLengthThreshold2 - length threshold to detect hooks
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::setHookLengthThreshold2(float hookLengthThreshold2)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setHookLengthThreshold2" <<endl;
+ if(hookLengthThreshold2 < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<"LTKPreprocessor::setHookLengthThreshold2" <<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ this->m_hookLengthThreshold2 = hookLengthThreshold2;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_hookLengthThreshold2 = " << m_hookLengthThreshold2 <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setHookLengthThreshold2" <<endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : setHookAngleThreshold
+* DESCRIPTION : sets the angle threshold to detect hooks
+* ARGUMENTS : hookAngleThreshold - angle threshold to detect hooks
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::setHookAngleThreshold(float hookAngleThreshold)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::setHookAngleThreshold" <<endl;
+
+ if(hookAngleThreshold < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<"LTKPreprocessor::setHookAngleThreshold" <<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ this->m_hookAngleThreshold = hookAngleThreshold;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "m_hookAngleThreshold = " << m_hookAngleThreshold <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::setHookAngleThreshold" <<endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 31-May-2007
+* NAME : setQuantizationStep
+* DESCRIPTION : sets the value of the quantization step used in resampling
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*Nidhi Sharma 13-Sept-2007 Added a check on input parameter
+*************************************************************************************/
+
+
+int LTKPreprocessor::setQuantizationStep(int quantizationStep)
+{
+ if(quantizationStep < 1)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECONFIG_FILE_RANGE <<":"<< getErrorMessage(ECONFIG_FILE_RANGE)
+ <<"LTKPreprocessor::setQuantizationStep" <<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+ }
+
+ m_quantizationStep = quantizationStep;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 31-May-2007
+* NAME : setResamplingMethod
+* DESCRIPTION : sets the type of resampling method being used in preprocessing
+* ARGUMENTS :
+* RETURNS : SUCCESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Nidhi Sharma 13-Sept-2007 Added a check on input parameter
+*************************************************************************************/
+int LTKPreprocessor::setResamplingMethod(const string& resamplingMethod)
+{
+ int returnVal = FAILURE;
+
+ if ( LTKSTRCMP(resamplingMethod.c_str(), LENGTHBASED) == 0 ||
+ LTKSTRCMP(resamplingMethod.c_str(), POINTBASED ) == 0 ||
+ LTKSTRCMP(resamplingMethod.c_str(), INTERPOINTDISTBASED) == 0)
+ {
+ m_resamplingMethod = resamplingMethod;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Resampling Method = " << m_resamplingMethod << endl;
+
+ return SUCCESS;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECONFIG_FILE_RANGE <<":"<< getErrorMessage(ECONFIG_FILE_RANGE)
+ <<"LTKPreprocessor::setResamplingMethod" <<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : calculateSlope
+* DESCRIPTION : calculates the slope of the line joining two 2-d points
+* ARGUMENTS : x1 - x co-ordinate of point 1
+* y1 - y co-ordinate of point 1
+* x2 - x co-ordinate of point 2
+* y2 - y co-ordinate of point 2
+* RETURNS : slope of the line joining the two 2-d points
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::calculateSlope (float x1,float y1,float x2,float y2)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::calculateSlope" <<endl;
+
+ // yet to be implemented
+
+ float slope=0.0f;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::calculateSlope" <<endl;
+
+ return slope;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 23-DEC-2004
+* NAME : calculateEuclidDist
+* DESCRIPTION : calculates the euclidean distance between two 2-d points
+* ARGUMENTS : x1 - x co-ordinate of point 1
+* x2 - x co-ordinate of point 2
+* y1 - y co-ordinate of point 1
+* y2 - y co-ordinate of point 2
+* RETURNS : euclidean distance between the two 2-d points
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+float LTKPreprocessor::calculateEuclidDist(float x1,float x2,float y1,float y2)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::calculateEuclidDist" <<endl;
+
+ float euclidDistance;
+
+ euclidDistance = sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::calculateEuclidDist" <<endl;
+
+ return euclidDistance;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 19-MAR-2005
+* NAME : GetQuantisedSlope
+* DESCRIPTION : Extracts the quantised Slope values from the input trace group.
+* ARGUMENTS : Input trace group
+* RETURNS : Quantised Slope Vector
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::getQuantisedSlope(const LTKTrace& trace, vector<int>& qSlopeVector)
+{
+ int errorCode;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered DTWFeatureExtractor::GetQuantisedSlope" <<endl;
+
+ floatVector slope; //Is a temporary variable which stores the slope values computed at each coordinate.
+
+ int dimension; //Stores the dimension of the CoordinatePoints
+
+ float dx,dy; //Temporary variales.
+
+ int pointIndex;
+
+ floatVector xVec, yVec;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::centerTraces"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ qSlopeVector.clear();
+
+ dimension = trace.getNumberOfPoints(); //character.size();
+
+ for(pointIndex=0; pointIndex < dimension-1; ++pointIndex)
+ {
+ dx = xVec[pointIndex+1] - xVec[pointIndex];
+
+ dy = yVec[pointIndex+1] - yVec[pointIndex];
+
+ if(fabs(dx) < EPS && fabs(dy) < EPS)
+ {
+ slope.push_back(1000.0);
+ }
+ else if(fabs(dx) < EPS)
+ {
+ if(dy > 0.0)
+ {
+ slope.push_back(90.0);
+ }
+ else
+ {
+ slope.push_back(-90.0);
+ }
+ }
+ else
+ {
+ slope.push_back((float)atan((double)(dy/dx))*(180/3.14));
+ }
+ }
+
+ slope.push_back(1000.0);
+
+ for(pointIndex = 0; pointIndex < dimension - 1; ++pointIndex)
+ {
+ if(slope[pointIndex] == 1000.0)
+ {
+ qSlopeVector.push_back(-1);
+ }
+ else if((xVec[pointIndex+1] >= xVec[pointIndex]) && (slope[pointIndex]< 22.5) && (slope[pointIndex]>= -22.5))
+ {
+ qSlopeVector.push_back(1);
+ }
+
+ else if((xVec[pointIndex+1] >= xVec[pointIndex]) && (yVec[pointIndex+1] >= yVec[pointIndex]) && (slope[pointIndex] < 67.5) && (slope[pointIndex]>=22.5))
+ {
+ qSlopeVector.push_back(2);
+ }
+
+ else if((yVec[pointIndex+1] >= yVec[pointIndex]) && ((slope[pointIndex]>= 67.5) || (slope[pointIndex] < -67.5)) )
+ {
+ qSlopeVector.push_back(3);
+ }
+
+ else if((xVec[pointIndex+1] < xVec[pointIndex]) && (yVec[pointIndex+1] >= yVec[pointIndex]) && (slope[pointIndex]< -22.5 ) && (slope[pointIndex]>= -67.5))
+ {
+ qSlopeVector.push_back(4);
+ }
+
+ else if((xVec[pointIndex+1] < xVec[pointIndex]) && (slope[pointIndex] >= -22.5) && (slope[pointIndex] < 22.5))
+ {
+ qSlopeVector.push_back(5);
+ }
+
+ else if((xVec[pointIndex+1] < xVec[pointIndex]) && (yVec[pointIndex+1] < yVec[pointIndex]) && (slope[pointIndex]>=22.5) && (slope[pointIndex]< 67.5))
+ {
+ qSlopeVector.push_back(6);
+ }
+
+ else if((yVec[pointIndex+1] < yVec[pointIndex]) && ((slope[pointIndex]>= 67.5) || (slope[pointIndex]< -67.5)))
+ {
+ qSlopeVector.push_back(7);
+ }
+
+ else if((xVec[pointIndex+1] >= xVec[pointIndex]) && (yVec[pointIndex+1] < yVec[pointIndex]) && (slope[pointIndex]>= -67.5) && (slope[pointIndex]< -22.5))
+ {
+ qSlopeVector.push_back(8);
+ }
+ }
+
+ if(dimension >= 2)
+ {
+ qSlopeVector.push_back(qSlopeVector[dimension-2]);
+ }
+ else
+ {
+ qSlopeVector.push_back(-1);
+ }
+
+ slope.clear();
+
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 19-MAR-2005
+* NAME : DetermineDominantPoints
+* DESCRIPTION : Identify the dominant points in the trace group based on the quantised slope information
+* ARGUMENTS : QSlopeVector,flexibility Index
+* RETURNS : Dominant Points
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::determineDominantPoints(const vector<int>& qSlopeVector, int flexibilityIndex, vector<int>& dominantPts)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered DTWFeatureExtractor::DetermineDominantPoints" <<endl;
+
+ int initSlope; //Temporary Variable to store the slope value at the previous point.
+
+ dominantPts.clear();
+
+ dominantPts.push_back(0); //adding the first point
+
+ initSlope = qSlopeVector[0];
+
+ int pointIndex;
+
+ for(pointIndex = 1; pointIndex < qSlopeVector.size() - 1; ++pointIndex)
+ {
+ if(initSlope == -1)
+ {
+ initSlope = qSlopeVector[pointIndex];
+
+ continue;
+ }
+
+ if(qSlopeVector[pointIndex] != -1)
+ {
+ if((qSlopeVector[pointIndex] - initSlope + 8) % 8 >= flexibilityIndex && (initSlope - qSlopeVector[pointIndex] + 8) % 8 >= flexibilityIndex)
+ {
+ dominantPts.push_back(pointIndex);
+ }
+
+ initSlope = qSlopeVector[pointIndex];
+ }
+
+ }
+
+ dominantPts.push_back(qSlopeVector.size() - 1); //adding the last point
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting DTWFeatureExtractor::DetermineDominantPoints" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 19-MAR-2005
+* NAME : computeTraceLength
+* DESCRIPTION : computes the length of the given trace between two given point indices
+* ARGUMENTS : trace - trace whose total/partial length is required
+* : fromPoint - point from which the trace length has to be computed
+* : toPoint - point to which the trace length has to be computed
+* RETURNS : total/partial length of the trace
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Balaji MNA 4-Aug-2008 Check for argument point index.
+*************************************************************************************/
+
+int LTKPreprocessor::computeTraceLength(const LTKTrace& trace, int fromPoint, int toPoint, float& outLength)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::computeTraceLength" <<endl;
+
+ int NoOfPoints = trace.getNumberOfPoints();
+
+ if( (fromPoint < 0 || fromPoint > (NoOfPoints-1))
+ || (toPoint < 0 || toPoint > (NoOfPoints-1)))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EPOINT_INDEX_OUT_OF_BOUND <<":"<< getErrorMessage(EPOINT_INDEX_OUT_OF_BOUND)
+ <<"LTKPreprocessor::computeTraceLength" <<endl;
+
+ LTKReturnError(EPOINT_INDEX_OUT_OF_BOUND);
+ }
+
+ int pointIndex;
+
+ float xDiff, yDiff;
+
+ float pointDistance;
+
+ outLength = 0;
+
+ floatVector xVec, yVec;
+
+ int errorCode;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::computeTraceLength"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::computeTraceLength"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ for(pointIndex = fromPoint; pointIndex < toPoint; ++pointIndex)
+ {
+ xDiff = xVec[pointIndex] - xVec[pointIndex+1];
+
+ yDiff = yVec[pointIndex] - yVec[pointIndex+1];
+
+ pointDistance = (float) (sqrt(xDiff*xDiff + yDiff*yDiff)); //distance between 2 points.
+
+ outLength += pointDistance; // finding the length of trace.
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "point distance: " << pointDistance <<endl;
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::computeTraceLength" <<endl;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 19-MAR-2005
+* NAME : removeDuplicatePoints
+* DESCRIPTION : remove consecutively repeating x, y coordinates (thinning)
+* ARGUMENTS : inTraceGroup - trace group which has to be thinned
+* : outTraceGroup - thinned trace group
+* RETURNS : SUCCESS on successful thinning operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKPreprocessor::removeDuplicatePoints(const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ int errorCode;
+ int numTraces;
+
+ int traceIndex;
+
+ int pointIndex;
+
+ int numPoints;
+
+ floatVector newXVec, newYVec;
+
+ numTraces = inTraceGroup.getNumTraces();
+
+ vector<LTKTrace> tempTraceVector;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "numTraces = " << numTraces <<endl;
+
+ for(traceIndex = 0; traceIndex < numTraces; ++traceIndex)
+ {
+ LTKTrace trace;
+
+ inTraceGroup.getTraceAt(traceIndex, trace);
+
+ floatVector xVec, yVec;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::removeDuplicatePoints"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::removeDuplicatePoints"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ numPoints = trace.getNumberOfPoints();
+
+ if(numPoints > 0)
+ {
+ newXVec.push_back(xVec[0]);
+
+ newYVec.push_back(yVec[0]);
+ }
+
+ for(pointIndex = 1; pointIndex < numPoints; ++pointIndex)
+ {
+ if((xVec[pointIndex] != xVec[pointIndex - 1]) || (yVec[pointIndex] != yVec[pointIndex - 1]))
+ {
+ newXVec.push_back(xVec[pointIndex]);
+
+ newYVec.push_back(yVec[pointIndex]);
+ }
+ }
+
+ float2DVector allChannelValuesVec;
+ allChannelValuesVec.push_back(newXVec);
+ allChannelValuesVec.push_back(newYVec);
+
+ LTKTrace newTrace;
+ if( (errorCode = newTrace.setAllChannelValues(allChannelValuesVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::removeDuplicatePoints"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ tempTraceVector.push_back(newTrace);
+
+ newXVec.clear();
+
+ newYVec.clear();
+ }
+
+
+ LTKTraceGroup tempTraceGroup(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+
+ outTraceGroup = tempTraceGroup;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Balaji R.
+* DATE : 19-MAR-2005
+* NAME : calculateSweptAngle
+* DESCRIPTION : calculates the swept angle of the curve.
+* ARGUMENTS : Input trace
+* RETURNS : Swept angle of the trace
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Balaji MNA 4-Aug-2008 Define new error code ESINGLE_POINT_TRACE.
+*************************************************************************************/
+
+int LTKPreprocessor::calculateSweptAngle(const LTKTrace& trace, float& outSweptAngle)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered DTWFeatureExtractor::calculateSweptAngle" <<endl;
+
+ outSweptAngle = 0.0;
+
+ float prevSlope;
+
+ float slope; //Is a temporary variable which stores the slope values computed at each coordinate.
+
+ int dimension; //Stores the dimension of the CoordinatePoints
+
+ float dx,dy; //Temporary variales.
+
+ int pointIndex;
+
+ floatVector xVec, yVec;
+
+ int errorCode;
+
+ if( (errorCode = trace.getChannelValues(X_CHANNEL_NAME, xVec))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::calculateSweptAngle"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ if( (errorCode = trace.getChannelValues(Y_CHANNEL_NAME, yVec)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::calculateSweptAngle"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ dimension = trace.getNumberOfPoints(); //character.size();
+
+ if(dimension < 2)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ESINGLE_POINT_TRACE <<":"<< getErrorMessage(ESINGLE_POINT_TRACE)
+ <<"LTKPreprocessor::calculateSweptAngle" <<endl;
+ LTKReturnError(ESINGLE_POINT_TRACE);
+ }
+
+
+ dx = xVec[1] - xVec[0];
+
+ dy = yVec[1] - yVec[0];
+
+ prevSlope = (float)atan2(dy, dx)*(180/3.14);
+
+ for(pointIndex=1; pointIndex < dimension-1; ++pointIndex)
+ {
+ dx = xVec[pointIndex+1] - xVec[pointIndex];
+
+ dy = yVec[pointIndex+1] - yVec[pointIndex];
+
+ slope = (float)atan2(dy, dx)*(180/3.14);
+
+ outSweptAngle = slope - prevSlope;
+
+ prevSlope = slope;
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Vijayakumara M.
+* DATE : 13-JULY-2005
+* NAME : LTKPreprocessor
+* DESCRIPTION : This function will add the function name and its address to the
+* maping variable.
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+void LTKPreprocessor::initFunAddrMap ()
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered default constructor of LTKPreprocessor" <<endl;
+
+ string normalizeSize = NORMALIZE_FUNC;
+ string removeDuplicatePoints = REMOVE_DUPLICATE_POINTS_FUNC;
+ string smoothenTraceGroup = SMOOTHEN_TRACE_GROUP_FUNC;
+ string dehookTraces = DEHOOKTRACES_FUNC;
+ string normalizeOrientation = NORMALIZE_ORIENTATION_FUNC;
+ string resampleTraceGroup = RESAMPLE_TRACE_GROUP_FUNC;
+
+ m_preProcMap[normalizeSize]=&LTKPreprocessorInterface::normalizeSize;
+ m_preProcMap[removeDuplicatePoints]=&LTKPreprocessorInterface::removeDuplicatePoints;
+ m_preProcMap[smoothenTraceGroup]=&LTKPreprocessorInterface::smoothenTraceGroup;
+ m_preProcMap[dehookTraces]=&LTKPreprocessorInterface::dehookTraces;
+ m_preProcMap[normalizeOrientation]=&LTKPreprocessorInterface::normalizeOrientation;
+ m_preProcMap[resampleTraceGroup]=&LTKPreprocessorInterface::resampleTraceGroup;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting default constructor of LTKPreprocessor" <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Vijayakumara M.
+* DATE : 13-JULY-2005
+* NAME : getPreprocptr
+* DESCRIPTION : This function returs the preprocessor function pointer.
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+FN_PTR_PREPROCESSOR LTKPreprocessor::getPreprocptr(const string &funName)
+{
+ return m_preProcMap[funName];
+}
+
+/**********************************************************************************
+* AUTHOR : Thanigai
+* DATE : 20-SEP-2005
+* NAME : initPreprocFactoryDefaults
+* DESCRIPTION : This function assigns the factory default values for the
+* preprocessor attributes
+* ARGUMENTS : void
+* RETURNS : 0 on success
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKPreprocessor::initPreprocFactoryDefaults()
+{
+ m_sizeThreshold = PREPROC_DEF_SIZE_THRESHOLD;
+ m_aspectRatioThreshold = PREPROC_DEF_ASPECTRATIO_THRESHOLD;
+ m_dotThreshold = PREPROC_DEF_DOT_THRESHOLD;
+ m_loopThreshold = PREPROC_DEF_LOOP_THRESHOLD;
+ m_hookLengthThreshold1 = PREPROC_DEF_HOOKLENGTH_THRESHOLD1;
+ m_hookLengthThreshold2 = PREPROC_DEF_HOOKLENGTH_THRESHOLD2;
+ m_hookAngleThreshold = PREPROC_DEF_HOOKANGLE_THRESHOLD;
+ m_filterLength = PREPROC_DEF_FILTER_LENGTH;
+ m_preserveAspectRatio = PREPROC_DEF_PRESERVE_ASPECT_RATIO;
+ m_preserveRelativeYPosition = PREPROC_DEF_PRESERVE_RELATIVE_Y_POSITION;
+ m_quantizationStep = PREPROC_DEF_QUANTIZATIONSTEP;
+ m_resamplingMethod = PREPROC_DEF_RESAMPLINGMETHOD;
+ m_traceDimension = PREPROC_DEF_TRACE_DIMENSION;
+
+ m_interPointDist = (float)PREPROC_DEF_NORMALIZEDSIZE/(float)PREPROC_DEF_INTERPOINT_DIST_FACTOR;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Dinesh M
+* DATE : 30-May-2007
+* NAME : resampleTraceGroup
+* DESCRIPTION : This function resamples the tracegroup
+* ARGUMENTS : Input tracegroup, Output tracegroup
+* RETURNS : 0 on success
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::resampleTraceGroup(const LTKTraceGroup& inTraceGroup,
+ LTKTraceGroup& outTraceGroup)
+{
+ int errorCode;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::resampleTraceGroup1" <<endl;
+ int total = 0;
+ float totalLength = 0;
+ int totalPoints = 0;
+
+ const vector<LTKTrace>& tracesVector = inTraceGroup.getAllTraces();
+ vector<LTKTrace> tempTraceVector;
+
+ int numberOfTraces = tracesVector.size();
+
+ if(numberOfTraces==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_TRACE_GROUP <<" : "<<
+ getErrorMessage(EEMPTY_TRACE_GROUP)
+ <<"LTKPreprocessor::resampleTraceGroup" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+ vector<int> pointsPerTrace(numberOfTraces, 0);
+
+ if(m_resamplingMethod == LENGTHBASED)
+ {
+ int maxIndex = 0;
+ float maxLength = 0.0;
+
+ floatVector lengthsVec(numberOfTraces, 0.0f);
+
+ for(int j=0; j < numberOfTraces; ++j)
+ {
+ float length;
+ const LTKTrace& trace = tracesVector[j];
+ if( (errorCode = computeTraceLength(trace, 0, trace.getNumberOfPoints() - 1,length))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+ lengthsVec[j] = length;
+ if(fabs(lengthsVec[j]) < EPS)
+ {
+ lengthsVec[j] = EPS;
+ }
+ totalLength += lengthsVec[j];
+ if(lengthsVec[j] > maxLength)
+ {
+ maxLength = lengthsVec[j];
+ maxIndex = j;
+ }
+ }
+
+
+ if(m_quantizationStep == 1)
+ {
+ for(int i = 0; i < numberOfTraces; ++i)
+ {
+ if( i == (numberOfTraces -1))
+ pointsPerTrace[i] = ((m_traceDimension - numberOfTraces) - total);
+ else
+ {
+ pointsPerTrace[i] = int(floor((m_traceDimension - numberOfTraces) *
+ lengthsVec[i] / totalLength));
+ }
+
+ total += pointsPerTrace[i];
+
+ }
+ }
+ else
+ {
+ for(int i = 0; i < numberOfTraces; ++i)
+ {
+ if(i != maxIndex)
+ {
+ pointsPerTrace[i] = m_quantizationStep * int(floor((m_traceDimension * lengthsVec[i] / (m_quantizationStep * totalLength)) + 0.5f));
+
+ if(pointsPerTrace[i] <= 0)
+ {
+ pointsPerTrace[i] = 1;
+ }
+
+ total += pointsPerTrace[i];
+ }
+ }
+ pointsPerTrace[maxIndex] = m_traceDimension - total;
+
+ }
+ int sum =0;
+ for(int temp =0; temp < pointsPerTrace.size(); ++temp)
+ {
+ sum+=pointsPerTrace[temp];
+ }
+
+ }
+ else if(m_resamplingMethod == POINTBASED)
+ {
+ for(int j=0; j < numberOfTraces; ++j)
+ totalPoints += tracesVector[j].getNumberOfPoints();
+
+ if(totalPoints==0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_TRACE_GROUP <<":"<< getErrorMessage(EEMPTY_TRACE_GROUP)
+ <<"LTKPreprocessor::resampleTraceGroup" <<endl;
+
+ LTKReturnError(EEMPTY_TRACE_GROUP);
+ }
+
+ for(int i=0; i < numberOfTraces; ++i)
+ {
+ const LTKTrace& trace = tracesVector.at(i);
+ if( i == (numberOfTraces - 1))
+ pointsPerTrace[i] = ((m_traceDimension - numberOfTraces) - total);
+ else
+ {
+ pointsPerTrace[i] = int(floor((m_traceDimension - numberOfTraces) * trace.getNumberOfPoints() / float(totalPoints) ));
+ }
+
+ total += pointsPerTrace[i];
+
+ }
+
+ }
+ else if(m_resamplingMethod == INTERPOINTDISTBASED)
+ {
+
+
+ for(int j=0; j < numberOfTraces; ++j)
+ {
+ float length;
+ LTKTrace trace = tracesVector[j];
+
+ LTKTraceGroup tempTraceGroup(trace,inTraceGroup.getXScaleFactor(),inTraceGroup.getYScaleFactor());
+
+ if(isDot(tempTraceGroup))
+ {
+ pointsPerTrace[j] = -1;
+ }
+ else
+ {
+
+ if( (errorCode = computeTraceLength(trace, 0, trace.getNumberOfPoints() - 1,length))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ pointsPerTrace[j] = ((int)floor((length/m_interPointDist)+0.5f)) + 1; //0.5f is for rounding the result to the nearest integer
+
+
+
+ }
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECONFIG_FILE_RANGE <<":"<< getErrorMessage(ECONFIG_FILE_RANGE)
+ <<"LTKPreprocessor::resampleTraceGroup" <<endl;
+
+ LTKReturnError(ECONFIG_FILE_RANGE);
+
+ }
+
+ for(int i=0; i < numberOfTraces; ++i)
+ {
+ LTKTrace newTrace;
+ const LTKTrace& trace = tracesVector.at(i);
+ if(m_resamplingMethod == "lengthbased" && m_quantizationStep != 1)
+ {
+ if( (errorCode = resampleTrace(trace,pointsPerTrace[i], newTrace))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+ }
+ else if(m_resamplingMethod == "interpointdistbased")
+ {
+ if(pointsPerTrace[i] == -1) //if the trace corresponds to a dot
+ {
+ vector<float> avgPoint;
+
+
+ if( (errorCode = resampleTrace(trace,1, newTrace))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ if( (errorCode = newTrace.getPointAt(0,avgPoint))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+ //Adding the average point 5 times in the new trace
+ for(int p=0;p<4;++p)
+ {
+ newTrace.addPoint(avgPoint);
+ }
+
+
+
+ }
+ else
+ {
+ if( (errorCode = resampleTrace(trace,pointsPerTrace[i]+1, newTrace))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+ }
+ }
+ else
+ {
+ if( (errorCode = resampleTrace(trace,pointsPerTrace[i]+1, newTrace))!= SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::resampleTraceGroup"<<endl;
+ LTKReturnError(errorCode);
+ }
+ }
+ tempTraceVector.push_back(newTrace);
+ }
+
+
+ outTraceGroup.setAllTraces(tempTraceVector,
+ inTraceGroup.getXScaleFactor(),
+ inTraceGroup.getYScaleFactor());
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::resampleTraceGroup1" <<endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 13-Sept-2007
+* NAME : setTraceDimension
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+* Nidhi Sharma 13-Sept-2007 Added a check on function parameter, assignment happens
+* only if input parameter is on zero
+*************************************************************************************/
+int LTKPreprocessor::setTraceDimension(int traceDimension)
+{
+ if(traceDimension <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<"LTKPreprocessor::setTraceDimension" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+ m_traceDimension = traceDimension;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 13-Sept-2007
+* NAME : initialize
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKPreprocessor::readConfig(const string& cfgFilePath)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Entering LTKPreprocessor::readConfig" <<endl;
+
+ LTKConfigFileReader* configurableProperties = NULL;
+ string tempStringVar = "";
+
+
+ try
+ {
+ configurableProperties = new LTKConfigFileReader(cfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ delete configurableProperties;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: "
+ << e.getErrorCode() <<" LTKPreprocessor::readConfig()"<<endl;
+
+ LTKReturnError(e.getErrorCode());
+ }
+
+ // Read the key-values pairs defined in the cfg file
+
+ /*
+ * Trace Dimension
+ */
+ int errorCode = FAILURE;
+
+ try
+ {
+ errorCode = configurableProperties->getConfigValue(TRACEDIMENSION,
+ tempStringVar);
+ if( errorCode == SUCCESS )
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ if (setTraceDimension(atoi((tempStringVar).c_str())) != SUCCESS)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " : " << TRACEDIMENSION <<
+ " is out of permitted range" <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ /*
+ * Size Threshold
+ */
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(SIZETHRESHOLD,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ if (setSizeThreshold(LTKStringUtil::convertStringToFloat(tempStringVar)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << SIZETHRESHOLD <<
+ " should be atleast less than 1/100'th of NORMALIZEDSIZE"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << " for " << SIZETHRESHOLD <<
+ " LTKPreprocessor::readConfig()" << endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ /*
+ * Aspect ratio threshold
+ */
+
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(ASPECTRATIOTHRESHOLD,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ if (setAspectRatioThreshold(LTKStringUtil::convertStringToFloat(tempStringVar)) != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ ASPECTRATIOTHRESHOLD << " should be positive" << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE << " Invalid value " <<
+ tempStringVar << "for " << ASPECTRATIOTHRESHOLD <<
+ " LTKPreprocessor::readConfig()" << endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ /*
+ * Dot Threshold
+ */
+
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(DOTTHRESHOLD,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isFloat(tempStringVar) )
+ {
+ if (setDotThreshold(LTKStringUtil::convertStringToFloat(tempStringVar)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << DOTTHRESHOLD <<
+ " should be positive" << endl ;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << " for " << DOTTHRESHOLD <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ /*
+ * Preserve relative y position
+ */
+
+ tempStringVar = "";
+ configurableProperties->getConfigValue(PRESERVERELATIVEYPOSITION,
+ tempStringVar);
+
+ if(LTKSTRCMP(tempStringVar.c_str(), "true") == 0)
+ {
+ m_preserveRelativeYPosition = true;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< PRESERVERELATIVEYPOSITION <<
+ " turned on during normalization"<<endl;
+ }
+ else if(LTKSTRCMP(tempStringVar.c_str(), "false") == 0)
+ {
+ m_preserveRelativeYPosition = false;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< PRESERVERELATIVEYPOSITION <<
+ " turned on during normalization"<<endl;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << " for " << PRESERVERELATIVEYPOSITION <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+
+ /*
+ * Preserve aspect ratio
+ */
+
+ tempStringVar = "";
+ configurableProperties->getConfigValue(PRESERVEASPECTRATIO,
+ tempStringVar);
+
+ if(LTKSTRCMP(tempStringVar.c_str(), "false") ==0)
+ {
+ setPreserveAspectRatio(false);
+ }
+ else if (LTKSTRCMP(tempStringVar.c_str(), "true") ==0)
+ {
+ setPreserveAspectRatio(true);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << " for " << PRESERVEASPECTRATIO <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+
+ /*
+ * Resampling method
+ */
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(RESAMPLINGMETHOD,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if (setResamplingMethod(tempStringVar) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<< "ERROR: " <<
+ " Invalid value " << tempStringVar << " for " <<
+ RESAMPLINGMETHOD << " LTKPreprocessor::readConfig()" << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+
+ /*
+ * Quantation step, needed only f the resampling method is length based
+ */
+ if ( LTKSTRCMP(m_resamplingMethod.c_str(), LENGTHBASED) == 0 )
+ {
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(QUANTIZATIONSTEP,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ if (setQuantizationStep(atoi((tempStringVar).c_str())) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ QUANTIZATIONSTEP << " greater than one "<< endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << "for " <<
+ QUANTIZATIONSTEP <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+
+ /*
+ * SmoothWindowSize method
+ */
+ tempStringVar = "";
+ errorCode = configurableProperties->getConfigValue(SMOOTHFILTERLENGTH,
+ tempStringVar);
+
+ if( errorCode == SUCCESS)
+ {
+ if ( LTKStringUtil::isInteger(tempStringVar) )
+ {
+ if (setFilterLength(atoi((tempStringVar).c_str())) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ SMOOTHFILTERLENGTH << " greater than one "<< endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE
+ <<" LTKPreprocessor::readConfig()"<<endl;
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Error: " << ECONFIG_FILE_RANGE <<
+ " Invalid value " << tempStringVar << "for " <<
+ SMOOTHFILTERLENGTH <<
+ " LTKPreprocessor::readConfig()"<<endl;
+
+ throw LTKException(ECONFIG_FILE_RANGE);
+ }
+ }
+ }
+ catch(LTKException e)
+ {
+ delete configurableProperties;
+ LTKReturnError(e.getErrorCode());
+ }
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<<
+ "Exiting LTKPreprocessor::initialize" <<endl;
+
+ delete configurableProperties;
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Nidhi Sharma
+* DATE : 13-Sept-2007
+* NAME : initialize
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKPreprocessor::LTKPreprocessor(const LTKControlInfo& controlInfo)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered default constructor of LTKPreprocessor" <<endl;
+
+ initFunAddrMap();
+ initPreprocFactoryDefaults();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting default constructor of LTKPreprocessor" <<endl;
+
+ string cfgFilePath = "";
+
+ // Config file
+ if ( ! ((controlInfo.lipiRoot).empty()) &&
+ ! ((controlInfo.projectName).empty()) &&
+ ! ((controlInfo.profileName).empty()) &&
+ ! ((controlInfo.cfgFileName).empty()))
+ {
+ // construct the cfg path using project and profile name
+ cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING +
+ (controlInfo.projectName) + PROFILE_PATH_STRING +
+ (controlInfo.profileName) + SEPARATOR +
+ (controlInfo.cfgFileName) + CONFIGFILEEXT;
+ }
+ else if ( ! ((controlInfo.cfgFilePath).empty() ))
+ {
+ cfgFilePath = controlInfo.cfgFilePath;
+ }
+ else
+ {
+ return;
+ }
+
+ int returnVal = readConfig(cfgFilePath);
+ if (returnVal != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::LTKPreprocessor"<<endl;
+ throw LTKException(returnVal);
+ }
+}
+
+bool LTKPreprocessor::isDot(const LTKTraceGroup& inTraceGroup)
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Entered LTKPreprocessor::isDot" <<endl;
+
+ float xMin,yMin,xMax,yMax;
+
+ float xScale; // scale along the x direction
+
+ float yScale; // scale along the y direction
+
+ int errorCode;
+
+ // getting the bounding box information of the input trace group
+
+ if( (errorCode = inTraceGroup.getBoundingBox(xMin,yMin,xMax,yMax)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKPreprocessor::isDot"<<endl;
+ LTKReturnError(errorCode);
+ }
+
+
+ // width of the bounding box at scalefactor = 1
+
+ xScale = ((float)fabs(xMax - xMin))/inTraceGroup.getXScaleFactor();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "xScale = " << xScale <<endl;
+
+ // height of the bounding box at scalefactor = 1
+
+ yScale = ((float)fabs(yMax - yMin))/inTraceGroup.getYScaleFactor();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "yScale = " << yScale <<endl;
+
+
+ if(xScale <= (m_dotThreshold * m_captureDevice.getXDPI()) && yScale <= (m_dotThreshold * m_captureDevice.getYDPI()))
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::isDot" <<endl;
+ return true;
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<< "Exiting LTKPreprocessor::isDot" <<endl;
+ return false;
+ }
+
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.cpp
new file mode 100644
index 00000000..b6f4fa28
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.cpp
@@ -0,0 +1,109 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-08-01 09:48:58 +0530 (Fri, 01 Aug 2008) $
+ * $Revision: 583 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Defines the entry point for the DLL application.
+ *
+ * CONTENTS:
+ * DllMain
+ * createPreprocInst
+ * destroyPreprocInst
+ *
+ * AUTHOR: Vijayakumara M.
+ *
+ * DATE: July 28, 2005.
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+
+#include "preprocessing.h"
+#include "LTKException.h"
+#include "LTKErrors.h"
+
+#ifdef _WIN32
+#include <windows.h>
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+
+#endif
+/**********************************************************************************
+* AUTHOR : Vijayakumara M.
+* DATE : 13-JULY-2005
+* NAME : create
+* DESCRIPTION : This function creates the object of LTKPreprocessor class and returns
+ the address of the object.
+* ARGUMENTS : - N0 -
+* RETURNS : Address of the created object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int createPreprocInst(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocPtr)
+{
+
+ try
+ {
+ *preprocPtr = new LTKPreprocessor(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *preprocPtr = NULL;
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Vijayakumara M.
+* DATE : 13-JULY-2005
+* NAME : destroy
+* DESCRIPTION : Deletes the object,
+* ARGUMENTS : Address of the object of type LTKPreprocessorInterface
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void destroyPreprocInst(LTKPreprocessorInterface* p)
+{
+ delete p;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.def
new file mode 100644
index 00000000..ca038d78
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createPreprocInst @1
+ destroyPreprocInst @2 \ No newline at end of file
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.h
new file mode 100644
index 00000000..5d052153
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.h
@@ -0,0 +1,82 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: This file includes exporting function definitons.
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Vijayakumara M.
+ *
+ * DATE: 28-July-2005
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ ************************************************************************/
+#ifndef __PREPROCESSING_H_
+#define __PREPROCESSING_H_
+
+#ifdef _WIN32
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the PREPROCESSING_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// PREPROCESSING_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef PREPROCESSING_EXPORTS
+#define PREPROCESSING_API __declspec(dllexport)
+#else
+#define PREPROCESSING_API __declspec(dllimport)
+#endif
+#else
+#define PREPROCESSING_API
+#endif // #ifdef _WIN32
+
+
+#include "LTKPreprocessor.h"
+#include "LTKLoggerUtil.h"
+
+/**
+ * This function creates the object of type LTKPreprocessor and returns the adderss
+ * of type LTKPreprocessorInterface ( base class of LTKPreprocessor).
+ *
+ * @return the address of the new object create of type LTKPreprocessorInterface.
+ */
+
+extern "C" PREPROCESSING_API int createPreprocInst(const LTKControlInfo& controlInfo,
+ LTKPreprocessorInterface** preprocPtr);
+
+
+/**
+ * This function destroys the object of type LTKPreprocessorInterface by taking
+ * address of the instance.
+ *
+ * @param Address of the destroying object of type LTKPreprocessorInterface.
+ */
+
+extern "C" PREPROCESSING_API void destroyPreprocInst(LTKPreprocessorInterface* p);
+
+#endif //#ifndef __PREPROCESSING_H_
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.pro
new file mode 100644
index 00000000..e8a11983
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/preprocessing/preprocessing.pro
@@ -0,0 +1,20 @@
+TARGET = preproc
+LIPILIBS = shaperecommon ltkcommon ltkutil
+include(../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../common \
+
+HEADERS += \
+ preprocessing.h \
+
+SOURCES += \
+ LTKPreprocessor.cpp \
+ preprocessing.cpp \
+
+win32 {
+ DEFINES += PREPROCESSING_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = preprocessing.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/shaperec.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/shaperec.pro
new file mode 100644
index 00000000..8b5d5e3b
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/shaperec/shaperec.pro
@@ -0,0 +1,14 @@
+TEMPLATE = subdirs
+
+SUBDIRS += \
+ common \
+ featureextractor \
+ activedtw \
+ neuralnet \
+ nn \
+ preprocessing
+
+activedtw.depends = common featureextractor
+neuralnet.depends = common featureextractor
+nn.depends = common featureextractor
+preprocessing.depends = common
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.cpp
new file mode 100644
index 00000000..dbcdca58
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.cpp
@@ -0,0 +1,1336 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE US E OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-02-08 16:57:52 +0530 (Tue, 08 Feb 2011) $
+ * $Revision: 834 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of BoxedFieldRecognizer
+ * CONTENTS:
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: March 23, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of
+ ************************************************************************/
+
+#include "BoxFieldRecognizer.h"
+#include "LTKLoggerUtil.h"
+#include "LTKTrace.h"
+#include "LTKInc.h"
+#include "LTKTypes.h"
+#include "LTKErrors.h"
+#include "LTKErrorsList.h"
+#include "LTKTraceGroup.h"
+#include "LTKWordRecoConfig.h"
+
+#include "LTKShapeRecognizer.h"
+#include "LTKRecognitionContext.h"
+
+#include "LTKScreenContext.h"
+#include "LTKCaptureDevice.h"
+#include "LTKConfigFileReader.h"
+#include "LTKMacros.h"
+#include "LTKStrEncoding.h"
+#include "LTKException.h"
+#include "LTKOSUtilFactory.h"
+#include "LTKOSUtil.h"
+#include "LTKStringUtil.h"
+
+#include <functional>
+
+extern void *m_hAlgoDLLHandle;
+
+
+
+/*****************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : initializeWordRecognizer
+* DESCRIPTION : Initialization of Boxed word Recognizer. This function performs
+* -Create & initialize shape recognizer
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*****************************************************************************/
+BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo& controlInfo)
+:LTKWordRecognizer(BOXFLD),
+m_shapeRecognizer(NULL),
+m_numShapeRecoResults(DEFAULT_SHAPE_RECO_CHOICES),
+m_shapeRecoMinConfidence(DEFAULT_SHAPE_RECO_MIN_CONFID),
+m_module_createShapeRecognizer(NULL),
+m_module_deleteShapeRecognizer(NULL),
+m_numCharsProcessed(0),
+m_numTracesProcessed(0),
+m_boxedShapeProject(""),
+m_boxedShapeProfile(""),
+m_lipiRoot(""),
+m_lipiLib(""),
+m_boxedConfigFile(""),
+m_logFile(""),
+m_logLevel(LTKLogger::LTK_LOGLEVEL_ERR),
+m_toolkitVersion(""),
+m_OSUtilPtr(LTKOSUtilFactory::getInstance())
+{
+
+ string boxedShapeProfile; //profile name
+
+ int errorCode = 0;
+
+ LTKControlInfo tempControlInfo = controlInfo;
+
+ if ( tempControlInfo.lipiRoot.empty() )
+ {
+ throw LTKException(ELIPI_ROOT_PATH_NOT_SET);
+ }
+
+ if ( tempControlInfo.projectName.empty() )
+ {
+ throw LTKException(EINVALID_PROJECT_NAME);
+ }
+
+ if( (tempControlInfo.profileName).empty() )
+ {
+ tempControlInfo.profileName = DEFAULT_PROFILE;
+ }
+
+ if ( tempControlInfo.toolkitVersion.empty() )
+ {
+ throw LTKException(ENO_TOOLKIT_VERSION);
+ }
+
+ // initialize the data members
+ m_lipiRoot = tempControlInfo.lipiRoot;
+ m_lipiLib = tempControlInfo.lipiLib;
+ m_toolkitVersion = tempControlInfo.toolkitVersion;
+
+
+ //constructing the boxed Config filename
+ m_boxedConfigFile = m_lipiRoot + PROJECTS_PATH_STRING +
+ tempControlInfo.projectName + PROFILE_PATH_STRING +
+ tempControlInfo.profileName + SEPARATOR + BOXFLD + CONFIGFILEEXT;
+
+ readClassifierConfig();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo& )"
+ <<endl;
+
+ //Creating the shape recognizer object
+ if((errorCode = createShapeRecognizer(m_boxedShapeProject, m_boxedShapeProfile,&m_shapeRecognizer)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo&)"<<endl;
+
+ throw LTKException(errorCode);
+ }
+
+ if(m_shapeRecognizer == NULL)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECREATE_SHAPEREC <<":"<< getErrorMessage(ECREATE_SHAPEREC)
+ <<" BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo&)" <<endl;
+
+ throw LTKException(ECREATE_SHAPEREC);
+ }
+
+ //loading the model data file
+ if( (errorCode = (m_shapeRecognizer->loadModelData())) != SUCCESS )
+ {
+ m_module_deleteShapeRecognizer(m_shapeRecognizer);
+ m_shapeRecognizer = NULL;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo&)"<<endl;
+
+ throw LTKException(errorCode);
+ }
+
+ m_numCharsProcessed = 0; //initializing number of characters processed
+ m_numTracesProcessed = 0; //initializing number of traces processed
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::BoxedFieldRecognizer(const LTKControlInfo&)"
+ <<endl;
+}
+
+/******************************************************************************
+ * AUTHOR : Nidhi Sharma
+ * DATE : 28-Sept-2007
+ * NAME : readClassifierConfig
+ * DESCRIPTION : Reads the boxfld.cfg and initializes the data members of the class
+ * ARGUMENTS : none
+ * RETURNS : SUCCESS - If config file read successfully
+ * errorCode - If failure
+ * NOTES :
+ * CHANGE HISTROY
+ * Author Date Description
+ ******************************************************************************/
+int BoxedFieldRecognizer::readClassifierConfig()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::readClassifierConfig"
+ <<endl;
+
+ LTKConfigFileReader* boxedFldConfigMap = NULL;
+ string cfgFileValue = "";
+ int errorCode = FAILURE;
+
+ try
+ {
+ boxedFldConfigMap = new LTKConfigFileReader(m_boxedConfigFile);
+ }
+ catch(LTKException fofe)
+ {
+ delete boxedFldConfigMap;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::readClassifierConfig"<<endl;
+
+ LTKReturnError(ECONFIG_FILE_OPEN); // Error while reading project.cfg
+ }
+
+ //initializing the number of shape recognition choices required from the file
+
+ errorCode = boxedFldConfigMap->getConfigValue(NUMSHAPECHOICES, cfgFileValue);
+
+ if ( errorCode == SUCCESS )
+ {
+ m_numShapeRecoResults = atoi(cfgFileValue.c_str());
+
+ if(m_numShapeRecoResults <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<" BoxedFieldRecognizer::readClassifierConfig" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"Assuming default value for number of shape recognizer choices:"
+ <<m_numShapeRecoResults<<endl;
+ }
+
+
+
+ //initializing the minimum confidence threshold
+
+ cfgFileValue = "";
+ errorCode = boxedFldConfigMap->getConfigValue(MINSHAPECONFID, cfgFileValue);
+
+ if ( errorCode == SUCCESS )
+ {
+ m_shapeRecoMinConfidence = LTKStringUtil::convertStringToFloat(cfgFileValue);
+
+ if(m_shapeRecoMinConfidence < 0 || m_shapeRecoMinConfidence > 1)
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_CONFIDENCE_VALUE <<":"<< getErrorMessage(EINVALID_CONFIDENCE_VALUE)
+ <<" BoxedFieldRecognizer::readClassifierConfig" <<endl;
+
+
+ LTKReturnError(EINVALID_CONFIDENCE_VALUE);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"Assuming default value for minimum shape recognizer confidence:"
+ <<m_shapeRecoMinConfidence<<endl;
+
+ }
+
+ //retrieving the boxed shape project and profile
+ cfgFileValue = "";
+ errorCode = boxedFldConfigMap->getConfigValue(BOXEDSHAPEPROJECT, cfgFileValue);
+
+ if ( errorCode == SUCCESS )
+ {
+ m_boxedShapeProject = cfgFileValue;
+
+ if(m_boxedShapeProject.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_PROJECT_NAME <<":"<< getErrorMessage(EINVALID_PROJECT_NAME)
+ <<" BoxedFieldRecognizer::readClassifierConfig" <<endl;
+
+ LTKReturnError(EINVALID_PROJECT_NAME);
+ }
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENO_SHAPE_RECO_PROJECT <<":"<< getErrorMessage(ENO_SHAPE_RECO_PROJECT)
+ <<" BoxedFieldRecognizer::readClassifierConfig" <<endl;
+
+ LTKReturnError(ENO_SHAPE_RECO_PROJECT);
+ }
+
+
+ //retrieving the boxed shape project and profile
+ cfgFileValue = "";
+ errorCode = boxedFldConfigMap->getConfigValue(BOXEDSHAPEPROFILE, cfgFileValue);
+
+ if( errorCode == SUCCESS )
+ {
+ m_boxedShapeProfile = cfgFileValue;
+
+ if(m_boxedShapeProfile.empty())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"No profile specified for shape recognizer project.Assuming 'default' profile"<<endl;
+
+ m_boxedShapeProfile = DEFAULT_PROFILE;
+ }
+
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ <<"No profile specified for shape recognizer project. Assuming 'default' profile"<<endl;
+
+ m_boxedShapeProfile = DEFAULT_PROFILE;
+
+ }
+
+ delete boxedFldConfigMap;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::readClassifierConfig"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/*****************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : processInk
+* DESCRIPTION : This method is called from recognition context whenever new traces
+* : are added to it. The Recognizer need to process the new traces
+* : in this methods and updates the internal state.
+* ARGUMENTS : rc - The recognition context for the current recognition
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+******************************************************************************/
+int BoxedFieldRecognizer::processInk (LTKRecognitionContext& rc)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::processInk"
+ <<endl;
+
+ string tempStr = REC_UNIT_INFO;
+
+ int tempFlagValue=0;
+
+ int errorCode=0;
+
+ if((errorCode=rc.getFlag(tempStr,tempFlagValue))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::processInk"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //give an error if the Ink is not segmented into characters
+ if(tempFlagValue != REC_UNIT_CHAR)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_SEGMENT <<":"<< getErrorMessage(EINVALID_SEGMENT)
+ <<" BoxedFieldRecognizer::processInk" <<endl;
+
+ LTKReturnError(EINVALID_SEGMENT);
+ }
+
+ tempStr = REC_MODE;
+
+
+ if((errorCode=rc.getFlag(tempStr,tempFlagValue))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::processInk"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //if the recognizer mode is correct
+ if (tempFlagValue == REC_MODE_STREAMING)
+ {
+ //recognize the newly added strokes
+ recognizeTraces(rc);
+ }
+ else
+ {
+ //give an error otherwise
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_REC_MODE <<":"<< getErrorMessage(EINVALID_REC_MODE)
+ <<" BoxedFieldRecognizer::processInk" <<endl;
+
+
+ LTKReturnError(EINVALID_REC_MODE);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::processInk"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : endRecoUnit
+* DESCRIPTION : This function notifies the recognizer that end of current ink is
+* : the end of a logic segment. This information could be used in
+* : constraining the recognizer choices
+* ARGUMENTS :
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+void BoxedFieldRecognizer::endRecoUnit ()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::endRecoUnit"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::endRecoUnit"
+ <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : recognize
+* DESCRIPTION : This is the recognize call
+* : The results of the recognition is set on the Recognition context
+* : object. In case of BATCH_MODE recognition recognition of every
+* : character is performed. otherwise the recognizer updates the outputs
+* : with the recognized results
+* ARGUMENTS : rc - The recognition context for the current recognition
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+int BoxedFieldRecognizer::recognize (LTKRecognitionContext& rc)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::recognize"
+ <<endl;
+
+ string tempStr = REC_UNIT_INFO; //temp string required to pass the arguments to set/get Flags
+
+ int tempFlagValue = 0; //temp int to hold flag values
+
+ int errorCode = 0;
+
+ vector <LTKWordRecoResult>::iterator resultIter,resultEnd; //iterates through decoded recognition results
+
+ int numWordRecoResults ; //Number of results required by the application
+
+ int resultIndex ; //index to iterate through the results
+
+ vector<unsigned short> resultString; //result
+
+ float normConf; //normalized confidence
+
+ //Returning FAILURE if the recognition context
+ //is not segmented into characters
+
+ if((errorCode=rc.getFlag(tempStr,tempFlagValue))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognize"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if( tempFlagValue != REC_UNIT_CHAR)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_SEGMENT <<":"<< getErrorMessage(EINVALID_SEGMENT)
+ <<" BoxedFieldRecognizer::recognize" <<endl;
+
+ LTKReturnError(EINVALID_SEGMENT);
+ }
+
+ tempStr =REC_MODE;
+
+ if((errorCode=rc.getFlag(tempStr,tempFlagValue))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognize"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(tempFlagValue == REC_MODE_BATCH)
+ {
+ //clear all the recognizer state
+ clearRecognizerState();
+ recognizeTraces(rc);
+ }
+ else if (tempFlagValue == REC_MODE_STREAMING)
+ {
+ recognizeTraces(rc);
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_REC_MODE <<":"<< getErrorMessage(EINVALID_REC_MODE)
+ <<" BoxedFieldRecognizer::recognize" <<endl;
+
+ LTKReturnError(EINVALID_REC_MODE);
+ }
+
+ /* Now all the recognized results are in
+ * m_decodedResults.
+ */
+
+ resultEnd = m_decodedResults.end();
+
+ for(resultIter = m_decodedResults.begin(); resultIter != resultEnd ; ++resultIter)
+ {
+ normConf = (*resultIter).getResultConfidence();
+
+ normConf /= ((*resultIter).getResultWord()).size();
+
+ (*resultIter).setResultConfidence(normConf);
+
+ }
+
+ //number of requested results
+ numWordRecoResults = rc.getNumResults();
+
+ //checking with existing recognition results' size
+ if(numWordRecoResults > m_decodedResults.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO)
+ << "Don't have enough results to populate. Num of results available = "
+ << m_decodedResults.size() <<", however, results asked for ="
+ << numWordRecoResults <<endl;
+ }
+
+ resultEnd = m_decodedResults.end();
+ for(resultIndex =0,resultIter = m_decodedResults.begin();(resultIndex <numWordRecoResults)&&(resultIter != resultEnd); ++resultIndex,++resultIter)
+ {
+ //map the shape ids to unicode IDs
+ if((errorCode = LTKStrEncoding::shapeStrToUnicode(m_boxedShapeProject,(*resultIter).getResultWord(),resultString)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognize"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ //adding the recognition result to recognition context
+ rc.addRecognitionResult(LTKWordRecoResult(resultString,
+ (*resultIter).getResultConfidence()));
+
+ resultString.clear();
+
+ }
+
+ //clearing state of the recognizer
+ clearRecognizerState();
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::recognize"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : recognize
+* DESCRIPTION : This method reset the recognizer
+* ARGUMENTS : resetParam - This parameter could specify what to reset
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+ int BoxedFieldRecognizer::reset (int resetParam)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::reset"<<endl;
+
+ clearRecognizerState();
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::reset"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : recognize
+* DESCRIPTION : This method reset the recognizer
+* ARGUMENTS : resetParam - This parameter could specify what to reset
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+ int BoxedFieldRecognizer::unloadModelData()
+{
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::unloadModelData"
+ <<endl;
+
+ //clear the recognition state
+ clearRecognizerState();
+
+ int errorCode=FAILURE;
+
+ //unload the model data and
+ //delete the shape recognizer
+ if( m_shapeRecognizer && (m_module_deleteShapeRecognizer != NULL) )
+ {
+
+ if((errorCode = m_shapeRecognizer->unloadModelData()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::unloadModelData"<<endl;
+
+
+ LTKReturnError(errorCode);
+ }
+
+ if((errorCode = m_module_deleteShapeRecognizer(m_shapeRecognizer)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::unloadModelData"<<endl;
+
+
+ LTKReturnError(errorCode);
+ }
+
+ m_shapeRecognizer = NULL;
+ }
+
+ //Freeing the shape recognition library
+ if(m_hAlgoDLLHandle)
+ {
+ m_OSUtilPtr->unloadSharedLib(m_hAlgoDLLHandle);
+ m_hAlgoDLLHandle = NULL;
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::unloadModelData"
+ <<endl;
+
+ return SUCCESS;
+}
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : ~BoxedFieldRecognizer
+* DESCRIPTION : destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+
+BoxedFieldRecognizer::~BoxedFieldRecognizer()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::~BoxedFieldRecognizer"
+ <<endl;
+
+ //unload the model data
+
+ int errorCode = FAILURE;
+ if((errorCode = unloadModelData()) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::~BoxedFieldRecognizer"<<endl;
+
+ throw LTKException(errorCode);
+ }
+
+ delete m_OSUtilPtr;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::~BoxedFieldRecognizer"
+ <<endl;
+
+
+}
+
+
+//PRIVATE FUNCTIONS
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : clearRecognizerState
+* DESCRIPTION : Erase the state information of the recognizer
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+
+void BoxedFieldRecognizer::clearRecognizerState()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::clearRecognizerState"
+ <<endl;
+
+ m_numCharsProcessed = 0; //initializing number of characters processed
+ m_numTracesProcessed = 0; //initializing number of traces processed
+ m_decodedResults.clear(); //clearing all the partially decoded results
+ m_boxedChar = LTKTraceGroup(); //assigning a new empty LTKTraceGroup
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::clearRecognizerState"
+ <<endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : recognizeTraces
+* DESCRIPTION : performs the recognition of the new strokes added to rc
+* : pre condition - markers are present in this vector
+* : - m_numTracesProcessed and m_numCharsProcessed
+* : set to proper value
+* ARGUMENTS : rc - The recognitino context
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+int BoxedFieldRecognizer::recognizeTraces(LTKRecognitionContext& rc )
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::recognizeTraces"
+ <<endl;
+
+ vector<LTKTrace>::const_iterator traceIter,traceEnd,traceBegin;
+ //iterator for the traces
+
+ int errorCode = FAILURE;
+
+ int recUnit; //unit for recognition (should be char)
+
+ LTKTraceGroup emptyChar;
+ //TraceGroup object that buffers
+ //all ink corresponding to a character
+
+ vector<int> subSet;
+ //passing a null arguement for shape subset
+
+ vector<LTKShapeRecoResult> shapeRecoResults;
+ //The object to hold the output from shape recognizer
+
+ LTKScreenContext screenContext = rc.getScreenContext();
+ //retrieving the screen context
+
+ LTKCaptureDevice captureDevice = rc.getDeviceContext();
+ //retrieving the device context
+
+ const LTKTraceVector & traces = rc.getAllInk();
+ //retrieving the traces from recognition context
+
+ string tempStr; //temporary string object
+
+
+ if(m_shapeRecognizer == NULL)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) <<"Shape recognizer not initialized" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER)
+ <<" BoxedFieldRecognizer::recognizeTraces" <<endl;
+
+ LTKReturnError(ENULL_POINTER);
+
+ }
+ else if( (errorCode = m_shapeRecognizer->setDeviceContext(captureDevice)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Unable to set device context in shape rec : " << getErrorMessage(errorCode) <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognizeTraces"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ shapeRecoResults.reserve(m_numShapeRecoResults+1);//reserving memory
+
+
+ if(m_numTracesProcessed > traces.size())
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Invalid number of traces processed. "
+ << "Traces processed = " << m_numTracesProcessed
+ << " > total number of traces" << traces.size() <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_NUM_OF_TRACES <<":"<< getErrorMessage(EINVALID_NUM_OF_TRACES)
+ <<" BoxedFieldRecognizer::recognizeTraces" <<endl;
+
+ LTKReturnError(EINVALID_NUM_OF_TRACES);
+ }
+ //Start processing from the number of traces processed.
+ traceBegin = traces.begin() + m_numTracesProcessed;
+ traceEnd = traces.end();int r=0;
+
+ for(traceIter = traceBegin; traceIter != traceEnd; ++traceIter)
+ {
+ /* Marker strokes are inserted to detect
+ * end of segment. The marker strokes are
+ * identified by 9number of channels == 0)
+ */
+ if((*traceIter).getNumberOfPoints() == 0)
+ {
+ tempStr = REC_UNIT_INFO;
+ if((errorCode = rc.getFlag(tempStr,recUnit)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognizeTraces"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+ switch(recUnit)
+ {
+
+ /* The segment is character
+ * This algorithm recognizes
+ * only character segments
+ */
+ case REC_UNIT_CHAR:
+ shapeRecoResults.clear();
+ //calling the shape recognizer's recognize method.
+
+ if(m_boxedChar.getNumTraces() == 0)
+ {
+ LTKShapeRecoResult T;
+ T.setShapeId(SHRT_MAX);
+ T.setConfidence(1.0);
+ shapeRecoResults.push_back(T);
+ }
+ else if( (errorCode = m_shapeRecognizer->recognize(m_boxedChar,screenContext,subSet,
+ m_shapeRecoMinConfidence, m_numShapeRecoResults, shapeRecoResults ))!= SUCCESS )
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Shape recognition failed : " << getErrorMessage(errorCode) <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognizeTraces"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+
+ //This updates the recognition results using
+ //current shape recognition results
+
+ if((errorCode = updateRecognitionResults(shapeRecoResults,rc)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::recognizeTraces"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ for(r=0;r<shapeRecoResults.size();++r)
+ {
+ LTKShapeRecoResult& tempResult=shapeRecoResults[r];
+
+ }
+
+ m_boxedChar = emptyChar;//making the trace group empty again
+ break;
+
+ default:
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Unsupported reccognizer mode by Box Field" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_RECOGNITION_MODE <<":"<< getErrorMessage(EINVALID_RECOGNITION_MODE)
+ <<" BoxedFieldRecognizer::recognizeTraces" <<endl;
+
+ LTKReturnError(EINVALID_RECOGNITION_MODE);
+
+ }
+ ++m_numCharsProcessed; //incrementing number of characters processed
+ }
+ else
+ {
+ m_boxedChar.addTrace(*traceIter); //buffering the trace to the temp TraceGroup for recognition
+ }
+ ++m_numTracesProcessed; //incrementing the number of traces processed
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::recognizeTraces"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-AUG-2005
+* NAME : updateRecognitionResults
+* DESCRIPTION : This function tries to update the
+* : shape recognition choices with new shape recognition results
+* ARGUMENTS : results - new results for updating the results
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+int BoxedFieldRecognizer::updateRecognitionResults(const vector<LTKShapeRecoResult>& results, LTKRecognitionContext& rc)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::updateRecognitionResults"
+ <<endl;
+
+ multimap< float, pair<int,int>, greater<float> >backTrace;
+ //A multi map is used for finding best N paths
+ multimap< float, pair<int,int>, greater<float> >::iterator iter, iterend;
+ //Iterator for accessing elements of the map
+ pair<int,int> combination;
+ //Temporary variable that keeps a (int,int) pair
+ int wordResultIndex, shapeResultIndex;
+ //loop index variables
+ float wordConfidence, shapeConfidence;
+ //word level and shape level confidences
+ unsigned short newSymbol;
+ //temporary storage for shape recognizer id
+ float newConf; //temporary storage for shape recognizer confidence
+
+ vector<LTKWordRecoResult> newResultVector;
+ //new results after finding the best N paths
+
+ int numWordRecoResults = rc.getNumResults();
+ //number of word recognition results requested
+ int numShapeRecoResults = results.size();
+ //number of choices from the shape recognizer
+ vector<unsigned short>initVec;
+ //for initializing the trellis
+
+
+
+ //If there is no decoded results (First shape recognition in the word)
+ if(m_decodedResults.empty())
+ {
+ //Initializing the results vector
+ m_decodedResults.assign(numShapeRecoResults,LTKWordRecoResult());
+
+ //iterating through different word recognition choices
+ for(wordResultIndex = 0; (wordResultIndex<numShapeRecoResults); ++wordResultIndex)
+ {
+ //Retrieving the shape recognition choices
+
+ newSymbol = results.at(wordResultIndex).getShapeId();
+ newConf = results.at(wordResultIndex).getConfidence();
+
+ //updating the results
+
+ initVec.assign(1,newSymbol);
+ m_decodedResults.at(wordResultIndex).setWordRecoResult(initVec,newConf);
+
+ }
+ }
+
+ else
+ {
+ //initializing a temporary result vector
+ //newResultVector.assign(smallerResultNumber,LTKWordRecoResult());
+
+ //iterating through each word recognition result
+ for(wordResultIndex=0; wordResultIndex<m_decodedResults.size(); ++wordResultIndex)
+ {
+ wordConfidence = (m_decodedResults.at(wordResultIndex)).getResultConfidence();
+
+ //iterating through each shape recognition results
+ for(shapeResultIndex =0; shapeResultIndex<numShapeRecoResults; ++shapeResultIndex )
+ {
+ //adding total confidence to the map. so that later they
+ //can be retrieved in the sorted order
+ shapeConfidence = (results.at(shapeResultIndex)).getConfidence();
+ backTrace.insert( pair<float, pair<int,int> >( (shapeConfidence+wordConfidence),
+ pair<int,int>(wordResultIndex,shapeResultIndex)));
+ }
+ }
+
+ iterend = backTrace.end();
+
+ //iterating through the map to retrieve the largest confidences.
+ for(wordResultIndex = 0,iter = backTrace.begin(); (wordResultIndex<numWordRecoResults)&&(iter!= iterend); ++wordResultIndex,++iter)
+ {
+
+ //confidence
+ wordConfidence = (*iter).first;
+
+ //the combination that gave this
+ //confidence
+ combination = (*iter).second;
+
+ //copying the word reco result corresponding to
+ //the combination to new result vector
+ //newResultVector.at(wordResultIndex) = m_decodedResults.at(combination.first);
+ LTKWordRecoResult tempWordRecoResult = m_decodedResults.at(combination.first);
+
+ //retrieving the shape recognition result id
+ //and confidence corresponding to the combination
+ newSymbol = results.at(combination.second).getShapeId();
+ newConf = results.at(combination.second).getConfidence();
+
+ //updating the word reco result with new id and confidence
+ //newResultVector.at(wordResultIndex).updateWordRecoResult(newSymbol, newConf);
+
+ tempWordRecoResult.updateWordRecoResult(newSymbol,newConf);
+ newResultVector.push_back(tempWordRecoResult);
+ }
+
+ //assigning the newly created result vector
+ m_decodedResults = newResultVector;
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::updateRecognitionResults"
+ <<endl;
+
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Thanigai
+* DATE : 29-JUL-2005
+* NAME : createShapeRecognizer
+* DESCRIPTION : create an instance of shape recognizer object and call initialize
+* function. Also loads the model data.
+* ARGUMENTS : strProjectName - project name; strProfileName - profile name
+* RETURNS : handle to the recognizer on success & NULL on error
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+ int BoxedFieldRecognizer::createShapeRecognizer(const string& strProjectName, const string& strProfileName,LTKShapeRecognizer** outShapeRecPtr)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::createShapeRecognizer"
+ <<endl;
+
+
+ LTKConfigFileReader* projectCfgFileEntries = NULL;
+ LTKConfigFileReader* profileCfgFileEntries = NULL;
+
+ string cfgFilePath = "";
+ string shapeRecDllPath = "";
+ int iResult = 0;
+ string recognizerName = "";
+ string strLocalProfileName(strProfileName);
+
+
+ /* invalid or no entry for project name */
+ if(strProjectName == "")
+ {
+
+ *outShapeRecPtr = NULL;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Invalid or no entry for project name" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_PROJECT_NAME <<":"<< getErrorMessage(EINVALID_PROJECT_NAME)
+ <<" BoxedFieldRecognizer::createShapeRecognizer" <<endl;
+
+ LTKReturnError(EINVALID_PROJECT_NAME);
+ }
+
+ if(strProfileName == "")
+ {
+ strLocalProfileName = DEFAULT_PROFILE; /* assume the "default" profile */
+ }
+
+ cfgFilePath = m_lipiRoot + PROJECTS_PATH_STRING + strProjectName +
+ PROFILE_PATH_STRING + PROJECT_CFG_STRING;
+
+ try
+ {
+ projectCfgFileEntries = new LTKConfigFileReader(cfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ delete projectCfgFileEntries;
+
+ *outShapeRecPtr = NULL; // Error exception thrown...
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::createShapeRecognizer"<<endl;
+
+ LTKReturnError(e.getErrorCode());
+
+
+ }
+
+ // Read the project.cfg and ensure this is a shaperecognizer; i.e. ProjectType = SHAPEREC;
+ string projectType = "";
+ projectCfgFileEntries->getConfigValue(PROJECT_TYPE_STRING, projectType);
+
+ /* Invalid configuration entry for ProjectType */
+ if(projectType != PROJECT_TYPE_SHAPEREC)
+ {
+ *outShapeRecPtr = NULL;
+
+ int errorCode = EINVALID_CONFIG_ENTRY;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EINVALID_CONFIG_ENTRY <<":"<< getErrorMessage(EINVALID_CONFIG_ENTRY)
+ <<" BoxedFieldRecognizer::createShapeRecognizer" <<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ // Read the profile.cfg and find out the recognition module to load;
+ cfgFilePath = m_lipiRoot + PROJECTS_PATH_STRING + strProjectName +
+ PROFILE_PATH_STRING + strLocalProfileName +
+ SEPARATOR + PROFILE_CFG_STRING;
+ try
+ {
+ profileCfgFileEntries = new LTKConfigFileReader(cfgFilePath);
+ }
+ catch(LTKException e)
+ {
+ *outShapeRecPtr = NULL;
+
+ delete profileCfgFileEntries;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::createShapeRecognizer"<<endl;
+
+ LTKReturnError(e.getErrorCode());
+
+ }
+
+ int errorCode = profileCfgFileEntries->getConfigValue(SHAPE_RECOGNIZER_STRING, recognizerName);
+
+ /* No recognizer specified. */
+ if(errorCode != SUCCESS)
+ {
+
+ *outShapeRecPtr = NULL;
+
+ errorCode = ENO_SHAPE_RECOGNIZER;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENO_SHAPE_RECOGNIZER <<":"<< getErrorMessage(ENO_SHAPE_RECOGNIZER)
+ <<" BoxedFieldRecognizer::createShapeRecognizer" <<endl;
+
+ delete projectCfgFileEntries;
+ delete profileCfgFileEntries;
+
+ LTKReturnError(errorCode);
+ }
+
+ m_hAlgoDLLHandle = NULL;
+ errorCode = m_OSUtilPtr->loadSharedLib(m_lipiLib, recognizerName, &m_hAlgoDLLHandle);
+
+ // Unable to load dll
+ if(errorCode != SUCCESS)
+ {
+ *outShapeRecPtr = NULL;
+
+ errorCode = ELOAD_SHAPEREC_DLL;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ELOAD_SHAPEREC_DLL <<":"<< getErrorMessage(ELOAD_SHAPEREC_DLL)
+ <<" BoxedFieldRecognizer::createShapeRecognizer" <<endl;
+
+ delete projectCfgFileEntries;
+ delete profileCfgFileEntries;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ // Map Algo DLL functions...
+
+ // Unable to map the functions
+ if((errorCode = mapShapeAlgoModuleFunctions()) != SUCCESS)
+ {
+ *outShapeRecPtr = NULL;
+ delete projectCfgFileEntries;
+ delete profileCfgFileEntries;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: BoxedFieldRecognizer::createShapeRecognizer"<<endl;
+
+ LTKReturnError(errorCode)
+ }
+
+ // Construct LTKControlInfo object
+ LTKControlInfo controlInfo;
+ controlInfo.projectName = strProjectName;
+ controlInfo.profileName = strLocalProfileName;
+ controlInfo.lipiRoot = m_lipiRoot;
+ controlInfo.lipiLib = m_lipiLib;
+ controlInfo.toolkitVersion = m_toolkitVersion;
+
+ *outShapeRecPtr = NULL;
+
+ /* Error, unable to create shape recognizer instance */
+ if((errorCode = m_module_createShapeRecognizer(controlInfo,outShapeRecPtr)) != SUCCESS)
+ {
+
+ *outShapeRecPtr = NULL;
+
+ delete projectCfgFileEntries;
+ delete profileCfgFileEntries;
+
+ errorCode = ECREATE_SHAPEREC;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ECREATE_SHAPEREC <<":"<< getErrorMessage(ECREATE_SHAPEREC)
+ <<" BoxedFieldRecognizer::createShapeRecognizer" <<endl;
+
+
+
+ LTKReturnError(errorCode);
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting BoxedFieldRecognizer::createShapeRecognizer" << endl;
+
+ delete projectCfgFileEntries;
+ delete profileCfgFileEntries;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::createShapeRecognizer"
+ <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Thanigai
+* DATE : 29-JUL-2005
+* NAME : mapShapeAlgoModuleFunctions
+* DESCRIPTION : To map function addresses of the methods exposed by
+* the shape recognition modules
+* ARGUMENTS : None
+* RETURNS : 0 on success and other values on error
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of
+*************************************************************************************/
+int BoxedFieldRecognizer::mapShapeAlgoModuleFunctions()
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Entering: BoxedFieldRecognizer::mapShapeAlgoModuleFunctions"
+ <<endl;
+
+ int returnVal = SUCCESS;
+ m_module_createShapeRecognizer = NULL;
+
+ void* functionHandle = NULL;
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_hAlgoDLLHandle,
+ CREATESHAPERECOGNIZER_FUNC_NAME,
+ &functionHandle);
+
+ if(returnVal != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Exported function not found in module : createShapeRecognizer "<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EDLL_FUNC_ADDRESS <<":"<< getErrorMessage(EDLL_FUNC_ADDRESS)
+ <<" BoxedFieldRecognizer::mapShapeAlgoModuleFunctions" <<endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS);
+ // ERROR: Unable to link with createShapeRecognizer function in module */
+ }
+
+ m_module_createShapeRecognizer = (FN_PTR_CREATESHAPERECOGNIZER)functionHandle;
+
+ functionHandle = NULL;
+
+
+ // map delete shape recognizer function
+ returnVal = m_OSUtilPtr->getFunctionAddress(m_hAlgoDLLHandle,
+ DELETESHAPERECOGNIZER_FUNC_NAME,
+ &functionHandle);
+
+ if(returnVal != SUCCESS)
+ {
+ LOG( LTKLogger::LTK_LOGLEVEL_ERR) <<
+ "Exported function not found in module : deleteShapeRecognizer " << endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EDLL_FUNC_ADDRESS <<":"<< getErrorMessage(EDLL_FUNC_ADDRESS)
+ <<" BoxedFieldRecognizer::mapShapeAlgoModuleFunctions" <<endl;
+
+ LTKReturnError(EDLL_FUNC_ADDRESS);
+ }
+
+ m_module_deleteShapeRecognizer = (FN_PTR_DELETESHAPERECOGNIZER)functionHandle;
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
+ <<"Exiting: BoxedFieldRecognizer::mapShapeAlgoModuleFunctions"
+ <<endl;
+
+ return SUCCESS;
+}
+
+
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.h
new file mode 100644
index 00000000..e0703b5a
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/BoxFieldRecognizer.h
@@ -0,0 +1,231 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+* THE SOFTWARE.
+******************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Definitions for DP word recognizer
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: August 17, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of
+ ************************************************************************/
+
+#ifndef __BOXFIELDRECOGNIZER_H
+#define __BOXFIELDRECOGNIZER_H
+
+#include "LTKWordRecognizer.h"
+#include "LTKLoggerUtil.h"
+#include "LTKWordRecoResult.h"
+#include "LTKShapeRecoResult.h"
+
+class LTKShapeRecognizer;
+class LTKWordRecoConfig;
+class LTKOSUtil;
+
+typedef int (*FN_PTR_CREATESHAPERECOGNIZER)(const LTKControlInfo&,
+ LTKShapeRecognizer**);
+
+typedef int (*FN_PTR_DELETESHAPERECOGNIZER)(LTKShapeRecognizer*);
+
+
+/**
+* @class BoxedFieldWordRecognizer
+* <p> This class contains the implementation of the Boxed Field
+* word recognizer</p>
+*/
+
+class BoxedFieldRecognizer : public LTKWordRecognizer
+{
+private:
+
+ /** Boxed Field Recognizer config file name */
+ string m_boxedConfigFile;
+
+ /** Lipi root */
+ string m_lipiRoot;
+
+ /** Lipi libraries */
+ string m_lipiLib;
+
+ /** Isolated shape recognizer project used for recognizing each box */
+ string m_boxedShapeProject;
+
+ /** Profile for the shape recognition project */
+ string m_boxedShapeProfile;
+
+ /**
+ * @name shape recognizer related
+ */
+
+ // @{
+ LTKShapeRecognizer *m_shapeRecognizer; // shape recognizer
+
+ /** Number of results from shape recognizer */
+ int m_numShapeRecoResults;
+
+ /** The confidence parameter input to shape recognizer */
+ float m_shapeRecoMinConfidence;
+
+ /** Temporary trace group that holds the strokes for recognition */
+ LTKTraceGroup m_boxedChar;
+
+ string m_logFile;
+
+ LTKLogger::EDebugLevel m_logLevel;
+
+ string m_toolkitVersion;
+
+ LTKOSUtil* m_OSUtilPtr;
+ // @}
+
+ /**
+ * @name Shape recognizer loading
+ */
+
+ /** Factory method to create the shape recognizer */
+ FN_PTR_CREATESHAPERECOGNIZER m_module_createShapeRecognizer;
+
+ /** Factory method to delete the shape recognizer */
+ FN_PTR_DELETESHAPERECOGNIZER m_module_deleteShapeRecognizer;
+
+ //void * m_hAlgoDLLHandle; //handle to the wordrecognition algorithm
+
+ /**
+ * @name state of recognizer
+ */
+ // @{
+
+ /** Number of characters processed so far */
+ int m_numCharsProcessed;
+
+ /** Number of traces processed so far */
+ int m_numTracesProcessed;
+
+ /** maintains decoded recognition results after each trace, upto max style length */
+ vector <LTKWordRecoResult> m_decodedResults;
+
+ // @}
+
+public:
+ /**
+ * @name Constructors and Destructor
+ */
+ // @{
+
+
+ /**
+ * Parameterized Constructor
+ */
+
+ BoxedFieldRecognizer(const LTKControlInfo& controlInfo);
+ /**
+ * Destructor
+ */
+
+ virtual ~BoxedFieldRecognizer();
+ // @}
+
+
+ /**
+ * This method is called from recognition context whenever new traces
+ * are added to it. The Recognizer need to process the new traces
+ * in this methods and updates the internal state.
+ * @param rc The recognition context for the current recognition
+ */
+ int processInk (LTKRecognitionContext& rc);
+
+ /**
+ * This function notifies the recognizer that end of current ink is
+ * the end of a logic segment. This information could be used in
+ * constraining the recognizer choices
+ */
+ void endRecoUnit () ;
+
+ /**
+ * This is the recognize call. In case of trace by trace recognition
+ * The results of the recognition is set on the Recognition context
+ * object.
+ * @param rc The recognition context for the current recognition
+ */
+ int recognize (LTKRecognitionContext& rc) ;
+
+ /**
+ * This method unloads all the training data
+ * To re-initialize the recognizer call the
+ * API initialize again
+ */
+ int unloadModelData();
+
+
+ /**
+ * This method reset the recognizer.
+ * @param resetParam This parameter could specify what to reset
+ */
+ int reset (int resetParam = 0) ;
+ // @}
+private:
+
+ /**
+ * performs the recognition of the new strokes added to recognition context
+ * @param rc The recognitino context
+ */
+
+ int recognizeTraces(LTKRecognitionContext& rc);
+
+ /**
+ * Erase the state information of the recognizer
+ */
+ void clearRecognizerState();
+
+ /**
+ * This function tries to update the
+ * shape recognition choices with new shape recognition results
+ * @param results New results for updating the results
+ */
+ int updateRecognitionResults(const vector<LTKShapeRecoResult>& results, LTKRecognitionContext& rc);
+
+ /**
+ * This function loads and create a shape recognizer
+ * from DLL/shared object
+ **/
+ int createShapeRecognizer(const string& strProjectName, const string& strProfileName,LTKShapeRecognizer** outShapeRecPtr);
+
+ /**
+ * This function loads functions pointers
+ * from the shape recognizer DLL/SO
+ **/
+ int mapShapeAlgoModuleFunctions();
+
+
+ int readClassifierConfig();
+
+};
+#endif //#ifndef __BOXFIELDRECOGNIZER_H
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cfg b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cfg
new file mode 100644
index 00000000..b727da97
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cfg
@@ -0,0 +1,13 @@
+#Number of characters per field
+MaxBoxCount = 30
+
+#The shaperecognizer project and profile name
+BoxedShapeProject = numerals
+BoxedShapeProfile = default
+
+#Min confidence from shape recognizer
+MinShapeConfid = 0
+
+#Number of choices requested from the shape recognizer
+NumShapeChoices = 3
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cpp
new file mode 100644
index 00000000..45969652
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.cpp
@@ -0,0 +1,129 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2011-01-11 13:48:17 +0530 (Tue, 11 Jan 2011) $
+ * $Revision: 827 $
+ * $Author: mnab $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of boxfld dll exported functions.
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: Aug 23, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of
+ ************************************************************************/
+#include "boxfld.h"
+#include "LTKMacros.h"
+#include "LTKException.h"
+
+
+#ifdef _WIN32
+
+//DLL MAIN for Windows
+BOOL APIENTRY DllMain( HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved
+ )
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
+
+#endif
+
+/**********************************************************************************
+* AUTHOR : Deepu V
+* DATE : 23-Aug-2005
+* NAME : createWordRecognizer
+* DESCRIPTION : Crates instance of type BoxField Recongnizer and retuns of type
+ LTKWordRecongizer. (Acts as a Factory Method).
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKWordRecoginzer.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description of
+*************************************************************************************/
+int createWordRecognizer(const LTKControlInfo& controlInfo,LTKWordRecognizer** boxFldRecoPtr)
+{
+
+ try
+ {
+ *boxFldRecoPtr = (LTKWordRecognizer*) new BoxedFieldRecognizer(controlInfo);
+ }
+ catch(LTKException e)
+ {
+ *boxFldRecoPtr = NULL;
+ LTKReturnError(e.getErrorCode());
+ }
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V
+* DATE : 23-Aug-2005
+* NAME : deleteWordRecognizer
+* DESCRIPTION :
+* ARGUMENTS :
+* RETURNS : returns an instace of type LTKWordRecoginzer.
+* NOTES :
+* CHANGE HISTORY
+* Author Date Description of
+*************************************************************************************/
+//Destroys the instance by taking its addess as its argument.
+int deleteWordRecognizer(LTKWordRecognizer* obj)
+{
+ /*delete obj;
+
+ obj = NULL;
+
+ return SUCCESS;*/
+
+ try
+ {
+ if (obj != NULL )
+ {
+ delete obj;
+ obj = NULL;
+ }
+ }
+ catch(LTKException e)
+ {
+ LTKReturnError(e.getErrorCode());
+ }
+
+
+ return SUCCESS;
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.def b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.def
new file mode 100644
index 00000000..452b6dd6
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.def
@@ -0,0 +1,3 @@
+EXPORTS
+ createWordRecognizer @1
+ deleteWordRecognizer @2
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.h b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.h
new file mode 100644
index 00000000..f44d2ab3
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.h
@@ -0,0 +1,90 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate: 2008-07-18 15:00:39 +0530 (Fri, 18 Jul 2008) $
+ * $Revision: 561 $
+ * $Author: sharmnid $
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Definitions for boxfld dll exporting functions.
+ *
+ * CONTENTS:
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: Aug 23, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of
+ ************************************************************************/
+#ifndef __BOXFLD_H__
+#define __BOXFLD_H__
+
+#ifdef _WIN32
+#include <windows.h>
+// The following ifdef block is the standard way of creating macros which make exporting
+// from a DLL simpler. All files within this DLL are compiled with the DTW_EXPORTS
+// symbol defined on the command line. this symbol should not be defined on any project
+// that uses this DLL. This way any other project whose source files include this file see
+// DTW_API functions as being imported from a DLL, wheras this DLL sees symbols
+// defined with this macro as being exported.
+#ifdef BOXFLD_EXPORTS
+#define BOXFLD_API __declspec(dllexport)
+#else
+#define BOXFLD_API __declspec(dllimport)
+#endif
+#else
+#define BOXFLD_API
+#endif //#ifdef _WIN32
+
+
+#include "LTKWordRecognizer.h"
+#include "BoxFieldRecognizer.h"
+#include "LTKLoggerUtil.h"
+#include "LTKErrors.h"
+
+void *m_hAlgoDLLHandle;
+
+/**
+ * Crates instance of type PCAShaperecongnizer and retuns of type
+ * LTKShpeRecongizer. (Acts as a Factory Method).
+ *
+ * @param void - No argument
+ *
+ * @return LTKShapeRecognizer - an instace of type LTKShapeRecoginzer.
+ */
+
+//Creates Instance of the Box Field recognizer and returns base class (LTKWordRecognizer) pointer
+extern "C" BOXFLD_API int createWordRecognizer(const LTKControlInfo& controlInfo,LTKWordRecognizer** boxFldRecoPtr);
+
+/**
+ * Destry the instance by taking the address as its argument.
+ *
+ * @param obj - Address of LTKShapeRecognizer instnace.
+ *
+ * @return 0 on Success
+ */
+
+//Destroys the instance by taking its addess as its argument.
+extern "C" BOXFLD_API int deleteWordRecognizer(LTKWordRecognizer* obj);
+
+#endif //#ifndef __BOXFLD_H__
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.pro
new file mode 100644
index 00000000..5d16d041
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/boxfld/boxfld.pro
@@ -0,0 +1,20 @@
+LIPILIBS = shaperecommon ltkcommon ltkutil wordreccommon
+include(../../../lipiplugin.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+ ../common \
+
+HEADERS += \
+ BoxFieldRecognizer.h \
+ boxfld.h \
+
+SOURCES += \
+ BoxFieldRecognizer.cpp \
+ boxfld.cpp \
+
+win32 {
+ DEFINES += BOXFLD_EXPORTS
+ LIBS += Advapi32.lib
+ #DEF_FILE = boxfld.def
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKRecognitionContext.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKRecognitionContext.cpp
new file mode 100644
index 00000000..4fc45305
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKRecognitionContext.cpp
@@ -0,0 +1,1065 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate$
+ * $Revision$
+ * $Author$
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of LTKRecognitionContext that holds the context
+ * for recognition
+ *
+ * CONTENTS:
+ * addTrace
+ * addTraceGroup
+ * beginRecoUnit
+ * endRecoUnit
+ * getAllInk
+ * getConfidThreshold
+ * getDeviceContext
+ * getFlag
+ * getLanguageModel
+ * getNextBestResults
+ * getNumResults
+ * getScreenContext
+ * getTopResult
+ * setConfidThreshold
+ * setDeviceContext
+ * setFlag
+ * setLanguageModel
+ * setNumResults
+ * setScreenContext
+ * addRecognitionResult
+ * recognize
+ * reset
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: February 22, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ * Thanigai 3-AUG-2005 Added default constructor and setWordRecoEngine
+ * methods.
+ *
+ * Deepu 30-AUG-2005 Replaced LTKWordRecoEngine with LTKWordRecognizer
+ * Changed the representation of m_recognitionFlags
+ * since there was a problem with dlls
+************************************************************************/
+
+#include "LTKRecognitionContext.h"
+#include "LTKMacros.h"
+#include "LTKErrors.h"
+#include "LTKTrace.h"
+
+#include "LTKErrorsList.h"
+
+#include "LTKTraceGroup.h"
+
+#include "LTKWordRecoResult.h"
+
+#include "LTKWordRecognizer.h"
+
+#include "LTKLoggerUtil.h"
+
+#include "LTKException.h"
+
+/**********************************************************************************
+* AUTHOR : Thanigai
+* DATE : 3-AUG-2005
+* NAME : LTKRecognitionContext
+* DESCRIPTION : Default constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKRecognitionContext::LTKRecognitionContext()
+:m_confidThreshold(0),
+m_numResults(0),
+m_nextBestResultIndex(0),
+m_wordRecPtr(NULL)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::LTKRecognitionContext()" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::LTKRecognitionContext()" << endl;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-FEB-2005
+* NAME : LTKRecognitionContext
+* DESCRIPTION : Initialization constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer *wordRecPtr )
+:m_wordRecPtr(wordRecPtr),
+m_confidThreshold(0),
+m_numResults(0),
+m_nextBestResultIndex(0)
+
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" << endl;
+
+ if(m_wordRecPtr == NULL)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER)
+ <<" LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" <<endl;
+
+ throw LTKException(ENULL_POINTER);
+ }
+
+ m_recognitionFlags.clear();
+ m_wordRecPtr = wordRecPtr;
+
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::LTKRecognitionContext(LTKWordRecognizer*)" << endl;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : Thanigai
+* DATE : 3-AUG-2005
+* NAME : setWordRecoEngine
+* DESCRIPTION : Accepts the handle to word recognition engine and store it locally
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::setWordRecoEngine(LTKWordRecognizer *wordRecPtr)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setWordRecoEngine()" << endl;
+
+ if(wordRecPtr == NULL)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER)
+ <<" LTKRecognitionContext::setWordRecoEngine()" <<endl;
+
+ LTKReturnError(ENULL_POINTER);
+ }
+ m_wordRecPtr = wordRecPtr;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setWordRecoEngine()" << endl;
+
+ return SUCCESS;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-FEB-2005
+* NAME : addTrace
+* DESCRIPTION : This function adds a trace to the recognition context for
+* recognition
+* ARGUMENTS : trace - the trace to be added
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::addTrace (const LTKTrace& trace)
+{
+ int recMode; //strokes temporary string for getFlag
+ string tempStr; // the recognition mode
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::addTrace()" << endl;
+
+
+ m_fieldInk.push_back(trace); //pushing incoming trace to local buffer
+
+ //if the recognition mode is set to streaming mode
+ //the recognizer is called at this point
+
+ tempStr = REC_MODE;
+
+ int errorCode;
+
+ if((errorCode = getFlag(tempStr,recMode))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKRecognitionContext::addTrace()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(recMode == REC_MODE_STREAMING)
+ {
+ m_wordRecPtr->processInk(*this);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::addTrace()" << endl;
+
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-FEB-2005
+* NAME : addTraceGroup
+* DESCRIPTION : Adds a vector of tracegroup for recognition in the recognition context
+* ARGUMENTS : fieldInk - the ink to be added.
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::addTraceGroups (const LTKTraceGroupVector& fieldInk)
+{
+ int numTraceGroups = fieldInk.size(); //number of trace groups
+ int numTraces =0; //number of traces in each trace group
+ string tempStr; //strokes temporary string for getFlag
+ int recMode =0; // the recognition mode
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::addTraceGroups()" << endl;
+
+ for(int i =0; i<numTraceGroups; ++i)
+ {
+ //accessing each trace group
+ const LTKTraceGroup& traceGp = fieldInk[i];
+
+ //get all traces from tracegp
+ //const LTKTraceVector& allTraces = traceGp.getAllTraces();
+ const LTKTraceVector& allTraces = traceGp.getAllTraces();
+
+ //push each trace to local buffer
+ numTraces = allTraces.size();
+
+ for(int j = 0; j<numTraces; ++j)
+ {
+ m_fieldInk.push_back(allTraces[j]);
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_INFO) << "Pushed Trace Group:"<<i<<endl;
+
+ }
+
+ //if the recognition mode is set to streaming mode
+ //the recognizer is called at this point
+ tempStr = REC_MODE;
+
+ int errorCode;
+
+ if((errorCode = getFlag(tempStr,recMode))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKRecognitionContext::addTraceGroups()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ if(recMode == REC_MODE_STREAMING)
+ {
+ m_wordRecPtr->processInk(*this);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::addTraceGroups()" << endl;
+
+
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : beginRecoUnit
+* DESCRIPTION : This function marks the beginning of a recognition unit of Ink.
+* ARGUMENTS : none
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKRecognitionContext::beginRecoUnit ( )
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::beginRecoUnit()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::beginRecoUnit()" << endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : clearRecognitionResult
+* DESCRIPTION : clears all the recognition results
+* ARGUMENTS : none
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::clearRecognitionResult ( )
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::clearRecognitionResult()" << endl;
+
+ //clearing the results
+ m_results.clear();
+
+ //reset the index of next best result
+ m_nextBestResultIndex = 0;
+
+ m_fieldInk.clear();
+
+ int errorCode;
+
+ if((errorCode=m_wordRecPtr->reset())!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKRecognitionContext::clearRecognitionResult()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::clearRecognitionResult()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : endRecoUnit
+* DESCRIPTION : This function marks the ending of a recognition unit of Ink.
+* ARGUMENTS : none
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+void LTKRecognitionContext::endRecoUnit ( )
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::endRecoUnit()" << endl;
+
+ //pushing a "marker" into the stream
+ m_fieldInk.push_back(LTKTrace());
+
+ //calling the marker of the recognizer
+ m_wordRecPtr->endRecoUnit();
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::endRecoUnit()" << endl;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getAllInk
+* DESCRIPTION : Access function for the internal Ink data.
+* ARGUMENTS : none
+* RETURNS : reference to internal Ink data
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const LTKTraceVector& LTKRecognitionContext::getAllInk () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getAllInk()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getAllInk()" << endl;
+
+ return m_fieldInk;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getConfidThreshold
+* DESCRIPTION : Access function for internal confidence threshold
+* ARGUMENTS : none
+* RETURNS : confidence threshold
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float LTKRecognitionContext::getConfidThreshold () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getConfidThreshold()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getConfidThreshold()" << endl;
+
+ return m_confidThreshold;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getDeviceContext
+* DESCRIPTION : Access function for device context
+* ARGUMENTS : none
+* RETURNS : reference to LTKCapture device
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const LTKCaptureDevice& LTKRecognitionContext::getDeviceContext ( ) const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getDeviceContext()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getDeviceContext()" << endl;
+
+ return m_deviceContext;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getFlag
+* DESCRIPTION : Returns the value of the flag
+* ARGUMENTS : key - index of map
+* RETURNS : value of queried flag (int)
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKRecognitionContext::getFlag (const string& key,int& outValue) const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getFlag()" << endl;
+
+ if(key=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKRecognitionContext::getFlag()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ vector<pair<string,int> >::const_iterator iter,iterEnd;
+
+ iterEnd = m_recognitionFlags.end();
+
+ //Iterating through the vector to find the key
+ for(iter = m_recognitionFlags.begin(); iter != iterEnd; ++iter)
+ {
+ if( (*iter).first == key )
+ {
+ outValue = (*iter).second;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getFlag()" << endl;
+
+ return SUCCESS;
+ }
+ }
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EKEY_NOT_FOUND <<":"<< getErrorMessage(EKEY_NOT_FOUND)
+ <<" LTKRecognitionContext::getFlag()" <<endl;
+
+ LTKReturnError(EKEY_NOT_FOUND);
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getLanguageModel
+* DESCRIPTION : returns the current language model indexed by the key
+* ARGUMENTS : key - index of map
+* RETURNS : value of the queried language model (string)
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKRecognitionContext::getLanguageModel (const string& key,
+ string& outValue) const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getLanguageModel()" << endl;
+
+ if(key=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKRecognitionContext::getLanguageModel()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+
+ stringStringMap::const_iterator iterMap;
+
+ iterMap = this->m_languageModels.find(key);
+
+ if(iterMap != m_languageModels.end() )
+ {
+ outValue = iterMap->second;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getLanguageModel()" << endl;
+ return SUCCESS;
+ }
+
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EKEY_NOT_FOUND <<":"<< getErrorMessage(EKEY_NOT_FOUND)
+ <<" LTKRecognitionContext::getLanguageModel()" <<endl;
+
+ LTKReturnError(EKEY_NOT_FOUND);
+
+
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getNextBestResults
+* DESCRIPTION : returns the next N best results
+* ARGUMENTS : numResults - number of results required
+* : results - This will be populated with results
+* RETURNS : SUCCESS/FAILURE
+* NOTES : Maximum number of results added is limited by number of results
+* : available.
+* : vector is not cleared inside the function
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::getNextBestResults (int numResults,
+ LTKWordRecoResultVector& outWordRecResults)
+{
+ int lastIndex = 0;//Last index
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getNextBestResults()" << endl;
+
+ if(numResults<=0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"<< getErrorMessage(ENON_POSITIVE_NUM)
+ <<" LTKRecognitionContext::getNextBestResults()" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+
+ vector<LTKWordRecoResult>::const_iterator resultBegin, resultEnd, resultIter;
+
+ //Finding index of requested results
+ resultBegin = m_results.begin() + m_nextBestResultIndex;
+
+ //Finding index of requested results
+ resultEnd = m_results.begin() + m_nextBestResultIndex + numResults;
+
+ if(resultBegin > resultEnd
+)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ "Exiting LTKRecognitionContext::getNextBestResults" <<endl;
+
+ return SUCCESS;
+ }
+
+ //limiting the end to the limits of available results
+ if(resultEnd > m_results.end() )
+ resultEnd = m_results.end();
+
+ //pushing back the results
+ for(resultIter = resultBegin; resultIter< resultEnd; ++resultIter)
+ {
+ outWordRecResults.push_back(*resultIter);
+ }
+
+ //updating next best result index
+ m_nextBestResultIndex += numResults;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getNextBestResults()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getNumResults
+* DESCRIPTION : parameter number of results
+* ARGUMENTS : none
+* RETURNS : number of results (int)
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKRecognitionContext::getNumResults () const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getNumResults()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getNumResults()" << endl;
+
+ return m_numResults;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getScreenContext
+* DESCRIPTION : access function for the screen context
+* ARGUMENTS : none
+* RETURNS : reference to screencontext object
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const LTKScreenContext& LTKRecognitionContext::getScreenContext ( ) const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getScreenContext()" << endl;
+
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getScreenContext()" << endl;
+
+ return m_screenContext;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : getTopResult
+* DESCRIPTION : get the top result from the recognition context
+* ARGUMENTS : result - will be assigned to the top recognition result
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::getTopResult (LTKWordRecoResult& outTopResult)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::getTopResult()" << endl;
+
+ if(m_results.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_WORDREC_RESULTS <<":"<< getErrorMessage(EEMPTY_WORDREC_RESULTS)
+ <<" LTKRecognitionContext::getTopResult()" <<endl;
+
+ LTKReturnError(EEMPTY_WORDREC_RESULTS);
+ }
+
+ m_nextBestResultIndex = 1;
+
+ //assigning the value to output
+ outTopResult = m_results[0];
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::getTopResult()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setConfidThreshold
+* DESCRIPTION : set the confidence threshold
+* ARGUMENTS : thresh - the threshold value to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::setConfidThreshold (float thresh)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setConfidThreshold()" << endl;
+
+ if(thresh < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"
+ << getErrorMessage(ENEGATIVE_NUM)
+ <<" LTKRecognitionContext::setConfidThreshold()" <<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+ }
+
+ m_confidThreshold = thresh;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setConfidThreshold()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setDeviceContext
+* DESCRIPTION : set the device context
+* ARGUMENTS : dc - reference to device context object to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKRecognitionContext::setDeviceContext (const LTKCaptureDevice& dc)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setDeviceContext()" << endl;
+
+ m_deviceContext = dc;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setDeviceContext()" << endl;
+
+
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setFlag
+* DESCRIPTION : sets the flag
+* ARGUMENTS : key - index of the flag to be set
+* : value - value of the flag to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKRecognitionContext::setFlag (const string& key, int value)
+{
+ vector<pair<string,int> >::iterator iter,iterEnd;//iterators for iterating through all flags
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setFlag()" << endl;
+
+ if(key=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKRecognitionContext::setFlag()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ iterEnd = m_recognitionFlags.end();
+
+ //looping through the map to check whether the flag exists
+ for(iter = m_recognitionFlags.begin(); iter != iterEnd; ++iter)
+ {
+ if((*iter).first == key)
+ {
+ (*iter).second = value;
+ break;
+ }
+ }
+
+ //if the flag is not there in the map add a new flag
+ if((iter == iterEnd)||(m_recognitionFlags.empty()) )
+ {
+ m_recognitionFlags.push_back(pair<string,int>(key,value));
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setFlag()" << endl;
+
+ return SUCCESS;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setLanguageModel
+* DESCRIPTION : sets the language model
+* ARGUMENTS : property - name of ppty to be set (DICTIONARY, GRAMMAR)
+* : value - value to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::setLanguageModel (const string& property, const string& value)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setLanguageModel()" << endl;
+
+ if(property=="" || value=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<
+ "Either property or value is empty"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKRecognitionContext::setLanguageModel()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ m_languageModels [property] = value;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setLanguageModel()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setNumResults
+* DESCRIPTION : sets parameter number of results to be buffered from recognizer
+* ARGUMENTS : numResults - the value to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKRecognitionContext::setNumResults (int numResults)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setNumResults()" << endl;
+
+ if(numResults <= 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENON_POSITIVE_NUM <<":"
+ << getErrorMessage(ENON_POSITIVE_NUM)
+ <<" LTKRecognitionContext::setNumResults()" <<endl;
+
+ LTKReturnError(ENON_POSITIVE_NUM);
+ }
+
+ m_numResults = numResults;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setNumResults()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : setScreenContext
+* DESCRIPTION : sc - reference to the screencontext object to be set
+* ARGUMENTS : numResults - the value to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKRecognitionContext::setScreenContext (const LTKScreenContext& sc)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::setScreenContext()" << endl;
+
+ m_screenContext = sc;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::setScreenContext()" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : addRecognitionResult
+* DESCRIPTION : used by the recognizer to set the results back in the recognition context
+* ARGUMENTS : result - the value to be added
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+void LTKRecognitionContext::addRecognitionResult (const LTKWordRecoResult& result)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::addRecognitionResult()" << endl;
+
+ //adding the result to the internal data structure
+ m_results.push_back(result);
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::addRecognitionResult()" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : recognize
+* DESCRIPTION : the recognize call from the application.
+* : calls the recognize emthod of the recognizer
+* ARGUMENTS : numResults - the value to be set
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKRecognitionContext::recognize ()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::recognize()" << endl;
+
+ int errorCode;
+
+ //calling recognize method of the recognizer
+ if(m_wordRecPtr!=NULL)
+ {
+ if( (errorCode = m_wordRecPtr->recognize(*this)) != SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKRecognitionContext::recognize()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ }
+ else
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Recognizer is not initialized" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENULL_POINTER <<":"<< getErrorMessage(ENULL_POINTER)
+ <<" LTKRecognitionContext::recognize()" <<endl;
+
+
+ LTKReturnError(ENULL_POINTER);
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::recognize()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 28-FEB-2005
+* NAME : reset
+* DESCRIPTION : Reset various parameters.
+* ARGUMENTS : resetParam - specifies data to be rest
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+/**
+* This function is used to reset the different components of recognition context
+* @param resetParam : parameter that identifies the component to be reset
+* @return SUCCESS/FAILURE
+*/
+int LTKRecognitionContext::reset (int resetParam)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKRecognitionContext::reset()" << endl;
+
+ if(resetParam & LTK_RST_INK)
+ {
+ m_fieldInk.clear();
+ }
+
+ if(resetParam & LTK_RST_RECOGNIZER)
+ {
+ int errorCode=0;
+
+ if((errorCode=m_wordRecPtr->reset(resetParam))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKRecognitionContext::reset()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+ }
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKRecognitionContext::reset()" << endl;
+
+ return SUCCESS;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 22-FEB-2005
+* NAME : LTKRecognitionContext
+* DESCRIPTION : Destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKRecognitionContext::~LTKRecognitionContext()
+{
+
+}
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoConfig.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoConfig.cpp
new file mode 100644
index 00000000..57fc6317
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoConfig.cpp
@@ -0,0 +1,477 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate$
+ * $Revision$
+ * $Author$
+ *
+ ************************************************************************/
+
+/************************************************************************
+ * FILE DESCR: Definition of LTKWordRecoConfig holds the config data for
+ * the recognizer at the time of loading.
+ *
+ * CONTENTS:
+ * getClassifierName
+ * getDictionaryPath
+ * getLipiRoot
+ * getNumClasses
+ * getProfile
+ * getScript
+ * getShapeSet
+ * readConfigFile
+ * setLipiRoot
+ *
+ * AUTHOR: Mudit Agrawal.
+ *
+ * DATE: Mar 2, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ * Deepu 24-MAR-2005 Added getGrammarPath
+ ************************************************************************/
+
+
+#include "LTKWordRecoConfig.h"
+
+#include "LTKMacros.h"
+
+#include "LTKErrors.h"
+
+#include "LTKErrorsList.h"
+
+#include "LTKException.h"
+
+#include "LTKLoggerUtil.h"
+
+#include "LTKConfigFileReader.h"
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 01-MAR-2005
+* NAME : LTKWordRecoConfig
+* DESCRIPTION : DEFAULT CONSTRUCTOR
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+LTKWordRecoConfig::LTKWordRecoConfig()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoConfig::LTKWordRecoConfig()" << endl;
+ m_lipiRoot = "";
+ m_problemName = "";
+ m_profile = "";
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoConfig::LTKWordRecoConfig()" << endl;
+
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : LTKWordRecoConfig
+* DESCRIPTION : Initialization Constructor
+* ARGUMENTS : lipiRoot
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+LTKWordRecoConfig::LTKWordRecoConfig(const string& lipiRoot)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoConfig::LTKWordRecoConfig(const string&)" << endl;
+
+ if(lipiRoot=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKWordRecoConfig::LTKWordRecoConfig(const string&)" <<endl;
+
+ throw LTKException(EEMPTY_STRING);
+ }
+
+ m_lipiRoot = lipiRoot;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "m_lipiRoot = " << m_lipiRoot <<endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoConfig::LTKWordRecoConfig(const string&)" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getClassifierName
+* DESCRIPTION : This function returns the classifier name
+* ARGUMENTS : none
+* RETURNS : returns the classifier name
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+string LTKWordRecoConfig::getClassifierName() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::getClassifierName()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getClassifierName()" <<endl;
+
+ return m_classifierName;
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getDictionaryPath
+* DESCRIPTION : This function returns the Dictionary Path
+* ARGUMENTS : none
+* RETURNS : returns the Dictionary Path
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+string LTKWordRecoConfig::getDictionaryPath() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entered: LTKWordRecoConfig::getDictionaryPath()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getDictionaryPath()" <<endl;
+
+ return m_dictionaryPath;
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getDictionaryPath
+* DESCRIPTION : This function returns the Dictionary Path
+* ARGUMENTS : none
+* RETURNS : returns the Dictionary Path
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+string LTKWordRecoConfig::getGrammarPath() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entered: LTKWordRecoConfig::getGrammarPath()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getGrammarPath()" <<endl;
+
+ return m_grammarPath;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getLipiRoot
+* DESCRIPTION : This function returns the lipi root
+* ARGUMENTS : none
+* RETURNS : returns the lipi root
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+string LTKWordRecoConfig::getLipiRoot() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::getLipiRoot()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getLipiRoot()" <<endl;
+
+ return m_lipiRoot;
+}
+
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getProfile
+* DESCRIPTION : This function returns the profile
+* ARGUMENTS : none
+* RETURNS : returns the profile
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+string LTKWordRecoConfig::getProfile() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::getProfile()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getProfile()" <<endl;
+
+ return m_profile;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : getScript
+* DESCRIPTION : This function returns the script
+* ARGUMENTS : none
+* RETURNS : returns the script
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+string LTKWordRecoConfig::getScript() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::getScript()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getScript()" <<endl;
+
+ return m_script;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 23-MAR-2005
+* NAME : getProblemName
+* DESCRIPTION : returns the problem name
+* ARGUMENTS : none
+* RETURNS : returns the problem name
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+string LTKWordRecoConfig::getProblemName() const
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::getProblemName()" <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::getProblemName()" <<endl;
+
+ return m_problemName;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : setLipiRoot
+* DESCRIPTION : sets the lipiRoot
+* ARGUMENTS : none
+* RETURNS : SUCCEESS on successful set operation
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKWordRecoConfig::setLipiRoot(const string& lipiRoot)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::setLipiRoot()" <<endl;
+
+ if(lipiRoot=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKWordRecoConfig::LTKWordRecoConfig(const string&)" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ this->m_lipiRoot = lipiRoot;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "m_lipiRoot = " << m_lipiRoot <<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::setLipiRoot()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : readConfigFile
+* DESCRIPTION : reads the main config file and inturn other config files also (defined in main.cfg)
+* ARGUMENTS : none
+* RETURNS : SUCCESS on successful reads
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKWordRecoConfig::readConfigFile(const string& configFileName)
+{
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering: LTKWordRecoConfig::readConfigFile()" <<endl;
+
+ LTKConfigFileReader* cfgFileMap;
+
+ try
+ {
+ cfgFileMap= new LTKConfigFileReader(configFileName);
+
+ }
+ catch(LTKException e)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(e.getErrorCode());
+
+ }
+
+ int errorCode = 0;
+
+ if((errorCode=cfgFileMap->getConfigValue("script", m_script))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ if((errorCode=cfgFileMap->getConfigValue("problem", m_problemName))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ if(m_problemName=="")
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"problem string is empty"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKWordRecoConfig::readConfigFile()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ if((errorCode=cfgFileMap->getConfigValue("profile", m_profile))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+
+ if(m_profile=="")
+ {
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"profile string is empty"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKWordRecoConfig::readConfigFile()" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ if((errorCode=cfgFileMap->getConfigValue("dictmap", m_dictionaryPath))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ if((errorCode=cfgFileMap->getConfigValue("grammarmap", m_grammarPath))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+
+ }
+
+ if(m_lipiRoot=="")
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Lipiroot is empty"<<endl;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_STRING <<":"<< getErrorMessage(EEMPTY_STRING)
+ <<" LTKWordRecoConfig::LTKWordRecoConfig(const string&)" <<endl;
+
+ LTKReturnError(EEMPTY_STRING);
+ }
+
+ cfgFileMap = new LTKConfigFileReader(m_lipiRoot + SEPARATOR + m_problemName
+ + SEPARATOR + WORDFILE);
+
+
+ cfgFileMap = new LTKConfigFileReader(m_lipiRoot + SEPARATOR + m_problemName
+ + SEPARATOR + m_profile + SEPARATOR
+ + WORDPROFILEFILE);
+
+ if((errorCode=cfgFileMap->getConfigValue("classifier",
+ m_classifierName))!=SUCCESS)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error: LTKWordRecoConfig::readConfigFile()"<<endl;
+
+ LTKReturnError(errorCode);
+ }
+
+ delete cfgFileMap;
+
+ LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting: LTKWordRecoConfig::readConfigFile()" <<endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Mudit Agrawal
+* DATE : 03-MAR-2005
+* NAME : LTKWordRecoConfig
+* DESCRIPTION : DEFAULT DESTRUCTOR
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+
+LTKWordRecoConfig::~LTKWordRecoConfig()
+{
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoResult.cpp b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoResult.cpp
new file mode 100644
index 00000000..f7c60716
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/LTKWordRecoResult.cpp
@@ -0,0 +1,291 @@
+/*****************************************************************************************
+* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
+* Permission is hereby granted, free of charge, to any person obtaining a copy of
+* this software and associated documentation files (the "Software"), to deal in
+* the Software without restriction, including without limitation the rights to use,
+* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+* Software, and to permit persons to whom the Software is furnished to do so,
+* subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
+* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*****************************************************************************************/
+
+/************************************************************************
+ * SVN MACROS
+ *
+ * $LastChangedDate$
+ * $Revision$
+ * $Author$
+ *
+ ************************************************************************/
+/************************************************************************
+ * FILE DESCR: Implementation of the word recognition result
+ * CONTENTS: setWordRecoResult
+ * getResultWord
+ * getResultConfidence
+ *
+ * AUTHOR: Deepu V.
+ *
+ * DATE: March 11, 2005
+ * CHANGE HISTORY:
+ * Author Date Description of change
+ * Deepu V. 23-Aug-05 Added update word recognition result method
+ ************************************************************************/
+
+#include "LTKMacros.h"
+
+#include "LTKErrors.h"
+
+#include "LTKErrorsList.h"
+
+#include "LTKException.h"
+
+#include "LTKWordRecoResult.h"
+
+#include "LTKLoggerUtil.h"
+
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : LTKWordRecoResult
+* DESCRIPTION : Default Constructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKWordRecoResult::LTKWordRecoResult()
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::LTKWordRecoResult()" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::LTKWordRecoResult()" << endl;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : LTKWordRecoResult
+* DESCRIPTION : Constructor that takes two arguements
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+LTKWordRecoResult::LTKWordRecoResult(const vector< unsigned short >& word, float confidence = 0)
+:m_word(word)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::LTKWordRecoResult(const vector< unsigned short >&, float)" << endl;
+
+ if(confidence < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<" LTKWordRecoResult::LTKWordRecoResult"
+ <<"(vector< unsigned short >&, float)" <<endl;
+
+ throw LTKException(ENEGATIVE_NUM);
+ }
+
+ m_confidence = confidence;
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::LTKWordRecoResult(const vector< unsigned short >&, float)" << endl;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : setWordRecoResult
+* DESCRIPTION : assign values to the word recognition result
+* ARGUMENTS : word - unicode result string
+* confidence - confidence of the current word (default 0)
+* RETURNS : SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKWordRecoResult::setWordRecoResult(const vector< unsigned short >& word, float confidence = 0)
+{
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::setWordRecoResult()" << endl;
+
+ if(confidence < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<" LTKWordRecoResult::setWordRecoResult()"<<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+
+ }
+
+ if(word.size() == 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< EEMPTY_VECTOR <<":"<< getErrorMessage(EEMPTY_VECTOR)
+ <<" LTKWordRecoResult::setWordRecoResult()"<<endl;
+
+ LTKReturnError(EEMPTY_VECTOR);
+ }
+
+ //assigning the values
+ m_word = word;
+
+ m_confidence = confidence;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::setWordRecoResult()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : getResultWord
+* DESCRIPTION : returns the result word
+* ARGUMENTS :
+* RETURNS : Returns unicode result string
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+const vector<unsigned short>& LTKWordRecoResult::getResultWord() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::getResultWord()" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::getResultWord()" << endl;
+
+ return m_word;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : getResultConfidence
+* DESCRIPTION : returns the confidence of result
+* ARGUMENTS :
+* RETURNS : Returns float confidence value
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+float LTKWordRecoResult::getResultConfidence() const
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::getResultConfidence()" << endl;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::getResultConfidence()" << endl;
+
+ return m_confidence;
+}
+
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : setResultConfidence
+* DESCRIPTION : sets the confidence of result
+* ARGUMENTS :
+* RETURNS : Returns SUCCESS if completed successfully
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+int LTKWordRecoResult::setResultConfidence(float confidence)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::setResultConfidence()" << endl;
+
+ if(confidence < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<" LTKWordRecoResult::setResultConfidence()"<<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+
+ }
+
+ m_confidence = confidence;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::setResultConfidence()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 19-MAR-2005
+* NAME : updateWordRecoResult
+* DESCRIPTION : This method adds to the existing word recognition result
+* : with a new symbol
+* ARGUMENTS : newSymbol - This will be appended to the existing word
+* : confidence - confidence of the new symbol, will be added
+* : to existing confidence
+* RETURNS : Returns SUCCESS/FAILURE
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+int LTKWordRecoResult::updateWordRecoResult( unsigned short newSymbol, float confidence)
+{
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Entering: LTKWordRecoResult::updateWordRecoResult()" << endl;
+
+ if(confidence < 0)
+ {
+ LOG(LTKLogger::LTK_LOGLEVEL_ERR)
+ <<"Error : "<< ENEGATIVE_NUM <<":"<< getErrorMessage(ENEGATIVE_NUM)
+ <<" LTKWordRecoResult::updateWordRecoResult()"<<endl;
+
+ LTKReturnError(ENEGATIVE_NUM);
+
+ }
+
+ m_word.push_back(newSymbol);
+ m_confidence += confidence;
+
+ LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) <<
+ " Exiting: LTKWordRecoResult::updateWordRecoResult()" << endl;
+
+ return SUCCESS;
+}
+
+/**********************************************************************************
+* AUTHOR : Deepu V.
+* DATE : 11-MAR-2005
+* NAME : ~LTKWordRecoResult
+* DESCRIPTION : Destructor
+* ARGUMENTS :
+* RETURNS :
+* NOTES :
+* CHANGE HISTROY
+* Author Date Description of change
+*************************************************************************************/
+
+LTKWordRecoResult::~LTKWordRecoResult()
+{
+}
+
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/common.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/common.pro
new file mode 100644
index 00000000..bac16ef9
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/common/common.pro
@@ -0,0 +1,10 @@
+TARGET = wordreccommon
+include(../../../lipilib.pri)
+
+INCLUDEPATH += \
+ ../../../util/lib \
+
+SOURCES += \
+ LTKRecognitionContext.cpp \
+ LTKWordRecoConfig.cpp \
+ LTKWordRecoResult.cpp
diff --git a/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/wordrec.pro b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/wordrec.pro
new file mode 100644
index 00000000..cf49e45d
--- /dev/null
+++ b/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/reco/wordrec/wordrec.pro
@@ -0,0 +1,7 @@
+TEMPLATE = subdirs
+
+SUBDIRS += \
+ common \
+ boxfld
+
+boxfld.depends = common