Example #1
0
JNIEXPORT jstring JNICALL Java_JMatLink_engOutputBufferNATIVE  
                             (JNIEnv *env, jobject obj,  jint engine, jint buflen)
{
  // !!!!! buflen not implemented yet

    // Check if engine pointer is within allowed region
    if (( engine < 1 ) || ( engine >= enginePMax ))
    {
        return; // Pointer is out of allowed region
    }

   engOutputBuffer(engineP[ engine ], buffer, BUFSIZE);

   if (debugB) printf("JMatLink %s", buffer);
   return (*env)->NewStringUTF(env, buffer);
}
Example #2
0
Int_t TMatlab::OutputBuffer(char* buffer, Int_t buflen) { 
#ifdef HAVE_MATLAB
  if (!fEngine) return 0;
 
  if (fOutputBuffer) delete [] fOutputBuffer;

  if (!buffer) {
    buffer = new char[buflen];
  }
  
  fOutputBuffer = buffer;

  return engOutputBuffer((Engine*)fEngine, buffer,buflen);
#else
  return 0;
#endif
}
Example #3
0
PyObject * mlabraw_oldeval(PyObject *, PyObject *args)
{
  //XXX how large should this be?
  const int  BUFSIZE=10000;
  char buffer[BUFSIZE];
  char *lStr;
  char *retStr = buffer;
  PyObject *ret;
  PyObject *lHandle;

  if (! PyArg_ParseTuple(args, "Os:eval", &lHandle, &lStr)) return NULL;
  if (! PyCapsule_CheckExact(lHandle)) {
    PyErr_SetString(PyExc_TypeError, "Invalid object passed as mlabraw session handle");
    return NULL;
  }
  engOutputBuffer((Engine *)PyCapsule_GetPointer(lHandle, NULL), retStr, BUFSIZE-1);
  if (engEvalString((Engine *)PyCapsule_GetPointer(lHandle, NULL), lStr) != 0) {
    PyErr_SetString(mlabraw_error,
                   "Unable to evaluate string in MATLAB(TM) workspace");
    return NULL;
  }
  // skip the prompt if there is one
  if (strncmp(">> ", retStr, 3) == 0) {
    retStr += 3;
  }
  else {
    //XXX I think there is no prompt under windoze
//     printf("###DEBUG: matlab output doesn't start with \">> \"!\n"
//            "It starts with: '%s'\n"
//            "The command was: '%s'\n", retStr, lStr);
  }
  // "??? " is how an error message begins in matlab
  // obviously there is no proper way to test whether a command was
  // succesful... AAARGH
  if (strncmp("??? ", retStr, 4) == 0) {
    PyErr_SetString(mlabraw_error, retStr + 4); // skip "??? "
    return NULL;
  }
#ifdef PY3K
  ret = PyUnicode_FromString(retStr);
#else
  ret = (PyObject *)PyString_FromString(retStr);
#endif
  return ret;
}
Example #4
0
// Execute arbitrary MATLAB code and return the MATLAB output
IGL_INLINE std::string igl::mleval(Engine** mlengine, std::string code)
{
  if (*mlengine == 0)
    mlinit(mlengine);
  
  const char *matlab_code = code.c_str();
  const int BUF_SIZE = 4096*4096;
  // allocate on the heap to avoid running out of stack
  std::string bufauto(BUF_SIZE+1, '\0');
  char *buf = &bufauto[0];
  
  assert(matlab_code != NULL);
  
  // Use RAII ensure that on leaving this scope, the output buffer is
  // always nullified (to prevent Matlab from accessing memory that might
  // have already been deallocated).
  struct cleanup {
    Engine *m_ep;
    cleanup(Engine *ep) : m_ep(ep) { }
    ~cleanup() { engOutputBuffer(m_ep, NULL, 0); }
  } cleanup_obj(*mlengine);
  
  if (buf != NULL)
    engOutputBuffer(*mlengine, buf, BUF_SIZE);
  
  int res = engEvalString(*mlengine, matlab_code);
  
  if (res != 0) {
    std::ostringstream oss;
    oss << "ERROR: Matlab command failed with error code " << res << ".\n";
    return oss.str();
  }
  
  if (buf[0] == '>' && buf[1] == '>' && buf[2] == ' ')
    buf += 3;
  if (buf[0] == '\n') ++buf;
  
  return std::string(buf);
}
MatLabEngine::MatLabEngine( std::string host ) : _ep( 0 ), _matLabLogFileStreamPtr( 0 ) {
	static std::string startError = "Could not start MatLab Engine.\n"
	 "The most common reasons for a MatLab exception are as follows:\n\n"
	 "   1) MatLab isn't installed on this (the local) machine.  MatLab *MUST*\n"
	 "      be installed on the machine on which MDL2MGA is run.\n"
	 "      IF YOU ARE RUNNING 64-bit WINDOWS XP, YOU MUST INSTALL THE\n"
	 "      32-BIT VERSION OF MATLAB FOR MDL2MGA TO RUN.\n\n"
	 "   2) If MatLab is installed on this machine, it may be that the\n"
	 "      MatLab service is not registered.  To register the MatLab service,\n"
	 "      in a command-prompt type:\n"
	 "        matlab /regserver\n"
	 "      Once you have done this, try running MDL2MGA again.\n\n"
	 "   3) If MatLab is installed on this machine and registered as a server,\n"
	 "      it may be that MatLab is taking a long time to initialize.  So long,\n"
	 "      in fact, that MDL2MGA is timing out before MatLab is able to respond\n"
	 "      to it.  To test this, re-execute MDL2MGA at least 3 more times.\n"
	 "      If MDL2MGA still will not run, please contact your support center.\n\n";

//		int retcode;
//		if (   !(  _ep = engOpenSingleUse( "\0", 0, &retcode )  )   ) {
//			throw Exception( "Cannot start MatLab engine (retcode = " + retcode + ')' );
//		}
//		if (   !(  _ep = engOpen( "\0" )  )   ) {

#ifdef LINUX
	host += "\0";
	if (   !(  _ep = engOpen( host.c_str() )  )   ) {
		throw MatLabUdm::Exception( startError );
	}
#else // Windows
	int retcode;
		if (   !(  _ep = engOpenSingleUse( "\0", 0, &retcode )  )   ) {
			throw std::exception( "Cannot start MatLab engine (retcode = " + retcode + ')' );
		}
#endif
	
	getBuffer()[ BUFSIZE ] = '\0';
	engOutputBuffer( _ep, getBuffer(), BUFSIZE );
}
Example #6
0
void MatlabPlotter::plot(void* array, std::string title, int id)
{
  //Send data to matlab
  engPutVariable((Engine*)engine_, "data", (mxArray*)array);

  //Use OutputBuffer to capture MATLAB output
  memset(buffer_, 0, 256 * sizeof(char));
  engOutputBuffer((Engine*)engine_, buffer_, 256);

  //Process in Matlab
  std::string command;
  if(mxIsComplex((mxArray*)array))
    command = buildComplexCommand(title, id);
  else
    command = buildScalarCommand(title, id);

  engEvalString((Engine*)engine_, command.c_str());

  //The evaluate string returns the result into the output buffer
  if (buffer_[0] != 0)
  {
    std::cout << "[WARNING} MatlabPlotter: " << buffer_ <<std::endl;
  }
}
Example #7
0
/*@C
    PetscMatlabEngineCreate - Creates a MATLAB engine object

    Not Collective

    Input Parameters:
+   comm - a separate MATLAB engine is started for each process in the communicator
-   machine - name of machine where MATLAB engine is to be run (usually NULL)

    Output Parameter:
.   mengine - the resulting object

   Options Database:
.    -matlab_engine_graphics - allow the MATLAB engine to display graphics

   Level: advanced

.seealso: PetscMatlabEngineDestroy(), PetscMatlabEnginePut(), PetscMatlabEngineGet(),
          PetscMatlabEngineEvaluate(), PetscMatlabEngineGetOutput(), PetscMatlabEnginePrintOutput(),
          PETSC_MATLAB_ENGINE_(), PetscMatlabEnginePutArray(), PetscMatlabEngineGetArray(), PetscMatlabEngine
@*/
PetscErrorCode  PetscMatlabEngineCreate(MPI_Comm comm,const char machine[],PetscMatlabEngine *mengine)
{
  PetscErrorCode    ierr;
  PetscMPIInt       rank,size;
  char              buffer[256];
  PetscMatlabEngine e;
  PetscBool         flg = PETSC_FALSE;

  PetscFunctionBegin;
  if (MATLABENGINE_CLASSID == -1) {
    ierr = PetscClassIdRegister("MATLAB Engine",&MATLABENGINE_CLASSID);CHKERRQ(ierr);
  }
  ierr = PetscOptionsGetBool(NULL,NULL,"-matlab_engine_graphics",&flg,NULL);CHKERRQ(ierr);

  ierr = PetscHeaderCreate(e,MATLABENGINE_CLASSID,"MatlabEngine","MATLAB Engine","Sys",comm,PetscMatlabEngineDestroy,NULL);CHKERRQ(ierr);

  if (!machine) machine = "\0";
  ierr = PetscStrcpy(buffer,PETSC_MATLAB_COMMAND);CHKERRQ(ierr);
  if (!flg) {
    ierr = PetscStrcat(buffer," -nodisplay ");CHKERRQ(ierr);
  }
  ierr  = PetscStrcat(buffer," -nojvm ");CHKERRQ(ierr);
  ierr  = PetscInfo2(0,"Starting MATLAB engine on %s with command %s\n",machine,buffer);CHKERRQ(ierr);
  e->ep = engOpen(buffer);
  if (!e->ep) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Unable to start MATLAB engine on %s",machine);
  engOutputBuffer(e->ep,e->buffer,1024);

  ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
  ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
  sprintf(buffer,"MPI_Comm_rank = %d; MPI_Comm_size = %d;\n",rank,size);
  engEvalString(e->ep, buffer);
  ierr = PetscInfo1(0,"Started MATLAB engine on %s\n",machine);CHKERRQ(ierr);

  *mengine = e;
  PetscFunctionReturn(0);
}
Example #8
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 };

	/*
	 * Call engOpen with a NULL string. This starts a MATLAB process 
     * on the current host using the command "matlab".
	 */
	if (!(ep = engOpen(""))) {
		fprintf(stderr, "\nCan't start MATLAB engine\n");
		return EXIT_FAILURE;
	}

	/*
	 * PART I
	 *
	 * For the first half of this demonstration, we will send data
	 * to MATLAB, analyze the data, and plot the result.
	 */

	/* 
	 * Create a variable for our data
	 */
	T = mxCreateDoubleMatrix(1, 10, mxREAL);
	memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
	/*
	 * Place the variable T into the MATLAB workspace
	 */
	engPutVariable(ep, "T", T);

	/*
	 * Evaluate a function of time, distance = (1/2)g.*t.^2
	 * (g is the acceleration due to gravity)
	 */
	engEvalString(ep, "D = .5.*(-9.8).*T.^2;");

	/*
	 * Plot the result
	 */
	engEvalString(ep, "plot(T,D);");
	engEvalString(ep, "title('Position vs. Time for a falling object');");
	engEvalString(ep, "xlabel('Time (seconds)');");
	engEvalString(ep, "ylabel('Position (meters)');");

	/*
	 * use fgetc() to make sure that we pause long enough to be
	 * able to see the plot
	 */
	printf("Hit return to continue\n\n");
	fgetc(stdin);
	/*
	 * We're done for Part I! Free memory, close MATLAB figure.
	 */
	printf("Done for Part I.\n");
	mxDestroyArray(T);
	engEvalString(ep, "close;");


	/*
	 * PART II
	 *
	 * For the second half of this demonstration, we will request
	 * a MATLAB string, which should define a variable X.  MATLAB
	 * will evaluate the string and create the variable.  We
	 * will then recover the variable, and determine its type.
	 */
	  
	/*
	 * Use engOutputBuffer to capture MATLAB output, so we can
	 * echo it back.  Ensure first that the buffer is always NULL
	 * terminated.
	 */

	buffer[BUFSIZE] = '\0';
	engOutputBuffer(ep, buffer, BUFSIZE);
	while (result == NULL) {
	    char str[BUFSIZE+1];
	    /*
	     * Get a string input from the user
	     */
	    printf("Enter a MATLAB command to evaluate.  This command should\n");
	    printf("create a variable X.  This program will then determine\n");
	    printf("what kind of variable you created.\n");
	    printf("For example: X = 1:5\n");
	    printf(">> ");

	    fgets(str, BUFSIZE, stdin);
	  
	    /*
	     * Evaluate input with engEvalString
	     */
	    engEvalString(ep, str);
	    
	    /*
	     * Echo the output from the command.  
	     */
	    printf("%s", buffer);
	    
	    /*
	     * Get result of computation
	     */
	    printf("\nRetrieving X...\n");
	    if ((result = engGetVariable(ep,"X")) == NULL)
	      printf("Oops! You didn't create a variable X.\n\n");
	    else {
		printf("X is class %s\t\n", mxGetClassName(result));
	    }
	}

	/*
	 * We're done! Free memory, close MATLAB engine and exit.
	 */
	printf("Done!\n");
	mxDestroyArray(result);
	engClose(ep);
	
	return EXIT_SUCCESS;
}
Example #9
0
/*
 * JS Changed coord arguments to double as external function API changed
 */
