Example #1
0
SparseVectors::SparseVectors(const int* pI, const int* pJ, const REAL* pS, int iN,int d0) :
  Points(), N(iN), current(0), I(pI), J(pJ), S(pS), may_delete(false) {
 
  //Step 1: Allocate space for all sparse vectors (indices and distances)
  mexPrintf("N = %i, d0 = %i\n", N, d0);
  mexEvalString("drawnow");
  std::vector<SVInfo>* VsIn = new vector<SVInfo>[N];
  SVInfo info;
  for (int row = 0; row < d0; row++) {
	info.idx = J[row];
	info.val = S[row];
	VsIn[I[row]].push_back(info); //NOTE: Expecting 0-indexing
	mexPrintf("row %i of %i\n", row, d0);
	mexEvalString("drawnow");
  }
  //Step 2: Sort the sparse elements in each vector in ascending order of index
  for (int i = 0; i < N; i++) {
  	sort(VsIn[i].begin(), VsIn[i].end(), SVInfo_DistComparator());
  }
  //Step 3: Copy over sparse vectors from the vector object to C arrays
  for(int i = 0; i < N; i++) {
  	mexPrintf("Point %i of %i\n", i, N);
  	mexEvalString("drawnow");
  	SparseVector* s = new SparseVector(&VsIn[i]);
    vectors.push_back(s);
  }
  
  delete[] VsIn;
}
Example #2
0
int train_callback(mkl_network *net){
	learning_info info;
	char in_message[1024];
	info.MSE = net->MSE;
	info.grad = 0;
	info.time = net->elpased_time;
	info.epoch = net->epoch;
	net_send_info(&info);
	mexPrintf("MSE: %e\tTime: %d\n", net->MSE, net->elpased_time);
	MSE_log[net->epoch - 1] = net->MSE;
	time_log[net->epoch - 1] = net->elpased_time;
	mexEvalString("drawnow;");
	if (utIsInterruptPending()){
		mexPrintf("Cought Ctrl+C. Wait a 5 sec.\n");
		mexEvalString("drawnow;");
		utSetInterruptPending(0);
		return -1;
	}
	if (net_receive_info(in_message)){
		if(!strcmp("{command:stop}", in_message)){
			return -1
		}
	}
	return 0;
}
//Solver Iteration Callback Monitor
int user_exit(int n, int k, struct blockmatrix C, double *a, double dobj, double pobj, double constant_offset, struct constraintmatrix *con, struct blockmatrix X, double *y, struct blockmatrix Z, struct paramstruc params)
{   
    double evaltime;
    
    //Get Execution Time
    end = clock();
    evaltime = ((double)(end-start))/CLOCKS_PER_SEC;
  
    //Check max time
    if(evaltime > maxtime)
        return CSDP_MAX_TIME;

    //Check ctrl-c
    if (utIsInterruptPending()) {
        utSetInterruptPending(false); /* clear Ctrl-C status */
        mexPrintf("\nCtrl-C Detected. Exiting CSDP...\n\n");
        return CSDP_USER_TERMINATION; //terminate
    }

    if(printLevel>1 && citer) {
        //Display heading if % 20 iters
        if(citer==1 || citer % 20 == 0)
            mexPrintf("Iter    Time    PP Objective      DD Objective\n");
            
        //Display parameters
        mexPrintf("%-3d   %6.2f %16.8e  %16.8e\n",citer,evaltime,pobj,dobj);
        mexEvalString("drawnow;"); //flush draw buffer
    }
    citer++;
    //Return ok
    return(0);
}
void insertGrid(vector<double> x_mm_list,
                                  vector<double> y_mm_list,
                                  vector<double> tilt_degrees_list,
                                  vector<double> rotation_degrees_list,
								  vector<double> hole_radius_list,
                                  CComPtr<IModelDoc2> swModel,
                                  CComPtr<IModelDocExtension> swModelDocExt,
                                  CComPtr<IFeatureManager> swFeatureManager,
                                  CComPtr<ISketchManager> swSketchManager) {

        int n = x_mm_list.size();

        for(int hole_number = 1; hole_number<=n; hole_number++) {

                double x_mm = x_mm_list[hole_number-1];
                double y_mm = y_mm_list[hole_number-1];
				double r_mm = hole_radius_list[hole_number-1];

                double tilt_degrees             = tilt_degrees_list[hole_number-1];
                double rotation_degrees = rotation_degrees_list[hole_number-1];

                // Display Grid Info
				mexPrintf("Punching hole %d / %d at position [%.2f, %.2f], rotation: %.2f, tilt = %.2f \n",
					hole_number,n,x_mm,y_mm, rotation_degrees,tilt_degrees);
				mexEvalString("drawnow;");
					
            insertIndividualGridHole(hole_number, x_mm, y_mm, tilt_degrees, rotation_degrees,r_mm,
                        swModel, swModelDocExt, swFeatureManager, swSketchManager);

        }

}
Example #5
0
void moveUnits(FILE * fid, unsigned char source, unsigned char target)
{
 unsigned long timeStamp;
 short packetID;
 int count;
 unsigned char unit;

 count = 0;
 while (fread(&timeStamp, 4, 1, fid)>0)
 {
   fread(&packetID, 2, 1, fid);
   fread(&unit,1,1,fid);

   if (unit == source)
   {
     fseek(fid,-1,SEEK_CUR);

     fwrite(&target,1,1,fid);
     count++;
   }

   fseek(fid,packetSize-7,SEEK_CUR);
 }

 mexPrintf("All waveforms (%i) from code %i moved to code %i\n",count,source, target);
 mexEvalString("drawnow;");
}
Example #6
0
File: scs.c Project: tkelman/scs
static void printInitHeader(Data * d, Work * w, Cone * k) {
	idxint i;
	char * coneStr = getConeHeader(k);
	char * linSysMethod = getLinSysMethod(d, w->p);
	_lineLen_ = -1;
	for (i = 0; i < HEADER_LEN; ++i) {
		_lineLen_ += (idxint) strlen(HEADER[i]) + 1;
	}
	for (i = 0; i < _lineLen_; ++i) {
		scs_printf("-");
	}
	scs_printf("\n\tSCS v%s - Splitting Conic Solver\n\t(c) Brendan O'Donoghue, Stanford University, 2012\n",
			SCS_VERSION);
	for (i = 0; i < _lineLen_; ++i) {
		scs_printf("-");
	}
    scs_printf("\n");
	if (linSysMethod) {
		scs_printf("Lin-sys: %s\n", linSysMethod);
		scs_free(linSysMethod);
	}
	if (d->NORMALIZE) {
		scs_printf("EPS = %.2e, ALPHA = %.2f, MAX_ITERS = %i, NORMALIZE = %i, SCALE = %2.2f\n", d->EPS, d->ALPHA,
				(int) d->MAX_ITERS, (int) d->NORMALIZE, d->SCALE);
	} else {
		scs_printf("EPS = %.2e, ALPHA = %.2f, MAX_ITERS = %i, NORMALIZE = %i\n", d->EPS, d->ALPHA, (int) d->MAX_ITERS,
				(int) d->NORMALIZE);
	}
	scs_printf("Variables n = %i, constraints m = %i\n", (int) d->n, (int) d->m);
	scs_printf("%s", coneStr);
	scs_free(coneStr);
#ifdef MATLAB_MEX_FILE
	mexEvalString("drawnow;");
#endif
}
Example #7
0
void pushSparseMatrix(CvSparseMat *tcm, char* matName)
{
	int nzCnt = 0;
	CvSparseMatIterator it;
	for(CvSparseNode *node = cvInitSparseMatIterator(tcm, &it); node != 0; node = cvGetNextSparseNode( &it))
	{
		nzCnt++;
	}
	double *mData = new double[3 * nzCnt];
	int ii=0;
	for(CvSparseNode *node = cvInitSparseMatIterator( tcm, &it );
		node != 0; node = cvGetNextSparseNode( &it )) 
	{
		int* idx = CV_NODE_IDX(tcm,node); 
		float val = ((float*)cvPtrND(tcm, idx))[0]; 

		mData[ii*3 + 0] = idx[0];
		mData[ii*3 + 1] = idx[1];
		mData[ii*3 + 2] = val;
		ii++;
	}
	mexPrintf("%s nzCnt: %d\n", matName, ii);
	mxArray *mArray = mxCreateDoubleMatrix(3, nzCnt, mxREAL);
	memcpy((void*)mxGetPr(mArray), (void*)mData, sizeof(double)*3*nzCnt);
	mexPutVariable("caller", "consMat", mArray);
	int pixCnt = tcm->size[0];
	char buffer[512];
	//_SS_ sprintf_s(buffer,"%s = sparse(consMat(1,:)+1,consMat(2,:)+1,consMat(3,:),%d,%d);", matName, pixCnt,pixCnt);
	sprintf(buffer,"%s = sparse(consMat(1,:)+1,consMat(2,:)+1,consMat(3,:),%d,%d);", matName, pixCnt,pixCnt);
	mexEvalString(buffer);
	delete [] mData;
	mxDestroyArray(mArray);	
}
Example #8
0
double iterfcn(int n, int s, int iter, int gbest, struct swarm *pop)
{
    bool stop = false;
    int stat;
    double ret = 1.0;
    double evaltime;
    
    //Get Execution Time
    end = clock();
    evaltime = ((double)(end-start))/CLOCKS_PER_SEC;
    
    //Iteration Printing
    if(printLevel > 1 && iter > 0) {      
        if(iter == 10 || !(iter%100))
            mexPrintf(" iter      feval     time[s]   leader     objective\n");
        
        mexPrintf("%5d     %5d     %5.2f      %5d  %12.5g\n",iter,noFeval,evaltime,gbest,pop->fy[gbest]);       
        mexEvalString("drawnow;"); //flush draw buffer        
    }
    
    //Check for Ctrl-C
    if (utIsInterruptPending()) {
        utSetInterruptPending(false); /* clear Ctrl-C status */
        mexPrintf("\nCtrl-C Detected. Exiting PSwarm...\n\n");
        ret = -1.0;
        ctrlCExit = true;
    }
    
    //Iteration Callback
    if(iterF.enabled && iter > 0)
    {
        iterF.plhs[0] = NULL;
        memcpy(mxGetData(iterF.prhs[1]), &iter, sizeof(int));
        memcpy(mxGetPr(iterF.prhs[2]), &pop->fy[gbest], sizeof(double));
        memcpy(mxGetPr(iterF.prhs[3]), &pop->y[gbest*n], n * sizeof(double));
        stat = mexCallMATLAB(1, iterF.plhs, 4, iterF.prhs, iterF.f);
        if(stat)
            mexErrMsgTxt("Error calling Callback Function!");

        //Collect return argument
        stop = *(bool*)mxGetData(iterF.plhs[0]);
        if(stop) 
        {   
            ctrlCExit = true;
            mexPrintf("\nIterFun Called Stop. Exiting PSwarm...\n\n");
            ret = -1;
        }
        // Clean up Ptr
        mxDestroyArray(iterF.plhs[0]);
    }
    
    //Check for maxtime expiry    
    if(evaltime > maxtime)
    {
        mexPrintf("\nMaximum Solver Time Exceeded. Exiting PSwarm...\n\n");
        ret = -1.0;
    }   
    
    return ret;
}
Example #9
0
File: ecos.c Project: mercelik/ecos
void printProgress(stats* info)
{
	if( info->iter == 0 )
	{
		/* print header at very first iteration */		
#if PRINTLEVEL == 2
		PRINTTEXT("\nECOS %s - (c) A. Domahidi, ETH Zurich & embotech 2012-14. Support: [email protected]\n\n", ECOS_VERSION);
#endif
#if defined _WIN32 || defined _WIN64		
		PRINTTEXT("It     pcost       dcost      gap   pres   dres    k/t    mu     step    IR\n");
		PRINTTEXT("%2d  %+5.3e  %+5.3e  %+2.0e  %2.0e  %2.0e  %2.0e  %2.0e   N/A    %d %d -\n",(int)info->iter, info->pcost, info->dcost, info->gap, info->pres, info->dres, info->kapovert, info->mu, (int)info->nitref1, (int)info->nitref2);
#else
		PRINTTEXT("It     pcost         dcost      gap     pres    dres     k/t     mu      step     IR\n");
		PRINTTEXT("%2d  %c%+5.3e  %c%+5.3e  %c%+2.0e  %c%2.0e  %c%2.0e  %c%2.0e  %c%2.0e    N/A     %d %d -\n",(int)info->iter, 32, info->pcost, 32, info->dcost, 32, info->gap, 32, info->pres, 32, info->dres, 32, info->kapovert, 32, info->mu, (int)info->nitref1, (int)info->nitref2);
#endif	
	}  else {
#if defined _WIN32 || defined _WIN64
		PRINTTEXT("%2d  %+5.3e  %+5.3e  %+2.0e  %2.0e  %2.0e  %2.0e  %2.0e  %6.4f  %d %d %d\n",(int)info->iter, info->pcost, info->dcost, info->gap, info->pres, info->dres, info->kapovert, info->mu, info->step, (int)info->nitref1, (int)info->nitref2, (int)info->nitref3);
#else
		PRINTTEXT("%2d  %c%+5.3e%c  %+5.3e %c %+2.0e%c  %2.0e%c  %2.0e%c  %2.0e%c  %2.0e%c  %6.4f   %d %d %d\n",(int)info->iter, 32,info->pcost, 32,info->dcost, 32, info->gap, 32, info->pres, 32, info->dres, 32, info->kapovert, 32, info->mu, 32, info->step, (int)info->nitref1, (int)info->nitref2, (int)info->nitref3);
#endif
	}

/* enable to flush printf in Matlab immediately */
#ifdef MATLAB_MEX_FILE
#if defined MATLAB_FLUSH_PRINTS
    mexEvalString("pause(0.0001);");
#endif
#endif
 
    
}
  /* Function: mdlStart =======================================================
   * Abstract:
   *    This function is called once at start of model execution. If you
   *    have states that should be initialized once, this is the place
   *    to do it.
   */
  static void mdlStart(SimStruct *S)
  {
	   //Initialize the states before Init method is called
	  real_T *x2 = ssGetRealDiscStates(S);

		x2[0] = u_fps;
		x2[1] = v_fps;
		x2[2] = w_fps;
		x2[3] = p_radsec;
		x2[4] = q_radsec;
		x2[5] = r_radsec;
		x2[6] = h_sl_ft;
		x2[7] = long_gc_deg;
		x2[8] = lat_gc_deg;
		x2[9] = phi_rad;
		x2[10] = theta_rad;
		x2[11] = psi_rad;
		//x[12] = alpha_rad;
		//x[13] = beta_rad;
		
		/* 8/25/10 Code added to support FlightViz visualization */
		mexEvalString("do_flightvue");
		
	char v_buf[128];
	mwSize v_buflen;
	v_buflen = mxGetNumberOfElements(verbosity) + 1;
	mxGetString(verbosity, v_buf, v_buflen);//v_buf contains the verbosity char string
	int is_debug = strcmp(v_buf,"debug");
	if(is_debug == 0){ 
		mexPrintf("\nMDL Start.\n");
	}
  }
