int main(int argc, char **argv) {
	char serialport[256];
    int n;

    if (argc==1) {
        exit(EXIT_SUCCESS);
    }

    // Parse options from the command line.
    int option_index = 0, opt;
    static struct option loptions[] = {
    	{"port", required_argument, 0, 'p'},		// Command line for setting port: -p /dev/tty.usbmodem####
	    {"delay", required_argument, 0, 'd'}		// Command line for zero delay: -d 0
	};

    while(1) {
    	opt = getopt_long(argc, argv, "hp:b:s:rn:d:", loptions, &option_index);
    	if (opt==-1) break;
    	switch (opt) {
			case '0': break;
	        case 'd':
	            n = strtol(optarg,NULL,10);
	            usleep(n * 1000); 									// Delay (sleep in milliseconds).
	            break;
	        case 'p':
	            strcpy(serialport,optarg);
	            fd = serialport_init(optarg, baudrate);
	            if(fd==-1) return -1;
	            break;
    	}
    }
	
	// Opens MATLAB engine, creates matrices & pointers for visual and timing samples.
	ep = engOpen(NULL);
	cppVisualSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	cppTimingSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	dataSetVisual = mxGetPr(cppVisualSamples);
	dataSetTiming = mxGetPr(cppTimingSamples);
    glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(window_width,window_height);					// Window size (in pixels).
	glutInitWindowPosition(100,100);								// Window position (from upper left).
	glutCreateWindow("Torquometer Visual Field");					// Window title.
	init();
	glutKeyboardFunc(myKeyboardFunc);								// Handles "normal" ascii symbols (letters).
	glutSpecialFunc(mySpecialKeyFunc);								// Handles "special" keyboard keys (up, down).
	glutDisplayFunc(display);										// Default display mode.
	glutIdleFunc(idleDisplay);										// Used with glutSwapBuffers();
	glEnable(GL_DEPTH_TEST);
	//glEnable(GL_TEXTURE_2D);
	makeCheckImage();												// Generates the gradient pattern in the background.
	glGenTextures(1, &texName);
	glBindTexture(GL_TEXTURE_2D, texName);
	//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
	glutMainLoop();
}
示例#2
0
bool GlobFit::createMatlabArraies()
{
  // matlabEngine = engOpen(NULL);
  matlabEngine = engOpen("matlab -nodesktop");
  if (NULL == matlabEngine) {
    fprintf(stderr, "Could not initialize the engine.\n");
    return false;
  }

  size_t numPrimitives = _vecPrimitive.size();
  for (size_t i = 0; i < numPrimitives; ++i) {
    const Primitive* pPrimitive = _vecPrimitive[i];
    if (pPrimitive->getType() != Primitive::PT_CONE) {
      continue;
    }

    Vector normal;
    pPrimitive->getNormal(normal);
    const std::vector<size_t>& vecVertexIdx = pPrimitive->getPointIdx();
    for (size_t j = 0, jEnd = vecVertexIdx.size(); j < jEnd; ++j) {
      size_t idx = j*numPrimitives+i;
      RichPoint* pRichPoint = _vecPointSet[vecVertexIdx[j]];
      if (pRichPoint->normal*normal < 0) {
        pRichPoint->normal = -pRichPoint->normal;
      }
    }
  }

  numVertices = mxCreateNumericMatrix(numPrimitives, 1, mxINT32_CLASS, mxREAL);
  int *pNumVertices = (int*)mxGetData(numVertices);

  maxIterNum = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL);
  int* pMaxIterNum = (int*)mxGetData(maxIterNum);
  *pMaxIterNum = 500;

  primitiveType = mxCreateNumericMatrix(numPrimitives, 1, mxINT32_CLASS, mxREAL);
  int *pPrimitiveType = (int*)mxGetData(primitiveType);

  int maxNumVertices = 0;
  for (size_t i = 0; i < numPrimitives; ++i) {
    const Primitive* pPrimitive = _vecPrimitive[i];
    pNumVertices[i] = std::max(1, (int)(pPrimitive->getPointIdx().size()));
    pPrimitiveType[i] = pPrimitive->getType();
    if (maxNumVertices < pNumVertices[i])
      maxNumVertices = pNumVertices[i];
  }

  coordX = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pCoordX = mxGetPr(coordX);

  coordY = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pCoordY = mxGetPr(coordY);

  coordZ = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pCoordZ = mxGetPr(coordZ);

  normalX = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pNormalX = mxGetPr(normalX);

  normalY = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pNormalY = mxGetPr(normalY);

  normalZ = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pNormalZ = mxGetPr(normalZ);

  confVertices = mxCreateDoubleMatrix(numPrimitives, maxNumVertices, mxREAL);
  double* pConfVertices = mxGetPr(confVertices);

  memset(pCoordX, 0, maxNumVertices*sizeof(double));
  memset(pCoordY, 0, maxNumVertices*sizeof(double));
  memset(pCoordZ, 0, maxNumVertices*sizeof(double));
  memset(pNormalX, 0, maxNumVertices*sizeof(double));
  memset(pNormalY, 0, maxNumVertices*sizeof(double));
  memset(pNormalZ, 0, maxNumVertices*sizeof(double));
  memset(pConfVertices, 0, maxNumVertices*sizeof(double));
  for (size_t i = 0; i < numPrimitives; ++i) {
    const Primitive* pPrimitive = _vecPrimitive[i];
    const std::vector<size_t>& vecVertexIdx = pPrimitive->getPointIdx();
    for (size_t j = 0, jEnd = vecVertexIdx.size(); j < jEnd; ++j) {
      size_t idx = j*numPrimitives+i;
      const RichPoint* pRichPoint = _vecPointSet[vecVertexIdx[j]];
      pCoordX[idx] = pRichPoint->point.x();
      pCoordY[idx] = pRichPoint->point.y();
      pCoordZ[idx] = pRichPoint->point.z();
      pNormalX[idx] = pRichPoint->normal.x();
      pNormalY[idx] = pRichPoint->normal.y();
      pNormalZ[idx] = pRichPoint->normal.z();
      pConfVertices[idx] = pRichPoint->confidence;
    }
  }

  engPutVariable(matlabEngine, "numVertices", numVertices);
  engPutVariable(matlabEngine, "primitiveType", primitiveType);
  engPutVariable(matlabEngine, "coordX", coordX);
  engPutVariable(matlabEngine, "coordY", coordY);
  engPutVariable(matlabEngine, "coordZ", coordZ);
  engPutVariable(matlabEngine, "normalX", normalX);
  engPutVariable(matlabEngine, "normalY", normalY);
  engPutVariable(matlabEngine, "normalZ", normalZ);
  engPutVariable(matlabEngine, "confVertices", confVertices);
  engPutVariable(matlabEngine, "maxIterNum", maxIterNum);

  return true;
}
示例#3
0
EXPORT CLASS *init(CALLBACKS *fntable, MODULE *module, int argc, char *argv[])
{
	if (set_callback(fntable)==NULL)
	{
		errno = EINVAL;
		return NULL;
	}

	// open a connection to the Matlab engine
	int status=0;
	static char server[1024];
	if (gl_global_getvar("matlab_server",server,sizeof(server)))
		matlab_server = server;
	if (strcmp(matlab_server,"standalone")==0)
		engine = engOpenSingleUse(NULL,NULL,&status);
	else
		engine = engOpen(matlab_server);
	if (engine==NULL)
	{
		gl_error("unable to start Matlab engine (code %d)",status);
		return NULL;
	}

	// prepare session
	char debug[8];
	if (gl_global_getvar("debug",debug,sizeof(debug)))
		debugmode = (atoi(debug)==1);
	engSetVisible(engine,debugmode?1:0);
	engEvalString(engine,"clear all;");
	char env[1024];
	_snprintf(env,sizeof(env),"NEVER=%g;INVALID=%g;",TOSERIAL(TS_NEVER),TOSERIAL(TS_INVALID));
	engEvalString(engine,env);

	// collect output from Matlab
	engOutputBuffer(engine,output,sizeof(output)); 

	// setup the Matlab module and run the class constructor
	engEvalString(engine,"global passconfig;");
	if (engEvalString(engine,argv[0])!=0)
		gl_error("unable to evaluate function '%s' in Matlab", argv[0]);
	else
		gl_matlab_output();

	// read the pass configuration
	mxArray *pcfg= engGetVariable(engine,"passconfig");
	if (pcfg && mxIsChar(pcfg))
	{
		char passinfo[1024];
		KEYWORD keys[] = {
			{"NOSYNC",PC_NOSYNC,keys+1},
			{"PRETOPDOWN",PC_PRETOPDOWN,keys+2},
			{"BOTTOMUP",PC_BOTTOMUP,keys+3},
			{"POSTTOPDOWN",PC_POSTTOPDOWN,NULL},
		};
		PROPERTY pctype = {0,"passconfig",PT_set,1,PA_PUBLIC,NULL,&passconfig,NULL,keys,NULL};
		set passdata;
		if (mxGetString(pcfg,passinfo,sizeof(passinfo))==0 && callback->convert.string_to_property(&pctype,&passdata,passinfo)>0)
		{
			passconfig = (PASSCONFIG)passdata;
			oclass=gl_register_class(module,argv[0],passconfig);
			if (oclass==NULL)
				gl_error("unable to register '%s' as a class",argv[0]);

			DELEGATEDTYPE *pDelegate = new DELEGATEDTYPE;
			pDelegate->oclass = oclass;
			strncpy(pDelegate->type,"matlab",sizeof(pDelegate->type));
			pDelegate->from_string = object_from_string;
			pDelegate->to_string = object_to_string;
			if (gl_publish_variable(oclass,PT_delegated,pDelegate,"data",0,NULL)<1) GL_THROW("unable to publish properties in %s",__FILE__);

		}
		else
			gl_error("passconfig is invalid (expected set of NOSYNC, PRETOPDOWN, BOTTOMUP, and POSTTOPDOWN)", passinfo);
	}
	else
		gl_error("passconfig not specified");

	// read the pass configuration
	mxArray *ans= engGetVariable(engine,"ans");
	if (ans && mxIsStruct(ans))
	{
		defaults = mxDuplicateArray(ans);

		// process the answer
		int nFields = mxGetNumberOfFields(ans), i;
		for (i=0; i<nFields; i++)
		{
			const char *name = mxGetFieldNameByNumber(ans,i);
			mxArray *data = mxGetFieldByNumber(ans,0,i);
			// @todo publish the structure
		}
	}
	else
		gl_error("result of call to matlab::%s did not return a structure", argv[0]);

#ifdef OPTIONAL
	/* TODO: publish global variables (see class_define_map() for details) */
	gl_global_create(char *name, ..., NULL);
	/* TODO: use gl_global_setvar, gl_global_getvar, and gl_global_find for access */
#endif

	/* always return the first class registered */
	return oclass;
}
示例#4
0
int testmatlab (void)
{
	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 };

	/*
	 * Start the MATLAB engine locally by executing the string
	 * "matlab"
	 *
	 * To start the session on a remote host, use the name of
	 * the host as the string rather than \0
	 *
	 * For more complicated cases, use any string with whitespace,
	 * and that string will be executed literally to start MATLAB
	 */
	if (!(ep = engOpen("\0"))) {
		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;
}
//#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;
}
示例#6
0
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);
}
示例#7
0
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, &param) == -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(&ltasks, &ft);
//		generate_intervals_gps(&intervals, &ltasks);/
//		w2fq_schedule(&lschedule, &ltasks,&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, &ltasks,&intervals,1);
//		w2fq_schedule_convert(&wsch2, &lschedule2);
//		compute_profile(&wsch2, &ft, 2);