int matlab_demo_(float *data,
		 double *xcoords, int *xsize,
		 double *ycoords, int *ysize,
		 float *bad_flag) {
  mxArray *T = NULL, *result = NULL;
  mxArray *mX = NULL, *mY = NULL;
  char buffer[BUFSIZE], cbuffer[BUFSIZE];
  double *ddata = 0, *mxData = 0, *myData = 0;;

				/* Open MATLAB engine */
  if (ep == 0){
    if (!(ep = engOpen("\0"))) {
      fprintf(stderr, "\nCan't start MATLAB engine\n");
      return EXIT_FAILURE;
    }
  }

  engOutputBuffer(ep, buffer, BUFSIZE);
				/* Convert from float->double */
  T = mxCreateDoubleMatrix(*xsize, *ysize, mxREAL);
  mxSetName(T, "FERRET_DATA");
  ddata = mxGetPr(T);

  mX = mxCreateDoubleMatrix(*xsize, 1, mxREAL);
  mxSetName(mX, "FERRET_XDATA");
  mxData = mxGetPr(mX);
  mY = mxCreateDoubleMatrix(*ysize, 1, mxREAL);
  mxSetName(mY, "FERRET_YDATA");
  myData = mxGetPr(mY);
  
  {
    int i;
    for (i=0; i < *xsize * *ysize; ++i){
      float theData = data[i];
      if (theData == *bad_flag){
	ddata[i] = NaN;
      } else {
	ddata[i] = data[i];
      }
    }

    memcpy(mxData, xcoords, sizeof(double)* *xsize);
    memcpy(myData, ycoords, sizeof(double)* *ysize);
  }

  /* Place the variables into the MATLAB workspace */
  engPutArray(ep, T);
  engPutArray(ep, mX);
  engPutArray(ep, mY);

  
  sprintf(cbuffer, "ferretdemo(FERRET_DATA', FERRET_XDATA', FERRET_YDATA');");
  engEvalString(ep, cbuffer);
  /*
   * Echo the output from the command.  First two characters are
   * always the double prompt (>>).
   */
  printf("%s", buffer+2);

  mxDestroyArray(T);
/*   engEvalString(ep, "close;"); */
/*   engClose(ep); */
	
  return EXIT_SUCCESS;
}
Example #10
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";
}
Example #11
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";
}
Example #12
0
 ~cleanup() { engOutputBuffer(m_ep, NULL, 0); }
