int MatlabEvaluator::runAnalysis(const Vector &x) { // Let's just make a direct call since we have the pointer to OpenSees domain // This replaces above call to Tcl command; however, in the reset command // revertToStart() is also called on theTransientIntegrator -- MHS needs to check if (theOpenSeesDomain->revertToStart() != 0) { opserr << "ERROR MatlabEvaluator -- error in resetting Domain" << endln; return -1; } // Put random variables into the structural domain according to the RandomVariablePositioners int rvIndex; RandomVariablePositionerIter rvPosIter = theReliabilityDomain->getRandomVariablePositioners(); RandomVariablePositioner *theRVPos; while ((theRVPos = rvPosIter()) != 0) { rvIndex = theRVPos->getRvIndex(); theRVPos->update(x(rvIndex)); } // Start a Matlab engine Engine *ep; ep = engOpen("\0"); // Execute a Matlab function called 'matlabgfun' char theMatlabCommand[50]; sprintf(theMatlabCommand,"matlabgfun"); engEvalString(ep, theMatlabCommand); // Shut down the Matlab engine engClose(ep); return 0; }
int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow){ char buffer[BUFSIZE]; mxArray *app; Engine *ep; /* 啟動 MATLAB 引擎 */ if (!(ep = engOpen(NULL))){ // 產生一個 MATLAB 引擎物件 MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine", (LPSTR)"plotViaMatlab01.c", MB_OK); exit(-1); } /* 切換目錄並執行 plotSine.m */ _getcwd(buffer, BUFSIZE); // 將此程式所在目錄存入字串 buffer app = mxCreateString(buffer); // 產生 MATLAB 內部的字串變數 app engPutVariable(ep, "appDir", app); // 將字串變數 app 至入工作空間的變數 appDir engEvalString(ep, "cd(appDir)"); // 將 MATLAB 的工作目錄切換至字串 appDir 所指定的目錄 engEvalString(ep, "plotSine"); // 執行同目錄下的 plotSine.m /* 取得 MATLAB 輸出訊息 */ engOutputBuffer(ep, buffer, BUFSIZE); // 設定 buffer 可以接收 MATLAB 的輸出訊息 engEvalString(ep, "whos"); // 在 MATLAB 引擎執行 whos 指令 MessageBox((HWND)NULL, (LPSTR)buffer, (LPSTR) "MATLAB - whos", MB_OK); // 顯示 buffer 的內容 engClose(ep); // 最後關閉 MATLAB 引擎 return(0); }
int main(int argc, char *argv[]) { printf("\n"); if (argc < 2) { printf("not enough arguments\n\n"); return 1; } printf("STARTING MATLAB ENGINE\n\n"); Engine *ep = engOpen(""); if (ep == NULL) { printf("unable to start MATLAB engine\n\n"); return 1; } engSetVisible(ep, false); char out[BUFSIZE]; engOutputBuffer(ep, out, BUFSIZE); printf("SETTING PATH TO CNS\n\n"); Eval(ep, out, "run(fullfile('%s', 'cns_path'));", argv[1]); bool ok = RunDemo(ep, out); printf("PRESS RETURN TO CONTINUE: "); fgets(out, BUFSIZE, stdin); printf("\n"); printf("CLOSING MATLAB ENGINE\n\n"); Eval(ep, out, "close all;"); engClose(ep); return ok ? 0 : 1; }
JNIEXPORT jint JNICALL Java_JMatLink_engCloseNATIVE__I (JNIEnv *env, jobject obj, jint engine) { int retValI; // Check if engine pointer is within allowed region if (( engine < 1 ) || ( engine >= enginePMax )) { return 0; // Pointer is out of allowed region } if ( engineP[ engine ] != NULL ) { retValI = engClose(engineP[ engine ]); delEnginePointer( engine ); if (engine == engOpenMarkerI) { // This engine was opened with engOpen() before engOpenMarkerI = 0; } if (debugB) printf("\n engClose \n"); } else { return 0; } }
int main(int argc, const char *argv[]) { Engine *ep; char buff[10240]; int i; /* matlab must be in the PATH! */ if (!(ep = engOpen("matlab -nodisplay"))) { fprintf(stderr, "Can't start MATLAB engine\n"); return -1; } engOutputBuffer(ep, buff, 10239); /* load the mex file */ if(argc<2){ fprintf(stderr, "Error. Give full path to the MEX file as input parameter.\n"); return -1; } void *handle = dlopen(argv[1], RTLD_NOW); if(!handle){ fprintf(stderr, "Error loading MEX file: %s\n", strerror(errno)); return -1; } /* grab mexFunction handle */ mexFunction_t mexfunction = (mexFunction_t)dlsym(handle, "mexFunction"); if(!mexfunction){ fprintf(stderr, "MEX file does not contain mexFunction\n"); return -1; } /* load input data - for convenience do that using MATLAB engine */ /* NOTE: parameters are MEX-file specific, so one has to modify this*/ /* to fit particular needs */ engEvalString(ep, "load input.mat"); mxArray *arg1 = engGetVariable(ep, "im1"); mxArray *arg2 = engGetVariable(ep, "im2"); mxArray *arg3 = engGetVariable(ep, "szx"); mxArray *arg4 = engGetVariable(ep, "szy"); mxArray *arg5 = engGetVariable(ep, "ngh"); mxArray *pargout[1] = {0}; const mxArray *pargin[5] = {arg1, arg2,arg3, arg4,arg5}; /* execute the mex function */ mexfunction(1, pargout, 5, pargin); /* print the results using MATLAB engine */ engPutVariable(ep, "result", pargout[0]); engEvalString(ep, "result"); printf("%s\n", buff); /* cleanup */ mxDestroyArray(pargout[0]); engEvalString(ep, "clear all;"); dlclose(handle); engClose(ep); return 0; }
~MatLabEngine( void ) { engClose( _ep ); _ep = 0; if ( _matLabLogFileStreamPtr ) { _matLabLogFileStreamPtr->close(); delete _matLabLogFileStreamPtr; _matLabLogFileStreamPtr = 0; } }
static int p_closematlab(void) { Engine *eng = Meng; Meng = NULL; if (Meng) return engClose(eng); else return FALSE; }
PyObject * mlabraw_close(PyObject *, PyObject *args) { PyObject *lHandle; if (! PyArg_ParseTuple(args, "O:close", &lHandle)) return NULL; if (engClose((Engine *)PyCObject_AsVoidPtr(lHandle)) != 0) { PyErr_SetString(mlabraw_error, "Unable to close session"); return NULL; } Py_INCREF(Py_None); return Py_None; }
EXPORT bool glx_term(glxlink* mod) { // close matlab engine MATLABLINK *matlab = (MATLABLINK*)mod->get_data(); if ( matlab && matlab->engine ) { if ( matlab->term ) { mxArray *ans = matlab_exec(matlab,"%s",matlab->term); if ( ans && mxIsDouble(ans) && (bool)*mxGetPr(ans)==false ) { gl_error("matlab term failed"); return false; } else if ( ans && mxIsChar(ans) ) { int buflen = (mxGetM(ans) * mxGetN(ans)) + 1; char *string =(char*)malloc(buflen); int status_error = mxGetString(ans, string, buflen); if (status_error == 0) { gl_error("'%s'",string); engClose(matlab->engine)==0; return false; } else { gl_error("Did not catch Matlab error"); engClose(matlab->engine)==0; return false; } } } if ( window_kill(matlab) ) engClose(matlab->engine)==0; } return true; }
int main(){ Engine *ep; mxArray *mX = NULL, *mY = NULL; const size_t N = 1024; if (!(ep = engOpen(NULL))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } mX = mxCreateDoubleMatrix(1, N, mxREAL); mY = mxCreateDoubleMatrix(1, N, mxREAL); double *x = (double *)mxGetPr(mX); double *y = (double *)mxGetPr(mY); for (size_t i=0; i<N; ++i){ x[i] = 2.0*M_PI*i/N; y[i] = sin(x[i]); } engPutVariable(ep, "x", mX); engPutVariable(ep, "y", mY); engEvalString(ep, "h = figure;"); engEvalString(ep, "plot(x, y); hold on;"); engEvalString(ep, "plot([0 0],ylim,'k'); plot(xlim,[0 0],'k');"); engEvalString(ep, "title('y = sin(x)');"); engEvalString(ep, "xlabel('x');"); engEvalString(ep, "ylabel('y');"); engEvalString(ep, "grid on; grid minor; box off;"); engEvalString(ep, "print(h,'-dpng','sin.png');"); engEvalString(ep, "close all;"); mxDestroyArray(mX); mxDestroyArray(mY); printf("Ok. Press ENTER to exit\n"); getchar(); engClose(ep); return EXIT_SUCCESS; }
void engclose(void) { bool SUCCESS = true; //success flag if (NULL == Eng) //if closed { msg("eng::noMLB"); //message MATLAB closed SUCCESS = false; } else { engClose(Eng); Eng = NULL; } if(SUCCESS) MLPutSymbol(stdlink, "Null"); else MLPutSymbol(stdlink, "$Failed"); }
int main (int argc, char** argv) { ros::init (argc, argv, "al_viz_objects_features"); nh_ = new ros::NodeHandle ("~"); sub_entities_ = nh_->subscribe ("/perception/entities", 1, &entitiesCallback); srv_cl_get_entities_visual_features_ = nh_->serviceClient<al_srvs::GetEntitiesVisualFeatures> ("/get_entities_visual_features", true); srv_cl_get_entities_visual_features_.waitForExistence (); srv_cl_get_entities_visual_features_ = nh_->serviceClient<al_srvs::GetEntitiesVisualFeatures> ("/get_entities_visual_features", true); ep_ = engOpen ("matlab -nodesktop -nosplash -nojvm"); if (ep_ == NULL) ROS_ERROR("Constructor: engOpen failed"); else ROS_DEBUG(" Matlab engine is working!"); //in any case surface normals should be calculated pcl::PointCloud<pcl::Normal>::Ptr pointcloud_normals (new pcl::PointCloud<pcl::Normal>); pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZ> ()); ne_.setSearchMethod (tree); ne_.setViewPoint (0, 0, 1.2);//this could be done more informed by getting this information from a topic ros::Rate r (30);//objects can be refreshed at most @30hz while (nh_->ok ()) { if (msg_entities_rcvd_) { msg_entities_rcvd_ = false; vizFeatures (); } ros::spinOnce (); r.sleep (); } engClose (ep_); return 0; }
int main() { Welcome_LSI(); if (Initialize_LSI()) { printf("Initialization Completed\n\n"); } else { printf("Initialization Failed\n"); return 0; } // for (int i = 0; i <= 10 ; ++i) rvsyn[i] = 100*i+77; // Show_Synonym_LSI(); // Show_Word_LSI(777); Work_LSI(); printf("Thanks for your searching! See you next time!\n"); fclose(inword); fclose(inpoems); engClose(ep); return 0; }
int main() { Engine* engine; printf("Opening matlab engine...\n"); if (!(engine = engOpen("\0"))) { fprintf(stderr, "Could not start MATLAB engine!\n"); return EXIT_FAILURE; } // mxArray *T = NULL, *result = NULL; // double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; // T = mxCreateDoubleMatrix(1, 10, mxREAL); // memcpy((void *)mxGetPr(T), (void *)time, sizeof(time)); // engPutVariable(ep, "T", T); // engEvalString(ep, "D = .5.*(-9.8).*T.^2;"); // engEvalString(ep, "plot(T,D);"); // mxDestroyArray(result); engClose(engine); printf("Done!\n"); return EXIT_SUCCESS; }
//#define BUFSIZE 1000 void AAM_Train::getMeanShape() { double threshold=0.002; //transplate all the shapes to its gradivity for (int i=0;i<shapeNum;i++) { shape[i]->centerPts(2); } //normalize shape[0],save as ref int refInd=4; //namedWindow("1"); //imshow("1",cvarrToMat(shape[refInd]->hostImage)); //waitKey(); //shape[refInd]->normalize(1); //if we want to control the complexity, do it here double *refshape=new double[shape[refInd]->ptsNum*2]; for (int i=0;i<shape[refInd]->ptsNum*2;i++) { refshape[i]=shape[refInd]->ptsForMatlab[i]*1.0; } shape_scale=normalize(refshape,shape[refInd]->ptsNum); //align the shape int width=shape[refInd]->ptsNum; int height=2; int arraysize=width*2*sizeof(double); mxArray *referShape = NULL,*curMatMean=NULL,*newMatMean=NULL, *inputShape=NULL,*result = NULL; if (!(ep = engOpen("\0"))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return; } referShape=mxCreateDoubleMatrix(width,height,mxREAL); curMatMean=mxCreateDoubleMatrix(width,height,mxREAL); newMatMean=mxCreateDoubleMatrix(width,height,mxREAL); inputShape=mxCreateDoubleMatrix(width,height,mxREAL); result=mxCreateDoubleMatrix(width,height,mxREAL); double *currentMean=new double[width*2]; double *newMean=new double[width*2]; //set the default refer shape memcpy((void *)mxGetPr(referShape), (void *)refshape, arraysize); //initialize currentMean to the refer shape for (int i=0;i<width*2;i++) { currentMean[i]=refshape[i]; } ofstream out3("F:/imgdata/AAM training data/train/refshape.txt",ios::out); //for (int i=0;i<shapeNum;i++) { for(int j=0;j<width;j++) { out3<<refshape[j]<<" "<<refshape[width+j]<<endl; } } out3.close(); //char buffer[BUFSIZE+1]; engPutVariable(ep, "referShape", referShape); engPutVariable(ep, "result", result); // engEvalString(ep,"save('F:/imgdata/AAM training data/train/refershape.mat','referShape');"); // engPutVariable(ep, "result", newMatMean); while(1) { //set current mean memcpy((void *)mxGetPr(curMatMean), (void *)currentMean, arraysize); engPutVariable(ep, "curMatMean", curMatMean); //allign all the shapes for (int i=0;i<shapeNum;i++) { memcpy((void *)mxGetPr(inputShape), (void *)shape[i]->ptsForMatlab, arraysize); engPutVariable(ep, "inputShape", inputShape); engEvalString(ep, "[m,result]=procrustes(curMatMean,inputShape);"); result = engGetVariable(ep,"result"); // delete []shape[i]->ptsForMatlab; shape[i]->ptsForMatlab=mxGetPr(result); engEvalString(ep,"save('F:/imgdata/AAM training data/train/result.mat','result','curMatMean','inputShape');"); //shape[i]->scale(shape[i]->scaleParameter,1);//reconver the scale } //caculate newMean and allign it to ref and normalize for (int i=0;i<width*2;i++) { newMean[i]=0; } for (int i=0;i<width*2;i++) { for (int j=0;j<shapeNum;j++) { newMean[i]+=shape[j]->ptsForMatlab[i]; } newMean[i]/=shapeNum; } memcpy((void *)mxGetPr(newMatMean), (void *)newMean, arraysize); engPutVariable(ep, "newMatMean", newMatMean); engEvalString(ep, "[m,result]=procrustes(referShape,newMatMean);"); //engEvalString(ep,"save('F:/imgdata/AAM training data/train/result.mat','result','referShape','newMatMean');"); //delete []newMean; newMean=mxGetPr( engGetVariable(ep,"result")); //normalize newMean normalize(newMean,width); ofstream out1("F:/imgdata/AAM training data/train/meanshape_ori.txt",ios::out); //for (int i=0;i<shapeNum;i++) { for(int j=0;j<width;j++) { out1<<newMean[j]<<" "<<newMean[width+j]<<endl; } } out1.close(); //caculate the diff of means, if smaller than threshold, stop double differ=0,n2_newmean=0; for (int i=0;i<width;i++) { differ+=sqrt((newMean[i]-refshape[i])*(newMean[i]-refshape[i])+ (newMean[width+i]-refshape[width+i])*(newMean[width+i]-refshape[width+i])); // n2_newmean+=sqrt(newMean[i]*newMean[i]+newMean[width+i]*newMean[width+i]); } cout<<"current difference: "<<differ/shape_scale<<endl; if (differ/shape_scale<threshold) { //ofstream out("meanshape.txt",ios::out); //for (int i=0;i<meanShape->ptsNum;i++) //{ // out<<meanShape->pts[i][0]<<" "<<meanShape->pts[i][1]<<endl; //} //out.close(); //save the new mean meanShape->getVertex(newMean,width,1,1); meanShape->scale(shape_scale,1); break; } //oldmean=newmean for (int i=0;i<width*2;i++) { currentMean[i]=newMean[i]; } } //rescale all the shapes engClose(ep); //for (int i=0;i<shapeNum;i++) //{ // shape[i]->scale(scaleParameter,2);//scale to normal size,only for traning data //} //tangent space if needed ofstream out("F:/imgdata/AAM training data/train/allignedshape.txt",ios::out); for (int i=0;i<shapeNum;i++) { for(int j=0;j<width;j++) { out<<shape[i]->ptsForMatlab[j]<<" "<<shape[i]->ptsForMatlab[width+j]<<endl; } } out.close(); ofstream out1("F:/imgdata/AAM training data/train/meanshape.txt",ios::out); //for (int i=0;i<shapeNum;i++) { for(int j=0;j<width;j++) { out1<<meanShape->ptsForMatlab[j]<<" "<<meanShape->ptsForMatlab[width+j]<<endl; } } out1.close(); //delete []currentMean; //delete []newMean; //delete []refshape; }
static int server(char **argv, char *pname[2], int p[2]) { Engine *ep; FILE *f; char buf[4096], buf1[4096], *msg, *s, *t; int rc; #if 0/*def SERVER_DEBUG*/ printf("Server got\tpname[0] = \"%s\"\nand\t\tpname[1] = \"%s\"\n", pname[0], pname[1]); if (*argv) { int i; printf("Args for MATLAB to interpret:\n"); for(i = 0; argv[i]; i++) printf("\t\"%s\"\n", argv[i]); } #endif if (exists(pname[0], 1) || exists(pname[1], 1)) return 1; if (mkfifo(pname[0], 0600)) return mkfifo_fail(pname[0]); if (mkfifo(pname[1], 0600)) { unlink(pname[0]); return mkfifo_fail(pname[1]); } s = *argv; //if(s){ printf("%s\n",s); fflush(stdout);} ep = engOpen(s ? s : "matlab -logfile engine.log"); if (!ep) { Squawk("could not start MATLAB\n"); return 1; } /*DEBUG*/engOutputBuffer(ep, mbuf, sizeof(mbuf)-1); if (s) while(s = *++argv) engEvalString(ep, s); if (p[1] >= 0) { close(p[0]); write(p[1], "OK\n", 3); close(p[1]); } rc = 1; for(;;) { f = fopen(pname[0], "r"); if (!f) break; s = fgets(buf, sizeof(buf), f); if (!s) { fclose(f); break; } trim(s); if (!*s) { Squawk("server: empty parameters_file name\n");\ bailout: fclose(f); break; } if (!strcmp(s,"quit")) { rc = 0; goto bailout; } t = fgets(buf1, sizeof(buf1), f); fclose(f); if (!t) { Squawk("server expected 2 lines from \"%s\"; only got 1.\n", pname[0]); break; } trim(t); msg = process(ep, s, t) ? "evaluation error" : "results_file written"; f = fopen(pname[1],"w"); if (!f) { Squawk("Could not open pipe2 file \"%s\"\n", pname[1]); break; } fprintf(f, "%s\n", msg); fclose(f); } engClose(ep); unlink(pname[0]); unlink(pname[1]); return rc; }
int main() { Engine *ep; mxArray *T = NULL, *result = NULL; char buffer[BUFSIZE+1]; // double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; double time[6] = { 1.2, 0.4, 2.1, 0.8, 1.9, 0.1, }; /* * Call engOpen with a NULL string. This starts a MATLAB process * on the current host using the command "matlab". */ if (!(ep = engOpen(""))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } /* * PART I * * For the first half of this demonstration, we will send data * to MATLAB, analyze the data, and plot the result. */ /* * Create a variable for our data */ // T = mxCreateDoubleMatrix(3, 2, mxREAL); // memcpy((void *)mxGetPr(T), (void *)time, sizeof(time)); // /* // * Place the variable T into the MATLAB workspace // */ // engPutVariable(ep, "T", T); std::string data_path = "X.csv"; std::string cmd = std::string("X = csvread('" + data_path + "');"); engEvalString(ep,cmd.c_str()); // engEvalString(ep, "X = csvread('X.csv');"); engEvalString(ep, "X = X(:,1:end-1);"); // /* // * Evaluate a function of time, distance = (1/2)g.*t.^2 // * (g is the acceleration due to gravity) // */ // engEvalString(ep, "D = .5.*(-9.8).*T.^2;"); // /* // * Plot the result // */ // engEvalString(ep, "plot(T,D);"); // engEvalString(ep, "title('Position vs. Time for a falling object');"); // engEvalString(ep, "xlabel('Time (seconds)');"); // engEvalString(ep, "ylabel('Position (meters)');"); engEvalString(ep, "[~,newX] = princomp(X);"); // engEvalString(ep, "newT = T';"); engEvalString(ep, "csvwrite('newX.csv',newX);"); // /* // * use fgetc() to make sure that we pause long enough to be // * able to see the plot // */ // printf("Hit return to continue\n\n"); // fgetc(stdin); /* * We're done for Part I! Free memory, close MATLAB figure. */ printf("Done for Part I.\n"); mxDestroyArray(T); engEvalString(ep, "close;"); /* * We're done! Free memory, close MATLAB engine and exit. */ printf("Done!\n"); engClose(ep); return EXIT_SUCCESS; }
TMatlab::~TMatlab(){ #ifdef HAVE_MATLAB if (fEngine) engClose((Engine*)fEngine); if (fOutputBuffer) delete [] fOutputBuffer; #endif }
void MainWindow::RunAdamsSim() { ButtonAdamsSim->setStyleSheet("QPushButton {border-radius: 2px;padding: 0.2em 0.2em 0.3em 0.2em;border: 1px solid rgb(100, 100,100);background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #34f32d, stop: 1 #000000);color: white;}"); std::ostringstream ossStringLHip, ossStringRHip, ossStringLKnee, ossStringRKnee, ossStringTimeLeft, ossStringTimeRight, ossPeriod, ossCycles, ossDelay; vector <double> vTimeLeftLeg, vTimeRightLeg; vector <double> vHipR, vHipL, vKneeR, vKneeL; ossPeriod <<"period="<<lineEditPeriod->text().toStdString(); ossCycles <<"cycles="<<lineEditCycles->text().toStdString(); ossDelay <<"delay="<<lineEditDelay->text().toStdString(); // Getting Time Values //GetTimeValues(vTimeValues); pHipRight->GetSamples(vTimeRightLeg); pHipLeft->GetSamples(vTimeLeftLeg); GetRobotObjectSampledValues(pHipLeft, vHipL); GetRobotObjectSampledValues(pHipRight, vHipR); GetRobotObjectSampledValues(pKneeLeft, vKneeL); GetRobotObjectSampledValues(pKneeRight, vKneeR); //pHipLeft->ExportMarkers(vTimeValues, vHipL); pHipLeft->GetValues(vTimeLeftLeg, vHipL); pHipRight->GetValues(vTimeRightLeg, vHipR); pKneeLeft->GetValues(vTimeLeftLeg, vKneeL); pKneeRight->GetValues(vTimeRightLeg, vKneeR); // Making string for left hip ossStringLHip << "vHipL=["; std::copy(vHipL.begin(), vHipL.end()-1, std::ostream_iterator <double>(ossStringLHip, " ")); ossStringLHip << vHipL.back(); ossStringLHip << "];"; std::cout<<ossStringLHip.str()<<std::endl; // Making string for left hip ossStringRHip << "vHipR=["; std::copy(vHipR.begin(), vHipR.end()-1, std::ostream_iterator <double>(ossStringRHip, " ")); ossStringRHip << vHipR.back(); ossStringRHip << "];"; // Making string for left knee ossStringLKnee << "vKneeL=["; std::copy(vKneeL.begin(), vKneeL.end()-1, std::ostream_iterator <double>(ossStringLKnee, " ")); ossStringLKnee << vKneeL.back(); ossStringLKnee << "];"; // Making string for right knee ossStringRKnee << "vKneeR=["; std::copy(vKneeR.begin(), vKneeR.end()-1, std::ostream_iterator <double>(ossStringRKnee, " ")); ossStringRKnee << vKneeR.back(); ossStringRKnee << "];"; // Making string for time values for Left Leg ossStringTimeLeft << "vTimeL=["; std::copy(vTimeLeftLeg.begin(), vTimeLeftLeg.end()-1, std::ostream_iterator <double>(ossStringTimeLeft, " ")); ossStringTimeLeft << vTimeLeftLeg.back(); ossStringTimeLeft << "];"; std::cout<<ossStringTimeLeft.str()<<std::endl; // Making string for time values for Right Leg ossStringTimeRight << "vTimeR=["; std::copy(vTimeRightLeg.begin(), vTimeRightLeg.end()-1, std::ostream_iterator <double>(ossStringTimeRight, " ")); ossStringTimeRight << vTimeRightLeg.back(); ossStringTimeRight << "];"; std::cout<<ossStringTimeRight.str()<<std::endl; Engine* m_matlabEngine; // Opening Matlab Engine m_matlabEngine=engOpen("\0"); // Clearing engEvalString(m_matlabEngine, "clear;"); engEvalString(m_matlabEngine, ossStringLHip.str().c_str()); engEvalString(m_matlabEngine, ossStringTimeLeft.str().c_str()); engEvalString(m_matlabEngine, ossStringTimeRight.str().c_str()); engEvalString(m_matlabEngine, ossStringRHip.str().c_str()); engEvalString(m_matlabEngine, ossStringRKnee.str().c_str()); engEvalString(m_matlabEngine, ossStringLKnee.str().c_str()); engEvalString(m_matlabEngine, ossPeriod.str().c_str()); engEvalString(m_matlabEngine, ossCycles.str().c_str()); engEvalString(m_matlabEngine, ossDelay.str().c_str()); QString runEval(QString("run('%1');").arg("C:/Users/Zahid/GUI/RobotSim2/test_final_m2.m")); engEvalString(m_matlabEngine, "cd('C:/Users/Zahid/GUI/RobotSim2');"); //engEvalString(m_matlabEngine, "Controls_Plant_2705_1"); //engEvalString(m_matlabEngine, "open('test_final_model');"); //engEvalString(m_matlabEngine, "sim('test_final_model');"); engEvalString(m_matlabEngine, runEval.toUtf8().constData()); engClose(m_matlabEngine); ButtonAdamsSim->setStyleSheet("QPushButton {border-radius: 2px;padding: 0.2em 0.2em 0.3em 0.2em;border: 1px solid rgb(100, 100,100);background: QLinearGradient( x1: 0, y1: 0.02, x2: 0, y2: 1.2, stop: 0 #220, stop: 1 #ffffff);color: white;}"); }
void Uav::unInitializeMatlabEngine() { engClose(matlabEngine); matlabEngine = nullptr; }
int main(int argc, char* argv[]) { cout<<"beta ="<<beta<<endl; if (argc < 6) { cout << "invalid format: <tasksets><hyperperiod length><computation utilization><interval> <seed>" << endl; exit(1); } #if(MATLAB_ENABLE) ep =engOpen(NULL); if(ep==0) { cout<<"connection with matlab engine failed"<<endl; } #endif #if (RT_ENABLE) struct sched_param param; signal(SIGINT, int_handler); freq_set(CORE,"performance"); cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(1,&mask); cout<<"setting affinity to processor "<<CORE<<endl; if(sched_setaffinity(0,CPU_COUNT(&mask),&mask)==-1) { perror("sched_setscheduler failed"); exit(-1); } param.sched_priority = MY_PRIORITY; //priority for the scheduler if (sched_setscheduler(0, SCHED_FIFO, ¶m) == -1) { //scheduler has cooporative scheduling perror("sched_setscheduler failed"); exit(-1); } //lock memory if(mlockall(MCL_CURRENT | MCL_FUTURE)==-1) { perror("mlockall failed"); exit(-2); } stack_prefault(); #endif corrected_threshold = corrected_temperature(THRESHOLD); cout<<"beta "<<beta<<" corrected threshold "<<corrected_threshold<<endl; // exit(1); int iter = atoi(argv[1]); int hyperperiod = atoi(argv[2]); int comp_util = atoi(argv[3]); int sched_interval=atoi(argv[4]); seed = atoi(argv[5]); string task_file; if (argc == 7) { task_file = argv[6]; } srand(seed); vector<task> tasks; vector<schedule> edf; vector<task> scaled_tasks; vector<double> speeds; vector<schedule> edf2; vector<task> discrete_scaled; vector<schedule> edf3; vector<schedule> edl2; vector<schedule> i_schedule; vector<schedule> opt; vector<schedule> opt_exact; vector<float> possible_speeds; vector<double> h_speed; vector<double> s_speed; vector<double> m_speed; vector<double> i_speed; vector<double> i_speed_temp; vector<slack> slacks; vector<schedule> edl; vector<task> scaled_max_first; vector<task> scaled_static; vector<task> scaled_matlab; vector<schedule> edf_max_first; vector<schedule> edf_static; vector<schedule> edf_matlab; for (int z = 0; z < iter; z++) { thermal_optimal = 0; // generate_tasksets(&tasks,1,hyperperiod,50,100); if (argc == 6) { // generate_tasksets(&tasks, 1, hyperperiod, comp_util, comp_util); } else { read_tasksets(&tasks, task_file); } int_pointer=&tasks; #if(OPT_ENABLE) call_gams(); store_opt(&tasks); #endif double t_util; // edf_schedule(&tasks, &edf); // consolidate_schedule(&edf, &tasks); thermal_optimal = 1; // compute_profile(&edf, &tasks, t_util); // edl_schedule2(&edl2, &edf); // consolidate_schedule(&edl2, &tasks); // populate_slacks(&slacks, &edf); // edl_schedule(&edl, &edf, &tasks, &slacks); // consolidate_schedule(&edl, &tasks); #if(INST_ENABLE) cout<<"entering optimize instances"<<endl; vector<int>slack; optimize_instances(&i_speed,&tasks,&i_schedule,&edl, &edl2,MIN_SPEED,MAX_SPEED,&i_speed_temp,&slack); cout<<"exiting optimize instances"<<endl; cout<<"printing optimal schedule"<<endl; for(unsigned int i=0;i<i_schedule.size();i++) { cout<<"task "<<i_schedule[i].task_id<<" start "<<i_schedule[i].start<<" end "<<i_schedule[i].end <<" speed "<<i_speed[i]<<" power "<<tasks[i_schedule[i].task_id].power*pow(i_speed[i],3.0)<< " slack "<<slack[i]<<" deadline "<<(i_schedule[i].start/tasks[i_schedule[i].task_id].period+1)*tasks[i_schedule[i].task_id].period<<endl; } verify(&i_schedule,&tasks,&i_speed); #endif #if(SLACK_ENABLE) verify(&edl, &tasks); opt_schedule_exact(&opt_exact, &tasks); opt_schedule(&opt, &tasks, &edl); #endif #if(MAX_ENABLE) vector<float_task>ft; vector<long_task>ltasks; vector<long_schedule>lschedule; vector<long_schedule>lschedule2; vector<long_schedule>lschedule3; vector<float_schedule>wsch; vector<float_schedule>wsch2; vector<float_schedule>wsch3; vector<float_schedule>fedf; vector<schedule>o_sch; vector<interval_s>intervals; // cout<<"generating task set "<<endl; float thermal_util=0.98; float computation_util=1.0; int num_tasks=rand() % (11) + 10; // generate_taskset(&ft, 1000, num_tasks,computation_util, thermal_util); // w2fq_task_convert(<asks, &ft); // generate_intervals_gps(&intervals, <asks);/ // w2fq_schedule(&lschedule, <asks,&intervals,0); // edf_schedule(&ft,&fedf); // w2fq_schedule_convert(&wsch, &lschedule); //cout<<" printing float schedule "<<endl; // compute_profile(&wsch, &ft, 1); // compute_profile(&fedf, &ft, 4); // instance_override(&ft); // dynamic_instance_schedule(&lschedule2, <asks,&intervals,1); // w2fq_schedule_convert(&wsch2, &lschedule2); // compute_profile(&wsch2, &ft, 2); // dynamic_instance_schedule(&lschedule3, <asks,&intervals,2); // w2fq_schedule_convert(&wsch3, &lschedule3); // compute_profile(&wsch3, &ft, 3); ft.clear(); ltasks.clear(); lschedule.clear(); fedf.clear(); wsch.clear(); float power; power=rand()/(float)RAND_MAX*20.00; power=power+18.00; cout<<power<<endl; float comp_util=1.5;//0.6; ofstream taskfile("taskset_file"); int ** matrix; matrix = new int *[20]; for(unsigned int i=0;i<20;i++) { matrix[i] =new int[20]; } resource_matrix(matrix,20,0.5); stringstream command; generate_taskset_multi(&ft, 100, 15,2.0); gams_include(&ft, matrix); ofstream tasksetfile("taskset"); for(unsigned int i=0;i<ft.size();i++) { tasksetfile<<"task"<<i<<"\t"<<ft[i].computation_time<<"\t"<<ft[i].period<<"\t"<<ft[i].power<<endl; } tasksetfile.close(); vector<instance>inst; vector<interval>speed_intervals; vector<long_schedule>lsch; generate_intervals_multi(&speed_intervals, "instanceassign_speed.put"); for(unsigned int i=0;i<speed_intervals.size();i++) { cout<<"start "<<speed_intervals[i].start<<" end "<<speed_intervals[i].end<<endl; for(unsigned int j=0;j<speed_intervals[i].get_size();j++) { cout<<"task "<<speed_intervals[i].exec[j].task<<"|"<<speed_intervals[i].exec[j].exec<<"|"<<speed_intervals[i].exec[j].core<<endl; } } //exit(1); instance_override_speed(&ft, &inst); w2fq_task_convert(<asks, &ft); dynamic_instance_schedule_speed(&lsch, <asks, &speed_intervals, &inst,0); // vector<long_schedule>lsch2; // dynamic_instance_schedule_speed(&lsch2, <asks, &speed_intervals, &inst,0); float scaled_power[CORE]; double avg_power; generate_power_trace(&lsch, "power_profile_scaled", hyperperiod, scaled_power); multi_simulate("power_profile_scaled", "multi.flp",0,avg_power); // dynamic_instance_schedule exit(1); float comps[CORE]; for(unsigned int i=0;i<speed_intervals.size();i++) { for(unsigned int j=0;j<CORE;j++) { comps[j]=0; } for(unsigned int j=0;j<speed_intervals[i].get_size();j++) { comps[speed_intervals[i].exec[j].core]=comps[speed_intervals[i].exec[j].core]+ speed_intervals[i].exec[j].exec; } cout<<speed_intervals[i].start<<"|"<<speed_intervals[i].end<<"|"<<comps[0]<<"|"<<comps[1]<<"|"<<comps[2]<<endl; } exit(1); float bins[BIN_LENGTH]={0.5,0.6,0.7,0.8,0.9,1.0,1.1}; int bin_count[BIN_LENGTH]={0,0,0,0,0,0,0}; int task_num=0; bool tutil_incomplete=true; while(comp_util<3.0)//1.0) { cout<<"generating for computil"<<comp_util<<endl; tutil_incomplete=true; for(unsigned int b=0;b<BIN_LENGTH;b++) { bin_count[b]=0; } while(tutil_incomplete) { //cout<<" task num "<<task_num<<endl; //generate_taskset(&ft, 100, 10, comp_util); generate_taskset_multi(&ft, 100, 15,comp_util); float avg_power=0.00; float real_cutil=0.00; for(unsigned int i=0;i<ft.size();i++) { avg_power=avg_power+ft[i].computation_time/ft[i].period*ft[i].power; real_cutil=real_cutil+ft[i].computation_time/ft[i].period; } float tutil=avg_power/(beta*corrected_threshold);//UTIL_POWER; bool accept=false; for(unsigned int b=0;b<BIN_LENGTH;b++) { if(tutil> bins[b] && tutil<(bins[b]+0.1) && bin_count[b]<10) { accept=true; bin_count[b]=bin_count[b]+1; } } if(accept) { /*if(tutil<0.6 && comp_util>0.75) { ofstream tasksetfile("taskset"); for(unsigned int i=0;i<ft.size();i++) { tasksetfile<<"task"<<i<<"\t"<<ft[i].computation_time<<"\t"<<ft[i].period<<"\t"<<ft[i].power<<endl; } taskfile<<real_cutil<<"\t"<<tutil<<endl; //w2fq_task_convert(<asks, &ft); //generate_intervals_gps(&intervals, <asks); //w2fq_schedule(&lschedule, <asks,&intervals,0); //edf_schedule(&ft,&fedf); //w2fq_schedule_convert(&wsch, &lschedule); //cout<<" printing float schedule "<<endl; //compute_profile(&wsch, &ft, 1); //compute_profile(&fedf, &ft, 4); //command<<"mkdir results_uni/"<<task_num<<";"; //command<<"cp profile_float results_uni/"<<task_num<<"/.;"; //command<<"cp profile_default results_uni/"<<task_num<<"/.;"; //command<<"cp taskset results_uni/"<<task_num<<"/."; //system(command.str().c_str()); //command.str(""); tasksetfile.close(); //exit(1); }*/ //cout<<"checkpoint 1 "<<endl; gams_include(&ft, matrix); //cout<<"checkpoint 2 "<<endl; system("cd gams_files; ~rehan/gams/gams lower_bound.gms"); system("cd gams_files; ~rehan/gams/gams task_assign.gms"); command<<"mkdir results/"<<task_num<<";"; command<<"cp gams_files/results.put results/"<<task_num<<"/.;"; command<<"cp gams_files/taskassign.put results/"<<task_num<<"/.;"; command<<"cp gams_files/taskassign_assign.put results/"<<task_num<<"/.;"; command<<"cp gams_files/task_assign.lst results/"<<task_num<<"/.;"; command<<"cp gams_files/lower_bound.lst results/"<<task_num<<"/.;"; command<<"cp gams_files/taskset.put results/"<<task_num<<"/."; system(command.str().c_str()); command.str(""); //cin.get(); //exit(1); task_num=task_num+1; tutil_incomplete=false; for(unsigned int b=0;b<BIN_LENGTH;b++) { if(bin_count[b]<10) { tutil_incomplete=true; } } //exit(1); } intervals.clear(); lschedule.clear(); ltasks.clear(); fedf.clear(); wsch.clear(); ft.clear();//only ft needs to be cleared for multicore simulation } //comp_util=comp_util+0.0025;//0.01; comp_util=comp_util+0.01;//0.01; } exit(1); /* int task_num=0; while(comp_util<3.0) { for(unsigned int m=0;m<10;m++) { generate_taskset_multi(&ft, 100, 15,comp_util); float avg_power=0.00; float real_cutil=0.00; for(unsigned int i=0;i<ft.size();i++) { avg_power=avg_power+ft[i].computation_time/ft[i].period*ft[i].power; real_cutil=real_cutil+ft[i].computation_time/ft[i].period; } float tutil=avg_power/UTIL_POWER; if(tutil>0.5 && tutil<1.2) { taskfile<<real_cutil<<"\t"<<tutil<<endl; cout<<"checkpoint 1 "<<endl; gams_include(&ft, matrix); cout<<"checkpoint 2 "<<endl; system("cd gams_files; ~rehan/gams/gams lower_bound.gms"); system("cd gams_files; ~rehan/gams/gams task_assign.gms"); command<<"mkdir results/"<<task_num<<";"; command<<"cp gams_files/results.put results/"<<atoi(argv[5])<<"/.;"; command<<"cp gams_files/taskassign.put results/"<<atoi(argv[5])<<"/.;"; command<<"cp gams_files/taskassign_assign.put results/"<<atoi(argv[5])<<"/.;"; command<<"cp gams_files/task_assign.lst results/"<<atoi(argv[5])<<"/.;"; command<<"cp gams_files/lower_bound.lst results/"<<atoi(argv[5])<<"/.;"; command<<"cp gams_files/taskset.put results/"<<atoi(argv[5])<<"/."; system(command.str().c_str()); command.str(""); task_num=task_num+1; } ft.clear(); } comp_util=comp_util+0.001; } /* exit(1); // generate_taskset_multi(&ft, 100, 8,2.5, power); //read_taskset_multi(&ft, "gams_folder/taskset.put"); float cutil=0; float tutil=0; for(unsigned int i=0;i<ft.size();i++) { cout<<"task "<<i<<" computation time "<<ft[i].computation_time<<" period " <<ft[i].period<<" power "<<ft[i].power<<" comp util "<<ft[i].computation_time/ft[i].period <<" thermal util "<<ft[i].computation_time*ft[i].power/(ft[i].period*beta*corrected_threshold)<<endl; cutil=cutil+ft[i].computation_time/ft[i].period; tutil=tutil+ft[i].computation_time*ft[i].power/(ft[i].period*beta*corrected_threshold); } cout<<" computation utilization "<<cutil<<" thermal utilization "<<tutil<<endl; int int_size=gams_include(&ft, matrix); populate_beta(); for(unsigned int i=0;i<CORE;i++) { for(unsigned int j=0;j<CORE;j++) { cout<<beta_multi[i][j]<<"\t"; } cout<<endl; } system("cd gams_files; ~rehan/gams/gams task_assign.gms");// //system("cd gams_files; ~rehan/gams/gams instance_assign.gms");// //vector<trace>ttrace; // read_ttrace("hotspot_files/thermal_profile", &ttrace); intervals.clear(); vector<mprofile>prof; generate_intervals_multi(&intervals,"gams_files/taskassign.put", &ft); vector<long_schedule>multi_sch; ltasks.clear(); w2fq_task_convert(<asks, &ft); multi_schedule(&multi_sch,&intervals, <asks); long hyperperiod=compute_lcm(<asks); float avg_power[CORE]; generate_power_trace(&multi_sch, "power_profile", hyperperiod, avg_power); generate_power_profile(&prof,&multi_sch, hyperperiod); cout<<"power profile length "<<prof.size()<<endl; double average_power; for(unsigned int i=0;i<ltasks.size();i++) { average_power=average_power+(((double)ltasks[i].computation_time)/((double)ltasks[i].period))*ltasks[i].power; } //compute_profile_multi(&multi_sch, <asks); //exit(1); // multi_simulate("power_profile", "multi.flp",0,average_power); exit(1); multi_sch.clear(); intervals.clear(); generate_intervals_multi(&intervals,"gams_files/instanceassign.put", &ft); multi_schedule(&multi_sch,&intervals, <asks); generate_power_trace(&multi_sch, "power_profile", hyperperiod, avg_power); //multi_simulate("power_profile", "multi.flp",1); // exit(1); system(command.str().c_str()); for(unsigned int i=0;i<intervals.size();i++) { cout<<" start "<<intervals[i].start<<" end "<<intervals[i].end<<endl; for(unsigned int k=0;k<CORE;k++) { cout<<" core"<<k<<": "; int total=0; float average_power=0; for(unsigned int j=0;j<ft.size();j++) { cout<<intervals[i].computations[j][k]<<" "; total=total+intervals[i].computations[j][k]; average_power=average_power+((float)intervals[i].computations[j][k])*ft[j].power/((float)(intervals[i].end-intervals[i].start)); } assert(total<=(intervals[i].end-intervals[i].start)); cout<<" total "<<total<<" average power "<<average_power<< endl; } } cout<<endl<<endl; for(unsigned int i=0;i<multi_sch.size();i++) { // cout<<"task "<<multi_sch[i].task_id<<" start "<<multi_sch[i].start<<" end "<<multi_sch[i].end<<" core "<<multi_sch[i].core<<endl; } //avg_power=(float*)malloc(sizeof(float)*CORE); cout<<" printing average power"<<endl; for(unsigned int i=0;i<CORE;i++) { cout<<"core"<<i<<" average power "<<avg_power[i]<<endl; } total_comps(&multi_sch,<asks,&intervals); // exit(1); // void w2fq_schedule(vector<long_schedule>*sch, vector<long_task>*tasks, vector<interval>*intervals, int core) /* while(computation_util<=1.0) { thermal_util=0.99; while(thermal_util<=1.0) { generate_taskset(&ft, 1000, computation_util, thermal_util); w2fq_task_convert(<asks, &ft); w2fq_schedule(&lschedule, <asks); edf_schedule(&ft,&fedf); w2fq_schedule_convert(&wsch, &lschedule); //cout<<" printing float schedule "<<endl; compute_profile(&wsch, &ft, 1); compute_profile(&fedf, &ft, 2); ft.clear(); ltasks.clear(); lschedule.clear(); fedf.clear(); wsch.clear(); thermal_util=thermal_util+0.001; } computation_util=computation_util+0.01; } */ /* // t_util=optimize_maxfirst(&h_speed,&tasks,0.75,1.2); timespec start_time,end_time; clock_gettime(1,&start_time); t_util=optimize_maxmin(&h_speed,&tasks,MIN_SPEED,MAX_SPEED); clock_gettime(1,&end_time); scale(&scaled_max_first,&tasks,&h_speed); edf_schedule(&scaled_max_first,&edf_max_first); thermal_optimal=4; compute_profile(&edf_max_first, &scaled_max_first,t_util); float max_first_time=time_diff(&start_time,&end_time); slacks.clear(); opt.clear(); opt_exact.clear(); edl.clear(); populate_slacks(&slacks, &edf_max_first); edl_schedule(&edl, &edf_max_first, &scaled_max_first, &slacks); consolidate_schedule(&edl, &scaled_max_first); clock_gettime(1,&start_time); //opt_schedule(&opt, &scaled_max_first, &edl); clock_gettime(1,&end_time); // opt_schedule_exact(&opt_exact, &scaled_max_first); // cout<<" schedule size "<<opt_exact.size()<<endl; // run_schedule(&opt,&scaled_max_first); // cout<<"TIME to find the optimal schedule "<<time_diff(&start_time,&end_time)<<"ms"<< " Maxfirst time" << max_first_time<<" Hyperperiod "<<tasksets[0].hyperperiod<<" tasks "<< tasks.size()<<endl; float max_speeds[tasks.size()]; for(unsigned int i=0;i<tasks.size();i++) { max_speeds[i]=((float)tasks[i].computation_time)/((float)scaled_max_first[i].computation_time); } vector<schedule>o_sch2; //run_dynamic(&scaled_max_first,max_speeds); vector<instance>dyn_inst; dynamic_instances(&scaled_max_first,max_speeds ,&dyn_inst); vector<instance>dyn_inst2; for(unsigned int i=0;i<dyn_inst.size();i++) { dyn_inst2.push_back(dyn_inst[i]); } double tutil=0; scheduler(&o_sch,&scaled_max_first,&dyn_inst,max_speeds,sched_interval); compute_profile_dynamic(&o_sch, &tasks,tutil,""); scheduler2(&o_sch2,&scaled_max_first,&dyn_inst2, max_speeds, sched_interval); compute_profile_dynamic(&o_sch2, &tasks,tutil,"window"); /* for(unsigned int i=0;i<o_sch2.size();i++) { cout<<"task "<<o_sch2[i].task_id<<" start "<<o_sch2[i].start<<" end "<<o_sch2[i].end<<" speed "<<o_sch2[i].speed<<endl; } */ #endif #if(STATIC_ENABLE) t_util=optimize_static(&s_speed,&tasks,MIN_SPEED,MAX_SPEED); scale(&scaled_static,&tasks,&s_speed); edf_schedule(&scaled_static,&edf_static); thermal_optimal=5; compute_profile(&edf_static, &scaled_static,t_util); #endif #if(MATLAB_ENABLE) t_util=optimize_matlab(&m_speed,&tasks,MIN_SPEED,MAX_SPEED); scale(&scaled_matlab,&tasks,&m_speed); edf_schedule(&scaled_matlab,&edf_matlab); thermal_optimal=6; compute_profile(&edf_matlab, &scaled_matlab,t_util); #endif #if(NOCONS_ENABLE) speed_scale(&scaled_tasks,&speeds,&tasks,1.0); edf_schedule(&scaled_tasks,&edf2); thermal_optimal=7; compute_profile(&edf2,&scaled_tasks,t_util); #endif #if(SPEED_DEBUG) for(int i=0;i<tasks.size();i++) { cout<<"matlab: "<<m_speed[i]<<" max first:"<<h_speed[i]<<" static speed:<<"<<s_speed[i]<<" nocons speed:"<< speeds[i]<<endl; } #endif #if(ENABLE_PRINTS) cout<<"max first taskset"<<endl; for(int i=0;i<scaled_max_first.size();i++) { cout<<"task "<<i<<" computation time:"<<scaled_max_first[i].computation_time<<" period:"<<scaled_max_first[i].period<<" power:"<<scaled_max_first[i].power<<endl; } cout<<"static speed taskset"<<endl; for(int i=0;i<scaled_max_first.size();i++) { cout<<"task "<<i<<" computation time:"<<scaled_static[i].computation_time<<" period:"<<scaled_static[i].period<<" power:"<<scaled_static[i].power<<endl; } #endif #if(ENABLE_PRINTS) for(unsigned int i=0;i<speeds.size();i++) { cout<<"speed for task: "<<i<<"|"<<speeds[i]<<endl; } #endif for (unsigned int i = 0; i < tasks.size(); i++) { // tasks[i].stat_stream->clear(); // tasks[i].stat_stream->close(); // util1=util1+(float)tasks[i].computation_time/(float)tasks[i].period; // util2=util2+(float)scaled_tasks[i].computation_time/(float)scaled_tasks[i].period; // util3=util3+(float)discrete_scaled[i].computation_time/(float)discrete_scaled[i].period; } #if(ENABLE_PRINTS) // cout<<"util "<<util1<<"|"<<util2<<"|"<<util3<<endl; // cout<<"globally optimal power"<<g_power<<endl; //cout<<"computed thermally optimal schedule"<<endl; #endif tasks.clear(); edf.clear(); scaled_tasks.clear(); speeds.clear(); edf2.clear(); discrete_scaled.clear(); edf3.clear(); possible_speeds.clear(); tasksets.clear(); opt.clear(); possible_speeds.clear(); slacks.clear(); h_speed.clear(); s_speed.clear(); m_speed.clear(); i_speed.clear(); i_speed_temp.clear(); scaled_max_first.clear(); scaled_static.clear(); scaled_matlab.clear(); edf_max_first.clear(); edf_static.clear(); edf_matlab.clear(); edl2.clear(); edl.clear(); i_schedule.clear(); o_sch.clear(); } #if(MATLAB_ENABLE) engClose(ep); #endif }
// Closes the MATLAB engine IGL_INLINE void igl::mlclose(Engine** mlengine) { engClose(*mlengine); *mlengine = 0; }
int PASCAL WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { Engine *ep; mxArray *T = NULL, *a = NULL, *d = NULL; char buffer[BUFSIZE+1]; double *Dreal, *Dimag; double time[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; /* * Start the MATLAB engine */ if (!(ep = engOpen(NULL))) { MessageBox ((HWND)NULL, (LPSTR)"Can't start MATLAB engine", (LPSTR) "Engwindemo.c", MB_OK); exit(-1); } /* * PART I * * For the first half of this demonstration, we will send data * to MATLAB, analyze the data, and plot the result. */ /* * Create a variable from our data */ T = mxCreateDoubleMatrix(1, 10, mxREAL); memcpy((char *) mxGetPr(T), (char *) time, 10*sizeof(double)); /* * Place the variable T into the MATLAB workspace */ engPutVariable(ep, "T", T); /* * Evaluate a function of time, distance = (1/2)g.*t.^2 * (g is the acceleration due to gravity) */ engEvalString(ep, "D = .5.*(-9.8).*T.^2;"); /* * Plot the result */ engEvalString(ep, "plot(T,D);"); engEvalString(ep, "title('Position vs. Time for a falling object');"); engEvalString(ep, "xlabel('Time (seconds)');"); engEvalString(ep, "ylabel('Position (meters)');"); /* * PART II * * For the second half of this demonstration, we will create another mxArray * put it into MATLAB and calculate its eigen values * */ a = mxCreateDoubleMatrix(3, 2, mxREAL); memcpy((char *) mxGetPr(a), (char *) Areal, 6*sizeof(double)); engPutVariable(ep, "A", a); /* * Calculate the eigen value */ engEvalString(ep, "d = eig(A*A')"); /* * Use engOutputBuffer to capture MATLAB output. Ensure first that * the buffer is always NULL terminated. */ buffer[BUFSIZE] = '\0'; engOutputBuffer(ep, buffer, BUFSIZE); /* * the evaluate string returns the result into the * output buffer. */ engEvalString(ep, "whos"); MessageBox ((HWND)NULL, (LPSTR)buffer, (LPSTR) "MATLAB - whos", MB_OK); /* * Get the eigen value mxArray */ d = engGetVariable(ep, "d"); engClose(ep); if (d == NULL) { MessageBox ((HWND)NULL, (LPSTR)"Get Array Failed", (LPSTR)"Engwindemo.c", MB_OK); } else { Dreal = mxGetPr(d); Dimag = mxGetPi(d); if (Dimag) sprintf(buffer,"Eigenval 2: %g+%gi",Dreal[1],Dimag[1]); else sprintf(buffer,"Eigenval 2: %g",Dreal[1]); MessageBox ((HWND)NULL, (LPSTR)buffer, (LPSTR)"Engwindemo.c", MB_OK); mxDestroyArray(d); } /* * We're done! Free memory, close MATLAB engine and exit. */ mxDestroyArray(T); mxDestroyArray(a); return(0); }
int main() { //SPECIFY PARMETERS, SEE CONFIG.H FILE FOR ENUM OPTIONS Configurations config; //Algorithm for solving for h config.algorithm_solve_h = NEWTON_BRUTE_FORCE; //Total time in years config.total_time = 20; // Initial time step in seconds config.initial_time_step = 30000;//12592000; // Injection stop config.injection_time = 100; // Pressure update interval in years config.pressure_update_injection = 2; config.pressure_update_migration = 5; // Permeability type config.perm_type = PERM_CONSTANT; // Name of formation config.formation_name = UTSIRA; // Parameter beta for the Corey permeability function config.beta = 0.4; ////////////////////////////////////////////////////////////////////////// if (config.formation_name == UTSIRA){ config.formation = "utsira"; config.formation_dir = "Utsira"; } else if(config.formation_name == JOHANSEN){ config.formation = "johansen"; config.formation_dir = "Johansen"; } else { printf("ERROR: No data for this formation"); } //Initialize some variables int nx, ny, nz; float dt, dz; float t, tf; int year = 60*60*24*365; // Device properties cudaSetDevice(0); int device; cudaGetDevice(&device); cudaDeviceProp p; cudaGetDeviceProperties(&p, device); printf("Device name: %s\n", p.name); // Set directory path of output and input files size_t buff_size= 100; char buffer[buff_size]; const char* path; readlink("/proc/self/exe", buffer, buff_size); printf("PATH %s", buffer); char* output_dir_path = "FullyIntegratedVESimulatorMATLAB/SimulationData/ResultData/"; char* input_dir_path = "FullyIntegratedVESimulatorMATLAB/SimulationData/FormationData/"; std::cout << "Trying to open " << input_dir_path << std::endl; std::cout << "Output will end up in " << output_dir_path << std::endl; // Filename strings char dir_input[300]; char filename_input[300]; char dir_output[300]; strcpy(dir_input, input_dir_path); strcat(dir_input, config.formation_dir); strcat(dir_input, "/"); strcpy(dir_output, output_dir_path); strcat(dir_output, config.formation_dir); strcat(dir_output, "/"); strcpy(filename_input, dir_input); strcat (filename_input, "dimensions.mat"); // Output txt files with results FILE* matlab_file_h; FILE* matlab_file_coarse_satu; FILE* matlab_file_volume; // Create output files for coarse saturation, interface height and volume // Files are stored in the directory createOutputFiles(matlab_file_h, matlab_file_coarse_satu, matlab_file_volume, dir_output); readDimensionsFromMATLABFile(filename_input, nx, ny, nz); InitialConditions IC(nx, ny, 5); printf("nx: %i, ny: %i nz: %i dt: %.10f", nx, ny, nz, dt); // Cpu pointers to store formation data from MATLAB CpuPtr_2D H(nx, ny, 0, true); CpuPtr_2D top_surface(nx, ny, 0, true); CpuPtr_2D h(nx, ny, 0, true); CpuPtr_2D normal_z(nx, ny, 0, true); CpuPtr_3D perm3D(nx, ny, nz + 1, 0, true); CpuPtr_3D poro3D(nx, ny, nz + 1, 0, true); CpuPtr_2D pv(nx, ny, 0, true); CpuPtr_2D flux_north(nx, ny, IC.border, true); CpuPtr_2D flux_east(nx, ny, IC.border, true); CpuPtr_2D source(nx, ny, 0, true); CpuPtr_2D grav_north(nx, ny, 0, true); CpuPtr_2D grav_east(nx, ny, 0, true); CpuPtr_2D K_face_north(nx, ny, 0, true); CpuPtr_2D K_face_east(nx, ny, 0, true); CpuPtr_2D active_east(nx, ny, 0, true); CpuPtr_2D active_north(nx, ny, 0, true); CpuPtr_2D volume(nx, ny, 0,true); strcpy(filename_input, dir_input); strcat (filename_input, "data.mat"); readFormationDataFromMATLABFile(filename_input, H.getPtr(), top_surface.getPtr(), h.getPtr(), normal_z.getPtr(), perm3D.getPtr(), poro3D.getPtr(), pv.getPtr(), flux_north.getPtr(), flux_east.getPtr(), grav_north.getPtr(), grav_east.getPtr(), K_face_north.getPtr(), K_face_east.getPtr(), dz); strcpy(filename_input, dir_input); strcat (filename_input, "active_cells.mat"); readActiveCellsFromMATLABFile(filename_input, active_east.getPtr(), active_north.getPtr()); //readDtTableFromMATLABFile(filename, dt_table, size_dt_table); Engine *ep; if (!(ep = engOpen(""))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } startMatlabEngine(ep, config.formation_dir); // Create double precision array for the data exchange between the GPU program and the MATLAB program mxArray *h_matrix = NULL, *flux_east_matrix = NULL, *flux_north_matrix=NULL; mxArray *source_matrix = NULL, *open_well = NULL; open_well = mxCreateLogicalScalar(true); engPutVariable(ep, "open_well", open_well); double * h_matlab_matrix; h_matlab_matrix = new double[nx*ny]; h_matrix = mxCreateDoubleMatrix(nx, ny, mxREAL); flux_east_matrix = mxCreateDoubleMatrix(nx+2*IC.border,ny+2*IC.border,mxREAL); flux_north_matrix = mxCreateDoubleMatrix(nx+2*IC.border,ny+2*IC.border,mxREAL); source_matrix = mxCreateDoubleMatrix(nx, ny, mxREAL); // Cpu Pointer to store the results CpuPtr_2D zeros(nx, ny, 0, true); //Initial Conditions IC.dz = dz; IC.createnIntervalsTable(H); IC.createScalingParameterTable(H, config.beta); IC.createInitialCoarseSatu(H, h); IC.computeAllGridBlocks(); IC.createDtVec(); // Create mask for sparse grid on GPU std::vector<int> active_block_indexes; std::vector<int> active_block_indexes_flux; int n_active_blocks = 0; int n_active_blocks_flux = 0; createGridMask(H, IC.grid, IC.block, nx, ny, active_block_indexes, n_active_blocks); createGridMaskFlux(H, IC.grid_flux, IC.block_flux, nx, ny, active_block_indexes_flux, n_active_blocks_flux); // Print grid mask properties printf("\n nBlocks: %i nActiveBlocks: %i fraction: %.5f\n", IC.grid.x * IC.grid.y, n_active_blocks, (float) n_active_blocks / (IC.grid.x * IC.grid.y)); printf("nBlocks: %i nActiveBlocks: %i fraction: %.5f\n", IC.grid_flux.x * IC.grid_flux.y, n_active_blocks_flux, (float) n_active_blocks_flux / (IC.grid_flux.x * IC.grid_flux.y)); printf("dz: %.3f\n", IC.dz); dim3 new_sparse_grid(n_active_blocks, 1, 1); dim3 new_sparse_grid_flux(n_active_blocks_flux, 1, 1); CommonArgs common_args; CoarseMobIntegrationKernelArgs coarse_mob_int_args; CoarsePermIntegrationKernelArgs coarse_perm_int_args; FluxKernelArgs flux_kernel_args; TimeIntegrationKernelArgs time_int_kernel_args; TimestepReductionKernelArgs time_red_kernel_args; SolveForhProblemCellsKernelArgs solve_problem_cells_args; printf("Cuda error 0.5: %s\n", cudaGetErrorString(cudaGetLastError())); initAllocate(&common_args, &coarse_perm_int_args, &coarse_mob_int_args, &flux_kernel_args, &time_int_kernel_args, &time_red_kernel_args, &solve_problem_cells_args); h.convertToDoublePointer(h_matlab_matrix); memcpy((void *)mxGetPr(h_matrix), (void *)h_matlab_matrix, sizeof(double)*nx*ny); engPutVariable(ep, "h_matrix", h_matrix); printf("Cuda error 1: %s\n", cudaGetErrorString(cudaGetLastError())); // Allocate and set data on the GPU GpuPtr_3D perm3D_device(nx, ny, nz + 1, 0, perm3D.getPtr()); GpuPtr_2D Lambda_c_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D Lambda_b_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D dLambda_c_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D dLambda_b_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D scaling_parameter_C_device(nx, ny, 0, IC.scaling_parameter.getPtr()); GpuPtr_2D K_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D H_device(nx, ny, 0, H.getPtr()); GpuPtr_2D h_device(nx, ny, 0, h.getPtr()); GpuPtr_2D top_surface_device(nx, ny, 0, top_surface.getPtr()); GpuPtr_2D z_diff_east_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D z_diff_north_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D nInterval_device(nx, ny, 0, IC.nIntervals.getPtr()); GpuPtr_2D U_x_device(nx, ny, IC.border, flux_east.getPtr()); GpuPtr_2D U_y_device(nx, ny, IC.border, flux_north.getPtr()); GpuPtr_2D source_device(nx, ny, 0, source.getPtr()); GpuPtr_2D K_face_east_device(nx, ny, 0, K_face_east.getPtr()); GpuPtr_2D K_face_north_device(nx, ny, 0, K_face_north.getPtr()); GpuPtr_2D grav_east_device(nx, ny, 0, grav_east.getPtr()); GpuPtr_2D grav_north_device(nx, ny, 0, grav_north.getPtr()); GpuPtr_2D normal_z_device(nx, ny, 0, normal_z.getPtr()); GpuPtr_2D R_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D pv_device(nx, ny, 0, pv.getPtr()); GpuPtr_2D output_test_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D active_east_device(nx, ny, 0, active_east.getPtr()); GpuPtr_2D active_north_device(nx, ny, 0, active_north.getPtr()); GpuPtr_2D vol_old_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D vol_new_device(nx, ny, 0, zeros.getPtr()); GpuPtr_2D coarse_satu_device(nx, ny, 0, IC.initial_coarse_satu_c.getPtr()); GpuPtr_1D global_dt_device(3, IC.global_time_data); GpuPtr_1D dt_vector_device(IC.nElements, IC.dt_vector); GpuPtrInt_1D active_block_indexes_device(n_active_blocks, &active_block_indexes[0]); GpuPtrInt_1D active_block_indexes_flux_device(n_active_blocks_flux, &active_block_indexes_flux[0]); cudaCheckError(); setCommonArgs(&common_args, IC.p_ci, IC.delta_rho, IC.g, IC.mu_c, IC.mu_b, IC.s_c_res, IC.s_b_res, IC.lambda_end_point_c, IC.lambda_end_point_b, active_east_device.getRawPtr(), active_north_device.getRawPtr(), H_device.getRawPtr(), pv_device.getRawPtr(), nx, ny, IC.border); setupGPU(&common_args); setCoarsePermIntegrationKernelArgs(&coarse_perm_int_args, K_device.getRawPtr(), perm3D_device.getRawPtr(), nInterval_device.getRawPtr(), IC.dz); callCoarsePermIntegrationKernel(IC.grid, IC.block, &coarse_perm_int_args); setCoarseMobIntegrationKernelArgs(&coarse_mob_int_args, Lambda_c_device.getRawPtr(), Lambda_b_device.getRawPtr(), dLambda_c_device.getRawPtr(), dLambda_b_device.getRawPtr(), h_device.getRawPtr(), perm3D_device.getRawPtr(), K_device.getRawPtr(), nInterval_device.getRawPtr(), scaling_parameter_C_device.getRawPtr(), active_block_indexes_device.getRawPtr(), IC.p_ci, IC.dz, config.perm_type); setFluxKernelArgs(&flux_kernel_args, Lambda_c_device.getRawPtr(),Lambda_b_device.getRawPtr(), dLambda_c_device.getRawPtr(), dLambda_b_device.getRawPtr(), U_x_device.getRawPtr(), U_y_device.getRawPtr(), source_device.getRawPtr(), h_device.getRawPtr(),top_surface_device.getRawPtr(), normal_z_device.getRawPtr(), K_face_east_device.getRawPtr(), K_face_north_device.getRawPtr(), grav_east_device.getRawPtr(), grav_north_device.getRawPtr(), R_device.getRawPtr(), dt_vector_device.getRawPtr(), active_block_indexes_flux_device.getRawPtr(), output_test_device.getRawPtr()); setTimestepReductionKernelArgs(&time_red_kernel_args, TIME_THREADS, IC.nElements, global_dt_device.getRawPtr(), IC.cfl_scale, dt_vector_device.getRawPtr()); //CUDPP CUDPPHandle plan; unsigned int* d_isValid; int* d_in; int* d_out; size_t* d_numValid = NULL; size_t numValidElements; unsigned int numElements=nx*ny; cudaCheckError(); cudaMalloc((void**) &d_isValid, sizeof(unsigned int)*numElements); cudaMalloc((void**) &d_in, sizeof(int)*numElements); cudaMalloc((void**) &d_out, sizeof(int)*numElements); cudaMalloc((void**) &d_numValid, sizeof(size_t)); cudaCheckError(); CUDPPHandle theCudpp; cudppCreate(&theCudpp); setUpCUDPP(theCudpp, plan, nx, ny, d_isValid, d_in, d_out, numElements); printf("\nCudaMemcpy error: %s", cudaGetErrorString(cudaGetLastError())); cudaCheckError(); setTimeIntegrationKernelArgs(&time_int_kernel_args, global_dt_device.getRawPtr(), IC.integral_res,pv_device.getRawPtr(), h_device.getRawPtr(), R_device.getRawPtr(),coarse_satu_device.getRawPtr(), scaling_parameter_C_device.getRawPtr(), vol_old_device.getRawPtr(), vol_new_device.getRawPtr(), d_isValid, d_in); cudaCheckError(); setSolveForhProblemCellsKernelArgs(&solve_problem_cells_args, h_device.getRawPtr(), coarse_satu_device.getRawPtr(), scaling_parameter_C_device.getRawPtr(), d_out, IC.integral_res, d_numValid); cudaCheckError(); //Compute start volume callCoarseMobIntegrationKernel(new_sparse_grid, IC.block, IC.grid.x, &coarse_mob_int_args); callFluxKernel(new_sparse_grid_flux, IC.block_flux, IC.grid_flux.x, &flux_kernel_args); callTimeIntegration(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args); cudaCheckError(); vol_old_device.download(volume.getPtr(), 0, 0, nx, ny); float total_volume_old = computeTotalVolume(volume, nx, ny); t = 0; double t2 = 0; tf = IC.global_time_data[2]; int iter_outer_loop = 0; int iter_inner_loop = 0; int iter_total = 0; int iter_total_lim = 5000; float time = 0; float injected = 0; int table_index = 1; double time_start = getWallTime(); double time_start_iter; double total_time_gpu = 0; while (time < config.total_time && iter_total < iter_total_lim){ t = 0; iter_inner_loop = 0; h_device.download(h.getPtr(), 0, 0, nx, ny); h.convertToDoublePointer(h_matlab_matrix); memcpy((void *)mxGetPr(h_matrix), (void *)h_matlab_matrix, sizeof(double)*nx*ny); engPutVariable(ep, "h_matrix", h_matrix); if (time >= config.injection_time){ open_well = mxCreateLogicalScalar(false); engPutVariable(ep, "open_well", open_well); IC.global_time_data[2] = 31536000*config.pressure_update_migration; tf = IC.global_time_data[2]; cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice); } // MATLAB call engEvalString(ep, "[source, east_flux, north_flux] = pressureFunctionToRunfromCpp(h_matrix, variables, open_well);"); // Get variables from MATLABs pressure solver flux_east_matrix = engGetVariable(ep, "east_flux"); flux_north_matrix = engGetVariable(ep, "north_flux"); source_matrix = engGetVariable(ep, "source"); memcpy((void *)flux_east.getPtr(), (void *)mxGetPr(flux_east_matrix), sizeof(float)*(nx+2*IC.border)*(ny+2*IC.border)); memcpy((void *)flux_north.getPtr(), (void *)mxGetPr(flux_north_matrix), sizeof(float)*(nx+2*IC.border)*(ny+2*IC.border)); memcpy((void *)source.getPtr(), (void *)mxGetPr(source_matrix), sizeof(float)*nx*ny); source_device.upload(source.getPtr(), 0, 0, nx, ny); U_x_device.upload(flux_east.getPtr(), 0, 0, nx+2*IC.border, ny+2*IC.border); U_y_device.upload(flux_north.getPtr(), 0, 0,nx+2*IC.border, ny+2*IC.border); time_start_iter = getWallTime(); while (t < tf && iter_total < iter_total_lim){ cudaCheckError(); callCoarseMobIntegrationKernel(new_sparse_grid, IC.block, IC.grid.x, &coarse_mob_int_args); cudaCheckError(); callFluxKernel(new_sparse_grid_flux, IC.block_flux, IC.grid_flux.x, &flux_kernel_args); cudaCheckError(); callTimestepReductionKernel(TIME_THREADS, &time_red_kernel_args); cudaCheckError(); // Set the initial time step if (iter_total < 1 && iter_inner_loop == 0){ IC.global_time_data[0] = config.initial_time_step; IC.global_time_data[1] += config.initial_time_step; cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice); } //For precomputed time step insertion /* IC.global_time_data[0] = (float)dt_table[table_index]; IC.global_time_data[1] += (float)dt_table[table_index]; cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice); */ cudaCheckError(); if (config.algorithm_solve_h == BRUTE_FORCE) callTimeIntegration(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args); else if (config.algorithm_solve_h == NEWTON_BRUTE_FORCE){ callTimeIntegrationNewton(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args); cudppCompact(plan, d_out, d_numValid, d_in, d_isValid, numElements); callSolveForhProblemCells(IC.grid_pc, IC.block_pc, &solve_problem_cells_args); } else if (config.algorithm_solve_h == NEWTON_BISECTION){ callTimeIntegrationNewton(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args); cudppCompact(plan, d_out, d_numValid, d_in, d_isValid, numElements); callSolveForhProblemCellsBisection(IC.grid_pc, IC.block_pc, &solve_problem_cells_args); } cudaCheckError(); cudaMemcpy(IC.global_time_data, global_dt_device.getRawPtr(), sizeof(float)*3, cudaMemcpyDeviceToHost); cudaCheckError(); // Keep track of injected volume, insert injection coordinate and rate injected += IC.global_time_data[0]*source(50,50); t += IC.global_time_data[0]; //table_index++; iter_inner_loop++; iter_total++; } total_time_gpu += getWallTime() - time_start_iter; printf("Total time in years: %.3f time in this round %.3f timestep %.3f GPU time %.3f time per iter %.8f \n", time, t, IC.global_time_data[0], getWallTime() - time_start_iter, (getWallTime() - time_start_iter)/iter_inner_loop); time += t/(year); iter_outer_loop++; } printf("Elapsed time program: %.5f gpu part: %.5f", getWallTime() - time_start, total_time_gpu); engClose(ep); h_device.download(zeros.getPtr(), 0, 0, nx, ny); zeros.printToFile(matlab_file_h); coarse_satu_device.download(zeros.getPtr(), 0, 0, nx, ny); // Divide by the formation thickness H to get the actual coarse satu for (int i = 0; i < nx; i++){ for (int j = 0; j < ny; j++){ if (H(i,j) != 0) zeros(i,j) = zeros(i,j)/H(i,j); } } zeros.printToFile(matlab_file_coarse_satu); vol_new_device.download(zeros.getPtr(), 0, 0, nx, ny); zeros.printToFile(matlab_file_volume); float total_volume_new = computeTotalVolume(zeros, nx, ny); printf("total volume new %.2f total volume old %.2f injected %.1f injected fraction %.10f", total_volume_new, total_volume_old, injected, (total_volume_new-injected)/(injected)); printf("volume fraction %.10f",(total_volume_new-total_volume_old)/(total_volume_old)); printf("\nCudaMemcpy error: %s", cudaGetErrorString(cudaGetLastError())); printf("FINITO precise time %.6f iter_total %i", time, iter_total); }
void DrawPic::drawPic(vector<double> edgeOldSfr,vector<double> edgeNewSfr,vector<double> allOldSfr,vector<double> allNewSfr) { double edgeOldSfrArray[9]; double edgeNewSfrArray[9]; double allOldSfrArray[9]; double allNewSfrArray[9]; vector<double>::iterator iter = edgeOldSfr.begin(); int i=0; while(iter!=edgeOldSfr.end()) { edgeOldSfrArray[i] = *iter++; i++; } iter = edgeNewSfr.begin(); i=0; while(iter!=edgeNewSfr.end()) { edgeNewSfrArray[i] = *iter++; i++; } iter = allOldSfr.begin(); i=0; while(iter!=allOldSfr.end()) { allOldSfrArray[i] = *iter++; i++; } iter = allNewSfr.begin(); i=0; while(iter!=allNewSfr.end()) { allNewSfrArray[i] = *iter++; i++; } Engine* m_pEngine; mxArray *_edgey1 = NULL; mxArray *_edgey2 = NULL; mxArray *_ally1 = NULL; mxArray *_ally2 = NULL; m_pEngine = engOpen(NULL); if( m_pEngine == NULL ) { cout<<"error!"<<endl; exit(-1); } //double y1[9] = {0, 2.827/9 , 10.2687/9 , 15.465/9 , 19.3475/9 , 23.769/9 , 26.688/9 , 32.155/9 , 36.284/9}; //double y2[9] = {0, 3.292/9 , 8.2671/9 ,16.416/9 , 22.601/9 , 25.7154/9 , 29.183/9 , 34.855/9 , 40.9438/9}; engEvalString(m_pEngine, "x = 0:10:80;"); _edgey1 = mxCreateDoubleMatrix(1, 9, mxREAL); _edgey2 = mxCreateDoubleMatrix(1, 9, mxREAL); _ally1 = mxCreateDoubleMatrix(1, 9, mxREAL); _ally2 = mxCreateDoubleMatrix(1, 9, mxREAL); memcpy((void *)mxGetPr(_edgey1), (void *)edgeOldSfrArray, sizeof(edgeOldSfrArray)); memcpy((void *)mxGetPr(_edgey2), (void *)edgeNewSfrArray, sizeof(edgeNewSfrArray)); memcpy((void *)mxGetPr(_ally1), (void *)allOldSfrArray, sizeof(allOldSfrArray)); memcpy((void *)mxGetPr(_ally2), (void *)allNewSfrArray, sizeof(allNewSfrArray)); engPutVariable(m_pEngine, "edgeOldSfr", _edgey1); engPutVariable(m_pEngine, "edgeNewSfr", _edgey2); engPutVariable(m_pEngine, "allOldSfr", _ally1); engPutVariable(m_pEngine, "allNewSfr", _ally2); //engEvalString(m_pEngine,"y1 = [0 2.827/9 10.2687/9 15.465/9 19.3475/9 23.769/9 26.688/9 32.155/9 36.284/9]"); //engEvalString(m_pEngine,"y2 = [0 3.292/9 8.2671/9 16.416/9 22.601/9 25.7154/9 29.183/9 34.855/9 40.9438/9]"); engEvalString(m_pEngine,"subplot(2,1,1);"); engEvalString(m_pEngine, "plot(x,edgeOldSfr,x,edgeNewSfr,'o-.');"); engEvalString(m_pEngine, "xlabel('小区用户数(个)','FontSize',12);"); engEvalString(m_pEngine, "ylabel('小区边缘用户吞吐量(Mb/s)','FontSize',12);"); engEvalString(m_pEngine, "legend('固定SFR','D-SFR','FontSize',12,2);"); engEvalString(m_pEngine,"subplot(2,1,2);"); engEvalString(m_pEngine,"plot(x,allOldSfr,x,allNewSfr,'o-.');"); engEvalString(m_pEngine,"xlabel('小区用户数(个)','FontSize',12);"); engEvalString(m_pEngine, "ylabel('小区吞吐量(Mb/s)','FontSize',12);"); engEvalString(m_pEngine, "legend('固定SFR','D-SFR','FontSize',12,2);"); MessageBox(NULL,_T("已经得到固定软频率复用和动态软频率复用仿真结果"),_T("通知"),MB_OK); engClose(m_pEngine); }
void tomat::close() { engClose(ep); }
int main() { Engine *ep; mxArray *T = NULL, *result = NULL; char buffer[BUFSIZE+1]; double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; /* * Call engOpen with a NULL string. This starts a MATLAB process * on the current host using the command "matlab". */ if (!(ep = engOpen(""))) { fprintf(stderr, "\nCan't start MATLAB engine\n"); return EXIT_FAILURE; } /* * PART I * * For the first half of this demonstration, we will send data * to MATLAB, analyze the data, and plot the result. */ /* * Create a variable for our data */ T = mxCreateDoubleMatrix(1, 10, mxREAL); memcpy((void *)mxGetPr(T), (void *)time, sizeof(time)); /* * Place the variable T into the MATLAB workspace */ engPutVariable(ep, "T", T); /* * Evaluate a function of time, distance = (1/2)g.*t.^2 * (g is the acceleration due to gravity) */ engEvalString(ep, "D = .5.*(-9.8).*T.^2;"); /* * Plot the result */ engEvalString(ep, "plot(T,D);"); engEvalString(ep, "title('Position vs. Time for a falling object');"); engEvalString(ep, "xlabel('Time (seconds)');"); engEvalString(ep, "ylabel('Position (meters)');"); /* * use fgetc() to make sure that we pause long enough to be * able to see the plot */ printf("Hit return to continue\n\n"); fgetc(stdin); /* * We're done for Part I! Free memory, close MATLAB figure. */ printf("Done for Part I.\n"); mxDestroyArray(T); engEvalString(ep, "close;"); /* * PART II * * For the second half of this demonstration, we will request * a MATLAB string, which should define a variable X. MATLAB * will evaluate the string and create the variable. We * will then recover the variable, and determine its type. */ /* * Use engOutputBuffer to capture MATLAB output, so we can * echo it back. Ensure first that the buffer is always NULL * terminated. */ buffer[BUFSIZE] = '\0'; engOutputBuffer(ep, buffer, BUFSIZE); while (result == NULL) { char str[BUFSIZE+1]; /* * Get a string input from the user */ printf("Enter a MATLAB command to evaluate. This command should\n"); printf("create a variable X. This program will then determine\n"); printf("what kind of variable you created.\n"); printf("For example: X = 1:5\n"); printf(">> "); fgets(str, BUFSIZE, stdin); /* * Evaluate input with engEvalString */ engEvalString(ep, str); /* * Echo the output from the command. */ printf("%s", buffer); /* * Get result of computation */ printf("\nRetrieving X...\n"); if ((result = engGetVariable(ep,"X")) == NULL) printf("Oops! You didn't create a variable X.\n\n"); else { printf("X is class %s\t\n", mxGetClassName(result)); } } /* * We're done! Free memory, close MATLAB engine and exit. */ printf("Done!\n"); mxDestroyArray(result); engClose(ep); return EXIT_SUCCESS; }
MatlabPlotter::~MatlabPlotter() { engClose((Engine*)engine_); }
void agent_close() { engEvalString(ep, "close;"); engClose(ep); }
/* Function: main * * Description: Main function to extract frames from 2 video files and runs the * rest of the program using them. Takes at least 10 commandline arguments, * in the order: * <number of camera pairs> * <pair 1 camera 1 filename> * <pair 1 camera 1 frame number> * <pair 1 camera 2 filename> * <pair 1 camera 2 frame number> * <pair 1 view name> * <pair 1 camera coefficients filename> * ... * <TPS smoothing parameter> * <feature detector> * <output directory> * * Parameters: * argc: number of commandline arguments * argv: string array of commandline arguments * * Returns: 0 on success, 1 on error. */ int main (int argc, char *argv[]) { // check for minimum number of commandline arguments if (argc < 11) { printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n"); exit(1); } // get the number of camera pairs int numCameraPairs = atoi(argv[1]); if (numCameraPairs <= 0) { printf("Invalid number of camera pairs.\n"); exit(1); } // number of commandline arguments should be numCameraPairs*6 + 5 if (argc != numCameraPairs*6 + 5) { printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n"); exit(1); } // allocate memory to store information for camera pairs char **camera1Filenames = (char **)malloc(numCameraPairs * sizeof(char *)); int *camera1Frames = (int *)malloc(numCameraPairs * sizeof(int)); if (camera1Filenames == NULL || camera1Frames == NULL) { printf("Out of memory error.\n"); exit(1); } char **camera2Filenames = (char **)malloc(numCameraPairs * sizeof(char *)); int *camera2Frames = (int *)malloc(numCameraPairs * sizeof(int)); if (camera2Filenames == NULL || camera2Frames == NULL) { printf("Out of memory error.\n"); exit(1); } char **cameraNames = (char **)malloc(numCameraPairs * sizeof(char *)); if (cameraNames == NULL) { printf("Out of memory error.\n"); exit(1); } char **cameraCoefficientsFilenames = (char **)malloc(numCameraPairs * sizeof(char *)); if (cameraCoefficientsFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } int argIndex = 2; for (int i = 0; i < numCameraPairs; i++) { camera1Filenames[i] = argv[argIndex]; camera1Frames[i] = atoi(argv[argIndex+1]); camera2Filenames[i] = argv[argIndex+2]; camera2Frames[i] = atoi(argv[argIndex+3]); cameraNames[i] = argv[argIndex+4]; cameraCoefficientsFilenames[i] = argv[argIndex+5]; // make sure input video frames are valid if (camera1Frames[i] <= 0) { printf("Invalid frame number for pair %d camera 1.\n", i+1); exit(1); } if (camera2Frames[i] <= 0) { printf("Invalid frame number for pair %d camera 1.\n", i+1); exit(1); } // make sure input filenames are valid if (!fileExists(camera1Filenames[i])) { printf("Could not open pair %d camera 1 video file.\n", i+1); exit(1); } if (!fileExists(camera2Filenames[i])) { printf("Could not open pair %d camera 2 video file.\n", i+1); exit(1); } if (!fileExists(cameraCoefficientsFilenames[i])) { printf("Could not open pair %d camera coefficients file.\n", i+1); exit(1); } argIndex += 6; } double regularization = atof(argv[argIndex]); char *featureDetector = argv[argIndex+1]; char *outputDirectory = argv[argIndex+2]; // make sure input feature dectector is recognized if (strcasecmp(featureDetector, FAST_FEATURE_DETECTOR) && strcasecmp(featureDetector, GFTT_FEATURE_DETECTOR) && strcasecmp(featureDetector, SURF_FEATURE_DETECTOR) && strcasecmp(featureDetector, SIFT_FEATURE_DETECTOR) && strcasecmp(featureDetector, SPEEDSIFT_FEATURE_DETECTOR)) { printf("Feature Detector not recognized. Please select from the following:\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s\n", FAST_FEATURE_DETECTOR, GFTT_FEATURE_DETECTOR, SURF_FEATURE_DETECTOR, SIFT_FEATURE_DETECTOR, SPEEDSIFT_FEATURE_DETECTOR); exit(1); } // make sure regularization parameter for TPS is valid if (regularization <= 0.0 || regularization == HUGE_VAL) { printf("Invalid smoothing parameter value.\n"); exit(1); } // if output directory doesn't end with '/' char, append '/' to the string. // this is so we can later append a filename to the directory when we want // to write the file to that directory if (outputDirectory[strlen(outputDirectory)-1] != '/') { strcat(outputDirectory, "/"); } DIR *dir = opendir(outputDirectory); // if output directory does not exist, create it with correct permissions if (dir == NULL) { printf("Output directory does not exist.\n"); if (mkdir(outputDirectory, S_IRWXO | S_IRWXG | S_IRWXU)) { printf("Could not create output directory.\n"); exit(1); } else { printf("Created output directory.\n"); } } else { closedir(dir); } // string for the MATLAB commands char command[500]; Engine *matlabEngine; // open MATLAB engine if (!(matlabEngine = engOpen("\0"))) { printf("Can't start MATLAB engine\n"); exit(1); } // create MATLAB arrays to retrieve values from MATLAB workspace mxArray **c1ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c1ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c1ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); if (c1ImageData == NULL || c1ImageDimensions == NULL || c1ImagePaddedWidths == NULL) { printf("Out of memory error.\n"); exit(1); } mxArray **c2ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c2ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c2ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); if (c2ImageData == NULL || c2ImageDimensions == NULL || c2ImagePaddedWidths == NULL) { printf("Out of memory error.\n"); exit(1); } // create IplImage arrays for camera 1 and 2 images for all camera pairs IplImage **c1Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *)); IplImage **c2Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *)); if (c1Images == NULL || c2Images == NULL) { printf("Out of memory error.\n"); exit(1); } // for each camera pair, get the specified frames from cameras 1 and 2, using // MATLAB functions for (int i = 0; i < numCameraPairs; i++) { char video1Extension[6]; // get the video file extension for the first video file if (getVideoFileExtension(camera1Filenames[i], video1Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR) { printf("Video files must be of extension .mrf or .cine.\n"); exit(1); } // call appropriate MATLAB function depending on whether video file is .cine // or .mrf to extract the frame as a MATLAB image. If neither, error. if ((strcasecmp(video1Extension, ".cine") == 0) || (strcasecmp(video1Extension, ".cin") == 0)) { sprintf(command, "c1 = cineRead('%s', %d);", camera1Filenames[i], camera1Frames[i]); engEvalString(matlabEngine, command); } else if (strcasecmp(video1Extension, ".mrf") == 0) { sprintf(command, "c1 = mrfRead('%s', %d);", camera1Filenames[i], camera1Frames[i]); engEvalString(matlabEngine, command); } else { printf("Videos must be of extension .mrf or .cine.\n"); exit(1); } char video2Extension[6]; // get the video file extension for the second video file if (getVideoFileExtension(camera2Filenames[i], video2Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR) { printf("Video files must be of extension .mrf or .cine.\n"); exit(1); } // call appropriate MATLAB function depending on whether video file is .cine // or .mrf to extract the frame as a MATLAB image. If neither, error. if ((strcasecmp(video2Extension, ".cine") == 0) || (strcasecmp(video2Extension, ".cin") == 0)) { sprintf(command, "c2 = cineRead('%s', %d);", camera2Filenames[i], camera2Frames[i]); engEvalString(matlabEngine, command); } else if (strcasecmp(video2Extension, ".mrf") == 0) { sprintf(command, "c2 = mrfRead('%s', %d);", camera2Filenames[i], camera2Frames[i]); engEvalString(matlabEngine, command); } else { printf("Videos must be of extension .mrf or .cine.\n"); exit(1); } // call MATLAB function convert_image_matlab2cv_gs on MATLAB images to convert // them into a format that will be compatible with the IplImages of OpenCV sprintf(command, "[c1_img c1_dim c1_padded_width] = convert_image_matlab2cv_gs(c1);"); engEvalString(matlabEngine, command); sprintf(command, "[c2_img c2_dim c2_padded_width] = convert_image_matlab2cv_gs(c2);"); engEvalString(matlabEngine, command); // retrieve the image data, image dimensions, and image padded width variables // from MATLAB for both camera images c1ImageData[i] = engGetVariable(matlabEngine, "c1_img"); c1ImageDimensions[i] = engGetVariable(matlabEngine, "c1_dim"); c1ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c1_padded_width"); c2ImageData[i] = engGetVariable(matlabEngine, "c2_img"); c2ImageDimensions[i] = engGetVariable(matlabEngine, "c2_dim"); c2ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c2_padded_width"); if (c1ImageData[i] == NULL || c1ImageDimensions[i] == NULL || c1ImagePaddedWidths[i] == NULL) { printf("Could not retrieve all necessary information for pair %d camera 1 frame %d from MATLAB.\n", i+1, camera1Frames[i]); exit(1); } if (c2ImageData[i] == NULL || c2ImageDimensions[i] == NULL || c2ImagePaddedWidths[i] == NULL) { printf("Could not retrieve all necessary information for pair %d camera 2 frame %d from MATLAB.\n", i+1, camera2Frames[i]); exit(1); } int c1Status, c2Status; ImageInfo c1ImageInfo, c2ImageInfo; // extract the image information from the MATLAB variables in the form of // mxArrays, and store in ImageInfo structs c1Status = getInputImageInfo(&c1ImageInfo, c1ImageData[i], c1ImageDimensions[i], c1ImagePaddedWidths[i]); c2Status = getInputImageInfo(&c2ImageInfo, c2ImageData[i], c2ImageDimensions[i], c2ImagePaddedWidths[i]); if (c1Status == IMAGE_INFO_DATA_ERROR) { printf("Pair %d camera 1: Images must have two dimensions.\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_DATA_ERROR) { printf("Pair %d camera 2: Images must have two dimensions.\n", i+1); exit(1); } if (c1Status == IMAGE_INFO_DIMENSIONS_ERROR) { printf("Pair %d camera 1: Image dimension vectors must contain two elements: [width, height].\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_DIMENSIONS_ERROR) { printf("Pair %d camera 2: Image dimension vectors must contain two elements: [width, height].\n", i+1); exit(1); } if (c1Status == IMAGE_INFO_PADDED_WIDTH_ERROR) { printf("Pair %d camera 1: Padded image widths must be scalars.\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_PADDED_WIDTH_ERROR) { printf("Pair %d camera 2: Padded image widths must be scalars.\n", i+1); exit(1); } if (c1Status == IMAGE_DEPTH_ERROR) { printf("Pair %d camera 1: Images must be represented by 8 or 16-bit integers.\n", i+1); exit(1); } if (c2Status == IMAGE_DEPTH_ERROR) { printf("Pair %d camera 2: Images must be represented by 8 or 16-bit integers.\n", i+1); exit(1); } // create IplImages using values in ImageInfo structs c1Status = createIplImageFromImageInfo(&(c1Images[i]), c1ImageInfo); c2Status = createIplImageFromImageInfo(&(c2Images[i]), c2ImageInfo); if (c1Status == OUT_OF_MEMORY_ERROR || c2Status == OUT_OF_MEMORY_ERROR) { printf("Out of memory error.\n"); exit(1); } // flip the images over the y-axis to compensate for the differences in axial // labels between MATLAB and OpenCV (camera coefficients would not correctly // correspond to image otherwise) cvFlip(c1Images[i], NULL, 1); cvFlip(c2Images[i], NULL, 1); } char errorMessage[500]; int numContours; char **contourNames; CvPoint3D32f **features3D; char **validFeatureIndicator; int *numFeaturesInContours; char contoursFilename[MAX_FILENAME_LENGTH]; // for each camera pair, run features and triangulation for (int i = 0; i < numCameraPairs; i++) { // create the output 2D features filename as "frame<frame number>_features2D_<camera name>.txt" char features2DFilename[MAX_FILENAME_LENGTH]; sprintf(features2DFilename, "%sframe%d_features2D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); // create the output contours filename as "frame<frame number>_contours_<camera name>.txt" char tempContoursFilename[MAX_FILENAME_LENGTH]; sprintf(tempContoursFilename, "%sframe%d_contours_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); printf("Camera pair for %s view:\n", cameraNames[i]); // run the features program to extract matching 2D features from the 2 // images within user defined contour if (features(c1Images[i], c2Images[i], features2DFilename, tempContoursFilename, featureDetector, errorMessage)) { printf("Features: %s\n", errorMessage); exit(1); } // we only need to save the contour(s) for the first camera pair, as that // is the one we will use to create the meshes, and we only use the contours // with the same name(s) in subsequent camera pairs if (i == 0) { strcpy(contoursFilename, tempContoursFilename); // get the contour names of the contours selected in features function for // output file naming and contour matching in other camera pairs int status = readContourNamesFromInputFile(&numContours, &contourNames, contoursFilename); if (status == INPUT_FILE_OPEN_ERROR) { printf("Could not open contour vertices file.\n"); exit(1); } if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR) { printf("Contour vertices file has incorrect format.\n"); exit(1); } if (status == OUT_OF_MEMORY_ERROR) { printf("Out of memory error.\n"); exit(1); } // allocate memory for 3D features features3D = (CvPoint3D32f **)malloc(numContours * sizeof(CvPoint3D32f *)); validFeatureIndicator = (char **)malloc(numContours * sizeof(char *)); numFeaturesInContours = (int *)malloc(numContours * sizeof(int)); if (features3D == NULL || numFeaturesInContours == NULL || validFeatureIndicator == NULL) { printf("Out of memory error.\n"); exit(1); } for (int j = 0; j < numContours; j++) { features3D[j] = (CvPoint3D32f *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(CvPoint3D32f)); validFeatureIndicator[j] = (char *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(char)); if (features3D[j] == NULL || validFeatureIndicator[j] == NULL) { printf("Out of memory error.\n"); exit(1); } numFeaturesInContours[j] = 0; } } // create the output 3D features filename as "frame<frame number>_features3D_<camera name>.txt" char features3DFilename[MAX_FILENAME_LENGTH]; sprintf(features3DFilename, "%sframe%d_features3D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); // triangulate the matching 2D features between cameras to find the 3D coordinates // of the features, and remove invalid features if (triangulation(cameraCoefficientsFilenames[i], features2DFilename, features3DFilename, c1Images[i], errorMessage)) { printf("Triangulation: %s\n", errorMessage); exit(1); } // if features from triangulation lie within contours that have the same // names as those defined for the first camera pair, add them to the // 3D features array for mesh creation int status = read3DFeaturesFromFileForMatchingContours(features3DFilename, features3D, numFeaturesInContours, numContours, contourNames); if (status == INPUT_FILE_OPEN_ERROR) { printf("Could not open 3D features file.\n"); exit(1); } if (status == INVALID_NUM_CONTOURS_ERROR) { printf("At least 1 contour region required.\n"); exit(1); } if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR) { printf("3D features file has incorrect format.\n"); exit(1); } } // for each contour (defined for the first camera pair), perform RANSAC on // the cumulative 3D features from all camera pairs that lie within the contour for (int i = 0; i < numContours; i++) { memset(validFeatureIndicator[i], 1, numFeaturesInContours[i] * sizeof(char)); // perform RANSAC to remove points that lie too far off a best-fit surface if (ransac(features3D[i], validFeatureIndicator[i], numFeaturesInContours[i], errorMessage)) { printf("RANSAC: %s\n", errorMessage); exit(1); } int numValidFeatures = 0; for (int j = 0; j < numFeaturesInContours[i]; j++) { if (validFeatureIndicator[i][j]) { numValidFeatures++; } } printf("Total valid features after RANSAC for contour %s: %d\n", contourNames[i], numValidFeatures); } // create the output 3D features filename for all camera pairs as // "frame<frame number>_features3D.txt", and write the result of RANSAC to // the file char features3DFilename[MAX_FILENAME_LENGTH]; sprintf(features3DFilename, "%sframe%d_features3D.txt", outputDirectory, camera1Frames[0]); int status = write3DFeaturesToFile(features3D, validFeatureIndicator, numFeaturesInContours, contourNames, numContours, features3DFilename); if (status == OUTPUT_FILE_OPEN_ERROR) { sprintf(errorMessage, "Could not open output file."); return 1; } char **meshFilenames = (char **)malloc(numContours * sizeof(char *)); if (meshFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } // for each contour, create a different mesh output file for (int i = 0; i < numContours; i++) { meshFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (meshFilenames[i] == NULL) { printf("Out of memory error.\n"); exit(1); } // create the output mesh filename as "frame<frame number>_mesh_<contour name>_<camera name>.txt" sprintf(meshFilenames[i], "%sframe%d_mesh_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]); } // create the wing meshes from the triangulated 3D points and the user-selected // contours, and write each mesh to a different file for each contour if (mesh(features3DFilename, contoursFilename, cameraCoefficientsFilenames[0], meshFilenames, numContours, regularization, errorMessage)) { printf("Mesh: %s\n", errorMessage); exit(1); } // we only calculate the flow of a wing mesh if there is a mesh file with the // same contour name in the output directory for the previous video frame char **flowFilenames = (char **)malloc(numContours * sizeof(char *)); if (flowFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } for (int i = 0; i < numContours; i++) { flowFilenames[i] = NULL; } int numFilesInDirectory; char **filenamesInDirectory = (char **)malloc(MAX_FILES_IN_DIRECTORY * sizeof(char *)); if (filenamesInDirectory == NULL) { printf("Out of memory error.\n"); exit(1); } for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++) { filenamesInDirectory[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (filenamesInDirectory[i] == NULL) { printf("Out of memory error.\n"); exit(1); } } // get all files in the output directory getAllFilenamesInDirectory(outputDirectory, &numFilesInDirectory, filenamesInDirectory); // for each contour check if previous frame mesh file for same contour exists // in output directory for (int i = 0; i < numContours; i++) { // set substring indicating match to be "frame<previous frame number>_mesh_<contour name>.txt" char filenameToMatch[MAX_FILENAME_LENGTH]; sprintf(filenameToMatch, "frame%d_mesh_%s.txt", camera1Frames[0]-1, contourNames[i]); // try to find a filename from the output directory that contains the // substring indicating a match for a previous frame mesh for the same // contour int fileExists = getIndexOfMatchingString(filenamesInDirectory, numFilesInDirectory, filenameToMatch); // if filename was found, create a flow output file for current contour // and call flow to calculate the flow between previous contour mesh and // current contour mesh if (fileExists != -1) { flowFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (flowFilenames[i] == NULL) { printf("Out of memory error.\n"); exit(1); } // create the output flow filename as "frame<frame number>_flow_<contour name>_<camera name>.txt" sprintf(flowFilenames[i], "%sframe%d_flow_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]); // add the output directory name to the beginning of the previous mesh // filename char prevFrameMeshFile[MAX_FILENAME_LENGTH]; sprintf(prevFrameMeshFile, "%s%s", outputDirectory, filenameToMatch); // call flow to find the flow between the previous mesh file and the // current mesh file for each mesh point current contour if (flow(prevFrameMeshFile, meshFilenames[i], flowFilenames[i], errorMessage)) { printf("Flow: %s\n", errorMessage); exit(1); } } else { printf("Mesh points file for previous frame not found for contour %s. Unable to calculate flow.\n", contourNames[i]); } } sprintf(command, "hold on;"); engEvalString(matlabEngine, command); // for each contour, display MATLAB 3D plot of the mesh, as well as the flow // for the mesh, if applicable for (int i = 0; i < numContours; i++) { if (flowFilenames[i] != NULL) { sprintf(command, "flows = load('%s');", flowFilenames[i]); engEvalString(matlabEngine, command); // plot the flows of the mesh points sprintf(command, "quiver3(flows(:,1), flows(:,2), flows(:,3), flows(:,4), flows(:,5), flows(:,6), 4, 'r-');"); engEvalString(matlabEngine, command); } sprintf(command, "mesh = importdata('%s', ' ', 1);", meshFilenames[i]); engEvalString(matlabEngine, command); // plot the mesh points sprintf(command, "plot3(mesh.data(:,1), mesh.data(:,2), mesh.data(:,3), 'b.');"); engEvalString(matlabEngine, command); } // reverse the z and y coordinates in the display sprintf(command, "set(gca,'zdir','reverse','ydir','reverse');"); engEvalString(matlabEngine, command); // scale the axes to be equal sprintf(command, "axis equal"); engEvalString(matlabEngine, command); // wait for the user to hit enter printf("Hit return to continue.\n"); fgetc(stdin); // close MATLAB engine engClose(matlabEngine); // cleanup free(camera1Filenames); free(camera1Frames); free(camera2Filenames); free(camera2Frames); free(cameraNames); free(cameraCoefficientsFilenames); for (int i = 0; i < numCameraPairs; i++) { mxDestroyArray(c1ImageData[i]); mxDestroyArray(c1ImageDimensions[i]); mxDestroyArray(c1ImagePaddedWidths[i]); mxDestroyArray(c2ImageData[i]); mxDestroyArray(c2ImageDimensions[i]); mxDestroyArray(c2ImagePaddedWidths[i]); free(c1Images[i]->imageData); cvReleaseImageHeader(&c1Images[i]); free(c2Images[i]->imageData); cvReleaseImageHeader(&c2Images[i]); } free(c1ImageData); free(c1ImageDimensions); free(c1ImagePaddedWidths); free(c2ImageData); free(c2ImageDimensions); free(c2ImagePaddedWidths); free(c1Images); free(c2Images); for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++) { free(filenamesInDirectory[i]); } free(filenamesInDirectory); for (int i = 0; i < numContours; i++) { free(contourNames[i]); free(features3D[i]); free(validFeatureIndicator[i]); free(meshFilenames[i]); if (flowFilenames[i] != NULL) { free(flowFilenames[i]); } } free(contourNames); free(features3D); free(validFeatureIndicator); free(numFeaturesInContours); free(meshFilenames); free(flowFilenames); exit(0); }