Added:
/trunk/models
/trunk/models/ReadMe.txt
/trunk/models/cir
/trunk/models/cir/CIR.cpp
/trunk/models/cir/CIR.h
/trunk/models/cir/CIRCalculate.cpp
/trunk/models/cir/CIRCalculate.h
/trunk/models/cir/CIRModel.cpp
/trunk/models/cir/CIRModel.h
/trunk/models/cir/CIRTest.cpp
/trunk/models/cir/Calibrate.cpp
/trunk/models/cir/Calibrate.h
/trunk/models/cir/DataExtracter.cpp
/trunk/models/cir/DataExtracter.h
/trunk/models/cir/Logs.cpp
/trunk/models/cir/Logs.h
/trunk/models/cir/Makefile
/trunk/models/cir/def.h
/trunk/models/cir/duration.cpp
/trunk/models/cir/duration.h
/trunk/models/gbm
/trunk/models/gbm/Calibrate.cpp
/trunk/models/gbm/Calibrate.h
/trunk/models/gbm/DataExtracter.cpp
/trunk/models/gbm/DataExtracter.h
/trunk/models/gbm/GBM.cpp
/trunk/models/gbm/GBM.h
/trunk/models/gbm/GBMTest.cpp
/trunk/models/gbm/GBMotion.cpp
/trunk/models/gbm/GBMotion.h
/trunk/models/gbm/Logs.cpp
/trunk/models/gbm/Logs.h
/trunk/models/gbm/Makefile
/trunk/models/gbm/def.h
/trunk/models/gbm/duration.cpp
/trunk/models/gbm/duration.h
/trunk/models/vasicek
/trunk/models/vasicek/Calibrate.cpp
/trunk/models/vasicek/Calibrate.h
/trunk/models/vasicek/DataExtracter.cpp
/trunk/models/vasicek/DataExtracter.h
/trunk/models/vasicek/Logs.cpp
/trunk/models/vasicek/Logs.h
/trunk/models/vasicek/Makefile
/trunk/models/vasicek/Vasicek.cpp
/trunk/models/vasicek/Vasicek.h
/trunk/models/vasicek/VasicekCalculate.cpp
/trunk/models/vasicek/VasicekCalculate.h
/trunk/models/vasicek/VasicekModel.cpp
/trunk/models/vasicek/VasicekModel.h
/trunk/models/vasicek/VasicekTest.cpp
/trunk/models/vasicek/def.h
/trunk/models/vasicek/duration.cpp
/trunk/models/vasicek/duration.h
/trunk/models/vasicek/str.cpp
=======================================
--- /dev/null
+++ /trunk/models/ReadMe.txt Sun Jan 17 01:15:09 2010
@@ -0,0 +1,2 @@
+This contain the financial models
+
=======================================
--- /dev/null
+++ /trunk/models/cir/CIR.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,1043 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+// CIR.cpp : Defines the entry point for the console application.
+//
+#include <mpi.h>
+#include <stdio.h>
+#include "CIRModel.h"
+#include "math.h"
+#include <stdlib.h>
+#include <ctype.h>
+#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include "def.h"
+#include <string.h>
+#include "CIR.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////
+/*
+Euler Discretization of CIR is given at
http://www.quantcode.com/modules/mydownloads/singlefile.php?cid=9&lid=390
+However it has been shown that Exact Discretization is more accurate than
Euler's
+Therefore exact discretization equation given at
http://www.quantcode.com/modules/mydownloads/singlefile.php?cid=9&lid=391
+has been used
+*/
+//////////////////////////////////////////////////////////////////////////
+
+extern int i_Rank;
+
+#define WRITE_LOG
+
+
+CIR::CIR(int argCount, char **args, char* pzDBName, char* pzIP, char*
pzUserName, char* pzPW, char* pzDataColumn, double dTimeStep)
+{
+ i_ArgCount = argCount;
+ pz_Args = args;
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ pz_TableName = NULL;
+ d_TimeStep = dTimeStep;
+
+ int iRc = MPI_Init(&i_ArgCount, &pz_Args);
+ if (iRc != MPI_SUCCESS)
+ {
+ printf ("error, Error starting MPI program. Terminating.\n");
+ MPI_Abort(MPI_COMM_WORLD, iRc);
+ }
+
+ MPI_Comm_rank(MPI_COMM_WORLD, &i_Rank);
+ MPI_Comm_size(MPI_COMM_WORLD, &i_Size);
+
+ #ifdef WRITE_LOG
+ poTansLog = new Logs(LOGTYPE);
+ poTansLog->WriteLog(HEADLINE);
+
+ Duration d;
+ poTansLog->WriteLog(d.getSysTime());
+ #endif
+}
+
+double* CIR::getParams()
+{
+ double dInitial, dDrift, dSigma, dLambda;
+
+// bool bValidParams = validateParams(i_ArgCount, pz_Args);
+ bool bValidParams = true;
+
+ if(!bValidParams)
+ {
+ if (i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return (double*) 0;
+ }
+ int iStdErr = dup(fileno(stderr));
+ close(fileno(stderr));
+ int iOption;
+
+ if(i_ArgCount == 9)
+ {
+ dInitial = (double)atof(pz_Args[1]);
+ dDrift = (double)atof(pz_Args[2]);
+ dSigma = (double)atof(pz_Args[3]);
+ dLambda = (double)atof(pz_Args[4]);
+
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 252.0;
+ //dDrift /= 252;
+ dSigma /= sqrt(252);
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 12.0;
+ //dDrift /= 12;
+ dSigma /= sqrt(12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 4.0;
+ //dDrift /= 4;
+ dSigma /= sqrt(4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0;
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ //d_TimeStep = 1.0 / (double)i_Forecasts;
+ //printf ("switches: %d:%f\n", i_Forecasts, d_TimeStep);
+ }
+ else if(i_ArgCount == 7)
+ {
+ double factorDrift, factorSigma;
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "t:d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 't':
+ pz_TableName = optarg;
+ break;
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 252.0;
+ //factorDrift = 1.0;
+ factorSigma = sqrt(252.0);
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 12.0;
+ //factorDrift = 252 / 12;
+ factorSigma = sqrt(12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 4.0;
+ //factorDrift = 252 / 4;
+ factorSigma = sqrt(4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0;
+ // factorDrift = 252.0;
+ factorSigma = 1;
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+
+ dup2(iStdErr, fileno(stderr));
+
+ //write(fileno(stderr), "fffff", 5); checking if stdErr is working
+
+ Calibrate *poCalc = new Calibrate(pz_DBName, pz_IPAddress,
pz_UserName, pz_Password, pz_TableName, pz_DataColumn,
i_Rank, i_Size, 1.0/252.0);
+ bool bTableStatus = poCalc->checkTable();
+ if (!bTableStatus)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,No records found in Database\n");
+ fflush(stdout);
+ }
+ return 0;
+ }
+ double *pdCalibValues;
+ pdCalibValues = poCalc->calcParameters();
+
+ dInitial = pdCalibValues[0] ;
+ dDrift = pdCalibValues[1] ;
+ dSigma = pdCalibValues[2] ;
+ dLambda = pdCalibValues[3] ;
+ }
+ else
+ {
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\t%d\n", i_ArgCount);
+
+ //MPI_Finalize();
+ return 0;
+ }
+
+ #ifdef WRITE_LOG
+
+ char pzJob[128];
+ sprintf(pzJob, "MC trials \t%d \nPredictions \t%d
\n",(int)i_Iterations/i_Size, i_Forecasts);
+ poTansLog->WriteLog(pzJob);
+
+ char pzCalibValues[256];
+ sprintf(pzCalibValues, "Initial Value \t%f \nMean \t\t%f \nSigma \t\t%f
\nMRS \t\t%f\nTime step\t%f \n", dInitial, dDrift, dSigma,
dLambda, d_TimeStep);
+ poTansLog->WriteLog(pzCalibValues);
+
+ #endif
+ //printf("params: %f\t%f\t%f\t%f\t%f\n",dInitial, dDrift, dSigma,
dLambda, d_TimeStep);
+ //fflush(stdout);
+ double* pd_Params = new double[4];
+ pd_Params[0] = dInitial;
+ pd_Params[1] = dDrift;
+ pd_Params[2] = dSigma;
+ pd_Params[3] = dLambda;
+
+ return pd_Params;
+}
+
+int CIR::getNthPrime(int n)
+{
+ int count = 0;
+ int primeNo = 0;
+ int k = 2;
+ while (count < n)
+ {
+
+ if (k == 2)
+ { // the only even prime
+ primeNo = 2;
+ count++;
+ }
+ else if (k % 2 == 0) // other even numbers are composite
+ {
+ k++;
+ continue;
+
+ }
+ else
+ {
+ bool prime = true;
+ int divisor = 3;
+ int upperLimit = static_cast<int>(sqrt(k) + 1);
+ while (divisor <= upperLimit)
+ {
+
+ if (k % divisor == 0)
+ prime = false;
+ divisor +=2;
+ }
+ if (prime == true)
+ {
+ primeNo = k;
+ count++;
+ }
+ }
+ k++;
+ }
+ return primeNo;
+}
+
+double* CIR::getPredicts(double *dParams)
+{
+ MPI_Status mpiStatus;
+ int iTag = 1;
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ int iSimsPerNode = i_Iterations / i_Size;
+ double dPerformaceRatio = 0;
+ double dPerformTotalRatio = 0;
+ int iGlobFreq = 0;
+
+
+ //check for file existance
+ Logs *poRatios = new Logs();
+ bool isFileExists = poRatios->checkFileExists("tuning.txt") ;
+
+ //tokenized tuning details
+ vector<vector<string> > *tuneFileList;
+ int iMachines = 0;
+
+ //////////////////////////////////////////////////////////
+ if(isFileExists)
+ {
+ char *cBuffer = poRatios->readLog("tuning.txt");
+ vector<string> *PerNodeRatio = poRatios->tokenizer(cBuffer, ';');
+
+ iMachines = PerNodeRatio->size();
+ tuneFileList = new vector<vector<string> >(iMachines, vector<string>
(3));
+
+ // read the tuning file
+ for(int i=0 ; i < iMachines; i++)
+ {
+ string temp = PerNodeRatio->at(i);
+ vector<string> *tmp= poRatios->tokenizer(temp, ' ');
+
+ for(int j = 0; j < 3 ; j++)
+ {
+ if(j != 2)
+ (*tuneFileList)[i][j] = tmp->at(j);
+ else
+ (*tuneFileList)[i][j] = NOTVISITED;
+ }
+ }
+
+ if(i_Rank != 0)
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0, iTag, MPI_COMM_WORLD);
+
+ else
+ {
+ int iNewMachinFreq = 0; // count new machines
+ char tempIPAddress[128];
+ vector< char* > *pIPRankDatails = new vector< char* >(i_Size); // IP
list according to their rank
+ vector< string *> *pvNewMachines = new vector< string *>; // IP List of
new machines
+
+ (*pIPRankDatails)[0] = strdup(psIPAddress);
+
+ for(int i =1; i < i_Size; i++)
+ {
+ MPI_Recv(&tempIPAddress, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ (*pIPRankDatails)[i] = strdup(tempIPAddress);
+ }
+
+ for(int j = 0; j < i_Size ; j++)
+ {
+ bool isMachineExists = false;
+ string sTempIPRank (pIPRankDatails->at(j));
+
+ // check whether the machine exists
+ for (int i =0; i < iMachines ; i++ )
+ {
+ string sTempTuneList((*tuneFileList)[i][0]);
+ if( sTempTuneList.compare(sTempIPRank) == 0)
+ {
+ isMachineExists = true;
+ break;
+ }
+ }
+
+ if( !isMachineExists )
+ {
+ bool bInMachineList = false;
+ for (int k =0; k < pvNewMachines->size() ; k++ )
+ {
+ if( sTempIPRank.compare((*pvNewMachines)[k][0]) == 0)
+ {
+ int iTempFreq = atoi((*pvNewMachines)[k][1].c_str());
+ iTempFreq++;
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",iTempFreq);
+ (*pvNewMachines)[k][1] = sTempFreq;
+ bInMachineList = true;
+ }
+ }
+
+ if(!bInMachineList)
+ {
+ string *vTemp = new string[2];
+ vTemp[0] = pIPRankDatails->at(j);
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",1);
+ vTemp[1] = sTempFreq;
+ pvNewMachines->push_back(vTemp);
+ iNewMachinFreq++;
+ iGlobFreq++;
+ }
+ }
+ }
+
+ // if new machine are not added
+ vector<vector<string> *> *frequencyList = new vector<vector<string> *>;
+ double tempTotal = 0;
+ double dtempRatios = 0;
+
+ // keep machine name : total ratio
+ vector< string > *pvFreqListElement;
+
+ for (int i = 0; i < iMachines; i++)
+ {
+
+ pvFreqListElement = new vector< string >(3);
+ int frequency=0;
+
+ for (int j = 0; j < i_Size; j++)
+ {
+ if((*tuneFileList)[i][0].compare(pIPRankDatails->at(j))==0)
+ frequency++;
+ }
+
+ // if machine is used for run the process insert to the frequency list
+ if(frequency > 0)
+ {
+ tempTotal += frequency * (atof((*tuneFileList)[i][1].c_str()));
+ dPerformTotalRatio += atof((*tuneFileList)[i][1].c_str());
+
+ char tempDRatio[sizeof(double) +1];
+ sprintf( tempDRatio,"%f",(frequency *
(atof((*tuneFileList)[i][1].c_str()))));
+ (*pvFreqListElement)[0] = (*tuneFileList)[i][0];
+ (*pvFreqListElement)[1] = tempDRatio;
+ (*pvFreqListElement)[2] = (*tuneFileList)[i][1];
+ frequencyList->push_back(pvFreqListElement);
+ iGlobFreq++;
+ }
+ }
+
+ for(int i = 0; i < i_Size ; i++ )
+ {
+ bool bNewFile = true;
+ for(int j = 0; j < frequencyList->size(); j++)
+ {
+ if(string((*pIPRankDatails)[i]).compare((*(*frequencyList)[j])[0]) ==
0)
+ {
+ double tempVal = atof((*(*frequencyList)[j])[2].c_str()) /
tempTotal ;
+ dtempRatios = tempVal * ( (double)(i_Size-
iNewMachinFreq)/(double)i_Size);
+
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+
+ bNewFile = false;
+ break;
+ }
+ }
+ if(bNewFile)
+ {
+ dtempRatios = 1.0 / (double)i_Size;
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+ }
+
+ }
+
+ delete frequencyList;
+ delete pIPRankDatails;
+ }
+
+ if(i_Rank != 0)
+ MPI_Recv(&dPerformaceRatio, 1, MPI_DOUBLE, 0, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ iSimsPerNode = (int)(dPerformaceRatio * i_Iterations);
+
+ }
+ else
+ iGlobFreq = i_Size;
+
+
+ double dInitial = dParams[0];
+ double dDrift = dParams[1];
+ double dSigma = dParams[2];
+ double dLambda = dParams[3];
+
+ Duration oDuration;
+ oDuration.setStart();
+
+ double dCurrTime = 0;
+
+
+ if(i_Rank == 0)
+ {
+ dCurrTime = (double)oDuration.getCurrTime();
+ }
+
+ MPI_Bcast ( &dCurrTime, 1, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ double dSeed = dCurrTime * getNthPrime( i_Rank + i_Size);
+
+ char cSeed[32];
+ sprintf(cSeed , "Seed value :%f \n" , dCurrTime);
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog(cSeed);
+ #endif
+
+ vector<vector<double> > *pvResults = new vector<vector<double>
>((i_Forecasts), vector<double> (iSimsPerNode));
+
+ for (int i = 0; i < iSimsPerNode ; i++)
+ {
+ CIRModel oCIR(dInitial, dDrift, dSigma, dLambda, d_TimeStep, dSeed); //
our brownian motion object
+
+ for (int k = 0; k < i_Forecasts; k++)
+ {
+ (*pvResults)[k][i] = oCIR.step();
+ //printf("%f,", (*pvResults)[k][i]);
+ //fflush(stdout);
+ }
+ }
+ double daLocalCalibVals[i_Forecasts];
+
+ for(int i=0; i< (i_Forecasts) ; i++ )
+ {
+ double dTotal = 0;
+
+ for(int k= 0; k < iSimsPerNode; k++ )
+ {
+ dTotal += (*pvResults)[i][k];
+ }
+
+ //daLocalCalibVals[i]= dTotal / iSimsPerNode;
+ daLocalCalibVals[i]= dTotal ;
+ }
+
+ delete pvResults;
+
+ oDuration.setEnd();
+ double dDuration = oDuration.getPassedTime() / iSimsPerNode;
+ double dInvDuration = 1/dDuration;
+
+ if (i_Rank != 0)
+ {
+ MPI_Send(&daLocalCalibVals, i_Forecasts, MPI_DOUBLE, 0,iTag,
MPI_COMM_WORLD);
+ MPI_Send(&dInvDuration, 1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0,iTag, MPI_COMM_WORLD);
+ }
+
+ double *dPredictValues = new double[i_Forecasts];
+ double *dInvDurationValues= new double[iGlobFreq];
+ char **pzIPAddress = new char*[iGlobFreq];
+ for (int i = 0; i < iGlobFreq; i++)
+ pzIPAddress[i] = new char[128];
+
+ if (i_Rank == 0)
+ {
+ double dTempDuration = 0;
+ double dTotal = 0;
+
+ dInvDurationValues[0] = dInvDuration;
+ dTotal = dInvDurationValues[0];
+ strcpy(pzIPAddress[0], psIPAddress);
+
+ double dTempResults[i_Forecasts];
+ vector<vector<double> > finalResults(i_Size, vector<double>
(i_Forecasts));
+
+ for (int i=0; i < i_Forecasts; i++)
+ finalResults[0][i] = daLocalCalibVals[i] ;
+
+ // Wait for results from other processes
+ for (int i = 1; i < i_Size; i++)
+ {
+
+ MPI_Recv(&dTempResults, i_Forecasts, MPI_DOUBLE, i, iTag,
MPI_COMM_WORLD, &mpiStatus);
+
+ for (int k=0; k < i_Forecasts; k++)
+ finalResults[i][k] = dTempResults[k];
+
+ char tempIP[128];
+ MPI_Recv(&dTempDuration, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ MPI_Recv(&tempIP, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD, &mpiStatus);
+
+ bool bReplicatedMachine = false;
+
+ for(int j = 0;j < i ;j++)
+ {
+ if(string(tempIP).compare(string(pzIPAddress[j])) == 0)
+ {
+ double dTemp = dInvDurationValues[j];
+ dInvDurationValues[j] = (dInvDurationValues[j]+dTempDuration) / 2;
+ bReplicatedMachine = true;
+ dTotal = dTotal - dTemp + dInvDurationValues[j];
+ }
+ }
+
+ if(!bReplicatedMachine)
+ {
+ strcpy(pzIPAddress[i], tempIP);
+ dInvDurationValues[i] = dTempDuration;
+ dTotal += dInvDurationValues[i];
+ }
+ }
+
+ for (int i = 0; i < i_Forecasts; i++ )
+ {
+ double totalForcastValues = 0;
+
+ for( int k =0; k < i_Size ; k++ )
+ totalForcastValues += finalResults[k][i];
+
+ dPredictValues[i] = totalForcastValues/ i_Iterations;
+
+
+ if(i != i_Forecasts-1)
+ {
+
+ }
+ }
+
+ /*for(int i=0; i < iGlobFreq; i++)
+ {
+ printf("%s:%f \n",pzIPAddress[i],dInvDurationValues[i]);
+ }*/
+
+ double *dRatio = new double[iGlobFreq];
+ char **pzTuningIPAddress ;
+ double *dModifiedRatio;
+
+ if(i_Size < iMachines )
+ {
+ dModifiedRatio = new double[iMachines];
+ pzTuningIPAddress = new char*[iMachines];
+ for (int i = 0; i < iMachines; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+ else
+ {
+ dModifiedRatio = new double[i_Size];
+ pzTuningIPAddress = new char*[i_Size];
+ for (int i = 0; i < i_Size; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+
+ for(int i = 0; i < iGlobFreq ;i++)
+ {
+ dRatio[i] = dInvDurationValues[i] / dTotal;
+ }
+
+ Logs *poTune = new Logs();
+
+ if((i_Size == iMachines) ||(iMachines == 0 && !isFileExists))
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (dRatio[i] +
atof((*tuneFileList)[i][1].c_str()))/2;
+ break;
+ }
+ }
+ }
+ if(i_Size > 2)
+ poTune->writeTuning( dModifiedRatio, pzIPAddress , iGlobFreq);
+ }
+ else
+ {
+ if(i_Size > 2)
+ poTune->writeTuning( dRatio, pzIPAddress , iGlobFreq);
+
+ }
+ }
+ else if(i_Size != iMachines )
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ bool bNewMachine = true;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (( dRatio[i] * dPerformTotalRatio)+
atof((*tuneFileList)[i][1].c_str()))/2;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ (*tuneFileList)[i][2] = VISITED;
+ bNewMachine = false;
+ break;
+ }
+ }
+ if(bNewMachine)
+ {
+ dModifiedRatio[j] = dRatio[j]/2.0;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ }
+ }
+
+ int tempIncrement =0;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][2].compare(NOTVISITED) == 0)
+ {
+ if(i_Size <= iMachines)
+ {
+ dModifiedRatio[tempIncrement+i_Size] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+i_Size],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ else
+ {
+ dModifiedRatio[tempIncrement+iMachines] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+iMachines],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ }
+ }
+ if(i_Size > 2)
+ {
+ if( iMachines >= i_Size )
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iMachines);
+ else
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iGlobFreq );
+ }
+ }
+ }
+ }
+
+ delete [] dInvDurationValues;
+ for (int i = 0; i < iGlobFreq; i++)
+ {
+ delete []pzIPAddress[i];
+ }
+ delete [] pzIPAddress;
+
+
+ MPI_Bcast (dPredictValues, i_Forecasts, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+ //MPI_Finalize();
+ return dPredictValues;
+
+
+}
+
+CIR::~CIR(void)
+{
+
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ //if (pz_TableName)
+ // delete pz_TableName;//TODO: FIND OUT WHY MEMORY CORRUPTION
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+
+ MPI_Finalize();
+
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog("-END- \n");
+ delete poTansLog;
+ #endif
+}
+
+bool CIR::validateParams(int i_ArgCount,char* args[])
+{
+ if(i_ArgCount == 9)
+ {
+ for(int i = 1; i < i_ArgCount; i++)
+ {
+ int iStrLen = strlen(args[i]);
+ int iDots = 0;
+
+ for (int j = 0; j < iStrLen; j++)
+ {
+ if(isdigit(args[i][j]) == 0)
+ {
+ if (j == 0 && args[i][j] == '-')
+ {
+ continue;
+ }
+
+ if(args[i][j] != '.')
+ {
+ return false;
+ }
+ else
+ {
+ iDots++;
+
+ if ((iStrLen == 1) || (iDots > 1))
+ {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ else if(i_ArgCount == 7)
+ {
+ if((strcmp(args[1], "-t") == 0) && ((strcmp(args[3], "-d") == 0) ||
(strcmp(args[3], "-m") == 0)) && (strcmp(args[5], "-n") == 0))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+/*bool validateParams(int argc,char* argv[]);// parameter validation
+
+int main(int argc, char* argv[])
+{
+
+ int iRc = MPI_Init(&argc, &argv);
+ if (iRc != MPI_SUCCESS)
+ {
+ printf ("Error starting MPI program. Terminating.\n");
+ MPI_Abort(MPI_COMM_WORLD, iRc);
+ return 0;
+ }
+
+ int iRank, iSize;
+
+ MPI_Comm_rank(MPI_COMM_WORLD, &iRank);
+ MPI_Comm_size(MPI_COMM_WORLD, &iSize);
+ MPI_Status mpiStatus;
+ int iTag = 1;
+
+ int iNumTrials = 50000; // number of MonteCarlo trials
+ int const iPredicts = 60; // number of forward predictions //TODO:
Paramerterize predictions
+ int iNoOfItrPerMachine = iNumTrials/iSize ;
+ double dTimeStep = (1.0/12.0); // monthly
+
+ bool bValidParams = validateParams(argc, argv);
+
+ if(!bValidParams)
+ {
+ if (iRank == 0)
+ {
+ printf("Incorrect Parameters1\n");
+ fflush(stdout);
+ }
+ MPI_Finalize();
+ return 0;
+ }
+
+ double *pdParams;
+
+ if(argc == 5)
+ {
+ pdParams = new double[4];
+ pdParams[0] = (double)atof(argv[1]);
+ pdParams[1] = (double)atof(argv[2]);
+ pdParams[2] = (double)atof(argv[3]);
+ pdParams[3] = (double)atof(argv[4]);
+ }
+ else if(argc == 3)
+ {
+ int iError;
+ if(iRank == 0)
+ {
+ char *pztableName = argv[2];
+ Calib oCalib(pztableName, dTimeStep);
+ //cout << "table name: " << pztableName << endl;
+ pdParams = oCalib.Calibrate();
+ if (pdParams == NULL)
+ {
+ MPI_Abort(MPI_COMM_WORLD, 0);// TODO: finalize mpi without abort
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ else
+ {
+ pdParams = new double[4];
+ }
+ if (pdParams == NULL)
+ {
+ MPI_Finalize();
+ return 0;
+ }
+ MPI_Bcast ( pdParams, 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ // monte carlo simulations
+
//---------------------------------------------------------------------------------------------------
+
+ double daPredictValues[ iPredicts ];
+ vector<vector<double> > vLocalResults(iPredicts , vector<double> (
iNoOfItrPerMachine ));
+
+ cout << "Params: " << pdParams[0] << " : " << pdParams[1] << " : " <<
pdParams[2] << " : " << pdParams[3] << " : "<< dTimeStep << endl;
+ for (int i = 0; i < iNoOfItrPerMachine; i++ )
+ {
+ //NOTE: Intitial value, mu, volatility etc should be in decimal values
e.g: for 6 per cent interest rate -> use 0.06
+ CIR vasicek_test(pdParams[0], pdParams[1], pdParams[2], pdParams[3],
dTimeStep);
+ int j;
+ for (j=0; j < iPredicts; j++)
+ {
+ vLocalResults[j][i] = vasicek_test.step();
+ }
+ //printf("result: %f\n", vLocalResults[j-1][i]);
+ //fflush(stdout);
+ }
+ delete []pdParams;
+ double daAvgLocResults[iPredicts];
+
+ for(unsigned int i = 0; i < vLocalResults.size() ; i++)
+ {
+ double dSum = 0;
+ for(unsigned int j = 0; j < vLocalResults[i].size(); j++)
+ {
+ dSum += vLocalResults[i][j];
+ }
+ daAvgLocResults[i] = dSum / vLocalResults[i].size();
+ }
+
+ if(iRank != 0)
+ {
+ MPI_Send(&daAvgLocResults, iPredicts, MPI_DOUBLE, 0, iTag,
MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > vaPatialResults(iSize, vector<double>
(iPredicts));
+ double daTempResults[iPredicts];
+
+ for(int i = 0; i < iPredicts ; i++ )
+ {
+ vaPatialResults[0][i] = daAvgLocResults[i];
+ }
+
+ for(int i = 1; i < iSize; i++)
+ {
+ MPI_Recv(&daTempResults, iPredicts, MPI_DOUBLE, i, iTag,
MPI_COMM_WORLD, &mpiStatus);
+
+ for(int k = 0; k < iPredicts; k++)
+ {
+ vaPatialResults[i][k] = daTempResults[k];
+ }
+ }
+
+ for (int i = 0; i < iPredicts ; i++)
+ {
+ double dTemp = 0;
+ for(int k = 0; k < iSize ; k++)
+ {
+ dTemp += vaPatialResults[k][i];
+ }
+ daPredictValues[i] = dTemp / iSize;
+
+ printf("%f", daPredictValues[i]);
+ fflush(stdout);
+
+ if(i != iPredicts - 1)
+ {
+ printf("\n");
+ fflush(stdout);
+ }
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+ MPI_Finalize();
+
+ return 0;
+}
+
***The diff for this file has been truncated for email.***
=======================================
--- /dev/null
+++ /trunk/models/cir/CIR.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,51 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+
+#include "Logs.h"
+
+class CIR
+{
+private:
+ int i_ArgCount;
+ char** pz_Args;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ char* pz_TableName;
+ int i_Size;
+ double d_TimeStep;
+ int i_Iterations;
+ bool validateParams(int argc,char* args[]);// parameter validation
+ Logs *poTansLog;
+ int getNthPrime(int n);
+
+public:
+ CIR(int argCount, char* args[], char* pzDBName, char* pzIP, char*
pzUserName, char* pzPW, char* pzDataColumn, double dTimeStep);
+
+ int i_Forecasts;
+ double* getParams();
+ double* getPredicts(double *dParams);
+ ~CIR(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/cir/CIRCalculate.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,273 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+#include "CIRCalculate.h"
+#ifdef _WIN32
+#include <winsock.h>
+#endif // Win32
+#include <boost/random.hpp>
+#include <stdio.h>
+#include <iostream>
+#include "Vasicek.h"
+#include "Calib.h"
+#include <ctime>
+#include <math.h>
+#include <sys/timeb.h>
+#include <vector>
+//#include <mysql.h>
+#include "DataExtracter.h"
+
+CIRCalculate::CIRCalculate() {
+ // TODO Auto-generated constructor stub
+
+}
+
+double* CIRCalculate::CalcCIRParralel(int iRank, int iSize, vector<double>
*vData, double dTimeStep, int n, int iNoOfItrPerMachine, double lastData ){
+
+ MPI_Status mpiStatus;
+
+ Calib cal(vData);
+ int iTag =1;
+ double sx, sy, sxx, syy, sxy;
+ double mu, lambda, sigma_square, sigma;
+ double partialParameters[5];
+ double finalParameters[3];
+
+ partialParameters[0] = cal.getSx();
+ partialParameters[1] = cal.getSy();//cout<<sy<<endl;;
+ partialParameters[2] = cal.getSxx();//cout<<sxx<<endl;;
+ partialParameters[3] = cal.getSyy();//cout<<syy<<endl;;
+ partialParameters[4] = cal.getSxy();//cout<<sxy<<endl;;
+
+ if(iRank != 0)
+ {
+ MPI_Send(&partialParameters, 5, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > parametersCollection(iSize, vector<double> (5));
+ double tempResults[5];
+
+ for(int i=0; i< 5 ; i++ )
+ {
+ parametersCollection[0][i] = partialParameters[i];
+ }
+
+ for(int i=1; i< iSize; i++)
+ {
+ MPI_Recv(&tempResults, 5, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < 5; k++)
+ {
+ parametersCollection[i][k] = tempResults[k];
+ }
+ }
+
+ for(int i=0; i < 5 ; i++ )
+ {
+ double temp = 0;
+
+ for(int k=0; k < iSize ; k++)
+ {
+ temp = temp + parametersCollection[k][i];
+ }
+
+ if(i == 0)
+ sx = temp;
+ else if(i == 1)
+ sy = temp;
+ else if(i == 2)
+ sxx = temp;
+ else if(i == 3)
+ syy = temp;
+ else if(i == 4)
+ sxy = temp;
+ }
+ mu = ((sy * sxx) - (sx * sxy)) / (21 * (sxx - sxy) - (pow(sx,2) - (sx *
sy)));
+ lambda = (-1/dTimeStep)*(log((sxy - mu*sx - mu*sy + n*pow(mu,2))/(sxx -
2*mu*sx + n*pow(mu,2))));
+ double alpha = exp(-1*lambda*dTimeStep);
+ double sigmahat_square = (syy - (2*alpha*sxy) + (pow(alpha,2)*sxx) -
(2*mu*(1-alpha)*(sy - alpha*sx)) + (n*pow(mu,2)*(pow((1-alpha),2))))/n;
+ sigma_square = sigmahat_square*2*lambda / (1 - pow(alpha,2));
+
+ finalParameters[0] = mu;
+ finalParameters[1] = lambda;
+ finalParameters[2] = sqrt(sigma_square) ;
+ }
+
+ if (iRank==0)
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+ else
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ mu = finalParameters[0];
+ lambda = finalParameters[1];
+ sigma = finalParameters[2];
+
+ double *CIRValues;
+
+ CIRValues= MonticarloSimulation(iRank, iSize, n, iNoOfItrPerMachine, mu,
sigma, lambda, lastData );
+
+ return CIRValues;
+}
+
+CIRCalculate::~CIRCalculate() {
+ // TODO Auto-generated destructor stub
+}
+
+double* CIRCalculate::CalcCIRSequentially(int iRank, int iSize,
vector<double> *vData,double dTimeStep, int n, int iNoOfItrPerMachine,
double lastData)
+{
+ int iTag =1;
+ MPI_Status mpiStatus;
+ double finalParameters[3];
+ double mu, lambda ,sigma;
+
+ if(iRank==0)
+ {
+
+ Calib cal(vData);
+
+ double sx = cal.getSx();//cout<<sx<<endl;;
+ double sy = cal.getSy();//cout<<sy<<endl;;
+ double sxx = cal.getSxx();//cout<<sxx<<endl;;
+ double syy = cal.getSyy();//cout<<syy<<endl;;
+ double sxy = cal.getSxy();//cout<<sxy<<endl;;
+
+ double mu = ((sy * sxx) - (sx * sxy)) / (21 * (sxx - sxy) - (pow(sx,2) -
(sx * sy)));
+ double lambda = (-1/dTimeStep)*(log((sxy - mu*sx - mu*sy +
n*pow(mu,2))/(sxx - 2*mu*sx + n*pow(mu,2))));
+ double alpha = exp(-1*lambda*dTimeStep);
+ double sigmahat_square = (syy - (2*alpha*sxy) + (pow(alpha,2)*sxx) -
(2*mu*(1-alpha)*(sy - alpha*sx)) + (n*pow(mu,2)*(pow((1-alpha),2))))/n;
+ double sigma_square = sigmahat_square*2*lambda / (1 - pow(alpha,2));
+
+ finalParameters[0] = mu;
+ finalParameters[1] = lambda;
+ finalParameters[2] = sqrt(sigma_square) ;
+ }
+
+ if (iRank==0)
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+ else
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ mu = finalParameters[0];
+ lambda = finalParameters[1];
+ sigma = finalParameters[2];
+ //CIR(double dSInitial, double dDrift, double dSigma, double
dMeanReversionSpeed, double dDelta)
+
+ double *CIRValues;
+
+ CIRValues= MonticarloSimulation(iRank, iSize, n, iNoOfItrPerMachine, mu,
sigma, lambda, lastData );
+
+ return CIRValues;
+
+}
+
+double* CIRCalculate::MonticarloSimulation(int iRank, int iSize, int n,
int iNoOfItrPerMachine, double mu, double sigma, double lambda, double
lastData )
+{
+ MPI_Status mpiStatus;
+ int iTag = 1;
+ double dTimeStep = (1.0/12.0);
+
+ double CIRValues[n+1];
+ vector<vector<double> > results(n+1, vector<double> (iNoOfItrPerMachine));
+
+ for (int i=0; i<iNoOfItrPerMachine; i++)
+ {
+ /*Vasicek vasicek_test(dInitial, dDrift, dSigma, dLambda, dTimeStep);*/
+ Vasicek vasicek_test(lastData, mu, sigma, lambda, dTimeStep);
+ for (int j=0; j < n+1 ;j++)
+ {
+ results[j][i] = vasicek_test.step();
+ }
+ }
+
+ double caliberatedValues[n+1];
+
+ // calibration on simulated data
+ unsigned int x,y;
+
+ for(x = 0;x < results.size();x++)
+ {
+ double sum = 0;
+ for(y = 0;y < results[x].size();y++)
+ {
+ sum += results[x][y];
+ }
+ caliberatedValues[x] = sum / results[x].size();
+ }
+
+ if(iRank != 0)
+ {
+ MPI_Send(&caliberatedValues, n+1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > finalResults(iSize, vector<double> (n+1));
+ double tempResults[n+1];
+
+ for(int i=0; i< n+1 ; i++ )
+ {
+ finalResults[0][i] = caliberatedValues[i];
+ }
+
+ for(int i=1; i< iSize; i++)
+ {
+ MPI_Recv(&tempResults, n+1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < n+1; k++)
+ {
+ finalResults[i][k] = tempResults[k];
+ }
+ }
+
+ for (int i=0; i < n+1 ; i++)
+ {
+ double temp = 0;
+ for(int k =0; k < iSize ; k++)
+ {
+ temp = temp + finalResults[k][i];
+ }
+ CIRValues[i] = temp/iSize;
+
+ printf("%f", CIRValues[i]);
+ fflush(stdout);
+
+ if(i != n)
+ {
+ printf(",");
+ fflush(stdout);
+ }
+ }
+
+ printf("\n");
+ fflush(stdout);
+ }
+
+ return CIRValues;
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/CIRCalculate.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,39 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+#include <mpi.h>
+#include <vector.h>
+
+
+class CIRCalculate {
+
+
+public:
+ CIRCalculate();
+ virtual ~CIRCalculate();
+
+public:
+ double* CalcCIRParralel(int iRank, int iSize, vector<double> *vData,
double dTimeStep, int n, int iNoOfItrPerMachine, double lastData );
+ double* CalcCIRSequentially(int iRank, int iSize, vector<double>
*vData,double dTimeStep, int n, int iNoOfItrPerMachine, double lastData);
+ double* MonticarloSimulation(int iRank, int iSize, int n, int
iNoOfItrPerMachine, double mu, double sigma, double lambda, double lastData
);
+};
+
=======================================
--- /dev/null
+++ /trunk/models/cir/CIRModel.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,115 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include "CIRModel.h"
+#include <iostream>
+#include "duration.h"
+#include "newran.h"
+
+
+using namespace boost;
+using namespace std;
+
+CIRModel::CIRModel(double dSInitial, double dDrift, double dSigma, double
dMeanReversionSpeed, double dTimeStep, double dSeed) {
+ Duration dur;
+
+ mt19937 rnd_gen2(dur.getCurrTime()); //Mersenne Twister generator
+ //std::tr1::normal_distribution<double> normal;
+ normal_distribution<> normal_dist;
+ d_vGen2 = new rnd_normal_t(rnd_gen2, normal_dist);
+ //rnd_poisson_t rnd_poisson( rnd_gen, boost::poisson_distribution<>(
lambda ));
+
+ urng = new MT(dSeed);
+ Random::Set(*urng);
+ d_CurrVal = dSInitial;
+ d_Drift = dDrift;
+ d_Sigma = dSigma;
+ d_Alpha = dMeanReversionSpeed;
+ d_TimeStep = dTimeStep;
+ d_d = 4 * d_Drift * d_Alpha / pow(d_Sigma, 2);
+}
+
+void CIRModel::invokePoisson(double dLambda)
+{
+ Duration dur;
+ mt19937 rnd_gen1(dur.getCurrTime()); //Mersenne Twister generator
+ d_vGen1 = new rnd_poisson_t( rnd_gen1, poisson_distribution<>(
dLambda/2.0 ));
+}
+
+double CIRModel::step(void)
+{
+ //MT urng(dur.getCurrTime()); // declare uniform
random number generator
+ //Random::Set(*urng); // set urng as generator to be
used
+
+ //for (int i=0; i<10; i++) cout << "chi: "<< CS.Next() << "\n";
+ double drift = pow(d_Sigma, 2) * (1 - exp((-1) * d_Alpha *
d_TimeStep)) / (4 * d_Alpha);
+ double d_Lambda = d_CurrVal * (exp((-1) * d_Alpha * d_TimeStep)) / drift;
+
+ //printf("This is d: %f\n", d_d);
+ //fflush(stdout);
+ if (d_d > 1){
+ //printf("d is greater than 1\n");
+ //fflush(stdout);
+ double dRanNumber_Normal = (*d_vGen2)();
+ //printf("Random Norm: %f\n", dRanNumber_Normal);
+ //fflush(stdout);
+ double degOfFreedom = d_d + 1;
+ ChiSq CS1(degOfFreedom);
+ double dRanNumber_Chi = CS1.Next();
+ //printf("Random Chi: %f\n", dRanNumber_Chi);
+ //fflush(stdout);
+ d_CurrVal = drift * (pow((dRanNumber_Normal + sqrt(d_Lambda)),2) +
dRanNumber_Chi);
+ //printf("CurVal: %f\n", d_CurrVal);
+ //fflush(stdout);
+ } else {
+ //printf("d is less than 1\n");
+ //fflush(stdout);
+
+ Duration dur;
+ mt19937 rnd_gen1(dur.getCurrTime()); //Mersenne Twister generator
+ d_vGen1 = new rnd_poisson_t( rnd_gen1, poisson_distribution<>(
d_Lambda/2.0 ));
+
+ //invokePoisson(d_Lambda);
+
+ double dRanNumber_Poisson = (*d_vGen1)();
+
+ while (dRanNumber_Poisson == 0.0)
+ dRanNumber_Poisson = (*d_vGen1)();
+ //TODO: WHat to do when poisson number is 0?
+ /*printf("This is the ran no: %f\n", dRanNumber_Poisson);
+ fflush(stdout);*/
+
+ double degOfFreedom = d_d + (2 * dRanNumber_Poisson);
+ /*printf("This is the degree: %f\n", degOfFreedom);
+ fflush(stdout);*/
+ ChiSq CS2(degOfFreedom);
+ double dRanNumber_Chi = CS2.Next();
+
+ d_CurrVal = drift * dRanNumber_Chi;
+ delete d_vGen1;
+ }
+
+ return d_CurrVal;
+}
+
+CIRModel::~CIRModel() {
+ delete d_vGen2;
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/CIRModel.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,58 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef CIR_H_
+#define CIR_H_
+#pragma once
+#include <boost/random.hpp>
+#include <vector>
+#include "newran.h"
+
+using namespace boost;
+
+typedef variate_generator<mt19937, poisson_distribution<> > rnd_poisson_t;
+typedef variate_generator<mt19937, normal_distribution<double> >
rnd_normal_t;
+
+class CIRModel {
+
+private:
+ rnd_poisson_t *d_vGen1;
+ rnd_normal_t *d_vGen2;
+
+ MT *urng;
+
+ double d_CurrVal; // initial security value (constant)
+ double d_Drift; // our drift
+ double d_Sigma; // our volatility
+ double d_Alpha; // our mean reversion rate
+ double d_TimeStep; // our time step
+ double d_CurrentTime; // the current elapsed time
+ double d_d;
+
+ void invokePoisson(double dLambda);
+
+public:
+ CIRModel(double dSInitial, double dDrift, double dSigma, double
dMeanReversionSpeed, double dTimeStep, double dSeed);
+ double step(void);
+ virtual ~CIRModel();
+};
+
+#endif /* CIR_H_ */
=======================================
--- /dev/null
+++ /trunk/models/cir/CIRTest.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,57 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <stdio.h>
+#include "CIR.h"
+#include "duration.h"
+#include "def.h"
+
+using namespace std;
+
+int i_Rank;
+
+int main(int argc, char* argv[])
+{
+ Duration d;
+ d.setStart();
+ double dTimeStep = 1.0 / 12.0;
+ CIR oCIR(argc, argv, DATABASE, IP, USER, PWORD, DATACOLUMN, dTimeStep);
+
+ double* params = oCIR.getParams();
+ if (params != 0)
+ {
+ double* predicts = oCIR.getPredicts(params);
+
+ d.setEnd();
+ double dTime = d.getPassedTime();
+ if (i_Rank == 0)
+ {
+ printf("Params,Intial
value=%f,Mean=%f,Sigma=%f,Lambda=%f,Time=%f:Values", params[0], params[1],
params[2], params[3], dTime);
+ fflush(stdout);
+ for (int i = 0; i < oCIR.i_Forecasts; i++)
+ {
+ printf(",%f",predicts[i]);
+ fflush(stdout);
+ }
+ }
+ }
+ return 0;
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/Calibrate.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,411 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+#include <stdio.h>
+#include <mysql.h>
+#include <stdlib.h>
+//#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include <math.h>
+#include <string.h>
+#include "def.h"
+
+using namespace std;
+
+Calibrate::Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char*
pzPW, char* pzTName, char* pzDataColumn, int i_Rank, int i_Size, double
dTimeStep)
+{
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ i_Rank = i_Rank;
+ i_Size = i_Size;
+ d_TimeStep = dTimeStep;
+ pd_Data = NULL;
+ i_Len = 0;
+}
+
+Calibrate::~Calibrate(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_TableName)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+ if (pd_Data)
+ delete []pd_Data;
+}
+
+bool Calibrate::checkTable()
+{
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ bool status = true;
+ i_Length = poDataEx->getNoOfRows();
+ if(i_Length == 0)
+ {
+ status = false;;
+ }
+ delete poDataEx;
+ return status;
+}
+
+double* Calibrate::calcParameters()
+{
+ double *pdCalibValues = calcParamInSingleMachine(); //TODO: perform size
check of table to decide on parallel calibration
+
+ return pdCalibValues;
+}
+
+double* Calibrate::calcParamReplicatedDB()
+{
+ MPI_Status mpiStatus;
+ int bIsSuccesl = 0;
+ double *pdCalibParams = new double[4];
+
+ int iTag =1;
+
+ double dSx, dSy, dSxx, dSyy, dSxy;
+ double mu, lambda, sigma_square, sigma;
+ double partialParameters[5];
+// printf("Para calib1\n");
+// fflush(stdout);
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ int iNoOfRows = i_Length / i_Size;
+
+ int iInitialRow = iNoOfRows * i_Rank + 1;
+ int iFinalRow;
+
+ if( i_Rank == i_Size - 1)
+ {
+ iFinalRow = i_Length;
+ }
+ else
+ {
+ iFinalRow = iNoOfRows * (i_Rank + 1);
+ }
+
+ pd_Data = poDataEx->getReplicatedDataParellel(iInitialRow, iFinalRow,
pz_DataColumn);
+ i_Len = iFinalRow - iInitialRow + 1;
+ partialParameters[0] = getSxPara();
+ partialParameters[1] = getSyPara();
+ partialParameters[2] = getSxxPara();
+ partialParameters[3] = getSyyPara();
+ partialParameters[4] = getSxyPara();
+ if(i_Rank != 0)
+ {
+ MPI_Send(&partialParameters, 5, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ // vector<vector<double> > parametersCollection(i_Size, vector<double>
(5));
+ double **parametersCollection = new double*[i_Size];
+ for (int i = 0; i < i_Size; i++)
+ {
+ parametersCollection[i] = new double[5];
+ }
+
+ double tempResults[5];
+
+ for(int i=0; i< 5 ; i++ )
+ {
+ parametersCollection[0][i] = partialParameters[i];
+ }
+
+ for(int i=1; i< i_Size; i++)
+ {
+ MPI_Recv(&tempResults, 5, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < 5; k++)
+ {
+ parametersCollection[i][k] = tempResults[k];
+ }
+ }
+
+ for(int i=0; i < 5 ; i++ )
+ {
+ double temp = 0;
+
+ for(int k=0; k < i_Size ; k++)
+ {
+ temp = temp + parametersCollection[k][i];
+ }
+
+ if(i == 0)
+ dSx = temp;
+ else if(i == 1)
+ dSy = temp;
+ else if(i == 2)
+ dSxx = temp;
+ else if(i == 3)
+ dSyy = temp;
+ else if(i == 4)
+ dSxy = temp;
+ }
+ i_Length = i_Length -1;
+
+ double dMu = ((dSy * dSxx) - (dSx * dSxy)) / ((i_Length * (dSxx - dSxy))
- (pow(dSx,2) - (dSx * dSy)));
+ double dLambda = (-1 / d_TimeStep) * (log((dSxy - dMu * dSx - dMu * dSy
+ i_Length * pow(dMu,2)) /
+ (dSxx - 2 * dMu * dSx + i_Length * pow(dMu,2))));
+
+ double dAlpha = exp(-1 * dLambda * d_TimeStep);
+
+ double dSigmaHatSq = (dSyy - (2 * dAlpha * dSxy) + (pow(dAlpha,2) *
dSxx) - (2 * dMu * (1-dAlpha) *
+ (dSy - dAlpha * dSx)) + (i_Length * pow(dMu,2) *
(pow((1-dAlpha),2)))) / i_Length;
+
+ double dSigmaSq = dSigmaHatSq * 2 * dLambda / (1 - pow(dAlpha,2));
+
+ pdCalibParams[0] = poDataEx->getLastData(pz_DataColumn);
+ pdCalibParams[1] = dMu;
+ pdCalibParams[2] = sqrt(dSigmaSq);
+ pdCalibParams[3] = dLambda;
+
+ for (int i = 0; i < i_Size; i++)
+ {
+ delete []parametersCollection[i];
+ }
+ delete []parametersCollection;
+
+ delete poDataEx;
+ }
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ if (i_Rank != 0)
+ {
+ MPI_Send ( &bIsSuccesl, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ for(int i = 1; i < i_Size; i++)
+ {
+ MPI_Recv( &bIsSuccesl , 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ }
+ }
+
+ return pdCalibParams;
+}
+
+double* Calibrate::calcParamInSingleMachine()
+{
+ MPI_Status mpiStatus;
+
+ double *pdCalibParams = new double[4];
+ int bIsSuccesl = 0;
+
+ if (i_Rank == 0)
+ {
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ int iLen = 0;
+ pd_Data = poDataEx->getData(DATACOLUMN, iLen);
+ i_Len = iLen;
+
+// printf("ILEN: %d", iLen);
+// fflush(stdout);
+
+ double dSx = getSx();
+ double dSy = getSy();
+ double dSxx = getSxx();
+ double dSyy = getSyy();
+ double dSxy = getSxy();
+// printf("Esses: %f,%f,%f,%f\n", dSx, dSy, dSxx, dSyy, dSxy);
+// fflush(stdout);
+ delete pd_Data;
+
+ i_Length = i_Length -1;
+
+ double dMu = ((dSy * dSxx) - (dSx * dSxy)) / ((i_Length * (dSxx - dSxy))
- (pow(dSx,2) - (dSx * dSy)));
+ double dLambda = (-1 / d_TimeStep) * (log((dSxy - dMu * dSx - dMu * dSy
+ i_Length * pow(dMu,2)) /
+ (dSxx - 2 * dMu * dSx + i_Length * pow(dMu,2))));
+
+ double dAlpha = exp(-1 * dLambda * d_TimeStep);
+
+ double dSigmaHatSq = (dSyy - (2 * dAlpha * dSxy) + (pow(dAlpha,2) *
dSxx) - (2 * dMu * (1-dAlpha) *
+ (dSy - dAlpha * dSx)) + (i_Length * pow(dMu,2) *
(pow((1-dAlpha),2)))) / i_Length;
+
+ double dSigmaSq = dSigmaHatSq * 2 * dLambda / (1 - pow(dAlpha,2));
+
+ pdCalibParams[0] = poDataEx->getLastData(pz_DataColumn);
+ pdCalibParams[1] = dMu;
+ pdCalibParams[2] = sqrt(dSigmaSq);
+ pdCalibParams[3] = dLambda;
+
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ delete poDataEx;
+ }
+ else
+ {
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ MPI_Send ( &bIsSuccesl, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ for(int i = 1; i < i_Size; i++)
+ {
+ MPI_Recv( &bIsSuccesl , 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ }
+ }
+
+ return pdCalibParams;
+}
+
+//************************************************************************
+
+double Calibrate::getSx()
+{
+ double dSx = 0;
+// printf("dSx: %d\n", i_Len);
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+// if (i == 1)
+// printf("dSx\n");
+ dSx += pd_Data[i - 1];
+ }
+ return dSx;
+}
+
+//************************************************************************
+
+double Calibrate::getSy()
+{
+ double dSy = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSy += pd_Data[i];//cout << pd_Data[i] << endl;
+ }
+ return dSy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxx()
+{
+ double dSxx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSxx += pow(pd_Data[i - 1],2);
+ }
+ return dSxx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyy()
+{
+ double dSyy= 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSyy += pow(pd_Data[i],2);
+ }
+ return dSyy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxy()
+{
+ double sumXY = 0;
+ for (unsigned int i = 1; i < i_Len; i++){
+ sumXY += pd_Data[i] * pd_Data[i-1];
+ }
+ return sumXY;
+}
+
+//************************************************************************
+
+double Calibrate::getSxPara()
+{
+ double dSx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSx += pd_Data[i - 1];
+ }
+ return dSx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyPara()
+{
+ double dSy = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSy += pd_Data[i];//cout << pd_Data[i] << endl;
+ }
+ return dSy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxxPara()
+{
+ double dSxx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSxx += pow(pd_Data[i - 1],2);
+ }
+ return dSxx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyyPara()
+{
+ double dSyy= 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSyy += pow(pd_Data[i],2);
+ }
+ return dSyy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxyPara()
+{
+ double sumXY = 0;
+ for (unsigned int i = 1; i < i_Len; i++){
+ sumXY += pd_Data[i] * pd_Data[i-1];
+ }
+ return sumXY;
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/Calibrate.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,72 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+//#include <iostream>
+//#include <vector>
+
+//using namespace std;
+
+class Calibrate
+{
+private:
+// std::vector<double> *pvData;
+ double *pd_Data;
+ unsigned int i_Len;
+ double getSx();
+ double getSy();
+ double getSxx();
+ double getSyy();
+ double getSxy();
+ double getSxPara();
+ double getSyPara();
+ double getSxxPara();
+ double getSyyPara();
+ double getSxyPara();
+ double d_TimeStep;
+
+ int i_Rank;
+ int i_Size;
+ int i_Length;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ double* calcParamInSingleMachine();
+ double* calcParamFromCentralDB();
+ double* calcParamReplicatedDB();
+// double* paramCalculation(vector<double> *data);
+// double parallelMGR(vector<double> *data);
+// double parallelVariance(vector<double> *data, double mean);
+ double* paramCalculation(double *data);
+ double parallelMGR(double *data);
+ double parallelVariance(double *data, double mean);
+
+public:
+ Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char* pzPW, char*
pzTName, char* pzDataColumn, int iRank, int iSize, double dTimeStep);
+ double* calcParameters();
+ bool checkTable();
+ ~Calibrate(void);
+
+
+};
=======================================
--- /dev/null
+++ /trunk/models/cir/DataExtracter.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,456 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+/*
+// //
+// // PROJECT : HPC4Finance
+// // MODULE : DataExtracter class Implimentation
+// // FILE : Data Extracter.cpp
+// // AUTHOR : Damitha Premadasa (dami...@gmail.com)
+// // DESC : The file consist of database related function in GBM.
+// This is satisfactorily tested with UNIX environment
+// and WINDOWS environment.
+// // TODO :
+// // HISTORY : Date of Creation: 5-Oct-2008
+// Modified:
+// //
+*/
+
+#include "DataExtracter.h"
+
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+
+#include "def.h"
+#include <stdio.h>
+#include <iostream>
+#include <mysql.h>
+#include <stdlib.h>
+#include <list>
+
+
+using namespace std;
+
+DataExtracter::DataExtracter(char* pzDName, char* pzUserName, char* pzPW,
char* pzTName, char* pzIP)
+{
+ pz_DBName = strdup(pzDName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+}
+
+
+DataExtracter::~DataExtracter(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+}
+
+// Get required data set for parameter calculation
+//vector<double> *DataExtracter::getData(char *coloumName)
+double *DataExtracter::getData(char *coloumName, int &iLen)
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ return NULL;
+ }
+ else
+ {
+ //cout << coloumName << " : " << pz_TableName << endl;
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s ORDER BY ID", coloumName ,pz_TableName
);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ mysql_close(pMysql);
+ return NULL;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);// DONE: check errors here
+ int iRows = pmsResult->row_count;
+ iLen = iRows;
+ if( iRows == 0 )
+ {
+ mysql_close(pMysql);
+ return NULL;
+ }
+
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+ return pdData;
+}
+
+// Get required data set for parameter calculation parallel
+//vector<double> *DataExtracter::getDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+double *DataExtracter::getDataParellel( int iStartingRow, int iEndingRow,
char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",
+ coloumName,pz_TableName ,iStartingRow,iEndingRow);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the number of records in the table
+int DataExtracter::getNoOfRows( void )
+{
+ int iRows;
+
+ MYSQL_RES *pmsResult;
+ MYSQL *pMysql = mysql_init(NULL);
+
+ if(!mysql_real_connect(pMysql,pz_IPAddress , pz_UserName,
pz_Password ,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ //const char* query = "SELECT Close FROM ibm";
+
+ char query[250];
+ sprintf(query, "SELECT * FROM %s", pz_TableName );
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult != NULL)
+ {
+ iRows = pmsResult->row_count;
+
+ if(iRows == 0)
+ {
+ return 0;
+ }
+ mysql_free_result(pmsResult);
+ }
+ else
+ {
+
+ if(mysql_errno(pMysql) == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ return 0;
+ }
+
+ return 0;
+ }
+ }
+ }
+
+
+ mysql_close(pMysql);
+
+ return iRows;
+}
+
+// Get data from local machines independently
+//vector<double> *DataExtracter::getReplicatedDataParellel( int
iStartingRow, int iEndingRow, char *coloumName )
+double *DataExtracter::getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",coloumName, pz_TableName, iStartingRow,iEndingRow);
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+
+ // pdData = new vector<double>;
+ pdData = new double[iRows];
+ int i = 0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the last item of the table
+double DataExtracter::getLastData(char* coloumName)
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ double result;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"select %s from %s where ID = (select max(ID) from %s )",
coloumName, pz_TableName, pz_TableName );
+ //const char* query = "select Close from ibm where ID = (select max(ID)
from ibm)";
+
+ mysql_select_db(pMysql, pz_DBName );
+
+ //int iQuery = mysql_real_query(pMysql, query, strlen(query));
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ result = atof(*msRow);
+ }
+
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+
+ return result;
+}
+
+// Get duration between first and last data element
+int DataExtracter::getDuration( void )
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ string cStartDate, cEndDate;
+ int iDateDifference;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query1[250];
+ sprintf(query1,"select Date from %s where ID = (select max(ID) from %s
)", pz_TableName, pz_TableName );
+ char query2[250];
+ sprintf(query2,"select Date from %s where ID = (select min(ID)
from %s)", pz_TableName , pz_TableName);
+
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ if(mysql_real_query(pMysql, query1, strlen(query1)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cEndDate = *msRow;
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ if(mysql_real_query(pMysql, query2, strlen(query2)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cStartDate = (*msRow);
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ char query[250];
+
+ sprintf(query,"SELECT DATEDIFF( \'%s\' , \'%s\'
)",cEndDate.c_str(),cStartDate.c_str());
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult == NULL)
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ iDateDifference = atoi(*msRow);
+ }
+ }
+ mysql_free_result(pmsResult);
+ }
+
+
+ }
+ }
+
+ mysql_close(pMysql);
+
+ return iDateDifference;
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/DataExtracter.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,57 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+//#include <vector>
+
+using namespace std;
+
+class DataExtracter
+{
+private:
+ int i_ResultLength;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_IPAddress;
+
+public:
+ DataExtracter(char* pzDName, char* pzUserName, char* pzPW, char* pzTName,
char* pzIP);
+// vector<double> *getData(char *coloumName);
+// vector<double> *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ double *getData(char *coloumName, int &iLen);
+ double *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ int getDuration(void);
+ int getNoOfRows(void);
+ double getLastData(char* coloumName);
+ //int getDurationParallel( int iStartingRow, int iEndingRow );
+// vector<double> *getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName );
+ double *getReplicatedDataParellel( int iStartingRow, int iEndingRow, char
*coloumName );
+ //int getReplicatedDurationParallel( int iStartingRow, int iEndingRow );
+ void setDBProperties(char* dbName, char* username, char* password, char*
tablename, char* ip );
+
+ int I_ResultLength() const { return i_ResultLength; }
+ void I_ResultLength(int val) { i_ResultLength = val; }
+
+public:
+ ~DataExtracter(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/cir/Logs.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,207 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <iostream>
+#include <fstream>
+//#include <sys/unistd.h>
+//#include <sys/socket.h>
+#include <vector>
+#include <netdb.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <exception>
+#include "def.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+Logs::Logs(char *czLogType) {
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ sprintf(pzFileName , "%s/%s/%s.txt", LOGLOCATION ,czLogType, psIPAddress);
+ poDuration = new Duration();
+ fLogs = new ofstream(pzFileName, ios::app);
+
+}
+
+Logs::Logs() {
+
+}
+
+void Logs::WriteLog(char *sError)
+{
+ char *pzMsg = strdup(sError);
+ int iMsgLen = strlen(pzMsg);
+
+ int isMsgFul = bIsMsgFull(iMsgLen);
+
+
+ if(isMsgFul == 1)
+ {
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else if(isMsgFul == 2)
+ {
+ strcat(pzErrorMsg,pzMsg);
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else
+ {
+ strcat(pzErrorMsg,pzMsg);
+ }
+}
+
+
+
+Logs::~Logs() {
+ // TODO Auto-generated destructor stub
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ fLogs->close();
+}
+
+int Logs::bIsMsgFull(int iLen)
+{
+ int iSize = strlen(pzErrorMsg)+ iLen;
+ if(iSize > 1024)
+ {
+ return 1;
+ }
+ else if(iSize == 1024)
+ {
+ return 2;
+ }
+
+ return 3;
+}
+
+void Logs::WriteLog(double dValue)
+{
+ char czValue[32];
+ sprintf(czValue,", %f",dValue);
+ WriteLog(czValue);
+}
+
+void Logs::writeTuning(double *dRatio, char **IPList, int size)
+{
+ char pzTuningFileName[256];
+ try {
+ sprintf(pzTuningFileName , "%s/tuning.txt", LOGLOCATION);
+ ofstream *fTuning = new ofstream(pzTuningFileName, ios::out);
+
+ for(int i = 0; i < size; i++)
+ {
+ char cTempValue[150];
+
+
+ if(i == size -1 )
+ {
+ sprintf(cTempValue,"%s %f", IPList[i] , dRatio[i] );
+ }
+ else
+ {
+ sprintf(cTempValue,"%s %f;", IPList[i] , dRatio[i] );
+ }
+
+ //printf("%d:%s",i,IPList[i] );
+ //fflush(stdout);
+
+ fTuning->write( cTempValue, strlen( cTempValue ));
+ //strcat(cTuningValue,cTempValue);
+ }
+ fTuning->close();
+ }
+ catch( const std::exception& e )
+ {
+ printf("%s", e.what());
+
+ return;
+ }
+
+}
+
+char* Logs::readLog(char *cpFileDestination)
+{
+ char *cpBuffer;
+ int iLength;
+ //pzFileName = strdup( cpFileDestination );
+ sprintf(pzFileName , "%s/%s", LOGLOCATION, cpFileDestination );
+
+ ifstream *fReading = new ifstream(pzFileName, ios::binary );
+
+ fReading->seekg (0, ios::end);
+ iLength = fReading->tellg();
+ fReading->seekg (0, ios::beg);
+
+ cpBuffer = new char [iLength];
+
+ fReading->read (cpBuffer,iLength);
+ fReading->close();
+ //printf("%s", cpBuffer );
+
+ return cpBuffer;
+}
+
+vector<string> *Logs::tokenizer(string cpBuffer, char cDelim)
+{
+ string sBuffer = cpBuffer;
+
+ vector<string> *psTokens = new vector<string>;
+
+ int lastPos=0, i=0;
+ // Find first "non-delimiter".
+ string::size_type pos = sBuffer.find_first_of(cDelim,lastPos);
+
+ while (string::npos != pos || string::npos != lastPos)
+ {
+ psTokens->push_back(sBuffer.substr(lastPos, pos - lastPos));
+
+ lastPos = sBuffer.find_first_not_of(cDelim, pos);
+ pos = sBuffer.find_first_of(cDelim, lastPos);
+ i++;
+ }
+
+ return psTokens;
+}
+
+bool Logs::checkFileExists(string fileName)
+{
+ bool bFileExists = true;
+ fstream inp;
+ //ofstream out;
+ sprintf(pzFileName , "%s/%s", LOGLOCATION ,fileName.c_str());
+
+ inp.open(pzFileName, ifstream::in);
+
+ //inp.close();
+ if(inp.fail())
+ {
+ inp.clear(ios::failbit);
+ bFileExists = false;
+ }
+
+ return bFileExists;
+
+}
=======================================
--- /dev/null
+++ /trunk/models/cir/Logs.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,56 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef Logs_H_
+#define Logs_H_
+
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include "duration.h"
+
+using namespace std;
+
+class Logs {
+
+
+private:
+ char *psIPAddress;
+ char pzFileName[250];
+ char pzErrorMsg[1024];
+ Duration *poDuration;
+ ofstream *fLogs;
+
+public:
+ Logs(char *czLogType);
+ Logs();
+ void WriteLog(char *sError);
+ void WriteLog(double dValue);
+ int bIsMsgFull(int iLen);
+ void writeTuning(double *dRatio, char **IPList, int size);
+ char *readLog(char *cpFileDestination);
+ vector<string> *tokenizer(string cpBuffer, char cDelim);
+ bool checkFileExists(string fileName);
+ virtual ~Logs();
+};
+
+#endif /* Logs_H_ */
=======================================
--- /dev/null
+++ /trunk/models/cir/Makefile Sun Jan 17 01:15:09 2010
@@ -0,0 +1,19 @@
+cir: DataExtracterO.o CalibrateO.o CIRModelO.o CIRTestO.o CIRO.o newran1.o
newran2.o myexcept.o simpstr.o extreal.o DurationO.o LogsO.o
+ mpicxx -O3 -Wall -L/usr/local/mysql/lib/mysql -lmysqlclient -lz
DataExtracterO.o CalibrateO.o CIRModelO.o CIRTestO.o CIRO.o newran1.o
newran2.o myexcept.o simpstr.o extreal.o DurationO.o LogsO.o -o cir
+CIRO.o: CIR.cpp CIR.h DataExtracter.h Calibrate.h CIRModel.h def.h Logs.h
+ mpicxx -O3 -Wall -I/home/cig4/mpich2-install/include
-I/home/cig4/Desktop/newran03 -c CIR.cpp -o CIRO.o
+DataExtracterO.o: DataExtracter.cpp DataExtracter.h def.h
+ g++ -O3 -Wall -I/usr/local/mysql/include/mysql -c DataExtracter.cpp -o
DataExtracterO.o
+CalibrateO.o: Calibrate.cpp Calibrate.h DataExtracter.h duration.h
+ mpicxx -O3 -Wall -I/usr/local/mysql/include/mysql
-I/home/cig4/mpich2-install/include -c Calibrate.cpp -o CalibrateO.o
+DurationO.o: duration.cpp duration.h
+ g++ -O3 -Wall -c duration.cpp -o DurationO.o
+LogsO.o: Logs.h Logs.cpp duration.h
+ g++ -O3 -Wall -c Logs.cpp -o LogsO.o
+CIRModelO.o: CIRModel.cpp CIRModel.h duration.h
+ g++ -O3 -Wall -I/home/cig4/Desktop/newran03 -c CIRModel.cpp -o CIRModelO.o
+CIRTestO.o: CIRTest.cpp CIR.h Calibrate.h DataExtracter.h duration.h
+ mpicxx -O3 -Wall -I/home/cig4/mpich2-install/include -c CIRTest.cpp -o
CIRTestO.o
+
+clean:
+ rm DataExtracterO.o CalibrateO.o CIRModelO.o CIRTestO.o CIRO.o
DurationO.o LogsO.o cir
=======================================
--- /dev/null
+++ /trunk/models/cir/def.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,41 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef _DEF_H_
+#define _DEF_H_
+#define DATABASE "data"
+#define DATACOLUMN "value"
+#define IP "10.8.102.27"
+#define USER "root"
+#define PWORD "cig4123"
+
+//Log Details
+#define LOGTYPE "transaction"
+#define LOGLOCATION "/mnt/models/logs"
+#define HEADLINE "\n========================Starting CIR Model
======================\n"
+
+//Tuning iterations
+#define ITERATIONS 1000
+#define TUNING ""
+#define NOTVISITED "notvisited"
+#define VISITED "visited"
+
+#endif //_DEF_H_
=======================================
--- /dev/null
+++ /trunk/models/cir/duration.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,80 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+#include "duration.h"
+//#include <iostream>
+
+//using namespace std;
+
+
+void Duration::setStart()
+{
+ gettimeofday(&tvStart, NULL);
+ tmStart = localtime(&tvStart.tv_sec);
+}
+
+void Duration::setEnd()
+{
+ gettimeofday(&tvEnd, NULL);
+ tmStart = localtime(&tvEnd.tv_sec);
+}
+
+double Duration::getPassedTime()
+{
+ double dStart = (double)tvStart.tv_sec +
(double)tvStart.tv_usec/1000000.0;
+ double dEnd = (double)tvEnd.tv_sec + (double)tvEnd.tv_usec/1000000.0;
+ return dEnd - dStart;
+}
+
+long int Duration::getCurrTime()
+{
+ gettimeofday(&tvEnd, NULL);
+ tmStart = localtime(&tvEnd.tv_sec);
+ long int dEnd = tvEnd.tv_sec * 1000000 + tvEnd.tv_usec;
+ return dEnd;
+}
+
+char* Duration::getSysTime()
+{
+ time_t rawtime;
+ time ( &rawtime );
+ char *czCurTime = new char[128];
+ sprintf(czCurTime, "%s",ctime (&rawtime));
+
+ return czCurTime;
+}
+//test programme
+/*int main(int argc, char* argv[])
+{
+ Duration du;
+ du.setStart();
+ sleep(5);
+ du.setEnd();
+ cout << du.getPassedTime() << endl;
+
+ return 0;
+}
+*/
+
=======================================
--- /dev/null
+++ /trunk/models/cir/duration.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,43 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef _DURATION_H_
+#define _DURATION_H_
+
+#include <time.h>
+#include <sys/time.h>
+
+class Duration
+{
+private:
+ struct timeval tvStart;
+ struct timeval tvEnd;
+ struct tm *tmStart;
+ struct tm *tmEnd;
+public:
+ void setStart();
+ void setEnd();
+ double getPassedTime();
+ long int getCurrTime();
+ char* getSysTime();
+};
+
+#endif //_DURATION_H_
=======================================
--- /dev/null
+++ /trunk/models/gbm/Calibrate.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,318 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+#include <stdio.h>
+#include <mysql.h>
+#include <stdlib.h>
+//#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include <math.h>
+#include <string.h>
+
+using namespace std;
+
+Calibrate::Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char*
pzPW, char* pzTName, char* pzDataColumn, int iRank, int iSize)
+{
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ i_Rank = iRank;
+ i_Size = iSize;
+}
+
+Calibrate::~Calibrate(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+}
+
+bool Calibrate::checkTable()
+{
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ bool status = true;
+ i_Length = poDataEx->getNoOfRows();
+ if(i_Length == 0)
+ {
+ status = false;;
+ }
+ else if (i_Length > 0)
+ {
+ i_Length = i_Length;
+ }
+ delete poDataEx;
+ return status;
+}
+
+// Calibrate mu, sigma for GBM using hostorical data
+double* Calibrate::calcParameters()
+{
+ double *pdCalibValues;
+ if(i_Length < 4000)
+ {
+ pdCalibValues = calcParamInSingleMachine();
+ }
+ else
+ {
+ pdCalibValues = calcParamReplicatedDB();
+ }
+
+ return pdCalibValues;
+}
+
+
+// Calibrate the mu and varience in a single machine
+double* Calibrate::calcParamInSingleMachine()
+{
+ MPI_Status mpiStatus;
+
+ double *pdCalibParams = new double[3];
+ int bIsSuccesl = 0;
+
+ if (i_Rank == 0)
+ {
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ //vector<double> *pdData = poDataEx->getData(pz_DataColumn);
+ int iLen = 0;
+ double *pdData = poDataEx->getData(pz_DataColumn, iLen);
+ if (iLen == 0)
+ {
+ return 0;
+ }
+
+ double *muAndSigma = paramCalculation(pdData, iLen);
+
+ pdCalibParams[0] = poDataEx->getLastData(pz_DataColumn);
+ pdCalibParams[1] = muAndSigma[0];
+ pdCalibParams[2] = muAndSigma[1];
+
+ MPI_Bcast ( pdCalibParams , 2, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ delete []muAndSigma;
+ delete pdData;
+ delete poDataEx;
+ }
+ else
+ {
+ MPI_Bcast ( pdCalibParams , 2, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ MPI_Send ( &bIsSuccesl, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ for(int i=1;i < i_Size ;i++)
+ {
+ MPI_Recv( &bIsSuccesl , 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ }
+ }
+
+ return pdCalibParams;
+}
+// Calibrate the mu and varience in multiple machines using replicated
datbases
+double* Calibrate::calcParamReplicatedDB()
+{
+ MPI_Status mpiStatus;
+ int iNoOfRows;
+
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, "localhost");
+ if (i_Length == 0)
+ return (double *)0;
+
+ iNoOfRows=(int)i_Length / i_Size;
+
+ int iInitialRow = iNoOfRows * i_Rank + 1;
+ int iFinalRow;
+
+ if( i_Rank == i_Size - 1)
+ {
+ iFinalRow = i_Length;
+ }
+ else
+ {
+ iFinalRow = iNoOfRows * (i_Rank + 1) + 1;
+ }
+
+// vector<double> *pdData =
poDataEx->getReplicatedDataParellel(iInitialRow,iFinalRow, pz_DataColumn);
+ double *pdData =
poDataEx->getReplicatedDataParellel(iInitialRow,iFinalRow, pz_DataColumn);
+
+ double dLocalTotMGR = parallelMGR(pdData, iFinalRow - iInitialRow + 1);
+
+ double dFinalStDev, dFinalMGR;
+ double dTotalVarience, dTotalMGR;
+
+ if(i_Rank != 0)
+ {
+ MPI_Send(&dLocalTotMGR, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ dTotalMGR = dLocalTotMGR;
+
+ double dTempParam;
+
+ for(int i=1;i < i_Size ;i++)
+ {
+ MPI_Recv(&dTempParam, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ dTotalMGR = dTotalMGR + dTempParam;
+ }
+ dFinalMGR = dTotalMGR / (i_Length-1);
+ }
+ MPI_Bcast ( &dFinalMGR, 1, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ fflush(stdout);
+ double dLocalTotVariance = parallelVariance(pdData, dFinalMGR, iFinalRow
- iInitialRow + 1);
+
+ if(i_Rank != 0)
+ {
+ MPI_Send(&dLocalTotVariance, 1, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ dTotalVarience = dLocalTotVariance;
+
+ double dTempParam;
+
+ for(int i = 1;i < i_Size ; i++)
+ {
+ MPI_Recv(&dTempParam, 1, MPI_DOUBLE, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ dTotalVarience += dTempParam;
+ }
+
+ double dFinalVarience = dTotalVarience / (i_Length-1);
+ dFinalStDev = sqrt(dFinalVarience);
+
+ }
+ MPI_Bcast ( &dFinalStDev, 1, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ double *resultSet = new double[3];
+
+ resultSet[0] = poDataEx->getLastData(pz_DataColumn);
+ resultSet[1] = dFinalMGR;
+ resultSet[2] = dFinalStDev;
+
+ delete pdData;
+ delete poDataEx;
+ return resultSet;
+}
+
+//double Calibrate::parallelVariance(vector<double> *data, double mean)
+double Calibrate::parallelVariance(double *data, double mean , int iSize)
+{
+ double dTotalVariance = 0;
+// int iArraySize = data->size();
+ int iArraySize = iSize;
+
+ for(int i = 1; i < iArraySize ; i++ )
+ {
+ double tempDifference =log(data[i]) - log(data[i-1]) ;
+ dTotalVariance += pow((tempDifference - mean),2) ;
+ }
+
+ return dTotalVariance;
+}
+
+//double Calibrate::parallelMGR(vector<double> *data)
+double Calibrate::parallelMGR(double *data, int iSize)
+{
+ double dTotalGrowthRate = 0;
+ //double dTotalSigma=0;
+ //double *partialParameters = new double[2];
+// vector<double> tempResults;
+// double *tempResults;
+// int iArraySize = data->size();
+ int iArraySize = iSize;
+
+ for (int i = 1;i < iArraySize ; i++ )
+ {
+ // double tempDifference = log(data->at(i)) - log(data->at(i-1)) ;
+ double tempDifference = log(data[i]) - log(data[i-1]) ;
+ dTotalGrowthRate += tempDifference;
+ }
+ return dTotalGrowthRate;
+}
+
+//double* Calibrate::paramCalculation(vector<double> *data)
+double* Calibrate::paramCalculation(double *data, int iSize)
+{
+
+ double dTotalGrowthRate = 0;
+ double dTotalSigma=0;
+ double *partialParameters = new double[2];
+// int iArraySize = data->size();
+ int iArraySize = iSize;
+// vector<double> tempResults;
+ double *tempResults = new double[iSize];
+
+ for (int i = 1; i < iArraySize; i++ )
+ {
+ if (data[i-1] == 0)
+ continue;
+ double tempDifference =log(data[i]) - log(data[i-1]) ;
+ // tempResults.push_back(tempDifference);
+ tempResults[i - 1] = tempDifference;
+ dTotalGrowthRate += tempDifference;
+ }
+
+ double average = dTotalGrowthRate / (iArraySize - 1);
+ partialParameters[0] = average;
+
+ for(int i = 1; i < iArraySize ; i++ )
+ {
+ // dTotalSigma += pow((tempResults.at(i-1) - average),2) ;
+ dTotalSigma += pow((tempResults[i-1] - average),2) ;
+ }
+
+ partialParameters[1] = sqrt(dTotalSigma / (iArraySize - 1));
+ delete []tempResults;
+
+ return partialParameters ;
+}
+
+// Calibrate the mu and varience in a multiple machines machine using
single database
+double* Calibrate::calcParamFromCentralDB()
+{
+ return 0;
+}
=======================================
--- /dev/null
+++ /trunk/models/gbm/Calibrate.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,52 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+//#include <vector.h>
+
+class Calibrate
+{
+private:
+ int i_Rank;
+ int i_Size;
+ int i_Length;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ double* calcParamInSingleMachine();
+ double* calcParamFromCentralDB();
+ double* calcParamReplicatedDB();
+// double* paramCalculation(vector<double> *data);
+// double parallelMGR(vector<double> *data);
+// double parallelVariance(vector<double> *data, double mean);
+ double* paramCalculation(double *data, int iSize);
+ double parallelMGR(double *data, int iSize);
+ double parallelVariance(double *data, double mean, int iSize);
+
+public:
+ Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char* pzPW, char*
pzTName, char* pzDataColumn, int iRank, int iSize);
+ double* calcParameters();
+ bool checkTable();
+ ~Calibrate(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/gbm/DataExtracter.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,458 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+/*
+// //
+// // PROJECT : HPC4Finance
+// // MODULE : DataExtracter class Implimentation
+// // FILE : DataExtracter.cpp
+// // AUTHOR : Damitha Premadasa (dami...@gmail.com)
+// // DESC : The file consist of database related function in GBM.
+// This is satisfactorily tested with UNIX environment
+// and WINDOWS environment.
+// // TODO :
+// // HISTORY : Date of Creation: 5-Oct-2008
+// Modified:
+// //
+*/
+
+#include "DataExtracter.h"
+
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+
+#include "def.h"
+#include <stdio.h>
+#include <iostream>
+#include <mysql.h>
+#include <stdlib.h>
+#include <list>
+
+
+using namespace std;
+
+DataExtracter::DataExtracter(char* pzDName, char* pzUserName, char* pzPW,
char* pzTName, char* pzIP)
+{
+ pz_DBName = strdup(pzDName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+}
+
+
+DataExtracter::~DataExtracter(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+}
+
+// Get required data set for parameter calculation
+//vector<double> *DataExtracter::getData(char *coloumName)
+double *DataExtracter::getData(char *coloumName, int &iLen)
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ return NULL;
+ }
+ else
+ {
+ //cout << coloumName << " : " << pz_TableName << endl;
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s ORDER BY ID", coloumName ,pz_TableName
);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ mysql_close(pMysql);
+ return NULL;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);// DONE: check errors here
+ int iRows = pmsResult->row_count;
+ iLen = iRows;
+
+ if( iRows == 0 )
+ {
+ mysql_close(pMysql);
+ return NULL;
+ }
+
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get required data set for parameter calculation parallel
+//vector<double> *DataExtracter::getDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+double *DataExtracter::getDataParellel( int iStartingRow, int iEndingRow,
char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",
+ coloumName,pz_TableName ,iStartingRow,iEndingRow);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the number of records in the table
+int DataExtracter::getNoOfRows( void )
+{
+ int iRows;
+
+ MYSQL_RES *pmsResult;
+ MYSQL *pMysql = mysql_init(NULL);
+
+ if(!mysql_real_connect(pMysql,pz_IPAddress , pz_UserName,
pz_Password ,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ //const char* query = "SELECT Close FROM ibm";
+
+ char query[250];
+ sprintf(query, "SELECT * FROM %s", pz_TableName );
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult != NULL)
+ {
+ iRows = pmsResult->row_count;
+
+ if(iRows == 0)
+ {
+ return 0;
+ }
+ mysql_free_result(pmsResult);
+ }
+ else
+ {
+
+ if(mysql_errno(pMysql) == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ return 0;
+ }
+
+ return 0;
+ }
+ }
+ }
+
+
+ mysql_close(pMysql);
+
+ return iRows;
+}
+
+// Get data from local machines independently
+//vector<double> *DataExtracter::getReplicatedDataParellel( int
iStartingRow, int iEndingRow, char *coloumName )
+double *DataExtracter::getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",coloumName, pz_TableName, iStartingRow,iEndingRow);
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+
+ // pdData = new vector<double>;
+ pdData = new double[iRows];
+ int i = 0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the last item of the table
+double DataExtracter::getLastData(char* coloumName)
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ double result;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"select %s from %s where ID = (select max(ID) from %s )",
coloumName, pz_TableName, pz_TableName );
+ //const char* query = "select Close from ibm where ID = (select max(ID)
from ibm)";
+
+ mysql_select_db(pMysql, pz_DBName );
+
+ //int iQuery = mysql_real_query(pMysql, query, strlen(query));
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ result = atof(*msRow);
+ }
+
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+
+ return result;
+}
+
+// Get duration between first and last data element
+int DataExtracter::getDuration( void )
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ string cStartDate, cEndDate;
+ int iDateDifference;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query1[250];
+ sprintf(query1,"select Date from %s where ID = (select max(ID) from %s
)", pz_TableName, pz_TableName );
+ char query2[250];
+ sprintf(query2,"select Date from %s where ID = (select min(ID)
from %s)", pz_TableName , pz_TableName);
+
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ if(mysql_real_query(pMysql, query1, strlen(query1)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cEndDate = *msRow;
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ if(mysql_real_query(pMysql, query2, strlen(query2)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cStartDate = (*msRow);
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ char query[250];
+
+ sprintf(query,"SELECT DATEDIFF( \'%s\' , \'%s\'
)",cEndDate.c_str(),cStartDate.c_str());
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult == NULL)
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ iDateDifference = atoi(*msRow);
+ }
+ }
+ mysql_free_result(pmsResult);
+ }
+
+
+ }
+ }
+
+ mysql_close(pMysql);
+
+ return iDateDifference;
+}
=======================================
--- /dev/null
+++ /trunk/models/gbm/DataExtracter.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,57 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+//#include <vector>
+
+using namespace std;
+
+class DataExtracter
+{
+private:
+ int i_ResultLength;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_IPAddress;
+
+public:
+ DataExtracter(char* pzDName, char* pzUserName, char* pzPW, char* pzTName,
char* pzIP);
+// vector<double> *getData(char *coloumName);
+// vector<double> *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ double *getData(char *coloumName, int &iLen);
+ double *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ int getDuration(void);
+ int getNoOfRows(void);
+ double getLastData(char* coloumName);
+ //int getDurationParallel( int iStartingRow, int iEndingRow );
+// vector<double> *getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName );
+ double *getReplicatedDataParellel( int iStartingRow, int iEndingRow, char
*coloumName );
+ //int getReplicatedDurationParallel( int iStartingRow, int iEndingRow );
+ void setDBProperties(char* dbName, char* username, char* password, char*
tablename, char* ip );
+
+ int I_ResultLength() const { return i_ResultLength; }
+ void I_ResultLength(int val) { i_ResultLength = val; }
+
+public:
+ ~DataExtracter(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/gbm/GBM.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,922 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+#include <stdio.h>
+#include "GBMotion.h"
+#include "math.h"
+#include <stdlib.h>
+#include <ctype.h>
+#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include "def.h"
+#include <string.h>
+#include "GBM.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+#define WRITE_LOG
+
+extern int i_Rank;
+
+
+GBM::GBM(int argCount, char **args, char* pzDBName, char* pzIP, char*
pzUserName, char* pzPW, char* pzDataColumn)
+{
+ i_ArgCount = argCount;
+ pz_Args = args;
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ pz_TableName = NULL;
+
+ int iRc = MPI_Init(&i_ArgCount, &pz_Args);
+ if (iRc != MPI_SUCCESS)
+ {
+ printf ("Error starting MPI program. Terminating.\n");
+ MPI_Abort(MPI_COMM_WORLD, iRc);
+ }
+
+ MPI_Comm_rank(MPI_COMM_WORLD, &i_Rank);
+ MPI_Comm_size(MPI_COMM_WORLD, &i_Size);
+
+ #ifdef WRITE_LOG
+ poTansLog = new Logs(LOGTYPE);
+ poTansLog->WriteLog(HEADLINE);
+
+ Duration d;
+ poTansLog->WriteLog(d.getSysTime());
+ #endif
+}
+
+double* GBM::getParams()
+{
+ double dInitial, dDrift, dSigma;
+
+ int iStdErr = dup(fileno(stderr));
+ close(fileno(stderr));
+ int iOption;
+ if(i_ArgCount == 8)
+ {
+ dInitial = (double)atof(pz_Args[1]);
+ dDrift = (double)atof(pz_Args[2]);
+ dSigma = (double)atof(pz_Args[3]);
+
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ dDrift /= 252;
+ dSigma /= sqrt(252);
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ dDrift /= 12;
+ dSigma /= sqrt(12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ dDrift /= 4;
+ dSigma /= sqrt(4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ //printf ("switches: %d:%d\n", i_Forecasts, i_Iterations);
+ }
+ else if(i_ArgCount == 7)
+ {
+ double factorDrift, factorSigma;
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "t:d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 't':
+ pz_TableName = optarg;
+ break;
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ factorDrift = 1.0;
+ factorSigma = 1.0;
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ factorDrift = 252 / 12;
+ factorSigma = sqrt(252 / 12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ factorDrift = 252 / 4;
+ factorSigma = sqrt(252 / 4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ factorDrift = 252.0;
+ factorSigma = sqrt(252);
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ //printf("Hi\n");
+ //fflush(stdout);
+ dup2(iStdErr, fileno(stderr));
+
+ //write(fileno(stderr), "fffff", 5); checking if stdErr is working
+ Calibrate *poCalc = new Calibrate(pz_DBName, pz_IPAddress,
pz_UserName, pz_Password, pz_TableName, pz_DataColumn,
i_Rank, i_Size);
+ //printf("Hi1\n");
+
+ bool bTableStatus = poCalc->checkTable();
+
+ if (!bTableStatus)
+ {
+ if (i_Rank == 0)
+ {
+ printf("error,No records found in Database");
+ fflush(stdout);
+ }
+ return 0;
+ }
+ double *pdCalibValues = poCalc->calcParameters();
+ if (pdCalibValues == NULL)
+ {
+ if (i_Rank == 0)
+ {
+ printf("error,No records found in Database");
+ fflush(stdout);
+ }
+ return 0;
+ }
+ dInitial = pdCalibValues[0] ;
+ dDrift = pdCalibValues[1] * factorDrift;
+ dSigma = pdCalibValues[2] * factorSigma;
+
+ delete poCalc;
+ }
+ else
+ {
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters\n");
+
+ //MPI_Finalize();
+ return 0;
+ }
+ if (i_Forecasts == 0)
+ {
+
+ if(i_Rank == 0)
+ {
+ printf("hi2\n");
+ fflush(stdout);
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ #ifdef WRITE_LOG
+
+ char pzJob[128];
+ sprintf(pzJob, "MC trials \t%d \nPredictions \t%d
\n",(int)i_Iterations/i_Size, i_Forecasts);
+ poTansLog->WriteLog(pzJob);
+
+ char pzCalibValues[256];
+ sprintf(pzCalibValues, "Initial Value \t%f \nMean \t\t%f \nSigma \t\t%f
\n", dInitial, dDrift, dSigma);
+ poTansLog->WriteLog(pzCalibValues);
+
+ #endif
+
+ double* pd_Params = new double[3];
+ pd_Params[0] = dInitial;
+ pd_Params[1] = dDrift;
+ pd_Params[2] = dSigma;
+
+ return pd_Params;
+}
+
+int GBM::getNthPrime(int n)
+{
+ int count = 0;
+ int primeNo = 0;
+ int k = 2;
+ while (count < n)
+ {
+
+ if (k == 2)
+ { // the only even prime
+ primeNo = 2;
+ count++;
+ }
+ else if (k % 2 == 0) // other even numbers are composite
+ {
+ k++;
+ continue;
+
+ }
+ else
+ {
+ bool prime = true;
+ int divisor = 3;
+ int upperLimit = static_cast<int>(sqrt(k) + 1);
+ while (divisor <= upperLimit)
+ {
+
+ if (k % divisor == 0)
+ prime = false;
+ divisor +=2;
+ }
+ if (prime == true)
+ {
+ primeNo = k;
+ count++;
+ }
+ }
+ k++;
+ }
+ return primeNo;
+}
+
+double* GBM::getPredicts(double *dParams)
+{
+ MPI_Status mpiStatus;
+ int iTag = 1;
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ int iSimsPerNode = i_Iterations / i_Size;
+ double dPerformaceRatio = 0;
+ double dPerformTotalRatio = 0;
+ int iGlobFreq = 0;
+
+
+ //check for file existance
+ Logs *poRatios = new Logs();
+ bool isFileExists = poRatios->checkFileExists("tuning.txt") ;
+
+ //tokenized tuning details
+ vector<vector<string> > *tuneFileList;
+ int iMachines = 0;
+
+ //////////////////////////////////////////////////////////
+ if(isFileExists)
+ {
+ char *cBuffer = poRatios->readLog("tuning.txt");
+ vector<string> *PerNodeRatio = poRatios->tokenizer(cBuffer, ';');
+
+ iMachines = PerNodeRatio->size();
+ tuneFileList = new vector<vector<string> >(iMachines, vector<string>
(3));
+
+ // read the tuning file
+ for(int i=0 ; i < iMachines; i++)
+ {
+ string temp = PerNodeRatio->at(i);
+ vector<string> *tmp= poRatios->tokenizer(temp, ' ');
+
+ for(int j = 0; j < 3 ; j++)
+ {
+ if(j != 2)
+ (*tuneFileList)[i][j] = tmp->at(j);
+ else
+ (*tuneFileList)[i][j] = NOTVISITED;
+ }
+ }
+
+ if(i_Rank != 0)
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0, iTag, MPI_COMM_WORLD);
+
+ else
+ {
+ int iNewMachinFreq = 0; // count new machines
+ char tempIPAddress[128];
+ vector< char* > *pIPRankDatails = new vector< char* >(i_Size); // IP
list according to their rank
+ vector< string *> *pvNewMachines = new vector< string *>; // IP List of
new machines
+
+ (*pIPRankDatails)[0] = strdup(psIPAddress);
+
+ for(int i =1; i < i_Size; i++)
+ {
+ MPI_Recv(&tempIPAddress, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ (*pIPRankDatails)[i] = strdup(tempIPAddress);
+ }
+
+ for(int j = 0; j < i_Size ; j++)
+ {
+ bool isMachineExists = false;
+ string sTempIPRank (pIPRankDatails->at(j));
+
+ // check whether the machine exists
+ for (int i =0; i < iMachines ; i++ )
+ {
+ string sTempTuneList((*tuneFileList)[i][0]);
+ if( sTempTuneList.compare(sTempIPRank) == 0)
+ {
+ isMachineExists = true;
+ break;
+ }
+ }
+
+ if( !isMachineExists )
+ {
+ bool bInMachineList = false;
+ for (int k =0; k < pvNewMachines->size() ; k++ )
+ {
+ if( sTempIPRank.compare((*pvNewMachines)[k][0]) == 0)
+ {
+ int iTempFreq = atoi((*pvNewMachines)[k][1].c_str());
+ iTempFreq++;
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",iTempFreq);
+ (*pvNewMachines)[k][1] = sTempFreq;
+ bInMachineList = true;
+ }
+ }
+
+ if(!bInMachineList)
+ {
+ string *vTemp = new string[2];
+ vTemp[0] = pIPRankDatails->at(j);
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",1);
+ vTemp[1] = sTempFreq;
+ pvNewMachines->push_back(vTemp);
+ iNewMachinFreq++;
+ iGlobFreq++;
+ }
+ }
+ }
+
+ // if new machine are not added
+ vector<vector<string> *> *frequencyList = new vector<vector<string> *>;
+ double tempTotal = 0;
+ double dtempRatios = 0;
+
+ // keep machine name : total ratio
+ vector< string > *pvFreqListElement;
+
+ for (int i = 0; i < iMachines; i++)
+ {
+
+ pvFreqListElement = new vector< string >(3);
+ int frequency=0;
+
+ for (int j = 0; j < i_Size; j++)
+ {
+ if((*tuneFileList)[i][0].compare(pIPRankDatails->at(j))==0)
+ frequency++;
+ }
+
+ // if machine is used for run the process insert to the frequency list
+ if(frequency > 0)
+ {
+ tempTotal += frequency * (atof((*tuneFileList)[i][1].c_str()));
+ dPerformTotalRatio += atof((*tuneFileList)[i][1].c_str());
+
+ char tempDRatio[sizeof(double) +1];
+ sprintf( tempDRatio,"%f",(frequency *
(atof((*tuneFileList)[i][1].c_str()))));
+ (*pvFreqListElement)[0] = (*tuneFileList)[i][0];
+ (*pvFreqListElement)[1] = tempDRatio;
+ (*pvFreqListElement)[2] = (*tuneFileList)[i][1];
+ frequencyList->push_back(pvFreqListElement);
+ iGlobFreq++;
+ }
+ }
+
+ for(int i = 0; i < i_Size ; i++ )
+ {
+ bool bNewFile = true;
+ for(int j = 0; j < frequencyList->size(); j++)
+ {
+ if(string((*pIPRankDatails)[i]).compare((*(*frequencyList)[j])[0]) ==
0)
+ {
+ double tempVal = atof((*(*frequencyList)[j])[2].c_str()) /
tempTotal ;
+ dtempRatios = tempVal * ( (double)(i_Size-
iNewMachinFreq)/(double)i_Size);
+
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+
+ bNewFile = false;
+ break;
+ }
+ }
+ if(bNewFile)
+ {
+ dtempRatios = 1.0 / (double)i_Size;
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+ }
+
+ }
+
+ delete frequencyList;
+ delete pIPRankDatails;
+ }
+
+ if(i_Rank != 0)
+ MPI_Recv(&dPerformaceRatio, 1, MPI_DOUBLE, 0, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ iSimsPerNode = (int)(dPerformaceRatio * i_Iterations);
+
+ }
+ else
+ iGlobFreq = i_Size;
+
+
+ double dInitial = dParams[0];
+ double dDrift = dParams[1];
+ double dSigma = dParams[2];
+ double dTimeDivisions = 10.0;
+
+ Duration oDuration;
+ oDuration.setStart();
+
+ double dCurrTime = 0;
+
+
+ if(i_Rank == 0)
+ {
+ dCurrTime = (double)oDuration.getCurrTime();
+ }
+
+ MPI_Bcast ( &dCurrTime, 1, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ double dSeed = dCurrTime * getNthPrime( i_Rank + i_Size);
+
+ char cSeed[32];
+ sprintf(cSeed , "Seed value :%f \n" , dCurrTime);
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog(cSeed);
+ #endif
+
+
+ vector<vector<double> > *pvResults = new vector<vector<double>
>((i_Forecasts), vector<double> (iSimsPerNode));
+
+ for (int i = 0; i < iSimsPerNode ; i++)
+ {
+
+ CGBMotion oGBM(dInitial, dDrift, dSigma, 1.0 / dTimeDivisions, dSeed);
// our brownian motion object
+
+ for (int k = 0; k < i_Forecasts; k++)
+ {
+ double dTemp = 0;
+ for (int j = 0; j < dTimeDivisions; j++)
+ {
+ dTemp = oGBM.step();
+ }
+ (*pvResults)[k][i] = dTemp;
+ //printf("%f,", (*pvResults)[k][i]);
+ }
+ }
+ double daLocalCalibVals[i_Forecasts];
+
+ for(int i=0; i< (i_Forecasts) ; i++ )
+ {
+ double dTotal = 0;
+
+ for(int k= 0; k < iSimsPerNode; k++ )
+ {
+ dTotal += (*pvResults)[i][k];
+ }
+
+ //daLocalCalibVals[i]= dTotal / iSimsPerNode;
+ daLocalCalibVals[i]= dTotal ;
+ }
+
+ delete pvResults;
+
+ oDuration.setEnd();
+ double dDuration = oDuration.getPassedTime() / iSimsPerNode;
+ double dInvDuration = 1/dDuration;
+
+ if (i_Rank != 0)
+ {
+ MPI_Send(&daLocalCalibVals, i_Forecasts, MPI_DOUBLE, 0,iTag,
MPI_COMM_WORLD);
+ MPI_Send(&dInvDuration, 1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0,iTag, MPI_COMM_WORLD);
+ }
+
+ double *dPredictValues = new double[i_Forecasts];
+ double *dInvDurationValues= new double[iGlobFreq];
+ char **pzIPAddress = new char*[iGlobFreq];
+ for (int i = 0; i < iGlobFreq; i++)
+ pzIPAddress[i] = new char[128];
+
+ if (i_Rank == 0)
+ {
+ double dTempDuration = 0;
+ double dTotal = 0;
+
+ dInvDurationValues[0] = dInvDuration;
+ dTotal = dInvDurationValues[0];
+ strcpy(pzIPAddress[0], psIPAddress);
+
+ double dTempResults[i_Forecasts];
+ vector<vector<double> > finalResults(i_Size, vector<double>
(i_Forecasts));
+
+ for (int i=0; i < i_Forecasts; i++)
+ finalResults[0][i] = daLocalCalibVals[i] ;
+
+ // Wait for results from other processes
+ for (int i = 1; i < i_Size; i++)
+ {
+
+ MPI_Recv(&dTempResults, i_Forecasts, MPI_DOUBLE, i, iTag,
MPI_COMM_WORLD, &mpiStatus);
+
+ for (int k=0; k < i_Forecasts; k++)
+ finalResults[i][k] = dTempResults[k];
+
+ char tempIP[128];
+ MPI_Recv(&dTempDuration, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ MPI_Recv(&tempIP, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD, &mpiStatus);
+
+ bool bReplicatedMachine = false;
+
+ for(int j = 0;j < i ;j++)
+ {
+ if(string(tempIP).compare(string(pzIPAddress[j])) == 0)
+ {
+ double dTemp = dInvDurationValues[j];
+ dInvDurationValues[j] = (dInvDurationValues[j]+dTempDuration) / 2;
+ bReplicatedMachine = true;
+ dTotal = dTotal - dTemp + dInvDurationValues[j];
+ }
+ }
+
+ if(!bReplicatedMachine)
+ {
+ strcpy(pzIPAddress[i], tempIP);
+ dInvDurationValues[i] = dTempDuration;
+ dTotal += dInvDurationValues[i];
+ }
+ }
+
+ for (int i = 0; i < i_Forecasts; i++ )
+ {
+ double totalForcastValues = 0;
+
+ for( int k =0; k < i_Size ; k++ )
+ totalForcastValues += finalResults[k][i];
+
+ dPredictValues[i] = totalForcastValues/ i_Iterations;
+
+
+ if(i != i_Forecasts-1)
+ {
+
+ }
+ }
+
+ /*for(int i=0; i < iGlobFreq; i++)
+ {
+ printf("%s:%f \n",pzIPAddress[i],dInvDurationValues[i]);
+ }*/
+
+ double *dRatio = new double[iGlobFreq];
+ char **pzTuningIPAddress ;
+ double *dModifiedRatio;
+
+ if(i_Size < iMachines )
+ {
+ dModifiedRatio = new double[iMachines];
+ pzTuningIPAddress = new char*[iMachines];
+ for (int i = 0; i < iMachines; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+ else
+ {
+ dModifiedRatio = new double[i_Size];
+ pzTuningIPAddress = new char*[i_Size];
+ for (int i = 0; i < i_Size; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+
+ for(int i = 0; i < iGlobFreq ;i++)
+ {
+ dRatio[i] = dInvDurationValues[i] / dTotal;
+ }
+
+ Logs *poTune = new Logs();
+
+ if((i_Size == iMachines) ||(iMachines == 0 && !isFileExists))
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (dRatio[i] +
atof((*tuneFileList)[i][1].c_str()))/2;
+ break;
+ }
+ }
+ }
+ if(i_Size > 2)
+ {
+ poTune->writeTuning( dModifiedRatio, pzIPAddress , iGlobFreq);
+ }
+ }
+ else
+ {
+ if(i_Size > 2)
+ {
+ poTune->writeTuning( dRatio, pzIPAddress , iGlobFreq);
+ }
+ }
+ }
+ else if(i_Size != iMachines )
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ bool bNewMachine = true;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (( dRatio[i] * dPerformTotalRatio)+
atof((*tuneFileList)[i][1].c_str()))/2;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ (*tuneFileList)[i][2] = VISITED;
+ bNewMachine = false;
+ break;
+ }
+ }
+ if(bNewMachine)
+ {
+ dModifiedRatio[j] = dRatio[j]/2.0;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ }
+ }
+
+ int tempIncrement =0;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][2].compare(NOTVISITED) == 0)
+ {
+ if(i_Size <= iMachines)
+ {
+ dModifiedRatio[tempIncrement+i_Size] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+i_Size],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ else
+ {
+ dModifiedRatio[tempIncrement+iMachines] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+iMachines],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ }
+ }
+ if(i_Size > 2)
+ {
+ if( iMachines >= i_Size )
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iMachines);
+ else
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iGlobFreq );
+ }
+ }
+ }
+ }
+
+ delete [] dInvDurationValues;
+ for (int i = 0; i < iGlobFreq; i++)
+ {
+ delete []pzIPAddress[i];
+ }
+ delete [] pzIPAddress;
+
+ MPI_Bcast (dPredictValues, i_Forecasts, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+ //MPI_Finalize();
+ return dPredictValues;
+}
+
+GBM::~GBM(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ //if (pz_TableName)
+ // delete pz_TableName;//TODO: FIND OUT WHY MEMORY CORRUPTION
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+
+ MPI_Finalize();
+
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog("-END- \n");
+ delete poTansLog;
+ #endif
+}
+
+bool GBM::validateParams(int i_ArgCount,char* args[])
+{
+ if(i_ArgCount == 8)
+ {
+ for(int i = 1; i < i_ArgCount; i++)
+ {
+ int iStrLen = strlen(args[i]);
+ int iDots = 0;
+
+ for (int j = 0; j < iStrLen; j++)
+ {
+ if(isdigit(args[i][j]) == 0)
+ {
+ if (j == 0 && args[i][j] == '-')
+ {
+ continue;
+ }
+
+ if(args[i][j] != '.')
+ {
+ return false;
+ }
+ else
+ {
+ iDots++;
+
+ if ((iStrLen == 1) || (iDots > 1))
+ {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ else if(i_ArgCount == 7)
+ {
+ if(((strcmp(args[1], "-t") == 0) && ((strcmp(args[3], "-d") == 0) ||
(strcmp(args[3], "-m") == 0)) && (strcmp(args[5], "-n") == 0)) ||
((strcmp(args[1], "-t") == 0) && ((strcmp(args[5], "-d") == 0) ||
(strcmp(args[5], "-m") == 0)) && (strcmp(args[3], "-n") == 0)))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+/*void GBM::tuneCluster(double *dParams)
+{
+ int iSimsPerNode = ITERATIONS;
+
+ int iTag = 1;
+ double dInitial = dParams[0];
+ double dDrift = dParams[1];
+ double dSigma = dParams[2];
+ double dTimeDivisions = 10.0;
+
+ Duration oDuration;
+ oDuration.setStart();
+
+ MPI_Status mpiStatus;
+
+ vector<vector<double> > *pvResults = new vector<vector<double>
>((i_Forecasts), vector<double> (iSimsPerNode));
+
+ for (int i = 0; i < iSimsPerNode ; i++)
+ {
+
+ CGBMotion oGBM(dInitial, dDrift, dSigma, 1.0 / dTimeDivisions); // our
brownian motion object
+
+ for (int k = 0; k < i_Forecasts; k++)
+ {
+ double dTemp = 0;
+ for (int j = 0; j < dTimeDivisions; j++)
+ {
+ dTemp = oGBM.step();
+ }
+ (*pvResults)[k][i] = dTemp;
+ //printf("%f,", (*pvResults)[k][i]);
+ }
+ }
+ double daLocalCalibVals[i_Forecasts];
+
+ for(int i=0; i< (i_Forecasts) ; i++ )
+ {
+ double dTotal = 0;
+
+ for(int k= 0; k < iSimsPerNode; k++ )
+ {
+ dTotal += (*pvResults)[i][k];
+ }
+
+ daLocalCalibVals[i]= dTotal / iSimsPerNode;
+ }
+
+ delete pvResults;
+
+ oDuration.setEnd();
+ double dDuration = oDuration.getPassedTime();
+
+
+ if (i_Rank != 0)
+ {
+ MPI_Send(&dDuration, 1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+
+ double* dDurationValues = new double[i_Size];
+
+ if (i_Rank == 0)
+ {
+ double dTempDuration;
+ double dTotal;
+
+ dDurationValues[0] = dDuration;
+ dTotal = dDurationValues[0];
+
+ printf("%f \t",dDurationValues[0]);
+ fflush(stdout);
+
+ // Wait for results from other processes
+ for (int i = 1; i < i_Size; i++)
+ {
+ MPI_Recv(&dTempDuration, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ dDurationValues[i] = dTempDuration;
+ dTotal += dDurationValues[i];
+
+ printf("%f \t",dDurationValues[i]);
+ fflush(stdout);
+ }
+
+ printf("Total = %f \t", dTotal);
+ fflush(stdout);
+
+
+ }
+
+}*/
+
+
=======================================
--- /dev/null
+++ /trunk/models/gbm/GBM.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,51 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+
+#include "Logs.h"
+
+class GBM
+{
+private:
+ int i_ArgCount;
+ char** pz_Args;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ char* pz_TableName;
+ int i_Size;
+ int i_Iterations;
+ bool validateParams(int argc,char* args[]);// parameter validation
+ Logs *poTansLog;
+ int getNthPrime(int n);
+
+public:
+ GBM(int argCount, char* args[], char* pzDBName, char* pzIP, char*
pzUserName, char* pzPW, char* pzDataColumn);
+
+ int i_Forecasts;
+ double* getParams();
+ double* getPredicts(double *dParams);
+ //void tuneCluster(double *dParams);
+ ~GBM(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/gbm/GBMTest.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,64 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <stdio.h>
+#include "GBM.h"
+#include "duration.h"
+#include "def.h"
+
+using namespace std;
+
+int i_Rank;
+
+int main(int argc, char* argv[])
+{
+ Duration d;
+ d.setStart();
+ {
+ GBM oGBM(argc, argv, DATABASE, IP, USER, PWORD, DATACOLUMN);
+
+ double* params = oGBM.getParams();
+ if (params != 0)
+ {
+ double* predicts = oGBM.getPredicts(params);
+ d.setEnd();
+
+ double dPassedTime = d.getPassedTime();
+ if (i_Rank == 0)
+ {
+ printf("Params,Intial value=%f,Mean=%f,Sigma=%f,Time=%f:Values",
params[0], params[1], params[2], dPassedTime);
+ fflush(stdout);
+ }
+
+ if (i_Rank == 0)
+ {
+ for (int i = 0; i < oGBM.i_Forecasts; i++)
+ {
+ printf(",%f",predicts[i]);
+ fflush(stdout);
+ }
+ }
+ delete []params;
+ delete []predicts;
+ }
+ }
+ return 0;
+}
=======================================
--- /dev/null
+++ /trunk/models/gbm/GBMotion.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,65 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+/*The exact solution of the Stochastic Differential Equation has been used
+refer: http://www.sitmo.com/eq/166
+There is a conflict with the equation given in
http://books.google.lk/books?id=nh6zHOf9tn0C&pg=PA63&lpg=PA63&dq=exact+solution+of+the+geometric+brownian+motion+SDE&source=web&ots=ZU7ooKCvwj&sig=DWnt0a4SGwloey70AC4FBtPmz-g&hl=en&sa=X&oi=book_result&resnum=5&ct=result#PPA65,M1
+The difference is the presence of a sqrt(t) term in the sitmo article.
+*/
+
+#include <stdio.h>
+#include "GBMotion.h"
+#include <math.h>
+#include <cstdlib>
+#include <ctime>
+#include "duration.h"
+
+using namespace boost;
+using namespace std;
+
+CGBMotion::CGBMotion(double nSInitial, double nDrift, double nSigma,
double deltaT, double dSeed)
+{
+ m_nCurrValue = nSInitial;
+ m_nDrift = nDrift;
+ m_nSigma = nSigma;
+ m_nDeltaT = deltaT;
+ //m_nCurrentDiffusion = 0;
+ static mt19937 engine(static_cast<unsigned> (dSeed));
+ normal_distribution<> normal_dist;
+ d_vGen = new variate_generator<mt19937&, normal_distribution<double>
>(engine, normal_dist);
+}
+
+CGBMotion::~CGBMotion(void)
+{
+ delete d_vGen;
+}
+
+double CGBMotion::step()
+{
+ double random_number = (*d_vGen)();
+ //cout << "Ran No: " << random_number << endl;
+ double m_nCurrentDiffusion = sqrt(m_nDeltaT) * random_number;
+ m_nCurrValue *= exp(m_nDrift*m_nDeltaT - .5* m_nSigma *
m_nSigma*m_nDeltaT
+ + m_nSigma*m_nCurrentDiffusion);
+
+ return m_nCurrValue;
+
+}
=======================================
--- /dev/null
+++ /trunk/models/gbm/GBMotion.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,44 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+#include <math.h>
+#include <boost/random.hpp>
+
+using namespace boost;
+
+class CGBMotion
+{
+private:
+ variate_generator<mt19937&, normal_distribution<double> > *d_vGen;
+
+ double m_nCurrValue; // initial security value (constant)
+ double m_nDrift; // our drift (constant)
+ double m_nSigma; // our volatility (constant)
+ double m_nDeltaT; // the current elapsed time
+
+public:
+
+ CGBMotion(double nSInitial, double nDrift, double nSigma, double deltaT,
double dSeed );
+ ~CGBMotion(void);
+ double step();
+
+};
=======================================
--- /dev/null
+++ /trunk/models/gbm/Logs.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,207 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <iostream>
+#include <fstream>
+//#include <sys/unistd.h>
+//#include <sys/socket.h>
+#include <vector>
+#include <netdb.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <exception>
+#include "def.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+Logs::Logs(char *czLogType) {
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ sprintf(pzFileName , "%s/%s/%s.txt", LOGLOCATION ,czLogType, psIPAddress);
+ poDuration = new Duration();
+ fLogs = new ofstream(pzFileName, ios::app);
+
+}
+
+Logs::Logs() {
+
+}
+
+void Logs::WriteLog(char *sError)
+{
+ char *pzMsg = strdup(sError);
+ int iMsgLen = strlen(pzMsg);
+
+ int isMsgFul = bIsMsgFull(iMsgLen);
+
+
+ if(isMsgFul == 1)
+ {
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else if(isMsgFul == 2)
+ {
+ strcat(pzErrorMsg,pzMsg);
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else
+ {
+ strcat(pzErrorMsg,pzMsg);
+ }
+}
+
+
+
+Logs::~Logs() {
+ // TODO Auto-generated destructor stub
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ fLogs->close();
+}
+
+int Logs::bIsMsgFull(int iLen)
+{
+ int iSize = strlen(pzErrorMsg)+ iLen;
+ if(iSize > 1024)
+ {
+ return 1;
+ }
+ else if(iSize == 1024)
+ {
+ return 2;
+ }
+
+ return 3;
+}
+
+void Logs::WriteLog(double dValue)
+{
+ char czValue[32];
+ sprintf(czValue,", %f",dValue);
+ WriteLog(czValue);
+}
+
+void Logs::writeTuning(double *dRatio, char **IPList, int size)
+{
+ char pzTuningFileName[256];
+ try {
+ sprintf(pzTuningFileName , "%s/tuning.txt", LOGLOCATION);
+ ofstream *fTuning = new ofstream(pzTuningFileName, ios::out);
+
+ for(int i = 0; i < size; i++)
+ {
+ char cTempValue[150];
+
+
+ if(i == size -1 )
+ {
+ sprintf(cTempValue,"%s %f", IPList[i] , dRatio[i] );
+ }
+ else
+ {
+ sprintf(cTempValue,"%s %f;", IPList[i] , dRatio[i] );
+ }
+
+ //printf("%d:%s",i,IPList[i] );
+ //fflush(stdout);
+
+ fTuning->write( cTempValue, strlen( cTempValue ));
+ //strcat(cTuningValue,cTempValue);
+ }
+ fTuning->close();
+ }
+ catch( const std::exception& e )
+ {
+ printf("%s", e.what());
+
+ return;
+ }
+
+}
+
+char* Logs::readLog(char *cpFileDestination)
+{
+ char *cpBuffer;
+ int iLength;
+ //pzFileName = strdup( cpFileDestination );
+ sprintf(pzFileName , "%s/%s", LOGLOCATION, cpFileDestination );
+
+ ifstream *fReading = new ifstream(pzFileName, ios::binary );
+
+ fReading->seekg (0, ios::end);
+ iLength = fReading->tellg();
+ fReading->seekg (0, ios::beg);
+
+ cpBuffer = new char [iLength];
+
+ fReading->read (cpBuffer,iLength);
+ fReading->close();
+ //printf("%s", cpBuffer );
+
+ return cpBuffer;
+}
+
+vector<string> *Logs::tokenizer(string cpBuffer, char cDelim)
+{
+ string sBuffer = cpBuffer;
+
+ vector<string> *psTokens = new vector<string>;
+
+ int lastPos=0, i=0;
+ // Find first "non-delimiter".
+ string::size_type pos = sBuffer.find_first_of(cDelim,lastPos);
+
+ while (string::npos != pos || string::npos != lastPos)
+ {
+ psTokens->push_back(sBuffer.substr(lastPos, pos - lastPos));
+
+ lastPos = sBuffer.find_first_not_of(cDelim, pos);
+ pos = sBuffer.find_first_of(cDelim, lastPos);
+ i++;
+ }
+
+ return psTokens;
+}
+
+bool Logs::checkFileExists(string fileName)
+{
+ bool bFileExists = true;
+ fstream inp;
+ //ofstream out;
+ sprintf(pzFileName , "%s/%s", LOGLOCATION ,fileName.c_str());
+
+ inp.open(pzFileName, ifstream::in);
+
+ //inp.close();
+ if(inp.fail())
+ {
+ inp.clear(ios::failbit);
+ bFileExists = false;
+ }
+
+ return bFileExists;
+
+}
=======================================
--- /dev/null
+++ /trunk/models/gbm/Logs.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,56 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef Logs_H_
+#define Logs_H_
+
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include "duration.h"
+
+using namespace std;
+
+class Logs {
+
+
+private:
+ char *psIPAddress;
+ char pzFileName[250];
+ char pzErrorMsg[1024];
+ Duration *poDuration;
+ ofstream *fLogs;
+
+public:
+ Logs(char *czLogType);
+ Logs();
+ void WriteLog(char *sError);
+ void WriteLog(double dValue);
+ int bIsMsgFull(int iLen);
+ void writeTuning(double *dRatio, char **IPList, int size);
+ char *readLog(char *cpFileDestination);
+ vector<string> *tokenizer(string cpBuffer, char cDelim);
+ bool checkFileExists(string fileName);
+ virtual ~Logs();
+};
+
+#endif /* Logs_H_ */
=======================================
--- /dev/null
+++ /trunk/models/gbm/Makefile Sun Jan 17 01:15:09 2010
@@ -0,0 +1,18 @@
+gbm: DataExtracterO.o CalibrateO.o DurationO.o GBMTestO.o GBMO.o
GBMotionO.o LogsO.o
+ mpicxx -O3 -ffast-math -Wall -L/usr/local/mysql/lib/mysql -lmysqlclient
-lz DataExtracterO.o CalibrateO.o DurationO.o LogsO.o GBMMotionO.o GBMO.o
GBMTestO.o -o gbm
+DataExtracterO.o: DataExtracter.cpp DataExtracter.h def.h
+ g++ -O3 -ffast-math -Wall -I/usr/local/mysql/include/mysql -c
DataExtracter.cpp -o DataExtracterO.o
+CalibrateO.o: Calibrate.cpp Calibrate.h DataExtracter.h duration.h
+ mpicxx -O3 -ffast-math -Wall -I/usr/local/mysql/include/mysql
-I/home/cig4/mpich2-install/include -c Calibrate.cpp -o CalibrateO.o
+DurationO.o: duration.cpp duration.h
+ g++ -O3 -ffast-math -Wall -c duration.cpp -o DurationO.o
+LogsO.o: Logs.h Logs.cpp duration.h
+ g++ -O3 -ffast-math -Wall -c Logs.cpp -o LogsO.o
+GBMotionO.o: GBMotion.cpp GBMotion.h duration.h
+ g++ -O3 -ffast-math -Wall -c GBMotion.cpp -o GBMMotionO.o
+GBMO.o: GBM.cpp GBM.h DataExtracter.h Calibrate.h GBMotion.h def.h Logs.h
+ mpicxx -O3 -ffast-math -Wall -I/home/cig4/mpich2-install/include
-I/usr/local/mysql/include/mysql -c GBM.cpp -o GBMO.o
+GBMTestO.o: GBMTest.cpp GBM.h def.h duration.h
+ g++ -O3 -ffast-math -Wall -c GBMTest.cpp -o GBMTestO.o
+clean:
+ rm *.o gbm
=======================================
--- /dev/null
+++ /trunk/models/gbm/def.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,41 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef _DEF_H_
+#define _DEF_H_
+#define DATABASE "data"
+#define DATACOLUMN "value"
+#define IP "10.8.102.27"
+#define USER "root"
+#define PWORD "cig4123"
+
+//Log Details
+#define LOGTYPE "transaction"
+#define LOGLOCATION "/mnt/models/logs"
+#define HEADLINE "\n========================Starting GBM Model
======================\n"
+
+//Tuning iterations
+#define ITERATIONS 1000
+#define TUNING ""
+#define NOTVISITED "notvisited"
+#define VISITED "visited"
+
+#endif //_DEF_H_
=======================================
--- /dev/null
+++ /trunk/models/gbm/duration.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,80 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/time.h>
+#include "duration.h"
+//#include <iostream>
+
+//using namespace std;
+
+
+void Duration::setStart()
+{
+ gettimeofday(&tvStart, NULL);
+ tmStart = localtime(&tvStart.tv_sec);
+}
+
+void Duration::setEnd()
+{
+ gettimeofday(&tvEnd, NULL);
+ tmStart = localtime(&tvEnd.tv_sec);
+}
+
+double Duration::getPassedTime()
+{
+ double dStart = (double)tvStart.tv_sec +
(double)tvStart.tv_usec/1000000.0;
+ double dEnd = (double)tvEnd.tv_sec + (double)tvEnd.tv_usec/1000000.0;
+ return dEnd - dStart;
+}
+
+long int Duration::getCurrTime()
+{
+ gettimeofday(&tvEnd, NULL);
+ tmStart = localtime(&tvEnd.tv_sec);
+ long int dEnd = tvEnd.tv_sec * 1000000 + tvEnd.tv_usec;
+ return dEnd;
+}
+
+char* Duration::getSysTime()
+{
+ time_t rawtime;
+ time ( &rawtime );
+ char *czCurTime = new char[128];
+ sprintf(czCurTime, "%s",ctime (&rawtime));
+
+ return czCurTime;
+}
+//test programme
+/*int main(int argc, char* argv[])
+{
+ Duration du;
+ du.setStart();
+ sleep(5);
+ du.setEnd();
+ cout << du.getPassedTime() << endl;
+
+ return 0;
+}
+*/
+
=======================================
--- /dev/null
+++ /trunk/models/gbm/duration.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,43 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef _DURATION_H_
+#define _DURATION_H_
+
+#include <time.h>
+#include <sys/time.h>
+
+class Duration
+{
+private:
+ struct timeval tvStart;
+ struct timeval tvEnd;
+ struct tm *tmStart;
+ struct tm *tmEnd;
+public:
+ void setStart();
+ void setEnd();
+ double getPassedTime();
+ long int getCurrTime();
+ char* getSysTime();
+};
+
+#endif //_DURATION_H_
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Calibrate.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,411 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+#include <stdio.h>
+#include <mysql.h>
+#include <stdlib.h>
+//#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include <math.h>
+#include <string.h>
+#include "def.h"
+
+using namespace std;
+
+Calibrate::Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char*
pzPW, char* pzTName, char* pzDataColumn, int i_Rank, int i_Size, double
dTimeStep)
+{
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ i_Rank = i_Rank;
+ i_Size = i_Size;
+ d_TimeStep = dTimeStep;
+ pd_Data = NULL;
+ i_Len = 0;
+}
+
+Calibrate::~Calibrate(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_TableName)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+ if (pd_Data)
+ delete []pd_Data;
+}
+
+bool Calibrate::checkTable()
+{
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ bool status = true;
+ i_Length = poDataEx->getNoOfRows();
+ if(i_Length == 0)
+ {
+ status = false;;
+ }
+ delete poDataEx;
+ return status;
+}
+
+double* Calibrate::calcParameters()
+{
+ double *pdCalibValues = calcParamInSingleMachine(); //TODO: perform size
check of table to decide on parallel calibration
+
+ return pdCalibValues;
+}
+
+double* Calibrate::calcParamReplicatedDB()
+{
+ MPI_Status mpiStatus;
+ int bIsSuccesl = 0;
+ double *pdCalibParams = new double[4];
+
+ int iTag =1;
+
+ double dSx, dSy, dSxx, dSyy, dSxy;
+ double mu, lambda, sigma_square, sigma;
+ double partialParameters[5];
+// printf("Para calib1\n");
+// fflush(stdout);
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ int iNoOfRows = i_Length / i_Size;
+
+ int iInitialRow = iNoOfRows * i_Rank + 1;
+ int iFinalRow;
+
+ if( i_Rank == i_Size - 1)
+ {
+ iFinalRow = i_Length;
+ }
+ else
+ {
+ iFinalRow = iNoOfRows * (i_Rank + 1);
+ }
+
+ pd_Data = poDataEx->getReplicatedDataParellel(iInitialRow, iFinalRow,
pz_DataColumn);
+ i_Len = iFinalRow - iInitialRow + 1;
+ partialParameters[0] = getSxPara();
+ partialParameters[1] = getSyPara();
+ partialParameters[2] = getSxxPara();
+ partialParameters[3] = getSyyPara();
+ partialParameters[4] = getSxyPara();
+ if(i_Rank != 0)
+ {
+ MPI_Send(&partialParameters, 5, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ // vector<vector<double> > parametersCollection(i_Size, vector<double>
(5));
+ double **parametersCollection = new double*[i_Size];
+ for (int i = 0; i < i_Size; i++)
+ {
+ parametersCollection[i] = new double[5];
+ }
+
+ double tempResults[5];
+
+ for(int i=0; i< 5 ; i++ )
+ {
+ parametersCollection[0][i] = partialParameters[i];
+ }
+
+ for(int i=1; i< i_Size; i++)
+ {
+ MPI_Recv(&tempResults, 5, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < 5; k++)
+ {
+ parametersCollection[i][k] = tempResults[k];
+ }
+ }
+
+ for(int i=0; i < 5 ; i++ )
+ {
+ double temp = 0;
+
+ for(int k=0; k < i_Size ; k++)
+ {
+ temp = temp + parametersCollection[k][i];
+ }
+
+ if(i == 0)
+ dSx = temp;
+ else if(i == 1)
+ dSy = temp;
+ else if(i == 2)
+ dSxx = temp;
+ else if(i == 3)
+ dSyy = temp;
+ else if(i == 4)
+ dSxy = temp;
+ }
+ i_Length = i_Length -1;
+
+ double dMu = ((dSy * dSxx) - (dSx * dSxy)) / ((i_Length * (dSxx - dSxy))
- (pow(dSx,2) - (dSx * dSy)));
+ double dLambda = (-1 / d_TimeStep) * (log((dSxy - dMu * dSx - dMu * dSy
+ i_Length * pow(dMu,2)) /
+ (dSxx - 2 * dMu * dSx + i_Length * pow(dMu,2))));
+
+ double dAlpha = exp(-1 * dLambda * d_TimeStep);
+
+ double dSigmaHatSq = (dSyy - (2 * dAlpha * dSxy) + (pow(dAlpha,2) *
dSxx) - (2 * dMu * (1-dAlpha) *
+ (dSy - dAlpha * dSx)) + (i_Length * pow(dMu,2) *
(pow((1-dAlpha),2)))) / i_Length;
+
+ double dSigmaSq = dSigmaHatSq * 2 * dLambda / (1 - pow(dAlpha,2));
+
+ pdCalibParams[0] = poDataEx->getLastData(pz_DataColumn);
+ pdCalibParams[1] = dMu;
+ pdCalibParams[2] = sqrt(dSigmaSq);
+ pdCalibParams[3] = dLambda;
+
+ for (int i = 0; i < i_Size; i++)
+ {
+ delete []parametersCollection[i];
+ }
+ delete []parametersCollection;
+
+ delete poDataEx;
+ }
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ if (i_Rank != 0)
+ {
+ MPI_Send ( &bIsSuccesl, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ for(int i = 1; i < i_Size; i++)
+ {
+ MPI_Recv( &bIsSuccesl , 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ }
+ }
+
+ return pdCalibParams;
+}
+
+double* Calibrate::calcParamInSingleMachine()
+{
+ MPI_Status mpiStatus;
+
+ double *pdCalibParams = new double[4];
+ int bIsSuccesl = 0;
+
+ if (i_Rank == 0)
+ {
+ DataExtracter *poDataEx = new DataExtracter(pz_DBName, pz_UserName,
pz_Password, pz_TableName, pz_IPAddress);
+
+ int iLen = 0;
+ pd_Data = poDataEx->getData(DATACOLUMN, iLen);
+ i_Len = iLen;
+
+// printf("ILEN: %d", iLen);
+// fflush(stdout);
+
+ double dSx = getSx();
+ double dSy = getSy();
+ double dSxx = getSxx();
+ double dSyy = getSyy();
+ double dSxy = getSxy();
+// printf("Esses: %f,%f,%f,%f\n", dSx, dSy, dSxx, dSyy, dSxy);
+// fflush(stdout);
+ delete pd_Data;
+
+ i_Length = i_Length -1;
+
+ double dMu = ((dSy * dSxx) - (dSx * dSxy)) / ((i_Length * (dSxx - dSxy))
- (pow(dSx,2) - (dSx * dSy)));
+ double dLambda = (-1 / d_TimeStep) * (log((dSxy - dMu * dSx - dMu * dSy
+ i_Length * pow(dMu,2)) /
+ (dSxx - 2 * dMu * dSx + i_Length * pow(dMu,2))));
+
+ double dAlpha = exp(-1 * dLambda * d_TimeStep);
+
+ double dSigmaHatSq = (dSyy - (2 * dAlpha * dSxy) + (pow(dAlpha,2) *
dSxx) - (2 * dMu * (1-dAlpha) *
+ (dSy - dAlpha * dSx)) + (i_Length * pow(dMu,2) *
(pow((1-dAlpha),2)))) / i_Length;
+
+ double dSigmaSq = dSigmaHatSq * 2 * dLambda / (1 - pow(dAlpha,2));
+
+ pdCalibParams[0] = poDataEx->getLastData(pz_DataColumn);
+ pdCalibParams[1] = dMu;
+ pdCalibParams[2] = sqrt(dSigmaSq);
+ pdCalibParams[3] = dLambda;
+
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ delete poDataEx;
+ }
+ else
+ {
+ MPI_Bcast ( pdCalibParams , 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ MPI_Send ( &bIsSuccesl, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
+ }
+
+ if(i_Rank == 0)
+ {
+ for(int i = 1; i < i_Size; i++)
+ {
+ MPI_Recv( &bIsSuccesl , 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpiStatus);
+ }
+ }
+
+ return pdCalibParams;
+}
+
+//************************************************************************
+
+double Calibrate::getSx()
+{
+ double dSx = 0;
+// printf("dSx: %d\n", i_Len);
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+// if (i == 1)
+// printf("dSx\n");
+ dSx += pd_Data[i - 1];
+ }
+ return dSx;
+}
+
+//************************************************************************
+
+double Calibrate::getSy()
+{
+ double dSy = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSy += pd_Data[i];//cout << pd_Data[i] << endl;
+ }
+ return dSy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxx()
+{
+ double dSxx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSxx += pow(pd_Data[i - 1],2);
+ }
+ return dSxx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyy()
+{
+ double dSyy= 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSyy += pow(pd_Data[i],2);
+ }
+ return dSyy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxy()
+{
+ double sumXY = 0;
+ for (unsigned int i = 1; i < i_Len; i++){
+ sumXY += pd_Data[i] * pd_Data[i-1];
+ }
+ return sumXY;
+}
+
+//************************************************************************
+
+double Calibrate::getSxPara()
+{
+ double dSx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSx += pd_Data[i - 1];
+ }
+ return dSx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyPara()
+{
+ double dSy = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSy += pd_Data[i];//cout << pd_Data[i] << endl;
+ }
+ return dSy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxxPara()
+{
+ double dSxx = 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSxx += pow(pd_Data[i - 1],2);
+ }
+ return dSxx;
+}
+
+//************************************************************************
+
+double Calibrate::getSyyPara()
+{
+ double dSyy= 0;
+ for (unsigned int i = 1; i < i_Len; i++)
+ {
+ dSyy += pow(pd_Data[i],2);
+ }
+ return dSyy;
+}
+
+//************************************************************************
+
+double Calibrate::getSxyPara()
+{
+ double sumXY = 0;
+ for (unsigned int i = 1; i < i_Len; i++){
+ sumXY += pd_Data[i] * pd_Data[i-1];
+ }
+ return sumXY;
+}
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Calibrate.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,72 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/s
+
+#pragma once
+//#include <iostream>
+//#include <vector>
+
+//using namespace std;
+
+class Calibrate
+{
+private:
+// std::vector<double> *pvData;
+ double *pd_Data;
+ unsigned int i_Len;
+ double getSx();
+ double getSy();
+ double getSxx();
+ double getSyy();
+ double getSxy();
+ double getSxPara();
+ double getSyPara();
+ double getSxxPara();
+ double getSyyPara();
+ double getSxyPara();
+ double d_TimeStep;
+
+ int i_Rank;
+ int i_Size;
+ int i_Length;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ double* calcParamInSingleMachine();
+ double* calcParamFromCentralDB();
+ double* calcParamReplicatedDB();
+// double* paramCalculation(vector<double> *data);
+// double parallelMGR(vector<double> *data);
+// double parallelVariance(vector<double> *data, double mean);
+ double* paramCalculation(double *data);
+ double parallelMGR(double *data);
+ double parallelVariance(double *data, double mean);
+
+public:
+ Calibrate(char* pzDBName, char* pzIP, char* pzUserName, char* pzPW, char*
pzTName, char* pzDataColumn, int iRank, int iSize, double dTimeStep);
+ double* calcParameters();
+ bool checkTable();
+ ~Calibrate(void);
+
+
+};
=======================================
--- /dev/null
+++ /trunk/models/vasicek/DataExtracter.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,457 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+/*
+// //
+// // PROJECT : HPC4Finance
+// // MODULE : DataExtracter class Implimentation
+// // FILE : Data Extracter.cpp
+// // AUTHOR : Damitha Premadasa (dami...@gmail.com)
+// // DESC : The file consist of database related function in GBM.
+// This is satisfactorily tested with UNIX environment
+// and WINDOWS environment.
+// // TODO :
+// // HISTORY : Date of Creation: 5-Oct-2008
+// Modified:
+// //
+*/
+
+#include "DataExtracter.h"
+
+
+#ifdef WIN32
+#include <windows.h>
+#include <winsock.h>
+#pragma warning (disable: 4514 4786)
+#pragma warning( push, 3 )
+#endif
+
+
+#include "def.h"
+#include <stdio.h>
+#include <iostream>
+#include <mysql.h>
+#include <stdlib.h>
+#include <list>
+
+
+using namespace std;
+
+DataExtracter::DataExtracter(char* pzDName, char* pzUserName, char* pzPW,
char* pzTName, char* pzIP)
+{
+ pz_DBName = strdup(pzDName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_TableName = strdup(pzTName);
+ pz_IPAddress = strdup(pzIP);
+}
+
+
+DataExtracter::~DataExtracter(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ if (pz_TableName)
+ delete pz_TableName;
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+}
+
+// Get required data set for parameter calculation
+//vector<double> *DataExtracter::getData(char *coloumName)
+double *DataExtracter::getData(char *coloumName, int &iLen)
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ return NULL;
+ }
+ else
+ {
+ //cout << coloumName << " : " << pz_TableName << endl;
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s ORDER BY ID", coloumName ,pz_TableName
);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ //printf("error,Incorrect Parameters\n");
+ //fflush(stdout);
+ mysql_close(pMysql);
+ return NULL;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);// DONE: check errors here
+ int iRows = pmsResult->row_count;
+ iLen = iRows;
+ if( iRows == 0 )
+ {
+ mysql_close(pMysql);
+ return NULL;
+ }
+
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+ return pdData;
+}
+
+// Get required data set for parameter calculation parallel
+//vector<double> *DataExtracter::getDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+double *DataExtracter::getDataParellel( int iStartingRow, int iEndingRow,
char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",
+ coloumName,pz_TableName ,iStartingRow,iEndingRow);
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+// pdData = new vector<double>;
+ pdData = new double[iRows];
+
+ int i =0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the number of records in the table
+int DataExtracter::getNoOfRows( void )
+{
+ int iRows;
+
+ MYSQL_RES *pmsResult;
+ MYSQL *pMysql = mysql_init(NULL);
+
+ if(!mysql_real_connect(pMysql,pz_IPAddress , pz_UserName,
pz_Password ,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ //const char* query = "SELECT Close FROM ibm";
+
+ char query[250];
+ sprintf(query, "SELECT * FROM %s", pz_TableName );
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult != NULL)
+ {
+ iRows = pmsResult->row_count;
+
+ if(iRows == 0)
+ {
+ return 0;
+ }
+ mysql_free_result(pmsResult);
+ }
+ else
+ {
+
+ if(mysql_errno(pMysql) == 0)
+ {
+ return 0;
+ }
+ else
+ {
+ return 0;
+ }
+
+ return 0;
+ }
+ }
+ }
+
+
+ mysql_close(pMysql);
+
+ return iRows;
+}
+
+// Get data from local machines independently
+//vector<double> *DataExtracter::getReplicatedDataParellel( int
iStartingRow, int iEndingRow, char *coloumName )
+double *DataExtracter::getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName )
+{
+// vector<double> *pdData;
+ double *pdData = NULL;
+
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"SELECT %s FROM %s where ID >= %d and ID <= %d ORDER BY
ID",coloumName, pz_TableName, iStartingRow,iEndingRow);
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ int iRows = pmsResult->row_count;
+
+ // pdData = new vector<double>;
+ pdData = new double[iRows];
+ int i = 0;
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+// pdData->push_back(atof(*msRow));
+ pdData[i] = atof(*msRow);
+ i++;
+ }
+ mysql_free_result(pmsResult);
+ }
+ }
+ }
+ mysql_close(pMysql);
+
+ return pdData;
+}
+
+// Get the last item of the table
+double DataExtracter::getLastData(char* coloumName)
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ double result;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,"localhost",pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query[250];
+ sprintf(query,"select %s from %s where ID = (select max(ID) from %s )",
coloumName, pz_TableName, pz_TableName );
+ //const char* query = "select Close from ibm where ID = (select max(ID)
from ibm)";
+
+ mysql_select_db(pMysql, pz_DBName );
+
+ //int iQuery = mysql_real_query(pMysql, query, strlen(query));
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ result = atof(*msRow);
+ }
+
+ mysql_free_result(pmsResult);
+ }
+ }
+ mysql_close(pMysql);
+
+ return result;
+}
+
+// Get duration between first and last data element
+int DataExtracter::getDuration( void )
+{
+ MYSQL_RES *pmsResult;
+ MYSQL_ROW msRow;
+
+ string cStartDate, cEndDate;
+ int iDateDifference;
+
+ MYSQL *pMysql = mysql_init(NULL);
+
+
if(!mysql_real_connect(pMysql,pz_IPAddress,pz_UserName,pz_Password,pz_DBName,0,NULL,0))
+ {
+ return 0;
+ }
+ else
+ {
+ char query1[250];
+ sprintf(query1,"select Date from %s where ID = (select max(ID) from %s
)", pz_TableName, pz_TableName );
+ char query2[250];
+ sprintf(query2,"select Date from %s where ID = (select min(ID)
from %s)", pz_TableName , pz_TableName);
+
+ if(mysql_select_db(pMysql, pz_DBName))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ if(mysql_real_query(pMysql, query1, strlen(query1)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cEndDate = *msRow;
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ if(mysql_real_query(pMysql, query2, strlen(query2)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ cStartDate = (*msRow);
+ }
+ mysql_free_result(pmsResult);
+ }
+
+ char query[250];
+
+ sprintf(query,"SELECT DATEDIFF( \'%s\' , \'%s\'
)",cEndDate.c_str(),cStartDate.c_str());
+
+ if(mysql_real_query(pMysql, query, strlen(query)))
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ pmsResult = mysql_store_result (pMysql);
+
+ if(pmsResult == NULL)
+ {
+ mysql_close(pMysql);
+ return 0;
+ }
+ else
+ {
+ while ((msRow = mysql_fetch_row(pmsResult)))
+ {
+ iDateDifference = atoi(*msRow);
+ }
+ }
+ mysql_free_result(pmsResult);
+ }
+
+
+ }
+ }
+
+ mysql_close(pMysql);
+
+ return iDateDifference;
+}
=======================================
--- /dev/null
+++ /trunk/models/vasicek/DataExtracter.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,57 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+//#include <vector>
+
+using namespace std;
+
+class DataExtracter
+{
+private:
+ int i_ResultLength;
+ char* pz_TableName;
+ char* pz_DBName;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_IPAddress;
+
+public:
+ DataExtracter(char* pzDName, char* pzUserName, char* pzPW, char* pzTName,
char* pzIP);
+// vector<double> *getData(char *coloumName);
+// vector<double> *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ double *getData(char *coloumName, int &iLen);
+ double *getDataParellel(int iStartingRow, int iEndingRow, char
*coloumName);
+ int getDuration(void);
+ int getNoOfRows(void);
+ double getLastData(char* coloumName);
+ //int getDurationParallel( int iStartingRow, int iEndingRow );
+// vector<double> *getReplicatedDataParellel( int iStartingRow, int
iEndingRow, char *coloumName );
+ double *getReplicatedDataParellel( int iStartingRow, int iEndingRow, char
*coloumName );
+ //int getReplicatedDurationParallel( int iStartingRow, int iEndingRow );
+ void setDBProperties(char* dbName, char* username, char* password, char*
tablename, char* ip );
+
+ int I_ResultLength() const { return i_ResultLength; }
+ void I_ResultLength(int val) { i_ResultLength = val; }
+
+public:
+ ~DataExtracter(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Logs.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,207 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <iostream>
+#include <fstream>
+//#include <sys/unistd.h>
+//#include <sys/socket.h>
+#include <vector>
+#include <netdb.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <exception>
+#include "def.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+Logs::Logs(char *czLogType) {
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ sprintf(pzFileName , "%s/%s/%s.txt", LOGLOCATION ,czLogType, psIPAddress);
+ poDuration = new Duration();
+ fLogs = new ofstream(pzFileName, ios::app);
+
+}
+
+Logs::Logs() {
+
+}
+
+void Logs::WriteLog(char *sError)
+{
+ char *pzMsg = strdup(sError);
+ int iMsgLen = strlen(pzMsg);
+
+ int isMsgFul = bIsMsgFull(iMsgLen);
+
+
+ if(isMsgFul == 1)
+ {
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else if(isMsgFul == 2)
+ {
+ strcat(pzErrorMsg,pzMsg);
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ pzErrorMsg[0] = (char)NULL;
+ }
+ else
+ {
+ strcat(pzErrorMsg,pzMsg);
+ }
+}
+
+
+
+Logs::~Logs() {
+ // TODO Auto-generated destructor stub
+ fLogs->write(pzErrorMsg, strlen(pzErrorMsg));
+ fLogs->close();
+}
+
+int Logs::bIsMsgFull(int iLen)
+{
+ int iSize = strlen(pzErrorMsg)+ iLen;
+ if(iSize > 1024)
+ {
+ return 1;
+ }
+ else if(iSize == 1024)
+ {
+ return 2;
+ }
+
+ return 3;
+}
+
+void Logs::WriteLog(double dValue)
+{
+ char czValue[32];
+ sprintf(czValue,", %f",dValue);
+ WriteLog(czValue);
+}
+
+void Logs::writeTuning(double *dRatio, char **IPList, int size)
+{
+ char pzTuningFileName[256];
+ try {
+ sprintf(pzTuningFileName , "%s/tuning.txt", LOGLOCATION);
+ ofstream *fTuning = new ofstream(pzTuningFileName, ios::out);
+
+ for(int i = 0; i < size; i++)
+ {
+ char cTempValue[150];
+
+
+ if(i == size -1 )
+ {
+ sprintf(cTempValue,"%s %f", IPList[i] , dRatio[i] );
+ }
+ else
+ {
+ sprintf(cTempValue,"%s %f;", IPList[i] , dRatio[i] );
+ }
+
+ //printf("%d:%s",i,IPList[i] );
+ //fflush(stdout);
+
+ fTuning->write( cTempValue, strlen( cTempValue ));
+ //strcat(cTuningValue,cTempValue);
+ }
+ fTuning->close();
+ }
+ catch( const std::exception& e )
+ {
+ printf("%s", e.what());
+
+ return;
+ }
+
+}
+
+char* Logs::readLog(char *cpFileDestination)
+{
+ char *cpBuffer;
+ int iLength;
+ //pzFileName = strdup( cpFileDestination );
+ sprintf(pzFileName , "%s/%s", LOGLOCATION, cpFileDestination );
+
+ ifstream *fReading = new ifstream(pzFileName, ios::binary );
+
+ fReading->seekg (0, ios::end);
+ iLength = fReading->tellg();
+ fReading->seekg (0, ios::beg);
+
+ cpBuffer = new char [iLength];
+
+ fReading->read (cpBuffer,iLength);
+ fReading->close();
+ //printf("%s", cpBuffer );
+
+ return cpBuffer;
+}
+
+vector<string> *Logs::tokenizer(string cpBuffer, char cDelim)
+{
+ string sBuffer = cpBuffer;
+
+ vector<string> *psTokens = new vector<string>;
+
+ int lastPos=0, i=0;
+ // Find first "non-delimiter".
+ string::size_type pos = sBuffer.find_first_of(cDelim,lastPos);
+
+ while (string::npos != pos || string::npos != lastPos)
+ {
+ psTokens->push_back(sBuffer.substr(lastPos, pos - lastPos));
+
+ lastPos = sBuffer.find_first_not_of(cDelim, pos);
+ pos = sBuffer.find_first_of(cDelim, lastPos);
+ i++;
+ }
+
+ return psTokens;
+}
+
+bool Logs::checkFileExists(string fileName)
+{
+ bool bFileExists = true;
+ fstream inp;
+ //ofstream out;
+ sprintf(pzFileName , "%s/%s", LOGLOCATION ,fileName.c_str());
+
+ inp.open(pzFileName, ifstream::in);
+
+ //inp.close();
+ if(inp.fail())
+ {
+ inp.clear(ios::failbit);
+ bFileExists = false;
+ }
+
+ return bFileExists;
+
+}
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Logs.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,56 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#ifndef Logs_H_
+#define Logs_H_
+
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include "duration.h"
+
+using namespace std;
+
+class Logs {
+
+
+private:
+ char *psIPAddress;
+ char pzFileName[250];
+ char pzErrorMsg[1024];
+ Duration *poDuration;
+ ofstream *fLogs;
+
+public:
+ Logs(char *czLogType);
+ Logs();
+ void WriteLog(char *sError);
+ void WriteLog(double dValue);
+ int bIsMsgFull(int iLen);
+ void writeTuning(double *dRatio, char **IPList, int size);
+ char *readLog(char *cpFileDestination);
+ vector<string> *tokenizer(string cpBuffer, char cDelim);
+ bool checkFileExists(string fileName);
+ virtual ~Logs();
+};
+
+#endif /* Logs_H_ */
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Makefile Sun Jan 17 01:15:09 2010
@@ -0,0 +1,18 @@
+vasicek: DataExtracterO.o CalibrateO.o VasicekModelO.o VasicekTestO.o
VasicekO.o DurationO.o LogsO.o
+ mpicxx -O3 -Wall -L/usr/local/mysql/lib/mysql -lmysqlclient -lz
DataExtracterO.o CalibrateO.o VasicekModelO.o VasicekTestO.o VasicekO.o
DurationO.o LogsO.o -o vasicek
+VasicekO.o: Vasicek.cpp Vasicek.h DataExtracter.h Calibrate.h
VasicekModel.h def.h Logs.h duration.h
+ mpicxx -O3 -Wall -I/home/cig4/mpich2-install/include
-I/usr/local/mysql/include/mysql -c Vasicek.cpp -o VasicekO.o
+DataExtracterO.o: DataExtracter.cpp DataExtracter.h def.h
+ g++ -O3 -Wall -I/usr/local/mysql/include/mysql -c DataExtracter.cpp -o
DataExtracterO.o
+CalibrateO.o: Calibrate.cpp Calibrate.h DataExtracter.h duration.h
+ mpicxx -O3 -Wall -I/usr/local/mysql/include/mysql
-I/home/cig4/mpich2-install/include -c Calibrate.cpp -o CalibrateO.o
+DurationO.o: duration.cpp duration.h
+ g++ -O3 -Wall -c duration.cpp -o DurationO.o
+LogsO.o: Logs.h Logs.cpp duration.h
+ g++ -O3 -Wall -c Logs.cpp -o LogsO.o
+VasicekModelO.o: VasicekModel.cpp VasicekModel.h
+ g++ -O3 -Wall -c VasicekModel.cpp -o VasicekModelO.o
+VasicekTestO.o: VasicekTest.cpp Vasicek.h Calibrate.h DataExtracter.h
duration.h
+ mpicxx -O3 -Wall -I/home/cig4/mpich2-install/include -c VasicekTest.cpp
-o VasicekTestO.o
+clean:
+ rm -f *.o vasicek
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Vasicek.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,1033 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+// Vasicek.cpp : Defines the entry point for the console application.
+//
+#include <mpi.h>
+#include <stdio.h>
+#include "VasicekModel.h"
+#include "math.h"
+#include <stdlib.h>
+#include <ctype.h>
+#include <vector>
+#include "Calibrate.h"
+#include "DataExtracter.h"
+#include "def.h"
+#include <string.h>
+#include "Vasicek.h"
+#include "Logs.h"
+#include "duration.h"
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////
+/*
+Euler Discretization of Vasicek is given at
http://www.quantcode.com/modules/mydownloads/singlefile.php?cid=9&lid=390
+However it has been shown that Exact Discretization is more accurate than
Euler's
+Therefore exact discretization equation given at
http://www.quantcode.com/modules/mydownloads/singlefile.php?cid=9&lid=391
+has been used
+*/
+//////////////////////////////////////////////////////////////////////////
+#define WRITE_LOG
+
+extern int i_Rank;
+
+
+Vasicek::Vasicek(int argCount, char **args, char* pzDBName, char* pzIP,
char* pzUserName, char* pzPW, char* pzDataColumn)
+{
+ i_ArgCount = argCount;
+ pz_Args = args;
+ pz_DBName = strdup(pzDBName);
+ pz_UserName = strdup(pzUserName);
+ pz_Password = strdup(pzPW);
+ pz_IPAddress = strdup(pzIP);
+ pz_DataColumn = strdup(pzDataColumn);
+ pz_TableName = NULL;
+
+ int iRc = MPI_Init(&i_ArgCount, &pz_Args);
+ if (iRc != MPI_SUCCESS)
+ {
+ printf ("error,Error starting MPI program. Terminating.\n");
+ MPI_Abort(MPI_COMM_WORLD, iRc);
+ }
+
+ MPI_Comm_rank(MPI_COMM_WORLD, &i_Rank);
+ MPI_Comm_size(MPI_COMM_WORLD, &i_Size);
+
+ #ifdef WRITE_LOG
+ poTansLog = new Logs(LOGTYPE);
+ poTansLog->WriteLog(HEADLINE);
+
+ Duration d;
+ poTansLog->WriteLog(d.getSysTime());
+ #endif
+}
+
+double* Vasicek::getParams()
+{
+ double dInitial, dDrift, dSigma, dLambda;
+
+// bool bValidParams = validateParams(i_ArgCount, pz_Args);
+ bool bValidParams = true;
+
+ if(!bValidParams)
+ {
+ if (i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return (double*) 0;
+ }
+ int iStdErr = dup(fileno(stderr));
+ close(fileno(stderr));
+ int iOption;
+
+ if(i_ArgCount == 9)
+ {
+ dInitial = (double)atof(pz_Args[1]);
+ dDrift = (double)atof(pz_Args[2]);
+ dSigma = (double)atof(pz_Args[3]);
+ dLambda = (double)atof(pz_Args[4]);
+
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 252.0;
+ //dDrift /= 252;
+ // dSigma /= sqrt(252);
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 12.0;
+ //dDrift /= 12;
+ // dSigma /= sqrt(12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 4.0;
+ //dDrift /= 4;
+ //dSigma /= sqrt(4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0;
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters from wrong arguments\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ //d_TimeStep = 1.0 / (double)i_Forecasts;
+ //printf ("switches: %d:%f\n", i_Forecasts, d_TimeStep);
+ }
+ else if(i_ArgCount == 7)
+ {
+ double factorDrift, factorSigma;
+ while ( (iOption = getopt(i_ArgCount, pz_Args, "t:d:m:q:y:s:")) != -1 )
+ {
+ switch (iOption)
+ {
+ case 't':
+ pz_TableName = optarg;
+ break;
+ case 'd':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 252.0;
+ //factorDrift = 252.0;
+ factorSigma = sqrt(252.0);
+ break;
+ case 'm':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 12.0;
+ //factorDrift = 252 / 12;
+ factorSigma = sqrt(12);
+ break;
+ case 'q':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0 / 4.0;
+ // factorDrift = 252 / 4;
+ factorSigma = sqrt(4);
+ break;
+ case 'y':
+ i_Forecasts = (int)atoi(optarg);
+ d_TimeStep = 1.0;
+ //factorDrift = 252.0;
+ factorSigma = 1.0;
+ break;
+ case 's':
+ i_Iterations = (int)atoi(optarg);
+ break;
+
+ default:
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters from wrong arguments\n");
+ fflush(stdout);
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ if (i_Forecasts == 0)
+ {
+ if(i_Rank == 0)
+ {
+ printf("error,Incorrect parameters\n");
+ fflush(stdout);
+ }
+ //MPI_Finalize();
+ return 0;
+ }
+ dup2(iStdErr, fileno(stderr));
+
+ //write(fileno(stderr), "fffff", 5); checking if stdErr is working
+
+ Calibrate *poCalc = new Calibrate(pz_DBName, pz_IPAddress,
pz_UserName, pz_Password, pz_TableName, pz_DataColumn,
i_Rank, i_Size, 1.0/252.0);
+ bool bTableStatus = poCalc->checkTable();
+
+ if (!bTableStatus)
+ {
+ if (i_Rank == 0)
+ {
+ printf("error,No records found in Database");
+ fflush(stdout);
+ }
+ return 0;
+ }
+
+ double *pdCalibValues;
+ pdCalibValues = poCalc->calcParameters();
+
+ dInitial = pdCalibValues[0] ;
+ dDrift = pdCalibValues[1] ;
+ dSigma = pdCalibValues[2];
+ dLambda = pdCalibValues[3];
+ }
+ else
+ {
+ if(i_Rank == 0)
+ printf("error,Incorrect parameters1\t%d\n", i_ArgCount);
+
+ //MPI_Finalize();
+ return 0;
+ }
+
+ #ifdef WRITE_LOG
+
+ char pzJob[128];
+ sprintf(pzJob, "MC trials \t%d \nPredictions \t%d
\n",(int)i_Iterations/i_Size, i_Forecasts);
+ poTansLog->WriteLog(pzJob);
+
+ char pzCalibValues[256];
+ sprintf(pzCalibValues, "Initial Value \t%f \nMean \t\t%f \nSigma \t\t%f
\nMRS \t\t%f\nTime step\t%f \n", dInitial, dDrift, dSigma,
dLambda, d_TimeStep);
+ poTansLog->WriteLog(pzCalibValues);
+
+ #endif
+ //printf("params: %f\t%f\t%f\t%f\t%f\n",dInitial, dDrift, dSigma,
dLambda, d_TimeStep);
+ //fflush(stdout);
+ double* pd_Params = new double[4];
+ pd_Params[0] = dInitial;
+ pd_Params[1] = dDrift;
+ pd_Params[2] = dSigma;
+ pd_Params[3] = dLambda;
+
+ return pd_Params;
+}
+
+int Vasicek::getNthPrime(int n)
+{
+ int count = 0;
+ int primeNo = 0;
+ int k = 2;
+ while (count < n)
+ {
+
+ if (k == 2)
+ { // the only even prime
+ primeNo = 2;
+ count++;
+ }
+ else if (k % 2 == 0) // other even numbers are composite
+ {
+ k++;
+ continue;
+
+ }
+ else
+ {
+ bool prime = true;
+ int divisor = 3;
+ int upperLimit = static_cast<int>(sqrt(k) + 1);
+ while (divisor <= upperLimit)
+ {
+
+ if (k % divisor == 0)
+ prime = false;
+ divisor +=2;
+ }
+ if (prime == true)
+ {
+ primeNo = k;
+ count++;
+ }
+ }
+ k++;
+ }
+ return primeNo;
+}
+
+double* Vasicek::getPredicts(double *dParams)
+{
+ MPI_Status mpiStatus;
+ int iTag = 1;
+
+ char psIPAddress[128];
+ gethostname(psIPAddress, sizeof psIPAddress);
+
+ int iSimsPerNode = i_Iterations / i_Size;
+ double dPerformaceRatio = 0;
+ double dPerformTotalRatio = 0;
+ int iGlobFreq = 0;
+
+
+ //check for file existance
+ Logs *poRatios = new Logs();
+ bool isFileExists = poRatios->checkFileExists("tuning.txt") ;
+
+ //tokenized tuning details
+ vector<vector<string> > *tuneFileList;
+ int iMachines = 0;
+
+ //////////////////////////////////////////////////////////
+ if(isFileExists)
+ {
+ char *cBuffer = poRatios->readLog("tuning.txt");
+ vector<string> *PerNodeRatio = poRatios->tokenizer(cBuffer, ';');
+
+ iMachines = PerNodeRatio->size();
+ tuneFileList = new vector<vector<string> >(iMachines, vector<string>
(3));
+
+ // read the tuning file
+ for(int i=0 ; i < iMachines; i++)
+ {
+ string temp = PerNodeRatio->at(i);
+ vector<string> *tmp= poRatios->tokenizer(temp, ' ');
+
+ for(int j = 0; j < 3 ; j++)
+ {
+ if(j != 2)
+ (*tuneFileList)[i][j] = tmp->at(j);
+ else
+ (*tuneFileList)[i][j] = NOTVISITED;
+ }
+ }
+
+ if(i_Rank != 0)
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0, iTag, MPI_COMM_WORLD);
+
+ else
+ {
+ int iNewMachinFreq = 0; // count new machines
+ char tempIPAddress[128];
+ vector< char* > *pIPRankDatails = new vector< char* >(i_Size); // IP
list according to their rank
+ vector< string *> *pvNewMachines = new vector< string *>; // IP List of
new machines
+
+ (*pIPRankDatails)[0] = strdup(psIPAddress);
+
+ for(int i =1; i < i_Size; i++)
+ {
+ MPI_Recv(&tempIPAddress, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ (*pIPRankDatails)[i] = strdup(tempIPAddress);
+ }
+
+ for(int j = 0; j < i_Size ; j++)
+ {
+ bool isMachineExists = false;
+ string sTempIPRank (pIPRankDatails->at(j));
+
+ // check whether the machine exists
+ for (int i =0; i < iMachines ; i++ )
+ {
+ string sTempTuneList((*tuneFileList)[i][0]);
+ if( sTempTuneList.compare(sTempIPRank) == 0)
+ {
+ isMachineExists = true;
+ break;
+ }
+ }
+
+ if( !isMachineExists )
+ {
+ bool bInMachineList = false;
+ for (int k =0; k < pvNewMachines->size() ; k++ )
+ {
+ if( sTempIPRank.compare((*pvNewMachines)[k][0]) == 0)
+ {
+ int iTempFreq = atoi((*pvNewMachines)[k][1].c_str());
+ iTempFreq++;
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",iTempFreq);
+ (*pvNewMachines)[k][1] = sTempFreq;
+ bInMachineList = true;
+ }
+ }
+
+ if(!bInMachineList)
+ {
+ string *vTemp = new string[2];
+ vTemp[0] = pIPRankDatails->at(j);
+ char sTempFreq[sizeof(int) + 1];
+ sprintf( sTempFreq,"%d",1);
+ vTemp[1] = sTempFreq;
+ pvNewMachines->push_back(vTemp);
+ iNewMachinFreq++;
+ iGlobFreq++;
+ }
+ }
+ }
+
+ // if new machine are not added
+ vector<vector<string> *> *frequencyList = new vector<vector<string> *>;
+ double tempTotal = 0;
+ double dtempRatios = 0;
+
+ // keep machine name : total ratio
+ vector< string > *pvFreqListElement;
+
+ for (int i = 0; i < iMachines; i++)
+ {
+
+ pvFreqListElement = new vector< string >(3);
+ int frequency=0;
+
+ for (int j = 0; j < i_Size; j++)
+ {
+ if((*tuneFileList)[i][0].compare(pIPRankDatails->at(j))==0)
+ frequency++;
+ }
+
+ // if machine is used for run the process insert to the frequency list
+ if(frequency > 0)
+ {
+ tempTotal += frequency * (atof((*tuneFileList)[i][1].c_str()));
+ dPerformTotalRatio += atof((*tuneFileList)[i][1].c_str());
+
+ char tempDRatio[sizeof(double) +1];
+ sprintf( tempDRatio,"%f",(frequency *
(atof((*tuneFileList)[i][1].c_str()))));
+ (*pvFreqListElement)[0] = (*tuneFileList)[i][0];
+ (*pvFreqListElement)[1] = tempDRatio;
+ (*pvFreqListElement)[2] = (*tuneFileList)[i][1];
+ frequencyList->push_back(pvFreqListElement);
+ iGlobFreq++;
+ }
+ }
+
+ for(int i = 0; i < i_Size ; i++ )
+ {
+ bool bNewFile = true;
+ for(int j = 0; j < frequencyList->size(); j++)
+ {
+ if(string((*pIPRankDatails)[i]).compare((*(*frequencyList)[j])[0]) ==
0)
+ {
+ double tempVal = atof((*(*frequencyList)[j])[2].c_str()) /
tempTotal ;
+ dtempRatios = tempVal * ( (double)(i_Size-
iNewMachinFreq)/(double)i_Size);
+
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+
+ bNewFile = false;
+ break;
+ }
+ }
+ if(bNewFile)
+ {
+ dtempRatios = 1.0 / (double)i_Size;
+ if(i != 0)
+ MPI_Send(&dtempRatios, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD);
+ else
+ dPerformaceRatio = dtempRatios;
+ }
+
+ }
+
+ delete frequencyList;
+ delete pIPRankDatails;
+ }
+
+ if(i_Rank != 0)
+ MPI_Recv(&dPerformaceRatio, 1, MPI_DOUBLE, 0, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ iSimsPerNode = (int)(dPerformaceRatio * i_Iterations);
+
+ }
+ else
+ iGlobFreq = i_Size;
+
+
+
+ double dInitial = dParams[0];
+ double dDrift = dParams[1];
+ double dSigma = dParams[2];
+ double dLambda = dParams[3];
+
+ Duration oDuration;
+ oDuration.setStart();
+
+ double dCurrTime = 0;
+
+ if(i_Rank == 0)
+ {
+ dCurrTime = (double)oDuration.getCurrTime();
+ }
+
+ MPI_Bcast ( &dCurrTime, 1, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+
+ double dSeed = dCurrTime * getNthPrime( i_Rank + i_Size);
+
+ char cSeed[32];
+ sprintf(cSeed , "Seed value :%f \n" , dCurrTime);
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog(cSeed);
+ #endif
+
+ vector<vector<double> > *pvResults = new vector<vector<double>
>((i_Forecasts), vector<double> (iSimsPerNode));
+
+ for (int i = 0; i < iSimsPerNode ; i++)
+ {
+ VasicekModel oVasicek(dInitial, dDrift, dSigma, dLambda, d_TimeStep,
dSeed); // our brownian motion object
+
+ for (int k = 0; k < i_Forecasts; k++)
+ {
+ (*pvResults)[k][i] = oVasicek.step();
+ }
+ }
+ double daLocalCalibVals[i_Forecasts];
+
+ for(int i=0; i< (i_Forecasts) ; i++ )
+ {
+ double dTotal = 0;
+
+ for(int k= 0; k < iSimsPerNode; k++ )
+ {
+ dTotal += (*pvResults)[i][k];
+ }
+
+ //daLocalCalibVals[i]= dTotal / iSimsPerNode;
+ daLocalCalibVals[i]= dTotal ;
+ }
+
+ delete pvResults;
+
+oDuration.setEnd();
+ double dDuration = oDuration.getPassedTime() / iSimsPerNode;
+ double dInvDuration = 1/dDuration;
+
+ if (i_Rank != 0)
+ {
+ MPI_Send(&daLocalCalibVals, i_Forecasts, MPI_DOUBLE, 0,iTag,
MPI_COMM_WORLD);
+ MPI_Send(&dInvDuration, 1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ MPI_Send(&psIPAddress, 128, MPI_CHAR, 0,iTag, MPI_COMM_WORLD);
+ }
+
+ double *dPredictValues = new double[i_Forecasts];
+ double *dInvDurationValues= new double[iGlobFreq];
+ char **pzIPAddress = new char*[iGlobFreq];
+ for (int i = 0; i < iGlobFreq; i++)
+ pzIPAddress[i] = new char[128];
+
+ if (i_Rank == 0)
+ {
+ double dTempDuration = 0;
+ double dTotal = 0;
+
+ dInvDurationValues[0] = dInvDuration;
+ dTotal = dInvDurationValues[0];
+ strcpy(pzIPAddress[0], psIPAddress);
+
+ double dTempResults[i_Forecasts];
+ vector<vector<double> > finalResults(i_Size, vector<double>
(i_Forecasts));
+
+ for (int i=0; i < i_Forecasts; i++)
+ finalResults[0][i] = daLocalCalibVals[i] ;
+
+ // Wait for results from other processes
+ for (int i = 1; i < i_Size; i++)
+ {
+
+ MPI_Recv(&dTempResults, i_Forecasts, MPI_DOUBLE, i, iTag,
MPI_COMM_WORLD, &mpiStatus);
+
+ for (int k=0; k < i_Forecasts; k++)
+ finalResults[i][k] = dTempResults[k];
+
+ char tempIP[128];
+ MPI_Recv(&dTempDuration, 1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+ MPI_Recv(&tempIP, 128, MPI_CHAR, i, iTag, MPI_COMM_WORLD, &mpiStatus);
+
+ bool bReplicatedMachine = false;
+
+ for(int j = 0;j < i ;j++)
+ {
+ if(string(tempIP).compare(string(pzIPAddress[j])) == 0)
+ {
+ double dTemp = dInvDurationValues[j];
+ dInvDurationValues[j] = (dInvDurationValues[j]+dTempDuration) / 2;
+ bReplicatedMachine = true;
+ dTotal = dTotal - dTemp + dInvDurationValues[j];
+ }
+ }
+
+ if(!bReplicatedMachine)
+ {
+ strcpy(pzIPAddress[i], tempIP);
+ dInvDurationValues[i] = dTempDuration;
+ dTotal += dInvDurationValues[i];
+ }
+ }
+
+ for (int i = 0; i < i_Forecasts; i++ )
+ {
+ double totalForcastValues = 0;
+
+ for( int k =0; k < i_Size ; k++ )
+ totalForcastValues += finalResults[k][i];
+
+ dPredictValues[i] = totalForcastValues/ i_Iterations;
+
+
+ if(i != i_Forecasts-1)
+ {
+
+ }
+ }
+
+ /*for(int i=0; i < iGlobFreq; i++)
+ {
+ printf("%s:%f \n",pzIPAddress[i],dInvDurationValues[i]);
+ }*/
+
+ double *dRatio = new double[iGlobFreq];
+ char **pzTuningIPAddress ;
+ double *dModifiedRatio;
+
+ if(i_Size < iMachines )
+ {
+ dModifiedRatio = new double[iMachines];
+ pzTuningIPAddress = new char*[iMachines];
+ for (int i = 0; i < iMachines; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+ else
+ {
+ dModifiedRatio = new double[i_Size];
+ pzTuningIPAddress = new char*[i_Size];
+ for (int i = 0; i < i_Size; i++)
+ pzTuningIPAddress[i] = new char[128];
+ }
+
+ for(int i = 0; i < iGlobFreq ;i++)
+ {
+ dRatio[i] = dInvDurationValues[i] / dTotal;
+ }
+
+ Logs *poTune = new Logs();
+
+ if((i_Size == iMachines) ||(iMachines == 0 && !isFileExists))
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (dRatio[i] +
atof((*tuneFileList)[i][1].c_str()))/2;
+ break;
+ }
+ }
+ }
+ if(i_Size> 2)
+ poTune->writeTuning( dModifiedRatio, pzIPAddress , iGlobFreq);
+ }
+ else
+ {
+ if(i_Size > 2)
+ poTune->writeTuning( dRatio, pzIPAddress , iGlobFreq);
+ }
+ }
+ else if(i_Size != iMachines )
+ {
+ if(isFileExists)
+ {
+ for(int j = 0; j < iGlobFreq ; j++)
+ {
+ bool bNewMachine = true;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][0].compare(pzIPAddress[j])==0)
+ {
+ dModifiedRatio[j] = (( dRatio[i] * dPerformTotalRatio)+
atof((*tuneFileList)[i][1].c_str()))/2;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ (*tuneFileList)[i][2] = VISITED;
+ bNewMachine = false;
+ break;
+ }
+ }
+ if(bNewMachine)
+ {
+ dModifiedRatio[j] = dRatio[j]/2.0;
+ strcpy(pzTuningIPAddress[j], pzIPAddress[j]);
+ }
+ }
+
+ int tempIncrement =0;
+ for (int i =0; i < iMachines ; i++ )
+ {
+ if( (*tuneFileList)[i][2].compare(NOTVISITED) == 0)
+ {
+ if(i_Size <= iMachines)
+ {
+ dModifiedRatio[tempIncrement+i_Size] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+i_Size],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ else
+ {
+ dModifiedRatio[tempIncrement+iMachines] =
atof((*tuneFileList)[i][1].c_str());
+ strcpy(pzTuningIPAddress[tempIncrement+iMachines],
(*tuneFileList)[i][0].c_str());
+ tempIncrement++;
+ }
+ }
+ }
+ if(i_Size > 2)
+ {
+ if( iMachines >= i_Size )
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iMachines);
+ else
+ poTune->writeTuning( dModifiedRatio, pzTuningIPAddress , iGlobFreq );
+ }
+ }
+ }
+ }
+
+ delete [] dInvDurationValues;
+ for (int i = 0; i < iGlobFreq; i++)
+ {
+ delete []pzIPAddress[i];
+ }
+ delete [] pzIPAddress;
+
+ MPI_Bcast (dPredictValues, i_Forecasts, MPI_DOUBLE, 0, MPI_COMM_WORLD);
+ return dPredictValues;
+}
+
+Vasicek::~Vasicek(void)
+{
+ if (pz_DBName)
+ delete pz_DBName;
+ if (pz_UserName)
+ delete pz_UserName;
+ if (pz_Password)
+ delete pz_Password;
+ //if (pz_TableName)
+ // delete pz_TableName;//TODO: FIND OUT WHY MEMORY CORRUPTION
+ if (pz_IPAddress)
+ delete pz_IPAddress;
+ if (pz_DataColumn)
+ delete pz_DataColumn;
+
+ MPI_Finalize();
+ #ifdef WRITE_LOG
+ poTansLog->WriteLog("-END- \n");
+ delete poTansLog;
+ #endif
+}
+
+bool Vasicek::validateParams(int i_ArgCount,char* args[])
+{
+ if(i_ArgCount == 9)
+ {
+ for(int i = 1; i < i_ArgCount; i++)
+ {
+ int iStrLen = strlen(args[i]);
+ int iDots = 0;
+
+ for (int j = 0; j < iStrLen; j++)
+ {
+ if(isdigit(args[i][j]) == 0)
+ {
+ if (j == 0 && args[i][j] == '-')
+ {
+ continue;
+ }
+
+ if(args[i][j] != '.')
+ {
+ return false;
+ }
+ else
+ {
+ iDots++;
+
+ if ((iStrLen == 1) || (iDots > 1))
+ {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ else if(i_ArgCount == 7)
+ {
+ if((strcmp(args[1], "-t") == 0) && ((strcmp(args[3], "-d") == 0) ||
(strcmp(args[3], "-m") == 0)) && (strcmp(args[5], "-n") == 0))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+/*bool validateParams(int argc,char* argv[]);// parameter validation
+
+int main(int argc, char* argv[])
+{
+
+ int iRc = MPI_Init(&argc, &argv);
+ if (iRc != MPI_SUCCESS)
+ {
+ printf ("Error starting MPI program. Terminating.\n");
+ MPI_Abort(MPI_COMM_WORLD, iRc);
+ return 0;
+ }
+
+ int iRank, iSize;
+
+ MPI_Comm_rank(MPI_COMM_WORLD, &iRank);
+ MPI_Comm_size(MPI_COMM_WORLD, &iSize);
+ MPI_Status mpiStatus;
+ int iTag = 1;
+
+ int iNumTrials = 50000; // number of MonteCarlo trials
+ int const iPredicts = 60; // number of forward predictions //TODO:
Paramerterize predictions
+ int iNoOfItrPerMachine = iNumTrials/iSize ;
+ double dTimeStep = (1.0/12.0); // monthly
+
+ bool bValidParams = validateParams(argc, argv);
+
+ if(!bValidParams)
+ {
+ if (iRank == 0)
+ {
+ printf("Incorrect Parameters1\n");
+ fflush(stdout);
+ }
+ MPI_Finalize();
+ return 0;
+ }
+
+ double *pdParams;
+
+ if(argc == 5)
+ {
+ pdParams = new double[4];
+ pdParams[0] = (double)atof(argv[1]);
+ pdParams[1] = (double)atof(argv[2]);
+ pdParams[2] = (double)atof(argv[3]);
+ pdParams[3] = (double)atof(argv[4]);
+ }
+ else if(argc == 3)
+ {
+ int iError;
+ if(iRank == 0)
+ {
+ char *pztableName = argv[2];
+ Calib oCalib(pztableName, dTimeStep);
+ //cout << "table name: " << pztableName << endl;
+ pdParams = oCalib.Calibrate();
+ if (pdParams == NULL)
+ {
+ MPI_Abort(MPI_COMM_WORLD, 0);// TODO: finalize mpi without abort
+ //MPI_Finalize();
+ return 0;
+ }
+ }
+ else
+ {
+ pdParams = new double[4];
+ }
+ if (pdParams == NULL)
+ {
+ MPI_Finalize();
+ return 0;
+ }
+ MPI_Bcast ( pdParams, 4, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ // monte carlo simulations
+
//---------------------------------------------------------------------------------------------------
+
+ double daPredictValues[ iPredicts ];
+ vector<vector<double> > vLocalResults(iPredicts , vector<double> (
iNoOfItrPerMachine ));
+
+ cout << "Params: " << pdParams[0] << " : " << pdParams[1] << " : " <<
pdParams[2] << " : " << pdParams[3] << " : "<< dTimeStep << endl;
+ for (int i = 0; i < iNoOfItrPerMachine; i++ )
+ {
+ //NOTE: Intitial value, mu, volatility etc should be in decimal values
e.g: for 6 per cent interest rate -> use 0.06
+ Vasicek vasicek_test(pdParams[0], pdParams[1], pdParams[2], pdParams[3],
dTimeStep);
+ int j;
+ for (j=0; j < iPredicts; j++)
+ {
+ vLocalResults[j][i] = vasicek_test.step();
+ }
+ //printf("result: %f\n", vLocalResults[j-1][i]);
+ //fflush(stdout);
+ }
+ delete []pdParams;
+ double daAvgLocResults[iPredicts];
+
+ for(unsigned int i = 0; i < vLocalResults.size() ; i++)
+ {
+ double dSum = 0;
+ for(unsigned int j = 0; j < vLocalResults[i].size(); j++)
+ {
+ dSum += vLocalResults[i][j];
+ }
+ daAvgLocResults[i] = dSum / vLocalResults[i].size();
+ }
+
+ if(iRank != 0)
+ {
+ MPI_Send(&daAvgLocResults, iPredicts, MPI_DOUBLE, 0, iTag,
MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > vaPatialResults(iSize, vector<double>
(iPredicts));
+ double daTempResults[iPredicts];
+
+ for(int i = 0; i < iPredicts ; i++ )
+ {
+ vaPatialResults[0][i] = daAvgLocResults[i];
+ }
+
+ for(int i = 1; i < iSize; i++)
+ {
+ MPI_Recv(&daTempResults, iPredicts, MPI_DOUBLE, i, iTag,
MPI_COMM_WORLD, &mpiStatus);
+
+ for(int k = 0; k < iPredicts; k++)
+ {
+ vaPatialResults[i][k] = daTempResults[k];
+ }
+ }
+
+ for (int i = 0; i < iPredicts ; i++)
+ {
+ double dTemp = 0;
+ for(int k = 0; k < iSize ; k++)
+ {
+ dTemp += vaPatialResults[k][i];
+ }
+ daPredictValues[i] = dTemp / iSize;
+
+ printf("%f", daPredictValues[i]);
+ fflush(stdout);
+
+ if(i != iPredicts - 1)
+ {
+ printf("\n");
+ fflush(stdout);
+ }
+ }
+ printf("\n");
+ fflush(stdout);
+ }
+ MPI_Finalize();
+
+ return 0;
+}
+
+bool validateParams(int argc,char* argv[])
+{
+ if(argc == 5)
+ {
+ for(int i = 1; i < argc; i++)
+ {
+ int iStrLen = strlen(argv[i]);
+ int iDots = 0;
+
+ for (int j = 0; j < iStrLen; j++)
***The diff for this file has been truncated for email.***
=======================================
--- /dev/null
+++ /trunk/models/vasicek/Vasicek.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,51 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+
+#include "Logs.h"
+
+class Vasicek
+{
+private:
+ int i_ArgCount;
+ char** pz_Args;
+ char* pz_DBName;
+ char* pz_IPAddress;
+ char* pz_UserName;
+ char* pz_Password;
+ char* pz_DataColumn;
+ char* pz_TableName;
+ int i_Size;
+ double d_TimeStep;
+ int i_Iterations;
+ bool validateParams(int argc,char* args[]);// parameter validation
+ Logs *poTansLog;
+ int getNthPrime(int n);
+
+public:
+ Vasicek(int argCount, char* args[], char* pzDBName, char* pzIP, char*
pzUserName, char* pzPW, char* pzDataColumn);
+
+ int i_Forecasts;
+ double* getParams();
+ double* getPredicts(double *dParams);
+ ~Vasicek(void);
+};
=======================================
--- /dev/null
+++ /trunk/models/vasicek/VasicekCalculate.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,273 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <mpi.h>
+#include "VasicekCalculate.h"
+#ifdef _WIN32
+#include <winsock.h>
+#endif // Win32
+#include <boost/random.hpp>
+#include <stdio.h>
+#include <iostream>
+#include "Vasicek.h"
+#include "Calib.h"
+#include <ctime>
+#include <math.h>
+#include <sys/timeb.h>
+#include <vector>
+//#include <mysql.h>
+#include "DataExtracter.h"
+
+VasicekCalculate::VasicekCalculate() {
+ // TODO Auto-generated constructor stub
+
+}
+
+double* VasicekCalculate::CalcVasicekParralel(int iRank, int iSize,
vector<double> *vData, double dTimeStep, int n, int iNoOfItrPerMachine,
double lastData ){
+
+ MPI_Status mpiStatus;
+
+ Calib cal(vData);
+ int iTag =1;
+ double sx, sy, sxx, syy, sxy;
+ double mu, lambda, sigma_square, sigma;
+ double partialParameters[5];
+ double finalParameters[3];
+
+ partialParameters[0] = cal.getSx();
+ partialParameters[1] = cal.getSy();//cout<<sy<<endl;;
+ partialParameters[2] = cal.getSxx();//cout<<sxx<<endl;;
+ partialParameters[3] = cal.getSyy();//cout<<syy<<endl;;
+ partialParameters[4] = cal.getSxy();//cout<<sxy<<endl;;
+
+ if(iRank != 0)
+ {
+ MPI_Send(&partialParameters, 5, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > parametersCollection(iSize, vector<double> (5));
+ double tempResults[5];
+
+ for(int i=0; i< 5 ; i++ )
+ {
+ parametersCollection[0][i] = partialParameters[i];
+ }
+
+ for(int i=1; i< iSize; i++)
+ {
+ MPI_Recv(&tempResults, 5, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < 5; k++)
+ {
+ parametersCollection[i][k] = tempResults[k];
+ }
+ }
+
+ for(int i=0; i < 5 ; i++ )
+ {
+ double temp = 0;
+
+ for(int k=0; k < iSize ; k++)
+ {
+ temp = temp + parametersCollection[k][i];
+ }
+
+ if(i == 0)
+ sx = temp;
+ else if(i == 1)
+ sy = temp;
+ else if(i == 2)
+ sxx = temp;
+ else if(i == 3)
+ syy = temp;
+ else if(i == 4)
+ sxy = temp;
+ }
+ mu = ((sy * sxx) - (sx * sxy)) / (21 * (sxx - sxy) - (pow(sx,2) - (sx *
sy)));
+ lambda = (-1/dTimeStep)*(log((sxy - mu*sx - mu*sy + n*pow(mu,2))/(sxx -
2*mu*sx + n*pow(mu,2))));
+ double alpha = exp(-1*lambda*dTimeStep);
+ double sigmahat_square = (syy - (2*alpha*sxy) + (pow(alpha,2)*sxx) -
(2*mu*(1-alpha)*(sy - alpha*sx)) + (n*pow(mu,2)*(pow((1-alpha),2))))/n;
+ sigma_square = sigmahat_square*2*lambda / (1 - pow(alpha,2));
+
+ finalParameters[0] = mu;
+ finalParameters[1] = lambda;
+ finalParameters[2] = sqrt(sigma_square) ;
+ }
+
+ if (iRank==0)
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+ else
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ mu = finalParameters[0];
+ lambda = finalParameters[1];
+ sigma = finalParameters[2];
+
+ double *vasicekValues;
+
+ vasicekValues= MonticarloSimulation(iRank, iSize, n, iNoOfItrPerMachine,
mu, sigma, lambda, lastData );
+
+ return vasicekValues;
+}
+
+VasicekCalculate::~VasicekCalculate() {
+ // TODO Auto-generated destructor stub
+}
+
+double* VasicekCalculate::CalcVasicekSequentially(int iRank, int iSize,
vector<double> *vData,double dTimeStep, int n, int iNoOfItrPerMachine,
double lastData)
+{
+ int iTag =1;
+ MPI_Status mpiStatus;
+ double finalParameters[3];
+ double mu, lambda ,sigma;
+
+ if(iRank==0)
+ {
+
+ Calib cal(vData);
+
+ double sx = cal.getSx();//cout<<sx<<endl;;
+ double sy = cal.getSy();//cout<<sy<<endl;;
+ double sxx = cal.getSxx();//cout<<sxx<<endl;;
+ double syy = cal.getSyy();//cout<<syy<<endl;;
+ double sxy = cal.getSxy();//cout<<sxy<<endl;;
+
+ double mu = ((sy * sxx) - (sx * sxy)) / (21 * (sxx - sxy) - (pow(sx,2) -
(sx * sy)));
+ double lambda = (-1/dTimeStep)*(log((sxy - mu*sx - mu*sy +
n*pow(mu,2))/(sxx - 2*mu*sx + n*pow(mu,2))));
+ double alpha = exp(-1*lambda*dTimeStep);
+ double sigmahat_square = (syy - (2*alpha*sxy) + (pow(alpha,2)*sxx) -
(2*mu*(1-alpha)*(sy - alpha*sx)) + (n*pow(mu,2)*(pow((1-alpha),2))))/n;
+ double sigma_square = sigmahat_square*2*lambda / (1 - pow(alpha,2));
+
+ finalParameters[0] = mu;
+ finalParameters[1] = lambda;
+ finalParameters[2] = sqrt(sigma_square) ;
+ }
+
+ if (iRank==0)
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+ else
+ {
+ MPI_Bcast ( &finalParameters, 3, MPI_DOUBLE , 0, MPI_COMM_WORLD );
+ }
+
+ mu = finalParameters[0];
+ lambda = finalParameters[1];
+ sigma = finalParameters[2];
+ //CIR(double dSInitial, double dDrift, double dSigma, double
dMeanReversionSpeed, double dDelta)
+
+ double *vasicekValues;
+
+ vasicekValues= MonticarloSimulation(iRank, iSize, n, iNoOfItrPerMachine,
mu, sigma, lambda, lastData );
+
+ return vasicekValues;
+
+}
+
+double* VasicekCalculate::MonticarloSimulation(int iRank, int iSize, int
n, int iNoOfItrPerMachine, double mu, double sigma, double lambda, double
lastData )
+{
+ MPI_Status mpiStatus;
+ int iTag = 1;
+ double dTimeStep = (1.0/12.0);
+
+ double vasicekValues[n+1];
+ vector<vector<double> > results(n+1, vector<double> (iNoOfItrPerMachine));
+
+ for (int i=0; i<iNoOfItrPerMachine; i++)
+ {
+ /*Vasicek vasicek_test(dInitial, dDrift, dSigma, dLambda, dTimeStep);*/
+ Vasicek vasicek_test(lastData, mu, sigma, lambda, dTimeStep);
+ for (int j=0; j < n+1 ;j++)
+ {
+ results[j][i] = vasicek_test.step();
+ }
+ }
+
+ double caliberatedValues[n+1];
+
+ // calibration on simulated data
+ unsigned int x,y;
+
+ for(x = 0;x < results.size();x++)
+ {
+ double sum = 0;
+ for(y = 0;y < results[x].size();y++)
+ {
+ sum += results[x][y];
+ }
+ caliberatedValues[x] = sum / results[x].size();
+ }
+
+ if(iRank != 0)
+ {
+ MPI_Send(&caliberatedValues, n+1, MPI_DOUBLE, 0,iTag, MPI_COMM_WORLD);
+ }
+ else
+ {
+ vector<vector<double> > finalResults(iSize, vector<double> (n+1));
+ double tempResults[n+1];
+
+ for(int i=0; i< n+1 ; i++ )
+ {
+ finalResults[0][i] = caliberatedValues[i];
+ }
+
+ for(int i=1; i< iSize; i++)
+ {
+ MPI_Recv(&tempResults, n+1, MPI_DOUBLE, i, iTag, MPI_COMM_WORLD,
&mpiStatus);
+
+ for(int k = 0; k < n+1; k++)
+ {
+ finalResults[i][k] = tempResults[k];
+ }
+ }
+
+ for (int i=0; i < n+1 ; i++)
+ {
+ double temp = 0;
+ for(int k =0; k < iSize ; k++)
+ {
+ temp = temp + finalResults[k][i];
+ }
+ vasicekValues[i] = temp/iSize;
+
+ printf("%f", vasicekValues[i]);
+ fflush(stdout);
+
+ if(i != n)
+ {
+ printf(",");
+ fflush(stdout);
+ }
+ }
+
+ printf("\n");
+ fflush(stdout);
+ }
+
+ return vasicekValues;
+}
=======================================
--- /dev/null
+++ /trunk/models/vasicek/VasicekCalculate.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,40 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+#include <mpi.h>
+#include <vector.h>
+
+
+class VasicekCalculate {
+
+
+public:
+ VasicekCalculate();
+ virtual ~VasicekCalculate();
+
+public:
+ double* CalcVasicekParralel(int iRank, int iSize, vector<double> *vData,
double dTimeStep, int n, int iNoOfItrPerMachine, double lastData );
+ double* CalcVasicekSequentially(int iRank, int iSize, vector<double>
*vData,double dTimeStep, int n, int iNoOfItrPerMachine, double lastData);
+ double* MonticarloSimulation(int iRank, int iSize, int n, int
iNoOfItrPerMachine, double mu, double sigma, double lambda, double lastData
);
+};
+
+//#endif /* VASICEKCALCULATE_H_ */
=======================================
--- /dev/null
+++ /trunk/models/vasicek/VasicekModel.cpp Sun Jan 17 01:15:09 2010
@@ -0,0 +1,66 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include "VasicekModel.h"
+#include <iostream>
+#include <math.h>
+#include <cstdlib>
+#include <ctime>
+#include <vector>
+using namespace std;
+
+using namespace boost;
+
+
+VasicekModel::VasicekModel(double dSInitial, double dDrift, double dSigma,
double dMeanReversionSpeed, double dTimeStep, double dSeed)
+{
+ static mt19937 engine(static_cast<unsigned> (dSeed));
+ normal_distribution<> normal_dist;
+ d_vGen = new variate_generator<mt19937&, normal_distribution<double>
>(engine, normal_dist);
+ v11 = new vector<double>;
+ /*cout << (*d_vGen)() << endl;
+ cout << (*d_vGen)() << endl;*/
+ d_SInitial = dSInitial;
+ d_Drift = dDrift;
+ d_Sigma = dSigma;
+ d_Lambda = dMeanReversionSpeed;
+ d_Delta = dTimeStep;
+ d_CurrValue = dSInitial;
+ d_Diff = 0;
+
+}
+
+VasicekModel::~VasicekModel(void)
+{
+ delete d_vGen;
+}
+
+double VasicekModel::step(void)
+{
+ //cout << (*d_vGen)() << endl;
+
+ double dRandomNumber = (*d_vGen)();
+ double d_Diff = d_Drift * (1 - exp(-1 * d_Lambda * d_Delta)) + d_Sigma *
sqrt((1 - exp(-2 * d_Lambda * d_Delta)) / (2 * d_Lambda)) *
dRandomNumber;
+ d_CurrValue = d_CurrValue*exp(-d_Lambda*d_Delta) + d_Diff;
+
+ return d_CurrValue;
+
+}
=======================================
--- /dev/null
+++ /trunk/models/vasicek/VasicekModel.h Sun Jan 17 01:15:09 2010
@@ -0,0 +1,54 @@
+/*
+ Copyright (c) 2008 by contributors:
+
+ * Damitha Premadasa
+ * Nilendra Weerasinghe
+ * Thilina Dampahala
+ * Waruna Ranasinghe - (http://warunapw.blogspot.com)
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+#include <math.h>
+#include <boost/random.hpp>
+#include <vector>
+
+using namespace boost;
+//typedef variate_generator<mt19937&, normal_distribution<>> RANDOMNUMBER
+
+class VasicekModel
+{
+private:
+ std::vector<double> *v11;
+ double d_SInitial; // initial security value (constant)
+ double d_Drift; // our drift
+ double d_Sigma; // our volatility
+ double d_Lambda; // our mean reversion rate
+ double d_Delta; // our time step
+ double d_Diff; // how much the process has diffused
+ double d_CurrValue; // value at the end of current time step
+
+ variate_generator<mt19937&, normal_distribution<double> > *d_vGen;
+ //RANDOMNUMBER *d_vGen;
+
+public:
+ VasicekModel(double dSInitial, double dDrift, double dSigma, double
dMeanReversionSpeed, double dDelta, double dSeed);
+ double step(void);
+ ~VasicekModel(void);
+ double getSx();
+ double getSy();
+ double getSxx();
+ double getSyy();
+ double getSxy();
+};
=======================================
***Additional files exist in this changeset.***