//		dynamic_instance_schedule(&lschedule3, &ltasks,&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(&ltasks, &ft);

		dynamic_instance_schedule_speed(&lsch, &ltasks, &speed_intervals, &inst,0);

	//	vector<long_schedule>lsch2;
	//	dynamic_instance_schedule_speed(&lsch2, &ltasks, &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(&ltasks, &ft);
						//generate_intervals_gps(&intervals, &ltasks);
						//w2fq_schedule(&lschedule, &ltasks,&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(&ltasks, &ft);
		multi_schedule(&multi_sch,&intervals, &ltasks);
		long hyperperiod=compute_lcm(&ltasks);
		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, &ltasks);

		//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, &ltasks);
		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,&ltasks,&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(&ltasks, &ft);
				w2fq_schedule(&lschedule, &ltasks);
				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
}
示例#8
0
文件: main.cpp 项目: duanqi1983/MyMVS
int main(int argc, char** argv)
{
	//OpenMesh::IO::Options r_options, w_options; 
	//string tmeshfile = "C:\\Users\\duan_qi\\Desktop\\Reconstruction\\PhotoSynthToolkit11\\templeRing\\pmvs\\models\\pmvs_options.txt.ply";
	//string fmeshfile = "C:\\Users\\duan_qi\\Desktop\\Reconstruction\\PhotoSynthToolkit11\\templeRing\\pmvs\\models\\pmvs_options.txt.filtered.off";
	//r_options.set(OpenMesh::IO::Options::VertexColor); w_options.set(OpenMesh::IO::Options::VertexColor);
	//OpenMesh::IO::read_mesh(ObjTriMesh, tmeshfile, r_options);
	//if ( !r_options.check( OpenMesh::IO::Options::VertexColor ) ) {
	//	cout << "Color is not loaded.." << endl;
	//}
	//int rcount = 0;
	//for (MyMesh::VertexIter v_it = ObjTriMesh.vertices_begin(); v_it != ObjTriMesh.vertices_end(); ++ v_it) {
	//	OpenMesh::Vec3f tColor;
	//	tColor[0] = ObjTriMesh.color(v_it).data()[0];
	//	tColor[1] = ObjTriMesh.color(v_it).data()[1];
	//	tColor[2] = ObjTriMesh.color(v_it).data()[2];
	//	if (tColor.norm() < 40) {
	//		ObjTriMesh.delete_vertex(v_it, false);
	//		rcount ++;
	//	}
	//}
	//ObjTriMesh.garbage_collection();
	//OpenMesh::IO::write_mesh(ObjTriMesh, fmeshfile, w_options);

	ParseParam(argc,argv, MOptions);
	ScaleDelta = MOptions.ScaleDelta;
	AnisotropicLaplace = MOptions.AnisotropicLaplace;
	RecordColor = MOptions.RecordColor;
	if (MOptions.UseMatlabSolver) {
		cout << "Use matlab solver for linear equations." << endl;
		if (!(m_ep = engOpen("\0"))) {
			std::cout << "Can not start Matlab engine" << std::endl;
			return false;
		}
		engSetVisible(m_ep, false);
	}
	ScaleDelta?cout<<"Scale delta P each time. ":cout<<" "; AnisotropicLaplace?cout<<"Using anisotropic laplacian term.":cout<<" "; 
	RecordColor?cout<<"Record vertex color to mesh. ":cout<<" "; cout << endl;
	path = MOptions.DirName;
	printf("Number of threads %d\n",omp_get_num_procs());
	omp_set_num_threads(omp_get_num_procs());
	omp_set_num_threads(8);
	double timer_start = (double)cv::getTickCount();
	if (!FileExisted( (MOptions.DirName + "InitialPoissonModel.ply").c_str() )) {
		if (!LoadMVSResult()) 
		{
			readMiddleBuryData2(MOptions.DirName);
			chooseStereoPairs();	

			stereoMatching();
			printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)/cv::getTickFrequency());

			buildTracks();
			printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)/cv::getTickFrequency());

			//writeToOBJ();
			//printf("\nTime = %lfs\n",((double)getTickCount()-timer_start)/getTickFrequency());

			calNormals();
			printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)/cv::getTickFrequency());

			verifyTracks();
			printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)/cv::getTickFrequency());
			
			SaveMVSResult();
		}
		writeToNPTS2(tracks,(MOptions.DirName + "PointInfo.npts"));
		//outputVerticesWithNormals(tracks,(MOptions.DirName + "PointModel.ply"));
		printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)/cv::getTickFrequency());
		//printf("\nTime = %lfs\n",((double)cv::getTickCount()-timer_start)w/cv::getTickFrequency());
		string PlyModelName = MOptions.DirName + "PoissonModel";
		PoissonReconstruction((MOptions.DirName + "PointInfo.npts"), PlyModelName);
		MyCopyFile(PlyModelName, (MOptions.DirName + "InitialPoissonModel.ply"));
	}

	readMiddleBuryData2(MOptions.DirName);

	//read the initial generated Poisson object model
	OpenMesh::IO::Options read_options, write_options;

	string ObjName = MOptions.DirName; 
	if (ObjName.find_last_of("\\") == ObjName.length()-1) {
		ObjName.erase(ObjName.end()-1);
	} 
	ObjName = ObjName.substr(ObjName.find_last_of("\\")+1, ObjName.length());   MOptions.meshname = ObjName;
	string meshfile = (MOptions.DirName + ObjName +"-remeshed.off");
	if (!FileExisted(meshfile.c_str())) {
		string cmd = "meshfix.exe "; cmd += MOptions.DirName + "InitialPoissonModel.ply";
		WinExec(cmd.c_str(),0);
		::Sleep(5000);
		MyMoveFile(MOptions.DirName + "InitialPoissonModel_fixed.off", MOptions.DirName + "temp.off");
		for (int i = 0; i < 5; ++ i) {
			cmd = "meshfix.exe "; cmd += MOptions.DirName + "temp.off";
			WinExec(cmd.c_str(),0);
			::Sleep(5000);
			MyMoveFile(MOptions.DirName + "temp_fixed.off", MOptions.DirName + "temp.off");
		}
		MyMoveFile(MOptions.DirName + "temp.off", meshfile);
	}
	fstream fin(meshfile,ios::in); string tag, temp_str;
	fin>>tag; fin>>temp_str;
	if (temp_str[0] == '#') {
		// need to load and rewrite the off file
		char buffer[100];
		fin.getline(buffer, 100);	fin.getline(buffer, 100);
		fstream fout(meshfile+"tmp",ios::out);
		int vnum, trinum, flag; double x, y, z; int a1, v0, v1, v2;
		fout<<tag<<endl;
		fin>>vnum>>trinum>>flag; fout<<vnum<<" "<<trinum<<" "<<flag<<endl;
		for (int i = 0; i < vnum; ++ i) {
			fin>>x>>y>>z; fout<<x<<" "<<y<<" "<<z<<endl;
		}
		for (int i = 0; i < trinum; ++i) {
			fin>>a1>>v0>>v1>>v2; fout<<a1<<" "<<v0<<" "<<v1<<" "<<v2<<endl;
		}
		fout.close();
		MyMoveFile(meshfile+"tmp", meshfile);
	} fin.close();