Example #11
0
  void MatlabJournal::PrintfImpl (EJournalCategory category, 
				  EJournalLevel level, const char* pformat, 
				  va_list ap) {
    const int maxStrLen = 1024;
    char      s[maxStrLen];
#ifdef HAVE_VSNPRINTF
# ifdef HAVE_VA_COPY
    va_list apcopy;
    va_copy(apcopy, ap);
    if (vsnprintf(s,maxStrLen,pformat,apcopy) >= maxStrLen)
      throw MatlabException("String buffer it too short for all the characters to be printed to MATLAB console");
    va_end(apcopy);
# else
    if (vsnprintf(s,maxStrLen,pformat,ap) >= maxStrLen)
      throw MatlabException("String buffer it too short for all the characters to be printed to MATLAB console");
# endif
#else
# ifdef HAVE__VSNPRINTF
#  ifdef HAVE_VA_COPY
    va_list apcopy;
    va_copy(apcopy, ap);
    if (_vsnprintf(s,maxStrLen,pformat,apcopy) >= maxStrLen)
      throw MatlabException("String buffer it too short for all the characters to be printed to MATLAB console");
    va_end(apcopy);
#  else
    if (_vsnprintf(s,maxStrLen,pformat,ap) >= maxStrLen)
      throw MatlabException("String buffer it too short for all the characters to be printed to MATLAB console");
#  endif
# else
    vsprintf(s,pformat,ap);
# endif
#endif
    mexPrintf(s);
    mexEvalString("drawnow;"); //flush draw buffer
  }