Example #13
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);
}
Example #14
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;
}
Example #15
0
PyObject * mlabraw_eval(PyObject *, PyObject *args)
{
  //XXX how large should this be? used to be 10000, but looks like matlab
  // hangs when it gets bigger than ~9000 I'm not aware of some actual limit
  // being documented anywhere; I don't want to make it too small since the
  // high overhead of engine calls means that it can be potentially useful to
  // eval large chunks.
  const int  BUFSIZE=4096;
  char* fmt = "try, %s; MLABRAW_ERROR_=0; catch, MLABRAW_ERROR_=1; end;";
  char buffer[BUFSIZE];
  char cmd[BUFSIZE];
  char *lStr;
  char *retStr = buffer;
  PyObject *ret;
  PyObject *lHandle;
  if (! PyArg_ParseTuple(args, "Os:eval", &lHandle, &lStr)) return NULL;
  if (! PyCObject_Check(lHandle)) {
    PyErr_SetString(PyExc_TypeError, "Invalid object passed as mlabraw session handle");
	return NULL;
  }

  bool ok = my_snprintf(cmd, BUFSIZE, fmt, lStr);
  if (! ok) {
	  PyErr_SetString(mlabraw_error,
					  "String too long to evaluate.");
	  return NULL;
  }
  // std::cout << "DEBUG: CMD " << cmd << std::endl << std::flush;
  engOutputBuffer((Engine *)PyCObject_AsVoidPtr(lHandle), retStr, BUFSIZE-1);
  if (engEvalString((Engine *)PyCObject_AsVoidPtr(lHandle), cmd) != 0) {
    PyErr_SetString(mlabraw_error,
                   "Unable to evaluate string in MATLAB(TM) workspace");
    return NULL;
  }
  {
    mxArray *lArray = NULL;
    char buffer2[BUFSIZE];
    char *retStr2 = buffer2;
    bool __mlabraw_error;
    if (NULL == (lArray = _getMatlabVar(lHandle, "MLABRAW_ERROR_")) ) {
      PyErr_SetString(mlabraw_error,
                      "Something VERY BAD happened whilst trying to evaluate string "
                      "in MATLAB(TM) workspace.");
      return NULL;
    }
    __mlabraw_error = (bool)*mxGetPr(lArray);
    mxDestroyArray(lArray);
    if (__mlabraw_error) {
      engOutputBuffer((Engine *)PyCObject_AsVoidPtr(lHandle), retStr2, BUFSIZE-1);
      if (engEvalString((Engine *)PyCObject_AsVoidPtr(lHandle),
                        "disp(subsref(lasterror(),struct('type','.','subs','message')))") != 0) {
        PyErr_SetString(mlabraw_error, "THIS SHOULD NOT HAVE HAPPENED!!!");
        return NULL;
      }
      PyErr_SetString(mlabraw_error, retStr2 + ((strncmp(">> ", retStr2, 3) == 0) ?  3 : 0));
      return NULL;
    }
  }
  if (strncmp(">> ", retStr, 3) == 0) { retStr += 3; } //FIXME
  ret = (PyObject *)PyString_FromString(retStr);
  return ret;
}
Example #16
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);
}
Example #17
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;
}
Example #18
0
bool GlobFit::solve(std::vector<RelationEdge>& vecRelationEdge, RelationEdge::RelationEdgeType currentStage, const std::string& stageName)
{
  // dump data to file for debugging in matlab
  dumpData(vecRelationEdge, stageName);

  size_t nConstraintNum = vecRelationEdge.size();
  std::string optimization;
  if (currentStage < RelationEdge::RET_COAXIAL) {
    optimization = "OptimizeNormal";
    std::cout << "Optimize Normal..." << std::endl;
  } else if (currentStage < RelationEdge::RET_COPLANAR) {
    optimization = "OptimizePoint";
    std::cout << "Optimize Point..." << std::endl;
  } else if (currentStage < RelationEdge::RET_EQUAL_RADIUS) {
    optimization = "OptimizeDistance";
    std::cout << "Optimize Distance..." << std::endl;
  } else {
    optimization = "OptimizeRadius";
    std::cout << "Optimize Radius..." << std::endl;
  }

  if (nConstraintNum == 0)
  {
    std::cout << "Empty constraint set." << std::endl;
    return true;
  }

  size_t numPrimitives = _vecPrimitive.size();
  mxArray* inputParameters = mxCreateDoubleMatrix(numPrimitives, Primitive::getNumParameter(), mxREAL);
  double* pInputParameters = mxGetPr(inputParameters);
  for (size_t i = 0; i < numPrimitives; ++i) {
    Primitive* pPrimitive = _vecPrimitive[i];
    pPrimitive->prepareParameters();
    for (size_t j = 0; j < Primitive::getNumParameter(); ++ j) {
      pInputParameters[j*numPrimitives+i] = pPrimitive->getParameter(j);
    }
  }
  engPutVariable(matlabEngine, "inputParameters", inputParameters);

  mxArray* constraints = mxCreateNumericMatrix(nConstraintNum, RelationEdge::getNumParameter(), mxINT32_CLASS, mxREAL);
  int* pConstraints = (int*)mxGetData(constraints);
  for (size_t i = 0; i < nConstraintNum; ++i) {
    vecRelationEdge[i].dumpData(pConstraints, nConstraintNum, i);
  }
  engPutVariable(matlabEngine, "constraints", constraints);

  std::string path = boost::filesystem::current_path().string();
  path = "cd "+path+"/matlab;";
  engEvalString(matlabEngine, path.c_str());

  size_t szOutputBuffer = 65536;
  char* matlabOutputBuffer = new char[szOutputBuffer];
  engOutputBuffer(matlabEngine, matlabOutputBuffer, szOutputBuffer);

  std::string output = "[outputParameters, initialFittingError, exitFittingError, exitFlag]";
  std::string input = "(inputParameters, maxIterNum, numVertices, primitiveType, coordX, coordY, coordZ, normalX, normalY, normalZ, confVertices, constraints);";

  std::string command = output+"="+optimization+input;
  engEvalString(matlabEngine, command.c_str());

  matlabOutputBuffer[szOutputBuffer - 1] = '\0';
  printf("%s\n", matlabOutputBuffer);
  engOutputBuffer(matlabEngine, NULL, 0);
  delete[] matlabOutputBuffer;

  mxArray* outputParameters = engGetVariable(matlabEngine, "outputParameters");
  double *pOutputParameters = mxGetPr(outputParameters);
  mxArray* initialFittingError = engGetVariable(matlabEngine, "initialFittingError");
  double *pInitialFittingError = mxGetPr(initialFittingError);
  mxArray* exitFittingError = engGetVariable(matlabEngine, "exitFittingError");
  double *pExitFittingError = mxGetPr(exitFittingError);
  mxArray* exitFlag = engGetVariable(matlabEngine, "exitFlag");
  double *pExitFlag = mxGetPr(exitFlag);

  bool bValidOptimization = (*pExitFlag >= 0);
  // posterior check: consider invalid if fitting error increased too much
  // however, if the threshold is very big, the fitting error may increase a lot
  // so, be careful with this
  bValidOptimization &= (*pExitFittingError < 10*(*pInitialFittingError));
  if (!bValidOptimization) {
    mxDestroyArray(constraints);
    mxDestroyArray(inputParameters);
    mxDestroyArray(outputParameters);
    mxDestroyArray(initialFittingError);
    mxDestroyArray(exitFittingError);
    mxDestroyArray(exitFlag);

    std::cout << "No feasible solution found." << std::endl;
    return false;
  }

  // update primitives
  for (size_t i = 0; i < numPrimitives; ++ i) {
    Primitive* pPrimitive = _vecPrimitive[i];
    for (size_t j = 0; j < Primitive::getNumParameter(); ++ j) {
      pPrimitive->setParameter(j, pOutputParameters[j*numPrimitives+i]);
    }
    pPrimitive->applyParameters();
  }

  // destroy matrix
  mxDestroyArray(constraints);
  mxDestroyArray(inputParameters);
  mxDestroyArray(outputParameters);
  mxDestroyArray(initialFittingError);
  mxDestroyArray(exitFittingError);
  mxDestroyArray(exitFlag);

  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;
	}