示例#9
0
void GraphNodeCtr::run()
{
	Logger<<"Start!.\n";

	IndexType nbCluster = 5;

	//read_label_file("labelInfo.txt");
	//read_label_file("labelInfo_edit.txt");
	//read_label_file("labelInfo_28.txt");
	//read_corres_file("corInfo.txt");

	//read_label_file("labelInfo_456.txt");
	//read_corres_file("corInfo_456.txt");


	read_label_file("tot_labels_dancer.txt");//dancer girl_f(91-110)

	read_corres_file("tot_cor_dancer.txt");

	pca_box_ctr();


	Engine*	ep;
	if (! (ep = engOpen(NULL)) )
	{
		Logger<< "Can't not start Matlab engine.\n";
		return;
	}

	// set buffer to display result
	IndexType	result_buffer_size = 1024*1000;
	char*		result_buffer = new char[result_buffer_size];
	engOutputBuffer(ep, result_buffer, result_buffer_size);

	//Get the executable file's path
	char cur_path[FILENAME_MAX];
	if (!get_current_dir(cur_path, sizeof(cur_path)))
	{
		return;
	}
	cur_path[sizeof(cur_path) - 1] = '\0';
	strcat(cur_path,"\\nCut");
	char cd_cur_path[FILENAME_MAX + 3] = "cd ";
	strcat(cd_cur_path, cur_path);
	engEvalString(ep, cd_cur_path );
	  
	IndexType n = cur_graph_index_;
	mxArray *mx_distMat = NULL;
	numeric::float64* dm_buffer;
	dm_buffer = new numeric::float64[n*n];
	mx_distMat = mxCreateDoubleMatrix(n,n,mxREAL);
	
	ScalarType a_w = 0.01f;

	//ScalarType avg_a_dis ,a_mid;
	//compute_mid_and_avg(avg_a_dis,a_mid,&GraphNodeCtr::dist_inside_frame);
	//Logger<<"avg and mid of adjacency"<<avg_a_dis<<" "<<a_mid<<endl;
	//ScalarType avg_cor_dis,cor_dis;
	//compute_mid_and_avg(avg_cor_dis,cor_dis,&GraphNodeCtr::dist_between_frame);
	//Logger<<"avg and mid of corresponcdence"<<avg_cor_dis<<" "<<cor_dis<<endl;

	for (int i=0; i<n;i++)
	{
		//dm_buffer[i*(n+1)] = exp(-a_w * a_w);
		dm_buffer[i*(n+1)] = a_w;
		for (int j=i+1; j<n; j++)
		{
			//ScalarType dist = weight2nodes(node_vec[i],node_vec[j]);
			ScalarType dist = weight2nodes(node_vec[i],node_vec[j],a_w);
			dm_buffer[i*n+j] = dm_buffer[j*n+i] = (numeric::float64)dist;

		}

	}


	//FILE *out_file = fopen("disMat","w");
	//for (int i=0;i<n;i++)
	//{
	//	for (int j=0;j<n;j++)
	//	{
	//		//fprintf(out_file,"%lf ",dm_buffer[i*n+j]);
	//		fprintf(out_file,"%lf ",disMat(i,j));
	//	}
	//	fprintf(out_file,"\n");
	//}
	//fclose(out_file);


	//FILE *in_file = fopen("weight_1_9","r");
	//for (int i=0;i<n;i++)
	//{
	//	for (int j=0;j<n;j++)
	//	{
	//		fscanf(in_file,"%lf",&dm_buffer[i*n+j]);
	//	}
	//}
	//fclose(in_file);

	

	memcpy((char*)mxGetPr(mx_distMat),(char*)dm_buffer,n*n*sizeof(numeric::float64));
	delete [] dm_buffer;
	engPutVariable(ep,"W",mx_distMat);

	char cmd_buf[128];
	sprintf(cmd_buf,"[NcutDiscrete,NcutEigenvectors,NcutEigenvalues] = ncutW(W,%d);",nbCluster);
	engEvalString(ep,cmd_buf);

	//Display output information
	Logger<<result_buffer<<std::endl;

	mxArray *mx_NcutDiscrete = NULL;
	mx_NcutDiscrete = engGetVariable(ep,"NcutDiscrete");

	numeric::float64 *ncutDiscrete = mxGetPr(mx_NcutDiscrete);
	IndexType k=0;
	for ( IndexType i=0;i<nbCluster;i++ )
	{
		for (IndexType j=0;j<n;j++)
		{
			if ( ncutDiscrete[k++]!=0 )
			{
				node_vec[j]->graph_label = i;
			}
		}
	}
	//Visualize
	SampleSet &smp_set = SampleSet::get_instance();
	IndexType frames[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
	for ( IndexType i=0; i<3;i++ )
	{
		for (IndexType j=0; j<smp_set[frames[i]].num_vertices(); j++)
		{
			smp_set[frames[i]][j].set_visble(false);
		}
	}
	for ( IndexType i=0; i<n;i++ )
	{
		GraphCutNode &node = *(node_vec[i]);
		smp_set[node.frame][node.index].set_label(node.graph_label);
		smp_set[node.frame][node.index].set_visble(true);
	}

	Logger<<"finished\n";
}
示例#10
0
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;
}
示例#11
0
EXPORT bool glx_init(glxlink *mod)
{
	gl_verbose("initializing matlab link");
	gl_verbose("PATH=%s", getenv("PATH"));

	// initialize matlab engine
	MATLABLINK *matlab = (MATLABLINK*)mod->get_data();
	matlab->status = 0;
#ifdef WIN32
	if ( matlab->command )
		matlab->engine = engOpen(matlab->command);
	else
		matlab->engine = engOpenSingleUse(NULL,NULL,&matlab->status);
	if ( matlab->engine==NULL )
	{
		gl_error("matlab engine start failed, status code is '%d'", matlab->status);
		return false;
	}
#else
	matlab->engine = engOpen(matlab->command);
	if ( matlab->engine==NULL )
	{
		gl_error("matlab engine start failed");
		return false;
	}
#endif

	// set the output buffer
	if ( matlab->output_buffer!=NULL )
		engOutputBuffer(matlab->engine,matlab->output_buffer,(int)matlab->output_size);

	// setup matlab engine
	engSetVisible(matlab->engine,window_show(matlab));

	gl_debug("matlab link is open");

	// special values needed by matlab
	mxArray *ts_never = mxCreateDoubleScalar((double)(TIMESTAMP)TS_NEVER);
	engPutVariable(matlab->engine,"TS_NEVER",ts_never);
	mxArray *ts_error = mxCreateDoubleScalar((double)(TIMESTAMP)TS_INVALID);
	engPutVariable(matlab->engine,"TS_ERROR",ts_error);
	mxArray *gld_ok = mxCreateDoubleScalar((double)(bool)true);
	engPutVariable(matlab->engine,"GLD_OK",gld_ok);
	mxArray *gld_err = mxCreateDoubleScalar((double)(bool)false);
	engPutVariable(matlab->engine,"GLD_ERROR",gld_err);

	// set the workdir
	if ( strcmp(matlab->workdir,"")!=0 )
	{
#ifdef WIN32
		_mkdir(matlab->workdir);
#else
		mkdir(matlab->workdir,0750);
#endif
		if ( matlab->workdir[0]=='/' )
			matlab_exec(matlab,"cd '%s'", matlab->workdir);
		else
			matlab_exec(matlab,"cd '%s/%s'", getcwd(NULL,0),matlab->workdir);
	}

	// run the initialization command(s)
	if ( matlab->init )
	{
		mxArray *ans = matlab_exec(matlab,"%s",matlab->init);
		if ( ans && mxIsDouble(ans) && (bool)*mxGetPr(ans)==false )
		{
			gl_error("matlab init 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);
				return false;
			}
			else
			{			
				gl_error("Did not catch Matlab error");
				return false;
			}
		}
	}

	if ( matlab->rootname!=NULL )
	{
		// build gridlabd data
		mwSize dims[] = {1,1};
		mxArray *gridlabd_struct = mxCreateStructArray(2,dims,0,NULL);

		///////////////////////////////////////////////////////////////////////////
		// build global data
		LINKLIST *item;
		mxArray *global_struct = mxCreateStructArray(2,dims,0,NULL);
		for ( item=mod->get_globals() ; item!=NULL ; item=mod->get_next(item) )
		{
			char *name = mod->get_name(item);
			GLOBALVAR *var = mod->get_globalvar(item);
			mxArray *var_struct = NULL;
			mwIndex var_index;
			if ( var==NULL ) continue;

			// do not map module or structured globals
			if ( strchr(var->prop->name,':')!=NULL )
			{
				// ignore module globals here
			}
			else if ( strchr(var->prop->name,'.')!=NULL )
			{
				char struct_name[256];
				if ( sscanf(var->prop->name,"%[^.]",struct_name)==0 )
				{
					gld_property prop(var);
					var_index = mxAddField(global_struct,prop.get_name());
					var_struct = matlab_create_value(&prop);
					if ( var_struct!=NULL )
					{
						//mod->add_copyto(var->prop->addr,mxGetData(var_struct));
						mxSetFieldByNumber(global_struct,0,var_index,var_struct);
					}
				}
			}
			else // simple data
			{
				gld_property prop(var);
				var_index = mxAddField(global_struct,prop.get_name());
				var_struct = matlab_create_value(&prop);
				if ( var_struct!=NULL )
				{
					//mod->add_copyto(var->prop->addr,mxGetData(var_struct));
					mxSetFieldByNumber(global_struct,0,var_index,var_struct);
				}
			}

			// update export list
			if ( var_struct!=NULL )
			{
				mod->set_addr(item,(void*)var_struct);
				mod->set_index(item,(size_t)var_index);
			}
		}

		// add globals structure to gridlabd structure
		mwIndex gridlabd_index = mxAddField(gridlabd_struct,"global");
		mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,global_struct);

		///////////////////////////////////////////////////////////////////////////
		// build module data
		dims[0] = dims[1] = 1;
		mxArray *module_struct = mxCreateStructArray(2,dims,0,NULL);

		// add modules
		for ( MODULE *module = callback->module.getfirst() ; module!=NULL ; module=module->next )
		{
			// create module info struct
			mwIndex dims[] = {1,1};
			mxArray *module_data = mxCreateStructArray(2,dims,0,NULL);
			mwIndex module_index = mxAddField(module_struct,module->name);
			mxSetFieldByNumber(module_struct,0,module_index,module_data);
			
			// create version info struct
			const char *version_fields[] = {"major","minor"};
			mxArray *version_data = mxCreateStructArray(2,dims,sizeof(version_fields)/sizeof(version_fields[0]),version_fields);
			mxArray *major_data = mxCreateDoubleScalar((double)module->major);
			mxArray *minor_data = mxCreateDoubleScalar((double)module->minor);
			mxSetFieldByNumber(version_data,0,0,major_data);
			mxSetFieldByNumber(version_data,0,1,minor_data);

			// attach version info to module info
			mwIndex version_index = mxAddField(module_data,"version");
			mxSetFieldByNumber(module_data,0,version_index,version_data);

		}
		gridlabd_index = mxAddField(gridlabd_struct,"module");
		mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,module_struct);

		///////////////////////////////////////////////////////////////////////////
		// build class data
		dims[0] = dims[1] = 1;
		mxArray *class_struct = mxCreateStructArray(2,dims,0,NULL);
		gridlabd_index = mxAddField(gridlabd_struct,"class");
		mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,class_struct);
		mwIndex class_id[1024]; // index into class struct
		memset(class_id,0,sizeof(class_id));

		// add classes
		for ( CLASS *oclass = callback->class_getfirst() ; oclass!=NULL ; oclass=oclass->next )
		{
			// count objects in this class
			mwIndex dims[] = {0,1};
			for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) )
			{
				OBJECT *obj = mod->get_object(item);
				if ( obj==NULL || obj->oclass!=oclass ) continue;
				dims[0]++;
			}
			if ( dims[0]==0 ) continue;
			mxArray *runtime_struct = mxCreateStructArray(2,dims,0,NULL);

			// add class 
			mwIndex class_index = mxAddField(class_struct,oclass->name);
			mxSetFieldByNumber(class_struct,0,class_index,runtime_struct);

			// add properties to class
			for ( PROPERTY *prop=oclass->pmap ; prop!=NULL && prop->oclass==oclass ; prop=prop->next )
			{
				mwIndex dims[] = {1,1};
				mxArray *property_struct = mxCreateStructArray(2,dims,0,NULL);
				mwIndex runtime_index = mxAddField(runtime_struct,prop->name);
				mxSetFieldByNumber(runtime_struct,0,runtime_index,property_struct);
			}

			// add objects to class
			for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) )
			{
				OBJECT *obj = mod->get_object(item);
				if ( obj==NULL || obj->oclass!=oclass ) continue;
				mwIndex index = class_id[obj->oclass->id]++;
				
				// add properties to class
				for ( PROPERTY *prop=oclass->pmap ; prop!=NULL && prop->oclass==oclass ; prop=prop->next )
				{
					gld_property p(obj,prop);
					mxArray *data = matlab_create_value(&p);
					mxSetField(runtime_struct,index,prop->name,data);
				}

				// update export list
				mod->set_addr(item,(void*)runtime_struct);
				mod->set_index(item,(size_t)index);
			}
		}

		///////////////////////////////////////////////////////////////////////////
		// build the object data
		dims[0] = 0;
		for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) )
		{
			if ( mod->get_object(item)!=NULL ) dims[0]++;
		}
		dims[1] = 1;
		memset(class_id,0,sizeof(class_id));
		const char *objfields[] = {"name","class","id","parent","rank","clock","valid_to","schedule_skew",
			"latitude","longitude","in","out","rng_state","heartbeat","lock","flags"};
		mxArray *object_struct = mxCreateStructArray(2,dims,sizeof(objfields)/sizeof(objfields[0]),objfields);
		mwIndex n=0;
		for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) )
		{
			OBJECT *obj = mod->get_object(item);
			if ( obj==NULL ) continue;
			class_id[obj->oclass->id]++; // index into class struct

			const char *objname[] = {obj->name&&isdigit(obj->name[0])?NULL:obj->name};
			const char *oclassname[] = {obj->oclass->name};

			if (obj->name) mxSetFieldByNumber(object_struct,n,0,mxCreateCharMatrixFromStrings(mwSize(1),objname));
			mxSetFieldByNumber(object_struct,n,1,mxCreateCharMatrixFromStrings(mwSize(1),oclassname));
			mxSetFieldByNumber(object_struct,n,2,mxCreateDoubleScalar((double)class_id[obj->oclass->id]));
			if (obj->parent) mxSetFieldByNumber(object_struct,n,3,mxCreateDoubleScalar((double)obj->parent->id+1));
			mxSetFieldByNumber(object_struct,n,4,mxCreateDoubleScalar((double)obj->rank));
			mxSetFieldByNumber(object_struct,n,5,mxCreateDoubleScalar((double)obj->clock));
			mxSetFieldByNumber(object_struct,n,6,mxCreateDoubleScalar((double)obj->valid_to));
			mxSetFieldByNumber(object_struct,n,7,mxCreateDoubleScalar((double)obj->schedule_skew));
			if ( isfinite(obj->latitude) ) mxSetFieldByNumber(object_struct,n,8,mxCreateDoubleScalar((double)obj->latitude));
			if ( isfinite(obj->longitude) ) mxSetFieldByNumber(object_struct,n,9,mxCreateDoubleScalar((double)obj->longitude));
			mxSetFieldByNumber(object_struct,n,10,mxCreateDoubleScalar((double)obj->in_svc));
			mxSetFieldByNumber(object_struct,n,11,mxCreateDoubleScalar((double)obj->out_svc));
			mxSetFieldByNumber(object_struct,n,12,mxCreateDoubleScalar((double)obj->rng_state));
			mxSetFieldByNumber(object_struct,n,13,mxCreateDoubleScalar((double)obj->heartbeat));
			mxSetFieldByNumber(object_struct,n,14,mxCreateDoubleScalar((double)obj->lock));
			mxSetFieldByNumber(object_struct,n,15,mxCreateDoubleScalar((double)obj->flags));
			n++;
		}
		gridlabd_index = mxAddField(gridlabd_struct,"object");
		mxSetFieldByNumber(gridlabd_struct,0,gridlabd_index,object_struct);

		///////////////////////////////////////////////////////////////////////////
		// post the gridlabd structure
		matlab->root = gridlabd_struct;
		engPutVariable(matlab->engine,matlab->rootname,matlab->root);
	}

	///////////////////////////////////////////////////////////////////////////
	// build the import/export data
	for ( LINKLIST *item=mod->get_exports() ; item!=NULL ; item=mod->get_next(item) )
	{
		OBJECTPROPERTY *objprop = mod->get_export(item);
		if ( objprop==NULL ) continue;

		// add to published items
		gld_property prop(objprop->obj,objprop->prop);
		item->addr = (mxArray*)matlab_create_value(&prop);
		engPutVariable(matlab->engine,item->name,(mxArray*)item->addr);
	}
	for ( LINKLIST *item=mod->get_imports() ; item!=NULL ; item=mod->get_next(item) )
	{
		OBJECTPROPERTY *objprop = mod->get_import(item);
		if ( objprop==NULL ) continue;

		// check that not already in export list
		LINKLIST *export_item;
		bool found=false;
		for ( export_item=mod->get_exports() ; export_item!=NULL ; export_item=mod->get_next(export_item) )
		{
			OBJECTPROPERTY *other = mod->get_export(item);
			if ( memcmp(objprop,other,sizeof(OBJECTPROPERTY)) )
				found=true;
		}
		if ( !found )
		{
			gld_property prop(objprop->obj,objprop->prop);
			item->addr = (mxArray*)matlab_create_value(&prop);
			engPutVariable(matlab->engine,item->name,(mxArray*)item->addr);
		}
	}

	static int32 matlab_flag = 1;
	gl_global_create("MATLAB",PT_int32,&matlab_flag,PT_ACCESS,PA_REFERENCE,PT_DESCRIPTION,"indicates that MATLAB is available",NULL);
	mod->last_t = gl_globalclock;
	return true;
}
 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;
	}