Example #12
0
void printProgress(stats* info)
{
	if( info->iter == 0 )
	{
		/* print header at very first iteration */		
#if PRINTLEVEL == 2
		PRINTTEXT("\nECOS - (c) A. Domahidi, Automatic Control Laboratory, ETH Zurich, 2012-13.\n\n");		
#endif
		PRINTTEXT("It     pcost         dcost      gap     pres    dres     k/t     mu     step    IR\n");
#if defined WIN32 || defined _WIN64		
		PRINTTEXT("%2d  %+5.3e  %+5.3e  %+2.0e  %2.0e  %2.0e  %2.0e  %2.0e   N/A    %d %d -\n",(int)info->iter, info->pcost, info->dcost, info->gap, info->pres, info->dres, info->kapovert, info->mu, (int)info->nitref1, (int)info->nitref2);
#else
		PRINTTEXT("%2d  %c%+5.3e  %c%+5.3e  %c%+2.0e  %c%2.0e  %c%2.0e  %c%2.0e  %c%2.0e   N/A    %d %d -\n",(int)info->iter, 32, info->pcost, 32, info->dcost, 32, info->gap, 32, info->pres, 32, info->dres, 32, info->kapovert, 32, info->mu, (int)info->nitref1, (int)info->nitref2);
#endif	
	}  else {
#if defined WIN32 || defined _WIN64
		PRINTTEXT("%2d  %+5.3e  %+5.3e  %+2.0e  %2.0e  %2.0e  %2.0e  %2.0e  %6.4f  %d %d %d\n",(int)info->iter, info->pcost, info->dcost, info->gap, info->pres, info->dres, info->kapovert, info->mu, info->step, (int)info->nitref1, (int)info->nitref2, (int)info->nitref3);
#else
		PRINTTEXT("%2d  %c%+5.3e%c  %+5.3e %c %+2.0e%c  %2.0e%c  %2.0e%c  %2.0e%c  %2.0e  %6.4f  %d %d %d\n",(int)info->iter, 32,info->pcost, 32,info->dcost, 32, info->gap, 32, info->pres, 32, info->dres, 32, info->kapovert, 32, info->mu, info->step, (int)info->nitref1, (int)info->nitref2, (int)info->nitref3);
#endif
	}

/* enable to flush printf in Matlab immediately */
#if PRINTLEVEL > 0
#ifdef MATLAB_MEX_FILE
#if defined MATLAB_FLUSH_PRINTS
    mexEvalString("drawnow;");
#endif
#endif
#endif
 
    
}
void BraidInPlace<T>::run(size_t NThreadsRequested) {

#ifndef BRAIDLAB_NOTHREADING
  // restrict the number of threads if there are fewer jobs than available
  // threads
  NThreadsRequested = NThreadsRequested > Nloops ? Nloops : NThreadsRequested;
#else
  NThreadsRequested = 1;
#endif
  if ( NThreadsRequested == 0 ) {
    mexErrMsgIdAndTxt("BRAIDLAB:braid:colorbraiding:numthreadsnotpositive",
                      "Number of threads requested must be positive");
  }

  // unthreaded version
  if (NThreadsRequested == 1) {
    if (2 <= BRAIDLAB_debuglvl)  {
      printf("loopsigma_helper: multiplication running UNTHREADED.\n" );
      mexEvalString("pause(0.001);"); //flush
    }
    for (mwIndex l = 0; l < Nloops; ++l) {
      applyToLoop(l);
    }
  }
#ifndef BRAIDLAB_NOTHREADING
  else {   // threaded version
    if (2 <= BRAIDLAB_debuglvl)  {
      printf("loopsigma_helper: multiplication running THREADED (%d threads).\n",
             NThreadsRequested);
      mexEvalString("pause(0.001);"); //flush
    }
    // scheduler for threads
    ThreadPool pool(NThreadsRequested); // (c) Jakob Progsch

    // std::bind creates a function reference to a member function
    // needed here b/c passing references to member functions
    // requires explicit object to be referred
    auto funApplyToLoop = std::bind(&BraidInPlace<T>::applyToLoop,
                                    this, std::placeholders::_1);

    for (mwIndex l = 0; l < Nloops; ++l) {
      pool.enqueue( funApplyToLoop, l);
    }
  }
#endif
}
Example #14
0
int igl::mexStream::overflow(int c) 
{
    if (c != EOF) {
      mexPrintf("%.1s",&c);
      mexEvalString("drawnow;"); // to dump string.
    }
    return 1;
}
// TT dispatcher handler -- called at the Time-Triggered slot boundaries
double ttDispatcherCodeFcn(int segment, void *data) {

	char buf[200];
	Task *task, *next;
	UserTask *userTask;
	TimeTriggeredDispatcher *dispatcher = (TimeTriggeredDispatcher*) data;
	int slotIndex=((int)((float)(rtsys->time/dispatcher->slotLength)) % dispatcher->schedulingTable.size());

	// Remove all tasks from readyQ belonging to TTDispatcher and move to tmpQ
	task = (Task*) rtsys->readyQs[dispatcher->affinity]->getFirst();
	while (task != NULL)
	{
		next = (Task*) task->getNext();
		if (task->isUserTask())
		{
			userTask = (UserTask*) task;
			if (userTask->ttdisp == dispatcher)
			{
				task->moveToList(dispatcher->tmpQ);
			}
		}
		task = next;
	}

	if (dispatcher->schedulingTable[slotIndex] > 0)
	{
		// Select the task to execute
		bool taskMoved = false;
		task = (Task*) dispatcher->tmpQ->getFirst();
		while (task != NULL)
		{
			next = (Task*) task->getNext();
			userTask = (UserTask*) task;
			// Select one of the tasks to execute
			if (userTask->taskIdentifier == dispatcher->schedulingTable[slotIndex])		// Current slot is for selected task
			{
				userTask->moveToList(rtsys->readyQs[dispatcher->affinity]);
				taskMoved = true;
				//OUT("Task %s moved to readyQ\n", userTask->name);
				break;
			}
			task = next;
		}
		// If job is not yet released, notify user
		if (!taskMoved)
		{
			sprintf(buf, "disp(\'@time %f: TTDispatcher Info: Task with identifier %d is not ready to execute\')", rtsys->time, dispatcher->schedulingTable[slotIndex]);
			mexEvalString(buf);
		}
	}

	// Schedule dispatcher timer for next slot
	dispatcher->slotTimer->time = rtsys->time + dispatcher->slotLength;
	dispatcher->slotTimer->moveToList(rtsys->timeQ);

	return FINISHED;
}
Example #16
0
static void mdlStart(SimStruct *S)
{
    char    string_aux[255];                // auxiliar string
    char    serial_port_path[255];          // auxiliar string
    char my_port[255];
    int baud_rate;
    comm_settings comm_settings_t;
  
    ssPrintf("qbmove simulink library version: %s\n", QBMOVE_SIMULINK_VERSION);

    //======================================================     opening serial port

    for (int i = 0; param_com_port(i); ++i)
        serial_port_path[i] = (char) param_com_port(i);    

    switch(param_com_baudrate){
        case 1:
            baud_rate = BAUD_RATE_2000000;
            break;
        case 2:
            baud_rate = BAUD_RATE_460800;
            break;
        case 3:
            baud_rate = BAUD_RATE_115200;
            break;
        case 4:
            baud_rate = BAUD_RATE_57600;
            break;
    }
    
    #if defined(_WIN32) || defined(_WIN64)
        sprintf(my_port, "\\\\.\\%s", serial_port_path);
    #else
        strcpy(my_port, serial_port_path);
    #endif
    
    openRS485(&comm_settings_t, my_port, baud_rate);
    
    pwork_handle = comm_settings_t.file_handle;

    #if defined(_WIN32) || defined(_WIN64)
        if(pwork_handle == INVALID_HANDLE_VALUE)
    #else
        if(pwork_handle == -1)
    #endif
    {
        ssPrintf("Check your COM port. \nCould not connect to %s\n", serial_port_path);
        out_handle = &pwork_handle;

        // Stop simulation
        mexEvalString("set_param(bdroot, 'SimulationCommand', 'stop')");

        return;
    }

    out_handle = &pwork_handle;
}
Example #17
0
File: scs.c Project: tkelman/scs
static void printFooter(Data * d, Work * w, Info * info) {
	idxint i;
	char * linSysStr = getLinSysSummary(w->p, info);
	char * coneStr = getConeSummary(info);
	for (i = 0; i < _lineLen_; ++i) {
		scs_printf("-");
	}
	scs_printf("\nStatus: %s\n", info->status);
	if (info->iter == d->MAX_ITERS) {
		scs_printf("Hit MAX_ITERS, solution may be inaccurate\n");
	}
	scs_printf("Timing: Total solve time: %1.2es\n", info->solveTime / 1e3);

	if (linSysStr) {
		scs_printf("%s", linSysStr);
		scs_free(linSysStr);
	}
	if (coneStr) {
		scs_printf("%s", coneStr);
		scs_free(coneStr);
	}

	for (i = 0; i < _lineLen_; ++i) {
		scs_printf("-");
	}
	scs_printf("\n");

	if (info->statusVal == INFEASIBLE) {
		scs_printf("Certificate of primal infeasibility:\n");
		scs_printf("|A'y|_2 * |b|_2 = %.4e\n", info->resDual);
		scs_printf("dist(y, K*) = 0\n");
		scs_printf("b'y = %.4f\n", info->dobj);
	} else if (info->statusVal == UNBOUNDED) {
		scs_printf("Certificate of dual infeasibility:\n");
		scs_printf("|Ax + s|_2 * |c|_2 = %.4e\n", info->resPri);
		scs_printf("dist(s, K) = 0\n");
		scs_printf("c'x = %.4f\n", info->pobj);
	} else {
		scs_printf("Error metrics:\n");
		scs_printf("|Ax + s - b|_2 / (1 + |b|_2) = %.4e\n", info->resPri);
		scs_printf("|A'y + c|_2 / (1 + |c|_2) = %.4e\n", info->resDual);
		scs_printf("|c'x + b'y| / (1 + |c'x| + |b'y|) = %.4e\n", info->relGap);
		scs_printf("dist(s, K) = 0, dist(y, K*) = 0, s'y = 0\n");
		for (i = 0; i < _lineLen_; ++i) {
			scs_printf("-");
		}
		scs_printf("\n");
		scs_printf("c'x = %.4f, -b'y = %.4f\n", info->pobj, info->dobj);
	}
	for (i = 0; i < _lineLen_; ++i) {
		scs_printf("=");
	}
	scs_printf("\n");
#ifdef MATLAB_MEX_FILE
	mexEvalString("drawnow;");
#endif
}
Example #18
0
static boolean_T   setSignalNames(char* blockHandle)
{
        short i;
        char buffer [120];

        for(i=0;i<numberOfInputs;i++)
        {
                sprintf (buffer, "set_input_signal_name('%s',%d,'%s');",blockHandle,i+1,inputSignals[i]);
                mexEvalString(buffer);
        }

        for(i=0;i<numberOfOutputs;i++)
        {
                sprintf (buffer, "set_output_signal_name('%s',%d,'%s');",blockHandle,i+1,outputSignals[i]);
                mexEvalString(buffer);
        }

        return true;
}
Example #19
0
void thresholdSpikes(FILE * fid, int threshold, unsigned char target, int lowThresh)
{
 unsigned long timeStamp;
 short packetID;
 int count;
 unsigned char unit;
 unsigned char unit2;
 short * waveform;
 int exceeds;
 int i;

 waveform = (short *)mxCalloc(numSamples,sizeof(short));

 count = 0;
 while (fread(&timeStamp, 4, 1, fid)>0)
 {
   fread(&packetID, 2, 1, fid);
   fread(&unit,1,1,fid);

   fseek(fid,1,SEEK_CUR);

   fread(waveform,bytesPerSample,numSamples,fid);
   exceeds = 0;

   for (i = 0; i < numSamples; i++)
   {
     if (waveform[i] > threshold || waveform[i] < -threshold)
       exceeds = 1;
   }

   if (!lowThresh)
     exceeds = 1 - exceeds;

   if (exceeds)
   {
     if (packetID < 129)
     {
       fseek(fid,-(int)packetSize+6,SEEK_CUR);
       fwrite(&target,1,1,fid);
       fseek(fid,packetSize-7,SEEK_CUR);
       count++;
     }
   }
 }

 mexPrintf("%i waveforms written as sort code %i\n",count,target);
 mexEvalString("drawnow;");

 mxFree(waveform);
}
Example #20
0
File: scs.c Project: tkelman/scs
static void printSummary(idxint i, struct residuals *r, timer * solveTimer) {
	scs_printf("%*i|", (int) strlen(HEADER[0]), (int) i);
	scs_printf("%*.2e ", (int) HSPACE, r->resPri);
	scs_printf("%*.2e ", (int) HSPACE, r->resDual);
	scs_printf("%*.2e ", (int) HSPACE, r->relGap);
	scs_printf("%*.2e ", (int) HSPACE, r->cTx);
	scs_printf("%*.2e ", (int) HSPACE, -r->bTy);
	scs_printf("%*.2e ", (int) HSPACE, r->kap / r->tau);
	scs_printf("%*.2e ", (int) HSPACE, tocq(solveTimer) / 1e3);
	scs_printf("\n");
#ifdef MATLAB_MEX_FILE
	mexEvalString("drawnow;");
#endif
}
Example #21
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{  
  // Check inputs to mex function
  if (nlhs != 1 || nrhs < 2 || nrhs > 3) {
    mexEvalString("help cv.medianFilter");
    mexErrMsgIdAndTxt ( "medianFilter:usage", "Incorrect number of inputs/outputs provided." );
  }


  // Parse input
  const mxArray*              image         = prhs[0];
  const mxArray*              mask          = prhs[1];
  const mxArray*              selection     = nrhs > 2 ? prhs[2] : 0;

  if (mxGetNumberOfDimensions(image) != 2)
    mexErrMsgIdAndTxt("medianFilter:image", "Only 2D images are supported for now.");
  if (mxIsComplex(image))
    mexErrMsgIdAndTxt("medianFilter:image", "Only real valued images are supported for now.");

  if (!mxIsLogical(mask))
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must be boolean.");
  if (mxGetM(mask) % 2 == 0)
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must have an odd number of rows.");
  if (mxGetN(mask) % 2 == 0)
    mexErrMsgIdAndTxt("medianFilter:mask", "mask must have an odd number of columns.");

  const bool*                 isSelected    = 0;
  if (selection) {
    if (!mxIsLogical(selection))
      mexErrMsgIdAndTxt("weightedSumFilter:selection", "selection must be a logical matrix.");
    if (mxGetNumberOfElements(selection) != mxGetNumberOfElements(image))
      mexErrMsgIdAndTxt("weightedSumFilter:selection", "selection must have the same number of elements as image.");
    isSelected                = (const bool*) mxGetData(selection);
  }


  //---------------------------------------------------------------------------

  // Create output structure
  mxArray*                    filtered      = mxCreateNumericArray( mxGetNumberOfDimensions(image)
                                                                  , mxGetDimensions(image)
                                                                  , mxGetClassID(image)
                                                                  , mxREAL
                                                                  );
  plhs[0]                     = filtered;

  // Create filter class and process
  applyFilter<MedianFilter2D>(image, mxGetData(filtered), isSelected, mask);
}
Example #22
0
void receive_poll(PtTimestamp ts, void *userData)
{
  int count, command;
  PmEvent event;
  
  if (inStream==NULL)
    return;
  
  if (Pm_Poll(inStream)!=TRUE)
    return;
  
  while ((count = Pm_Read(inStream, &event, 1))) {
    if (count == 1) {
      
      /* there seems to be a constant stream of MIDI events, not all of which are interesting */
      /* the status has the command in the highest 4 bits and the channel in the lowest 4 bits */
      command = Pm_MessageStatus(event.message) & MIDI_CODE_MASK;
      if ((command == MIDI_ON_NOTE)         ||
              (command == MIDI_OFF_NOTE )   ||
              (command == MIDI_CH_PROGRAM ) ||
              (command == MIDI_CTRL)        ||
              (command == MIDI_POLY_TOUCH ) ||
              (command == MIDI_TOUCH )      ||
              (command == MIDI_BEND )) {
        
        MUTEX_LOCK;
        channel   [numReceived] = (Pm_MessageStatus(event.message) & MIDI_CHN_MASK);
        note      [numReceived] = Pm_MessageData1(event.message);
        velocity  [numReceived] = Pm_MessageData2(event.message);
        timestamp [numReceived] = event.timestamp;
        
        if (verbose) {
          mexPrintf("channel = %2d, note = %3d, velocity = %3d, timestamp = %d\n", channel[numReceived], note[numReceived], velocity[numReceived], timestamp[numReceived]);
          mexEvalString("try, drawnow limitrate nocallbacks; end");
        }
        
        if (numReceived==INPUT_BUFFER_SIZE)
          mexWarnMsgTxt("midi buffer overrun");
        else
          numReceived++;
        
        MUTEX_UNLOCK;
      }
    }
    else
      mexWarnMsgTxt(Pm_GetErrorText(count));
  }
}
Example #23
0
//Solver Iteration Callback Monitor
static int DSDPMonitor(DSDP dsdp, void* dummy)
{
    int    iter;
    double pobj,dobj,pstp=0,dstp,mu,res,pnorm,pinfeas;
    double evaltime;
    
    //Get Execution Time
    end = clock();
    evaltime = ((double)(end-start))/CLOCKS_PER_SEC;
  
    //Check max time
    if(evaltime > maxtime)
        return DSDP_MAX_TIME;

    //Check ctrl-c
    if (utIsInterruptPending()) {
        utSetInterruptPending(false); /* clear Ctrl-C status */
        mexPrintf("\nCtrl-C Detected. Exiting DSDP...\n\n");
        return DSDP_USER_TERMINATION; //terminate
    }

    if(printLevel>1) {
        DSDPGetIts(dsdp,&iter);
        DSDPGetDDObjective(dsdp,&dobj);
    	DSDPGetPPObjective(dsdp,&pobj);
    	DSDPGetR(dsdp,&res);
    	DSDPGetPInfeasibility(dsdp,&pinfeas);
    	DSDPGetStepLengths(dsdp,&pstp,&dstp);
    	DSDPGetBarrierParameter(dsdp,&mu);
    	DSDPGetPnorm(dsdp,&pnorm);
        
        //Display heading if % 20 iters
        if(iter==0 || iter % 20 == 0)
            mexPrintf("Iter   Time[s]   PP Objective      DD Objective     PInfeas   DInfeas     Nu     StepLength   Pnrm\n");
            
        //Display parameters
        mexPrintf("%-3d   %6.2f  %16.8e  %16.8e  %9.1e %9.1e %9.1e",iter,evaltime,pobj,dobj,pinfeas,res,mu);
        mexPrintf("  %4.2f  %4.2f",pstp,dstp);
        if (pnorm>1.0e3)
            mexPrintf("  %1.0e \n",pnorm);
        else
            mexPrintf("  %5.2f \n",pnorm);
        mexEvalString("drawnow;"); //flush draw buffer
    }
    //Return ok
    return(0);
}
Example #24
0
// Assume that xhat and alphahat are initialized with zeros
void decode_patches_oracle(const MatrixXd &D, const MatrixXd &DtY, const MatrixXd &xOracle, const double idx_array[], size_t idx_array_size, MatrixXd &xhat, MatrixXd &alphahat){
  // creating a group_idx array that group indices of patches from the same group
  unsigned int* group_idx = new unsigned int[idx_array_size];
  double* idx = new double[idx_array_size];
  for (unsigned int i =0; i < idx_array_size; i++){
	group_idx[i] = i;
	idx[i] = idx_array[i];
  }
  quicksort(idx, group_idx, idx_array_size);
  // extract patches from the same group and decode them using pga_newton
  unsigned int max_idx = idx[idx_array_size-1];
  unsigned int cur_idx_loc = 0;
  size_t m = D.rows();
  size_t n = D.cols();
  // we skip the indices of the zero patches since their reconstruction is zero 
  for (; (unsigned int)idx[cur_idx_loc] == 0; cur_idx_loc++); 
  for (unsigned int cur_idx = 1; cur_idx <= max_idx; cur_idx++){
	unsigned int cur_group_size = 0;
	for (unsigned int cur_idx_loc_temp = cur_idx_loc; (unsigned int)idx[cur_idx_loc_temp] == cur_idx; cur_idx_loc_temp++){
	  cur_group_size++;
	}
	MatrixXd DtY_cur(n,cur_group_size);
	MatrixXd xOracle_cur(m,cur_group_size);
	MatrixXd alphahat_cur(n,cur_group_size);
	MatrixXd xhat_cur(m,cur_group_size);
	//extract patches from DtY
	for (unsigned int j=0; j < cur_group_size; j++){
	  DtY_cur.block(0,j,n,1).noalias() = DtY.block(0,group_idx[cur_idx_loc+j],n,1);
	  xOracle_cur.block(0,j,m,1).noalias() = xOracle.block(0,group_idx[cur_idx_loc+j],m,1);
	}
	pga_oracle_newton(D, DtY_cur, xOracle_cur, xhat_cur, alphahat_cur);
	//copy the decoded representation and patch
	for (unsigned int j=0; j < cur_group_size; j++){
	  xhat.block(0,group_idx[cur_idx_loc+j],m,1).noalias() = xhat_cur.block(0,j,m,1);
	  alphahat.block(0,group_idx[cur_idx_loc+j],n,1).noalias() = alphahat_cur.block(0,j,n,1);
	}
	cur_idx_loc = cur_idx_loc + cur_group_size;
	if(cur_idx%100 == 0){
		mexPrintf("PGA processed %u/%u\n", cur_idx, max_idx);
		mexEvalString("drawnow;");
	}
  }
  delete [] group_idx;
  delete [] idx;
}
Example #25
0
void receive_poll(PtTimestamp ts, void *userData)
{
  int count, command;
  unsigned int latest;
  PmEvent event;
  
  if (inStream==NULL)
    return;
  
  if (Pm_Poll(inStream)!=TRUE)
    return;
  
  while ((count = Pm_Read(inStream, &event, 1))) {
    if (count == 1) {
      
      /* there seems to be a constant stream of MIDI events, not all of which are interesting */
      /* the status has the command in the highest 4 bits and the channel in the lowest 4 bits */
      command = Pm_MessageStatus(event.message) & MIDI_CODE_MASK;
      if ((command == MIDI_ON_NOTE)         ||
              (command == MIDI_OFF_NOTE )   ||
              (command == MIDI_CH_PROGRAM ) ||
              (command == MIDI_CTRL)        ||
              (command == MIDI_POLY_TOUCH ) ||
              (command == MIDI_TOUCH )      ||
              (command == MIDI_BEND )) {
        
        /* store the latest event at the end of the ring buffer */
        latest = WRAP(numReceived, INPUT_BUFFER_SIZE);
        numReceived++;
        
        channel   [latest] = (double)(Pm_MessageStatus(event.message) & MIDI_CHN_MASK);
        note      [latest] = (double)Pm_MessageData1(event.message);
        velocity  [latest] = (double)Pm_MessageData2(event.message);
        timestamp [latest] = (double)event.timestamp;
        
        if (verbose) {
          mexPrintf("channel = %2d, note = %3d, velocity = %3d, timestamp = %g\n", (int)channel[latest], (int)note[latest], (int)velocity[latest], timestamp[latest]);
          mexEvalString("try, drawnow limitrate nocallbacks; end");
        }
      }
    }
    else
      mexWarnMsgTxt(Pm_GetErrorText(count));
  }
}
Example #26
0
bool lbfgsb_program::iterCallback (int t, double etime, double* x, double f)
{
    bool stop = false;

    //Check for Ctrl-C
    if (utIsInterruptPending()) {
        utSetInterruptPending(false); /* clear Ctrl-C status */
        mexPrintf("\nCtrl-C Detected. Exiting L-BFGS-B...\n\n");
        return true; //terminate asap
    }

    //Iteration Printing
    if(printLevel > 1) {
        if(t==1 || !(t%10))
            mexPrintf(" iter      feval     time[s]      objective\n");

        mexPrintf("%5d     %5d       %5.2f    %12.5g\n",t,noFevals,etime,f);
        mexEvalString("drawnow;"); //flush draw buffer
    }

    //Iteration Callback
    if(iterF->enabled)
    {
        iterF->plhs[0] = NULL;
        memcpy(mxGetData(iterF->prhs[1]), &t, sizeof(int));
        memcpy(mxGetPr(iterF->prhs[2]), &f, sizeof(double));
        memcpy(mxGetPr(iterF->prhs[3]), x, this->ndec * sizeof(double));
        try {
            mexCallMATLAB(1, iterF->plhs, 4, iterF->prhs, iterF->f);
        }
        catch(...)
        {
            mexWarnMsgTxt("Unrecoverable Error from Iteration Callback, Exiting LBFGSB...\n");
            //Force exit
            return true;
        }

        //Collect return argument
        stop = *(bool*)mxGetData(iterF->plhs[0]);
        // Clean up Ptr
        mxDestroyArray(iterF->plhs[0]);
    }

    return stop;
}
Example #27
0
File: scs.c Project: tkelman/scs
static void printHeader(Data * d, Work * w, Cone * k) {
	idxint i;
    if (d->WARM_START)
        scs_printf("SCS using variable warm-starting\n");
    for (i = 0; i < _lineLen_; ++i) {
        scs_printf("-");
    }
    scs_printf("\n");
    for (i = 0; i < HEADER_LEN - 1; ++i) {
        scs_printf("%s|", HEADER[i]);
    }
    scs_printf("%s\n", HEADER[HEADER_LEN - 1]);
    for (i = 0; i < _lineLen_; ++i) {
        scs_printf("-");
    }
    scs_printf("\n");
#ifdef MATLAB_MEX_FILE
    mexEvalString("drawnow;");
#endif
}
Example #28
0
void fann_save_matrices(struct fann *network, char *fname){
	unsigned int layers;
	unsigned int layer[100];
	unsigned int bias[100];
	unsigned int total_weights;
	unsigned int neuron_inputs;
	unsigned int writes_counter;
	DATA_TYPE weight;
	struct 	fann_connection *connections;
	FILE *array;
	char array_name[255];
	int i, j;
	writes_counter = 0;
	layers = fann_get_num_layers(network);
	fann_get_layer_array(network, layer);
	fann_get_bias_array(network, bias);
	total_weights = fann_get_total_connections(network);
	printf("Total weights: %i\n", total_weights);
	connections = (struct 	fann_connection *)
				malloc(total_weights * sizeof(struct 	fann_connection));
	fann_get_connection_array(network, connections);
	for(i = 1; i < layers; i++){
		sprintf(array_name, "%s_W%i.net", fname, i);
		array = fopen(array_name, "wb");
		for (j = 0; j < layer[i]*(layer[i-1] + 1); j++){
			weight = connections[writes_counter].weight;
#ifdef DEBUG
			mexPrintf("Number:\t%i\n", writes_counter);
			mexPrintf("Weight:\t%e\n", connections[writes_counter].weight);
			mexPrintf("From:\t%i\n", connections[writes_counter].from_neuron);
			mexPrintf("To:\t%i\n", connections[writes_counter].to_neuron);
			mexEvalString("drawnow;");
#endif
			fwrite(&weight, sizeof(DATA_TYPE) , 1, array);
			writes_counter++;
		}
		fclose(array);
	}
	return;
}
Example #29
0
void mexFunction( int nlhs, mxArray *plhs[], 
                  int nrhs, const mxArray*prhs[] ) { 
  if (first) {
    mexPrintf("treeupdate using NUM_THREADS=%u\n",NUM_THREADS);
    mexEvalString("drawnow;");
    first=0;
  }

  if (nrhs != 14) {
      mexErrMsgTxt("Wrong number of arguments. Fail.");
      return;
  }

  if (nlhs != 1) {
      mexErrMsgTxt("Wrong number of outputs. Fail.");
      return;
  }

  if (! mxIsSparse (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Hashxtic must be sparse. Fail.");
    return;
  }

  if (mxIsSparse (OAS_MATRIX_IN)) {      
    mexErrMsgTxt("Oas must be dense. Fail.");
    return;
  }

  if (! mxIsSingle (OAS_MATRIX_IN)) {
    mexErrMsgTxt("Oas must be single. Fail.");
    return;
  }

  if (mxGetM (OAS_MATRIX_IN) != mxGetM (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Hashxtic and oas have incompatible shape. Fail.");
    return;
  }

  if (! mxIsSparse (FILTMAT_MATRIX_IN)) { 
    mexErrMsgTxt("Filtmat must be sparse. Fail.");
    return;
  }

  if (mxGetN (OAS_MATRIX_IN) != mxGetM (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Oas and filtmat have incompatible shape. Fail.");
    return;
  }

  if (! mxIsSparse (EXINDEX_MATRIX_IN)) { 
    mexErrMsgTxt("Exindex must be sparse. Fail.");
    return;
  }

  if (mxGetN (EXINDEX_MATRIX_IN) != mxGetN (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Exindex and filtmat have incompatible shape. Fail.");
    return;
  }
  
  if (! mxIsCell (BIAS_CELL_IN)) {
    mexErrMsgTxt("Bias must be cell array. Fail.");
    return;
  }

  for (mwIndex i = 0; i < mxGetNumberOfElements (BIAS_CELL_IN); ++i)
    {
      const mxArray* mybias = mxGetCell (BIAS_CELL_IN, i);

      if (mybias) {
        if (! mxIsSingle (mybias)) {
          mexErrMsgTxt("Bias must contain single arrays. Fail.");
        }

        break;
      }
    }

  if (mxIsSparse (MOMENTUM_MATRIX_IN)) {      
    mexErrMsgTxt("Momentum must be dense. Fail.");
    return;
  }

  if (! mxIsSingle (MOMENTUM_MATRIX_IN)) {
    mexErrMsgTxt("Momentum must be single. Fail.");
    return;
  }

  if (! mxIsCell (MOMENTUM_BIAS_CELL_IN)) {
    mexErrMsgTxt("Momentum bias must be cell array. Fail.");
    return;
  }

  for (mwIndex i = 0; i < mxGetNumberOfElements (MOMENTUM_BIAS_CELL_IN); ++i)
    {
      const mxArray* mymombias = mxGetCell (MOMENTUM_BIAS_CELL_IN, i);

      if (mymombias) {
        if (! mxIsSingle (mymombias)) {
          mexErrMsgTxt("Momentum bias must contain single arrays. Fail.");
        }

        break;
      }
    }

  if (! mxIsSparse (YTIC_MATRIX_IN)) {
    mexErrMsgTxt("Ytic must be sparse. Fail.");
    return;
  }

  if (mxGetN (YTIC_MATRIX_IN) != mxGetN (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Ytic and hashxtic have incompatible shapes. Fail.");
    return;
  }

  if (mxGetM (YTIC_MATRIX_IN) != mxGetM (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Ytic and filtmat have incompatible shapes. Fail.");
    return;
  }

  if (! mxIsSingle (C_VECTOR_IN)) {
    mexErrMsgTxt("C must be single. Fail.");
    return;
  }

  if (mxGetNumberOfElements (C_VECTOR_IN) != mxGetM (OAS_MATRIX_IN)) {
    mexErrMsgTxt("C and oas have incompatible shapes. Fail.");
    return;
  }
  
  if (! mxIsDouble (NODE_PERM_VECTOR_IN)) {
    mexErrMsgTxt("Node perm must be double. Fail.");
    return;
  }

  if (mxGetNumberOfElements (NODE_PERM_VECTOR_IN) != mxGetN (FILTMAT_MATRIX_IN)) {
    mexErrMsgTxt("Node perm and filtmat have incompatible shapes. Fail.");
    return;
  } 

  if (! mxIsDouble (EX_PERM_VECTOR_IN)) {
    mexErrMsgTxt("Example perm must be double. Fail.");
    return;
  }

  if (mxGetNumberOfElements (EX_PERM_VECTOR_IN) != mxGetN (HASHXTIC_MATRIX_IN)) {
    mexErrMsgTxt("Example perm and hashxtic have incompatible shapes. Fail.");
    return;
  } 


  if (mxGetM (ETA_SCALAR_IN) != 1 || mxGetN (ETA_SCALAR_IN) != 1) {
    mexErrMsgTxt("Eta must be a double scalar. Fail.");
    return;
  }

  if (mxGetScalar (ETA_SCALAR_IN) <= 0) {
    mexErrMsgTxt("Eta must be positive. Fail.");
    return;
  }

  if (mxGetM (ALPHA_SCALAR_IN) != 1 || mxGetN (ALPHA_SCALAR_IN) != 1) {
    mexErrMsgTxt("Alpha must be a double scalar. Fail.");
    return;
  }

  if (mxGetScalar (ALPHA_SCALAR_IN) < 0 || mxGetScalar (ALPHA_SCALAR_IN) >= 1) {
    mexErrMsgTxt("Alpha must be in [0,1). Fail.");
    return;
  }

  if (! mxIsLogical (SOFTMAX_LOGICAL_IN) || mxGetM (SOFTMAX_LOGICAL_IN) != 1
      || mxGetN (SOFTMAX_LOGICAL_IN) != 1) {
    mexErrMsgTxt("Softmax option must be logical. Fail.");
    return;
  }

  NORM_DELTA_OUT = mxCreateNumericMatrix (1, 1, mxDOUBLE_CLASS, mxREAL);
  double* norm_delta_out = (double *) mxGetPr (NORM_DELTA_OUT);
  double* norm_deltas = (double*) mxCalloc(NUM_THREADS, sizeof(double));

  std::thread t[NUM_THREADS];

  if (mxIsLogicalScalarTrue (SOFTMAX_LOGICAL_IN)) {
    for (size_t i = 0; i + 1 < NUM_THREADS; ++i) {
      t[i] = std::thread (update<true>, prhs, norm_deltas + i, i, NUM_THREADS);
    }

    update<true> (prhs, norm_deltas + NUM_THREADS-1, NUM_THREADS-1, NUM_THREADS);
  }
  else {
    for (size_t i = 0; i + 1 < NUM_THREADS; ++i) {
      t[i] = std::thread (update<false>, prhs, norm_deltas + i, i, NUM_THREADS);
    }

    update<false> (prhs, norm_deltas + NUM_THREADS-1, NUM_THREADS-1, NUM_THREADS);
  }
  
  for (int i = 0; i + 1 < NUM_THREADS; ++i) {
    t[i].join ();
    norm_deltas[NUM_THREADS-1] += norm_deltas[i];
  }

  *norm_delta_out = norm_deltas[NUM_THREADS-1];

  return;
}
LRESULT CALLBACK keyboard_hook_procedure(int code, WPARAM wParam, LPARAM lParam) {
    //
    //  https://msdn.microsoft.com/en-us/library/windows/desktop/ms644985(v=vs.85).aspx
    //
    //  code :
    //      Determines how to process the message. If less than zero
    //      you must call CallNextHookEx
    //  wParam : 
    //      - WM_KEYDOWN
    //      - WM_KEYUP
    //      - WM_SYSKEYDOWN - alt key pressed
    //      - WM_SYSKEYUP
    //  lParam :
    //      pointer to a KBDLLHOOKSTRUCT structure
    //      Structure defined at:
    //          https://msdn.microsoft.com/en-us/library/windows/desktop/ms644967(v=vs.85).aspx
    //     typedef struct tagKBDLLHOOKSTRUCT {
    //               DWORD     vkCode; - https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
    //               DWORD     scanCode; - hardware scan code for key
    //               DWORD     flags;
    //               DWORD     time; - timestamp of the message
    //               ULONG_PTR dwExtraInfo; - Additional information associated with the message.
    
    
    
//    } KBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT, *LPKBDLLHOOKSTRUCT;
//         short shift_pressed = GetKeyState(VK_SHIFT);
//     short ctrl_pressed = GetKeyState(VK_CONTROL);
//     short caps_pressed = GetKeyState(VK_CAPITAL);

    
    KBDLLHOOKSTRUCT*  kbd = (KBDLLHOOKSTRUCT*)lParam;
    
    bool key_pressed;
    
    DWORD vkcode = kbd->vkCode;
    
    //WARNING:
    //--------
    //The hook procedure should process a message in less time than the data 
    //entry specified in the LowLevelHooksTimeout value in the following registry key:
    //      HKEY_CURRENT_USER\Control Panel\Desktop
    // The value is in milliseconds. If the hook procedure times out, the system 
    // passes the message to the next hook. However, on Windows 7 and later, 
    // the hook is silently removed without being called. There is no way 
    // for the application to know whether the hook is removed.
      
    //  This hook must call the next one ...
    //  CallNextHookEx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644974(v=vs.85).aspx
    //
    //  0 means, just call the next one ...
    if (code < 0){
        return CallNextHookEx(NULL, code, wParam, lParam);
    }
    
    //wParam
    
//     if (wParam == WM_KEYUP){
//         key_pressed = False;
//     }else if (wParam == WM_KEYDOWN){
//         key_pressed = True;
//     }else
//     {
//     	return CallNextHookEx(NULL, code, wParam, lParam); 
//     }
   
    if (wParam == WM_KEYUP || wParam == WM_KEYDOWN){
        //GetKeyState
        //Shift
        //Ctrl
        //Caps Lock
        key_pressed = !(wParam == WM_KEYUP);
        
        //This doesn't handle sticky keys ...
        //Added to ensure we don't miss capital letters ...
        if (vkcode == VK_LSHIFT || vkcode == VK_RSHIFT){
            shift_pressed = key_pressed;
        }else if (vkcode == VK_LCONTROL || vkcode == VK_RCONTROL){
            ctrl_pressed = key_pressed;
        }else if (vkcode == VK_CAPITAL){
            caps_pressed = key_pressed;
        }
        
        
        //I'm not sure of a better way to pass parameters ... :/
        sprintf(str,"sl.os.keyboard_logger.keyboardEvent('%d:%d:%d:%d:%d:%d:%d')\0",
                key_pressed,kbd->vkCode,kbd->scanCode,kbd->time,
                shift_pressed,ctrl_pressed,caps_pressed);
        mexEvalString(str);
    }
    
// // // //     //if (wParam == WM_KEYUP){
// // // //         //sprintf should add a terminating null character to terminate the string
// // // //         //thus I don't think we need to worry if the size of this string varies ...
// // // //         
// // // //         //Keys to know
// // // //         //Shift
// // // //         //Ctrl
// // // //         //caps lock
// // // //         //Alt
// // // //     
// // // //         BYTE keyState[256];
// // // //         
// // // //         GetKeyboardState((LPBYTE)&keyState);
// // // //         wchar_t keyBuf[10];
// // // //         int status = ToUnicodeEx(kbd->vkCode, kbd->scanCode, keyState, keyBuf, 10, 0 , hkl);
// // // //     
// // // //         if (status == 1 && keyBuf[0] > 0){
// // // //             sprintf(str,"sl.os.keyboard_logger.keyboardEvent('%d:%d:%g')\0",wParam,keyBuf[0],kbd->time);
// // // //             //This is a blocking call ...
// // // //             //TODO: It would be better to not block ...
// // // //             mexEvalString(str);
// // // //         }
// // // //     //}

   return CallNextHookEx(NULL, code, wParam, lParam);	
}