示例#13
0
/* 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);
}
示例#14
0
/*
 *	matlabShell.c
 *
 *	This is a simple program call MATLAB matlab.el
 *
 *    Copyright (c) 1998 by Robert A. Morris
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 * If you did not receive a copy of the GPL you can get it at
 *     //http://www.fsf.org
 * 
 * This program is a matlab shell which will run under WindowsNT, and possibly
 * any OS, and can be invoked either from from matlab.el or a native
 * command shell.
 *
 * See the usage notes at the end of this file, or invoke it with
 * -h argument for brief usage message

 *      02dec98 version 1.0 [email protected]
 *         -remove echo; instead require 
 *              matlab-shell-process-echoes nil
 *              in matlab-shell-mode-hook
 *         -works with matlab.el ver 2.2
 *      01nov98 version 0.91 [email protected]
 *      Bugs fixed:
 *        "exit" command processing should be case sensitive
 *        input not echoed properly
 *        line spacing different from Matlab standard window
 *
 *        - Matlab "exit" command must be all lower case, so
 *          replace isExitCommand() with simple strncmp()
 *        - echo input because something is erasing it on NT. Maybe comint.el?
 *        - make line spacing look like Matlab native shell
 *      Known deficiencies in 0.91:
 *      1. Matlab standard command window pops up when starting
 *      2. Matlab window doesn't exit if *matlab* buffer is killed without
 *       sending exit command to matlab from matlabShell
 *
 *	01nov98 version 0.9 [email protected]
 *	Known deficencies in 0.9
 *	1. should be quiet production mode and verbose C debugging modes
 *      2. Matlab Debug is untested, probably doesn't work
 *
 */
#include <stdlib.h>
#include <stdio.h>
#include "engine.h"

#define MAXLEN 1024;		/* default */
int main(int argc, char **argv)
{
  char version[]="MatlabShell 1.0. 02Dec1998.\nCopyright 1998 Robert A. Morris. \nThis is Free Software licensed under the GNU Public License.";
	Engine *ep;
	int inputMax; /* buffer size */
	char *inbuf;

	int outputMax; /*buffer size */
	char *fromEngine; 

	int noArgs;
	int len, pos;

	int debug = 0;
	int retval; /* for debug */
	
	int isExitCommand(char* str);

	/* matlab.el always invokes the shell command with two
	   arguments, the second of which is NULL unless the lisp
	   variable matlab-shell-command-switches is set, in which
	   case the string value of that variable is passed as the
	   argv[1] to the shell program. In that case we have to parse
	   this string. In the standalone case, we may see 1, 2, or 3
	   args, the first of which is always the program path
	*/

	printf("%s\n", version);
	noArgs = (argc==1) || (argv[1]==0 || argv[1][0] == 0);

	if ( (!noArgs) && (argv[1][0] == '?' || !strcmp(argv[1], "-h"))) {
	  printf("usage: %s <inbufSize> <outbufSize>", argv[0]);
	  exit(0);
	}

	/* Start the MATLAB engine */
	if (!(ep = engOpen(NULL))) {
	  printf("Can not start engine\n");
	  exit(-1);
	}

	inputMax = MAXLEN;
	outputMax = 0;
	
	/* if there are args they might be:
	   1. one string from matlab.el with either 1 or 2 numbers
	   2. one or two strings from a command shell invocation
	*/
	if ( !noArgs ){ 
	  inputMax = atoi(argv[1]);
	  if (argc>2 && argv[2]) /* doesn't happen under matlab.el */
	    outputMax = atoi(argv[2]);
	  else { /*matlab.el passes args as a single string */
	    len = strlen(argv[1]);
	    pos = strcspn(argv[1], " \t\n"); /* scan to white space */
	    if (debug) printf("argv[1]=%s len=%d pos=%d\n", argv[1], len, pos);
	    argv[1][pos]=0; /* split */
	    inputMax = atoi(argv[1]);
	    if (pos < len) /* there was stuff left */
	      outputMax = atoi(1+pos+argv[1]);
	  }
	}
	if (!outputMax)		/* nobody set it */
	  outputMax = 8*inputMax;

	inbuf = malloc(inputMax+2); /* room for newline and \0 */
	outputMax = inputMax*8;
	fromEngine = malloc(outputMax +2);
	engOutputBuffer(ep, fromEngine, outputMax);

	
	while (1) {
	  printf(">> "); fflush(stdout);
	  fgets(inbuf, inputMax, stdin);
	    
	    /* On NT, something erases input and I don't know what. It
	     might be the way comint.el is passing input to this
	     process. If this is platform dependent then other platforms
	     may see doubled input  */

	  //	  printf("%s",inbuf);   fflush(stdout);	/* re-echo input */
	  
	  /* it would be good to test retval, but on NT it seems
	     to return non-zero whether the engine is
	     running or not, contrary to Matlab doc.
	     In fact, I can't figure out how to know whether the
	     engine is running, so special case "exit"
	  */
	  
	  retval = engEvalString(ep, inbuf);
	  if (!strncmp(inbuf,"exit",4)) {
	    printf("exiting\n"); fflush(stdout);
	    exit(0);
	  }
	  if (fromEngine[0] == 0 ){ /*the command didn't return anything */
	    if(debug) 
	      printf("\ncmd returned nothing");
	  }
	  else {
	    printf("%s", fromEngine); /* show matlab reply */
	    fromEngine[0] = 0; /* clear buffer, else confusing */  
	    if (debug) {
	      printf("retval=%x\n");
	      fflush(stdout);
	    }
	  }
	}
	exit(0);
}
示例#15
0
// Init the MATLAB engine 
// (no need to call it directly since it is automatically invoked by any other command)
IGL_INLINE void igl::mlinit(Engine** mlengine)
{
  *mlengine = engOpen("\0");
}
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;}");
}
示例#17
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);
}
示例#18
0
void MultiObjectSeg::nCutProcess(HFrame& curFrame)
{
	Loggger<<"Start Graph Cut!.\n";

	IndexType nbCluster = 8;
	Loggger<<"segment number = "<<nbCluster<<endl;


	Engine*	ep;
	if (! (ep = engOpen(NULL)) )
	{
		Loggger<< "Can't not start Matlab engine.\n";
		return;
	}

	//	///set buffer to display result
	IndexType	result_buffer_size = 1024*1000;
	char*		result_buffer = new char[result_buffer_size];
	engOutputBuffer(ep, result_buffer, result_buffer_size);

	///Get the executable file's path
	char cur_path[FILENAME_MAX];
	if (!get_current_dir(cur_path, sizeof(cur_path)))
	{
		return;
	}
	cur_path[sizeof(cur_path) - 1] = '\0';
	strcat(cur_path,"\\nCut");
	char cd_cur_path[FILENAME_MAX + 3] = "cd ";
	strcat(cd_cur_path, cur_path);
	engEvalString(ep, cd_cur_path );

	IndexType fId = curFrame.frame_id;
	IndexType n = boost::num_vertices(*curFrame.pcGraph);  //cur_graph_index_;
	//	//

	//	//
	mxArray *mx_distMat = NULL;
	numeric::float64* dm_buffer;
	dm_buffer = new numeric::float64[n*n];
	mx_distMat = mxCreateDoubleMatrix(n,n,mxREAL);

	//	///all
	for (int rowId = 0; rowId < n; rowId++)
	{
		/*dm_buffer[rowId*(n+1)] = 0;*/
		for (int colId = 0; colId < n; colId++)
		{
			ScalarType dist = 0.;//weight2nodes_smooth(node_vec[rowId],node_vec[colId]);
			dm_buffer[rowId * n + colId] = (numeric::float64)dist;
		}
	}

	memcpy((char*)mxGetPr(mx_distMat),(char*)dm_buffer,n*n*sizeof(numeric::float64));
	delete [] dm_buffer;
	engPutVariable(ep,"W",mx_distMat);

	char cmd_buf[128];
	sprintf(cmd_buf,"[NcutDiscrete,NcutEigenvectors,NcutEigenvalues] = ncutW(W,%d);",nbCluster);
	engEvalString(ep,cmd_buf);

	//	///Display output information
	//		Loggger<<result_buffer<<std::endl;

	mxArray *mx_NcutDiscrete = NULL;
	mx_NcutDiscrete = engGetVariable(ep,"NcutDiscrete");

	numeric::float64 *ncutDiscrete = mxGetPr(mx_NcutDiscrete);

	Loggger<<"End for each nCut.\n";
}
void Project_Engine::Matlab_execution()
{
	Engine	*ep;
	mxArray *cust_array					= mxCreateDoubleMatrix(CUSTOMERS_MAX-1,1,mxREAL);
	mxArray *mov_avg_array				= mxCreateDoubleMatrix(MOVIES_MAX-1,1,mxREAL);
	mxArray *mov_count_array			= mxCreateDoubleMatrix(MOVIES_MAX-1,1,mxREAL);
	double	*p_rating_count				= mxGetPr(cust_array);
	double	*p_movie_avg				= mxGetPr(mov_avg_array);
	double	*p_mov_count				= mxGetPr(mov_count_array);
	int		i,j,counter;
	float	Current_movie,Current_cust;
	intHashTable*	movie_average		= new intHashTable(9);
	intHashTable*	user_average		= new intHashTable(9);

//======================USER AVERAGE DISTRIBUTION======================
	for (i=1;i<CUSTOMERS_MAX;i++){
		//Round up each customer rating average to the nearest 0.5 between 1 and 5
		Current_cust = floor((2*Customer_spec[i].Cust_RateAvg)+0.5)/2;
		for (j=0;j<9;j++){
			if (Current_cust<(1+0.5*j)){
					//According to the users rounded average, the corresponding id is inserted into a specific rating list 
					user_average->insert(i,Current_cust,j);
					break;
			}
		}
	}

mxArray *custrating_array	= mxCreateDoubleMatrix(9,1,mxREAL);
mxArray *custcount_array	= mxCreateDoubleMatrix(9,1,mxREAL);
double *pcustx				= mxGetPr(custrating_array);
double *pcusty				= mxGetPr(custcount_array);
Node** user_table			= user_average->getTable();

for (j=0;j<9;j++){
		counter = 0;
		pcustx[j] = 1+0.5*j;
		while(user_table[j]!=NULL){
			counter++;
			user_table[j] = user_table[j]->Next;
		}
		pcusty[j] = counter;
	}
memcpy((void*)mxGetPr(custrating_array),	(void*)pcustx, (9)*sizeof(float));
memcpy((void*)mxGetPr(custcount_array),		(void*)pcusty, (9)*sizeof(float));
//======================USER AVERAGE DISTRIBUTION======================

//======================MOVIE AVERAGE DISTRIBUTION======================
	for (i=1;i<MOVIES_MAX;i++){
		Current_movie = floor((2*Movie_spec[i].Movie_RateAvg)+0.5)/2;
		for (j=0;j<9;j++){
			if (Current_movie<(1+0.5*j)){
					movie_average->insert(i,Current_movie,j);
					break;
				}
		}
	}

mxArray *mrating_array	= mxCreateDoubleMatrix(9,1,mxREAL);
mxArray *mcount_array	= mxCreateDoubleMatrix(9,1,mxREAL);
double *px				= mxGetPr(mrating_array);
double *py				= mxGetPr(mcount_array);
Node** movie_table		= movie_average->getTable();

for (j=0;j<9;j++){
		counter = 0;
		px[j] = 1+0.5*j;
		while(movie_table[j]!=NULL){
			counter++;
			movie_table[j] = movie_table[j]->Next;
		}
		py[j] = counter;
	}
memcpy((void*)mxGetPr(mrating_array),	(void*)px, (9)*sizeof(float));
memcpy((void*)mxGetPr(mcount_array),	(void*)py, (9)*sizeof(float));
//======================MOVIE AVERAGE DISTRIBUTION======================	

	if (!(ep = engOpen("\0")))
		cerr << "Cant start MATLAB engine" << endl;

	for (i=1;i<CUSTOMERS_MAX;i++){
		p_rating_count[i-1]	=	Customer_spec[i].Cust_RateCount;		
	 };

	for (i=1;i<MOVIES_MAX;i++){
		p_movie_avg[i-1]		=	Movie_spec[i].Movie_RateAvg;
		p_mov_count[i-1]		=	Movie_spec[i].Movie_RateCount;
	 };

memcpy((void*)mxGetPr(cust_array),		(void*)p_rating_count,	(CUSTOMERS_MAX-1)*sizeof(float));
memcpy((void*)mxGetPr(mov_avg_array),	(void*)p_movie_avg,		(MOVIES_MAX-1)*sizeof(float));
memcpy((void*)mxGetPr(mov_count_array), (void*)p_mov_count,		(MOVIES_MAX-1)*sizeof(float));

engPutVariable(ep,"rating_count",cust_array);
engPutVariable(ep,"movie_avg"	,mov_avg_array);
engPutVariable(ep,"mov_count"	,mov_count_array);

engEvalString(ep, "figure(1);");
engEvalString(ep, "B=sort(rating_count);");
engEvalString(ep, "numberOfBins = 100;[counts, binValues] = hist(B, numberOfBins);normalizedCounts = 100 * counts / sum(counts);");
engEvalString(ep, "bar(sort(binValues),normalizedCounts,'r');set(gca,'XTick', []);");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Customer Rating Count Distribution')");
engEvalString(ep, "ylabel('Rating Count [%]')");

engEvalString(ep, "figure(2);");
engEvalString(ep, "B=sort(movie_avg);plot(B,'-.r*');");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Movie Average Distribution')");
engEvalString(ep, "xlabel('Movie ID')");
engEvalString(ep, "ylabel('Rating Average')");

engEvalString(ep, "figure(3);");
engEvalString(ep, "C=sort(mov_count);");
engEvalString(ep, "numberOfBins = 100;[counts, binValues] = hist(C, numberOfBins);normalizedCounts = 100 * counts / sum(counts);");
engEvalString(ep, "bar(sort(binValues),normalizedCounts);");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Movie Rating Count Distribution')");
engEvalString(ep, "ylabel('Rating Count [%]')");

engPutVariable(ep,"x",mrating_array);
engPutVariable(ep,"y",mcount_array);

engPutVariable(ep,"custx",custrating_array);
engPutVariable(ep,"custy",custcount_array);

engEvalString(ep, "figure(4);");
engEvalString(ep, "bar(x,y/sum(y));");
engEvalString(ep, "grid on;");
engEvalString(ep, "title('Average Rating Distribution of Movies')");
engEvalString(ep, "xlabel('Rating')");
engEvalString(ep, "ylabel('Density')");
engEvalString(ep, "hold on");
engEvalString(ep, "plot(custx,custy/sum(custy),'--r','LineWidth',2);");
engEvalString(ep, "hold off");

string s;
cout << "Press Any Key to exit MATLAB and continue the program:" << endl;
getline(cin, s);
mxDestroyArray(cust_array);
mxDestroyArray(mov_avg_array);
mxDestroyArray(mov_count_array);
engEvalString(ep,"close;");
}