コード例 #1
0
ファイル: fconvMTwin.cpp プロジェクト: mdqyy/ThesisCode
// matlab entry point
// C = fconv(A, cell of B, start, end);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    if (nrhs != 4)
        mexErrMsgTxt("Wrong number of inputs");
    if (nlhs != 1)
        mexErrMsgTxt("Wrong number of outputs");
    
    // get A
    const mxArray *mxA = prhs[0];
    if (mxGetNumberOfDimensions(mxA) != 3 ||
            mxGetClassID(mxA) != mxDOUBLE_CLASS)
        mexErrMsgTxt("Invalid input: A");
    
    // get B and start/end
    const mxArray *cellB = prhs[1];
    mwSize num_bs = mxGetNumberOfElements(cellB);
    int start = (int)mxGetScalar(prhs[2]) - 1;
    int end = (int)mxGetScalar(prhs[3]) - 1;
    if (start < 0 || end >= num_bs || start > end)
        mexErrMsgTxt("Invalid input: start/end");
    int len = end-start+1;
    
    // start threads
    thread_data *td = (thread_data *)mxCalloc(len, sizeof(thread_data));

    HANDLE  *hThreadArray = (HANDLE *)mxCalloc(len, sizeof(HANDLE));
    const mwSize *A_dims = mxGetDimensions(mxA);
    double *A = (double *)mxGetPr(mxA);
    
    // return value
    plhs[0] = mxCreateCellMatrix(1, len);
    int batch_len = ceil(1.0*len/THREAD_MAX);
    
    for(int b = 0; b<batch_len; b++) {
        int nthread = 0;
        for (int t = 0; t < THREAD_MAX; t++) {
            int i = b*THREAD_MAX + t;
            if(i >= len)
                break;
            nthread++;
            //mexPrintf("i = %d\n", i);
            const mxArray *mxB = mxGetCell(cellB, i+start);
            td[i].A_dims = A_dims;
            td[i].A = A;
            td[i].B_dims = mxGetDimensions(mxB);
            td[i].B = (double *)mxGetPr(mxB);
            if (mxGetNumberOfDimensions(mxB) != 3 ||
                    mxGetClassID(mxB) != mxDOUBLE_CLASS ||
                    td[i].A_dims[2] != td[i].B_dims[2])
                mexErrMsgTxt("Invalid input: B");
            
            // compute size of output
            int height = td[i].A_dims[0] - td[i].B_dims[0] + 1;
            int width = td[i].A_dims[1] - td[i].B_dims[1] + 1;
            if (height < 1 || width < 1)
                mexErrMsgTxt("Invalid input: B should be smaller than A");
            td[i].C_dims[0] = height;
            td[i].C_dims[1] = width;
            td[i].mxC = mxCreateNumericArray(2, td[i].C_dims, mxDOUBLE_CLASS, mxREAL);
            td[i].C = (double *)mxGetPr(td[i].mxC);
            
            hThreadArray[i] = CreateThread(
                    NULL,
                    0,
                    process,
                    &td[i],
                    0,
                    NULL);
            
            if (hThreadArray[i] == NULL)
                mexErrMsgTxt("Error creating thread");
        }
        
        // wait for the treads to finish and set return values
        WaitForMultipleObjects(nthread, hThreadArray+b*THREAD_MAX, TRUE, INFINITE);
        void *status;
        for (int t = 0; t < nthread; t++) {
            int i = b*THREAD_MAX + t;
            CloseHandle(hThreadArray[i]);
            mxSetCell(plhs[0], i, td[i].mxC);
        }
    }
    
    mxFree(td);
    mxFree(hThreadArray);
}
コード例 #2
0
void mexFunction(	int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{   
    int i,j, k, status,buflen,Cnt, Hndl, L,M,N,  NumHandles, commandswitch;
    
    int *HndlArray;
    mxArray  *mymxArray;
    double *myDblPr;
    chtype RequestType;
    
    char PVName[PV_NAME_LENGTH_MAX+1];
    // char MCAMessageString[MCA_MESSAGE_STRING_LENGTH_MAX+1];
    
    
      

    dbr_string_t StrBuffer;
    
        
    
    const char *MCAInfoFields[]={"PVName","ElementCount","NativeType","State","MCAMessage","Host"};
    char *NativeTypeStrings[] = {"STRING","INT","FLOAT","ENUM","CHAR","LONG","DOUBLE"};
    


    
    if(!CA_INITIALIZED) // Initialize CA if not initialized (first call)
    {   mexPrintf("Initializing MATLAB Channel Access ... \n");
        status = ca_task_initialize();
        if(status!=ECA_NORMAL)
            mexErrMsgTxt("Unable to initialise Challel Access\n");
        CA_INITIALIZED = true;
        // Register a function to be called when a this mex-file is cleared from memory
        // with 'clear' or when exitting MATLAB
        mexAtExit(mca_cleanup);
        // Lock the mex-file so that it can not be cleared without explicitly
        // mexUnclock
        mexLock();
        
        //start periodic polling:
/*        PollTimerHandle = SetTimer(NULL,NULL,MCA_POLL_PERIOD,background_poll);
        if(PollTimerHandle)
            mexPrintf("Periodic CA polling started! System Timer ID: %u\n",PollTimerHandle);
        else
            mexWarnMsgTxt("Failed to start periodic CA polling\n");
 */       
        
    }

    commandswitch = (int)mxGetScalar(prhs[0]);
   
    switch(commandswitch)
    {  case 0: 
            mexUnlock();
            break;
    
        case 1: // MCAOPEN - add channel(s) by PV names, all arguments following prhs[0]
               // must be strings - names of PV's
            for(i=1;i<nrhs;i++)
            {   mxGetString(prhs[i],PVName,PV_NAME_LENGTH_MAX+1);
                status = ca_search(PVName,&(CHNLS[HandlesUsed].CHID));
                if(status == ECA_NORMAL) // if not - go on to the next PV name
                {   status = ca_pend_io(MCA_SEARCH_TIMEOUT);
                    if (status == ECA_NORMAL)
                    {   // Allocate persistent memory for the DataBuffer on this channel
                        // to hold all elements of the DBR_XXX type
                        // nearest to the native type
                        // RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[HandlesUsed].CHID));
                        // Cnt=ca_element_count(CHNLS[HandlesUsed].CHID);
                        
                        
                        CHNLS[HandlesUsed].NumElements = ca_element_count(CHNLS[HandlesUsed].CHID);
                        CHNLS[HandlesUsed].NativeType2DBR = dbf_type_to_DBR(ca_field_type(CHNLS[HandlesUsed].CHID));
                        CHNLS[HandlesUsed].MonitorEventCount = 0;
                        
                        switch(CHNLS[HandlesUsed].NativeType2DBR)
                        {   case DBR_STRING:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_string_t));
                                
                            break;
                        
                            case DBR_INT: // As defined in db_access.h DBR_INT = DBR_SHORT = 1
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_short_t)); 
                            break;
                        
                            case DBR_FLOAT:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_float_t)); 
                            break;
                
                            case DBR_ENUM:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_enum_t)); 
                            break;
                
                            case DBR_CHAR:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_char_t)); 
                            break;
                    
                            case DBR_LONG:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_short_t)); 
                            break;
                    
                            case DBR_DOUBLE:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_double_t)); 
                            break;
                        }   
                        mexMakeMemoryPersistent(CHNLS[HandlesUsed].DataBuffer);
                        
                                 
                        if(CHNLS[HandlesUsed].NativeType2DBR==DBR_STRING) // CACHE
                        {   if(CHNLS[HandlesUsed].NumElements==1) // Create MATLAB string - originally empty
                                CHNLS[HandlesUsed].CACHE = mxCreateString("");
                            else // Create MATLAB cell array of strings
                            {   CHNLS[HandlesUsed].CACHE = mxCreateCellMatrix(1,CHNLS[HandlesUsed].NumElements);
                                for(k=0;k<CHNLS[HandlesUsed].NumElements;k++)
                                {   mymxArray = mxCreateString("");
                                    mexMakeArrayPersistent(mymxArray);
                                    mxSetCell(CHNLS[HandlesUsed].CACHE, k, mymxArray);
                                }
                            }
                        }
                        else // Make CACHE a numeric mxArray 
                        {    CHNLS[HandlesUsed].CACHE = mxCreateDoubleMatrix(1,CHNLS[HandlesUsed].NumElements,mxREAL);  
                        }
                        
                        mexMakeArrayPersistent(CHNLS[HandlesUsed].CACHE);
                        
                        plhs[i-1]=mxCreateScalarDouble(++HandlesUsed);                        
                    
                    }
                    else
                        plhs[i-1]=mxCreateScalarDouble(0);

                }
                else
                    plhs[i-1]=mxCreateScalarDouble(0);
            } break;
            
        
        case 2:// MCAOPEN - add channel(s) by PV names. The arguments following prhs[0]
               // argument must be a cell array of strings - PV names
            
            L = mxGetM(prhs[1])*mxGetN(prhs[1]);
            plhs[0] = mxCreateDoubleMatrix(1,L,mxREAL);
            myDblPr = mxGetPr(plhs[0]);
            
            for(i=0;i<L;i++)
            {   mymxArray = mxGetCell(prhs[1],i);
                mxGetString(mymxArray,PVName,PV_NAME_LENGTH_MAX+1);
                status = ca_search(PVName,&(CHNLS[HandlesUsed].CHID));
                if(status == ECA_NORMAL) // if not - go on to the next PV name
                {   status = ca_pend_io(MCA_IO_TIMEOUT);
                    if (status == ECA_NORMAL)
                    {   // Allcate persistent memory for the DataBuffer on this channel
                        //RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[HandlesUsed].CHID));
                        CHNLS[HandlesUsed].NativeType2DBR = dbf_type_to_DBR(ca_field_type(CHNLS[HandlesUsed].CHID));
                        CHNLS[HandlesUsed].NumElements = ca_element_count(CHNLS[HandlesUsed].CHID);
                        CHNLS[HandlesUsed].MonitorEventCount = 0;
                        //Cnt=ca_element_count(CHNLS[HandlesUsed].CHID);
                        switch(CHNLS[HandlesUsed].NativeType2DBR)
                        {   case DBR_STRING:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_string_t)); 
                            break;
                        
                            case DBR_INT: // As defined in db_access.h DBR_INT = DBR_SHORT = 1
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_short_t)); 
                            break;
                        
                            case DBR_FLOAT:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_float_t)); 
                            break;
                
                        
                            case DBR_ENUM:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_enum_t)); 
                            break;
                
                            case DBR_CHAR:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_char_t)); 
                            break;
                    
                            case DBR_LONG:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_short_t)); 
                            break;
                    
                            case DBR_DOUBLE:
                                CHNLS[HandlesUsed].DataBuffer = mxCalloc(CHNLS[HandlesUsed].NumElements,sizeof(dbr_double_t)); 
                            break;
                        }   
                        mexMakeMemoryPersistent(CHNLS[HandlesUsed].DataBuffer);   
                        
                        if(CHNLS[HandlesUsed].NativeType2DBR == DBR_STRING) // CACHE
                        {   CHNLS[HandlesUsed].CACHE = mxCreateCellMatrix(1,CHNLS[HandlesUsed].NumElements);
                            for(k=0;k<CHNLS[HandlesUsed].NumElements;k++)
                            {   mymxArray = mxCreateString(StrBuffer);
                                mexMakeArrayPersistent(mymxArray);
                                mxSetCell(CHNLS[HandlesUsed].CACHE, k, mymxArray);
                            }
                        }
                        else
                        {    CHNLS[HandlesUsed].CACHE = mxCreateDoubleMatrix(1,CHNLS[HandlesUsed].NumElements,mxREAL);  
                        }
                        
                        mexMakeArrayPersistent(CHNLS[HandlesUsed].CACHE);
                        
                        
                        myDblPr[i] = ++HandlesUsed;
                    }
                    else
                        myDblPr[i] = 0;
                }
                else
                    myDblPr[i] = 0;
            } break;
            
       case 3: // MCAOPEN Return names of connected channels as cell array of strings
            plhs[0] = mxCreateCellArray(1, &HandlesUsed);
            for(i=0;i<HandlesUsed;i++)
            {   if(CHNLS[i].CHID!=NULL)
                    {   mymxArray = mxCreateString(ca_name(CHNLS[i].CHID));
                        mxSetCell(plhs[0], i, mymxArray);
                    }
                else
                    {   mymxArray = mxCreateString("");
                        //mexPrintf("Handle: %d PV: %s\n",i+1, "Cleared Channel");
                        mxSetCell(plhs[0], i, mymxArray);
                    }
              } break;
        
        
         
        case 5: // MCACLOSE permanently clear channel
            Hndl = (int)mxGetScalar(prhs[1]);
            if(Hndl<1 || Hndl>HandlesUsed)
                mexErrMsgTxt("Handle out of range");  

            // If a monitor is installed, set the EVID pointer to NULL 
            // ca_clear_event dos not do it by itself

            if(CHNLS[Hndl-1].EVID) 
                CHNLS[Hndl-1].EVID = NULL;
                
            // If there is Callback String - destroy it
            if(CHNLS[Hndl-1].MonitorCBString)
            {   mxFree(CHNLS[Hndl-1].MonitorCBString); 
                CHNLS[Hndl-1].MonitorCBString =NULL;
            }    
            
            if(ca_state(CHNLS[Hndl-1].CHID)==3)
                mexWarnMsgTxt("Channel previously cleared");
            else
                if(ca_clear_channel(CHNLS[Hndl-1].CHID)!=ECA_NORMAL)
                    mexErrMsgTxt("ca_clear_channel failed");

            break;
            
        case 10: // MCAINFO return channels info as MATLAB structure array
            if(HandlesUsed>0)
            {   plhs[0] = mxCreateStructMatrix(1,HandlesUsed,6,MCAInfoFields);
                
                for(i=0;i<HandlesUsed;i++)
                {   mxSetFieldByNumber(plhs[0],i,0,mxCreateString(ca_name(CHNLS[i].CHID)));
                    mxSetFieldByNumber(plhs[0],i,1,mxCreateScalarDouble(ca_element_count(CHNLS[i].CHID)));
                    mxSetFieldByNumber(plhs[0],i,5,mxCreateString(ca_host_name(CHNLS[i].CHID)));
                    
                    switch(ca_state(CHNLS[i].CHID))
                    {   case 1: // Disconnected due to Server or Network - may reconnect 
                            mxSetFieldByNumber(plhs[0],i,2,mxCreateString("unknown"));
                            mxSetFieldByNumber(plhs[0],i,3,mxCreateString("disconnected"));
                            mxSetFieldByNumber(plhs[0],i,4,mxCreateString("Disconnected due to server or network problem"));
                            break;
                        case 2: // Normal connection
                            mxSetFieldByNumber(plhs[0],i,2,mxCreateString(NativeTypeStrings[ca_field_type(CHNLS[i].CHID)]));
                            mxSetFieldByNumber(plhs[0],i,3,mxCreateString("connected"));
                            mxSetFieldByNumber(plhs[0],i,4,mxCreateString("Normal connection"));
                            break;
                        case 3: // Disconnected by user
                            mxSetFieldByNumber(plhs[0],i,2,mxCreateString("unknown"));
                            mxSetFieldByNumber(plhs[0],i,3,mxCreateString("disconnected"));
                            mxSetFieldByNumber(plhs[0],i,4,mxCreateString("Permanently disconnected (cleared) by the user"));                    
                            break;
                    }    
                }
            }
            else
            {   mexWarnMsgTxt("No connected PV's found"); 
                plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
                
            }
            break;    
        
            
        case 11: // MCAINFO return info for 1 channel by handle number 
            Hndl = (int)mxGetScalar(prhs[1]);
            if(Hndl<1 || Hndl>HandlesUsed)
                mexErrMsgTxt("Handle out of range");  
                
            plhs[0] = mxCreateStructMatrix(1,1,6,MCAInfoFields);

            mxSetFieldByNumber(plhs[0],0,0,mxCreateString(ca_name(CHNLS[Hndl-1].CHID)));
            mxSetFieldByNumber(plhs[0],0,1,mxCreateScalarDouble(ca_element_count(CHNLS[Hndl-1].CHID)));
            mxSetFieldByNumber(plhs[0],0,5,mxCreateString(ca_host_name(CHNLS[Hndl-1].CHID)));
            
            switch(ca_state(CHNLS[Hndl-1].CHID))
            {  case 1: // Disconnected due to Server or Network - may reconnect 
                    mxSetFieldByNumber(plhs[0],0,2,mxCreateString("unknown"));
                    mxSetFieldByNumber(plhs[0],0,3,mxCreateString("disconnected"));
                    mxSetFieldByNumber(plhs[0],0,4,mxCreateString("Disconnected due to server or network problem"));
                    break;
                case 2: // Normal connection
                    mxSetFieldByNumber(plhs[0],0,2,mxCreateString(NativeTypeStrings[ca_field_type(CHNLS[Hndl-1].CHID)]));
                    mxSetFieldByNumber(plhs[0],0,3,mxCreateString("connected"));
                    mxSetFieldByNumber(plhs[0],0,4,mxCreateString("Normal connection"));
                    break;
                case 3: // Disconnected by user
                    mxSetFieldByNumber(plhs[0],0,2,mxCreateString("unknown"));
                    mxSetFieldByNumber(plhs[0],0,3,mxCreateString("disconnected"));
                    mxSetFieldByNumber(plhs[0],0,4,mxCreateString("Permanently disconnected (cleared) by the user"));                    
                    break;
            };    
            
        break;    
        
        case 12: // MCASTATE return an array of status (1 - OK, 0 - disconnected or cleared) 
            if(HandlesUsed>0)
            {   plhs[0] = mxCreateDoubleMatrix(1,HandlesUsed,mxREAL);
                myDblPr = mxGetPr(plhs[0]);
                for(i=0;i<HandlesUsed;i++)
                    myDblPr[i] = (double)(ca_state(CHNLS[i].CHID)==2);
            }
            else
            {   mexWarnMsgTxt("No connected PV's found"); 
                plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
                
            }
            break;    
        
        
        case 30: // poll
            ca_poll();
        break;
            

        case 50: // MCAGET Get PV values by their MCA handles
            
            for(i=0;i<nrhs-1;i++) // First loop: place all ca_get requests in the buffer
            {   Hndl = (int)mxGetScalar(prhs[1+i]); //start from[1]:  [0] argument is the commnads switch
                if(Hndl<1 || Hndl>HandlesUsed)
                    mexErrMsgTxt("Invalid Handle");
                
                RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID));
                Cnt = ca_element_count(CHNLS[Hndl-1].CHID);
                status = ca_array_get(RequestType,Cnt,CHNLS[Hndl-1].CHID,CHNLS[Hndl-1].DataBuffer);
                if(status!=ECA_NORMAL)
                    mexPrintf("Error in call to ca_array_get\n");
            }   
            
            status = ca_pend_io(MCA_GET_TIMEOUT);
            if(status!=ECA_NORMAL)
                mexErrMsgTxt("... ca_pend_io call timed out \n");
            
            
            for(i=0;i<nrhs-1;i++) // Another loop to copy data from temp structures to MATLAB
            
            {   Hndl = (int)mxGetScalar(prhs[1+i]);
                RequestType = RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID));
                Cnt = ca_element_count(CHNLS[Hndl-1].CHID);
                
                if(RequestType==DBR_STRING)
                {   if(Cnt==1)
                        plhs[i] = mxCreateString((char*)(*((dbr_string_t*)(CHNLS[Hndl-1].DataBuffer))));
                    else
                    {   plhs[i] = mxCreateCellMatrix(1,Cnt);
                        for(j=0;j<Cnt;j++)
                            mxSetCell(plhs[i], j, mxCreateString((char*)(*((dbr_string_t*)(CHNLS[Hndl-1].DataBuffer)+j))));
                    }
                }
                
                else 
                {   plhs[i] = mxCreateDoubleMatrix(1,Cnt,mxREAL);
                    myDblPr = mxGetPr(plhs[i]);
                                        
                    switch(dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID)))
                    
                    {   case DBR_INT: // As defined in db_access.h DBR_INT = DBR_SHORT = 1
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_short_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;    
                 
                        case DBR_FLOAT:
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_float_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;
                
                        case DBR_ENUM:
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_enum_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;
                
                        case DBR_CHAR:
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_char_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;
                    
                        case DBR_LONG:
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_long_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;
                    
                        case DBR_DOUBLE:
                        for(j=0;j<Cnt;j++)
                            myDblPr[j]= (double)(*((dbr_double_t*)(CHNLS[Hndl-1].DataBuffer)+j));
                        break;
                    } 

                }
                
            } break;            

            case 51: // MCAGET Get scalar PV of the same type 
                     // second argument is an array of handles
                     // returns an array of values
            
            myDblPr = mxGetPr(prhs[1]);
            M = mxGetM(prhs[1]);
            N = mxGetN(prhs[1]);
            
            NumHandles = M*N;
            plhs[0] = mxCreateDoubleMatrix(M,N,mxREAL);
            
            for(i=0;i<NumHandles;i++) // First loop: place all ca_get requests in the buffer
            {   Hndl = (int)myDblPr[i];
                if(Hndl<1 || Hndl>HandlesUsed)
                    mexErrMsgTxt("Invalid Handle");
                
                RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID));
                status = ca_array_get(DBR_DOUBLE,1,CHNLS[Hndl-1].CHID,mxGetPr(plhs[0])+i);
                if(status!=ECA_NORMAL)
                    mexPrintf("Error in call to ca_array_get\n");
            }   
            
            status = ca_pend_io(MCA_GET_TIMEOUT);
            if(status!=ECA_NORMAL)
                mexErrMsgTxt("... ca_pend_io call timed out \n");
            
            break;            

        
       
        case 70: // MCAPUT
            NumHandles = (nrhs-1)/2;
            for(i=0;i<NumHandles;i++)
            {   j = 2+i*2;
                Hndl = (int)mxGetScalar(prhs[1+i*2]); 
                if(Hndl<1 || Hndl>HandlesUsed)
                    mexErrMsgTxt("Handle out of range - no values written");
                // Set the status to 0 - mcaput_callback will write 1, if successful
                CHNLS[Hndl-1].LastPutStatus = 0;    
                RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID));            
                Cnt = ca_element_count(CHNLS[Hndl-1].CHID);
                
                
                // If a value to write is passed as a string - the number of elements to write 
                //   is 1 , NOT the length of the string returned by mxGetNumberOfElements
                if(mxIsChar(prhs[j])) 
                    L=1;
                else
                    L = min(mxGetNumberOfElements(prhs[j]),Cnt);
                

                // Copy double or string data from MATLAB prhs[] to DataBuffer
                // on each channel 
                
                if(RequestType==DBR_STRING)
                {   // STRING type is is passed as a cell array of strings
                    // A a 1-row MATLAB character array (1 string) may also be passed as a value
                    
                    if(mxIsChar(prhs[j]))
                    {   mxGetString(prhs[j], StrBuffer, sizeof(dbr_string_t));
                        strcpy((char*)(*((dbr_string_t*)(CHNLS[Hndl-1].DataBuffer))),StrBuffer);
                        
                    }
                    else if(mxIsCell(prhs[j]))
                    {   for(k=0;k<L;k++)
                        {   mxGetString(mxGetCell(prhs[j],k), StrBuffer, sizeof(dbr_string_t));
                            strcpy((char*)(*((dbr_string_t*)(CHNLS[Hndl-1].DataBuffer)+k)),StrBuffer);
                        }
                    }
                }
                else
                {   myDblPr = mxGetPr(prhs[j]); 
                    switch(RequestType)
                    {   
                        case DBR_INT: // As defined in db_access.h DBR_INT = DBR_SHORT = 1
                        for(k=0;k<L;k++)
                            *((dbr_short_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_short_t)(myDblPr[k]);
                        break;    
                 
                        case DBR_FLOAT:
                        for(k=0;k<L;k++)
                            *((dbr_float_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_float_t)(myDblPr[k]);
                        break;
                
                        case DBR_ENUM:
                        for(k=0;k<L;k++)
                            *((dbr_enum_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_enum_t)(myDblPr[k]);
                        break;
                
                        case DBR_CHAR:
                        for(k=0;k<L;k++)
                            *((dbr_char_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_char_t)(myDblPr[k]);
                        break;
                   
                        case DBR_LONG:
                        for(k=0;k<L;k++)
                            *((dbr_long_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_long_t)(myDblPr[k]);
                        break;
                    
                        case DBR_DOUBLE:
                        for(k=0;k<L;k++)
                            *((dbr_double_t*)(CHNLS[Hndl-1].DataBuffer)+k) = (dbr_double_t)(myDblPr[k]);
                        break;
                    } 
                }            
 
                // place request in the que 
                status = ca_array_put_callback(RequestType,L,CHNLS[Hndl-1].CHID,CHNLS[Hndl-1].DataBuffer,
                                                   mcaput_callback,&(CHNLS[Hndl-1].LastPutStatus));

                 if(status!=ECA_NORMAL)
                    mexPrintf("ca_array_put_callback failed\n");
            }   
            
            status = ca_pend_event(MCA_PUT_TIMEOUT);
            
            plhs[0]=mxCreateDoubleMatrix(1,NumHandles,mxREAL);
            myDblPr = mxGetPr(plhs[0]);  
            
            for(i=0;i<NumHandles;i++)
            {   Hndl = (int)mxGetScalar(prhs[1+i*2]);
                myDblPr[i] = (double)CHNLS[Hndl-1].LastPutStatus;
                
            }
           
            break;
        
       case 80: // MCAPUT - fast unconfirmed put for scalar numeric PV's
        
            myDblPr = mxGetPr(prhs[1]);
            M = mxGetM(prhs[1]);
            N = mxGetN(prhs[1]);                
            NumHandles = M*N;
            
            plhs[0] = mxCreateDoubleMatrix(M,N,mxREAL);
            myDblPr = mxGetPr(plhs[0]);  
            
            for(i=0;i<NumHandles;i++)
            {   myDblPr = mxGetPr(plhs[0]);
                Hndl = (int)(*(mxGetPr(prhs[1])+i)); 
                if(Hndl<1 || Hndl>HandlesUsed)
                    mexErrMsgTxt("Handle out of range - no values written");

                status = ca_array_put(DBR_DOUBLE,1,CHNLS[Hndl-1].CHID,mxGetPr(prhs[2])+i);

                if(status!=ECA_NORMAL)
                    {   myDblPr[i] = 0;
                        //mexPrintf("ca_array_put_callback failed\n");
                    }
                    else
                    {   myDblPr[i] = 1;
                    }
                    
            }   
            
            status = ca_pend_io(MCA_PUT_TIMEOUT);
            
            break;    
                 
            
        case 100: // MCAMON install Monitor or replace MonitorCBString
            
            Hndl = (int)mxGetScalar(prhs[1]); 
            
            // Check if the handle is within range 
            if(Hndl<1 || Hndl>HandlesUsed)
            {   plhs[0]=mxCreateScalarDouble(0);
                mexErrMsgTxt("Invalid Handle");
            }
            
            if(CHNLS[Hndl-1].EVID) // if VID is not NULL - another monitor is already installed - replace MonitorCBString
            {   if(CHNLS[Hndl-1].MonitorCBString) // Free memory for occupied by the old MonitorCBString
                {   mxFree(CHNLS[Hndl-1].MonitorCBString);
                    CHNLS[Hndl-1].MonitorCBString = NULL;
                }
                if(nrhs>2) // Check if the new string is specified
                {   if(mxIsChar(prhs[2]))
                    {   buflen = mxGetM(prhs[2])*mxGetN(prhs[2])+1;
                        CHNLS[Hndl-1].MonitorCBString = (char *)mxMalloc(buflen);
                        mexMakeMemoryPersistent(CHNLS[Hndl-1].MonitorCBString);
                        mxGetString(prhs[2],CHNLS[Hndl-1].MonitorCBString,buflen); 
                    } 
                    else
                        mexErrMsgTxt("Third argument must be a string\n");
                }
                plhs[0]=mxCreateScalarDouble(1);
            }
            else // No monitor is presently installed;
            {   RequestType = dbf_type_to_DBR(ca_field_type(CHNLS[Hndl-1].CHID)); // Closest to the native 
            
            
                if(nrhs>2)
                {   if(mxIsChar(prhs[2]))
                    {   buflen = mxGetM(prhs[2])*mxGetN(prhs[2])+1;
                        CHNLS[Hndl-1].MonitorCBString = (char *)mxMalloc(buflen);
                        mexMakeMemoryPersistent(CHNLS[Hndl-1].MonitorCBString);
                        mxGetString(prhs[2],CHNLS[Hndl-1].MonitorCBString,buflen); 
                    } 
                    else
                        mexErrMsgTxt("Third argument must be a string\n");
                }
                else
                    CHNLS[Hndl-1].MonitorCBString = NULL;  // Set MonitorCBString to NULL so that mcaMonitorEventHandler only copies data to CACHE
            
                // Count argument set to 0 - native count
                status = ca_add_array_event(RequestType,0,CHNLS[Hndl-1].CHID, mcaMonitorEventHandler, &CHNLS[Hndl-1], 0.0, 0.0, 0.0, &(CHNLS[Hndl-1].EVID));
              
                if(status!=ECA_NORMAL)
                {   mexPrintf("ca_add_array_event failed\n");      
                    plhs[0]=mxCreateScalarDouble(0);
                }
                else
                {   ca_poll();
                    plhs[0]=mxCreateScalarDouble(1);
                }
            }   
            break;
            
        case 200: // Clear Monitor MCACLEARMON
            
            Hndl = (int)mxGetScalar(prhs[1]); 
            if(Hndl<1 || Hndl>HandlesUsed)
                mexErrMsgTxt("Invalid Handle");
            if(!CHNLS[Hndl-1].EVID) 
                mexErrMsgTxt("No monitor installed - can not clear");
                
            status = ca_clear_event(CHNLS[Hndl-1].EVID);
            if(status!=ECA_NORMAL)
                mexPrintf("ca_clear_event failed\n");
                
            // Set the EVID pointer to NULL (ca_clear_event dos not do it by itself)
            // to use as a FLAG that no monitors are installed 
            CHNLS[Hndl-1].EVID = NULL;
            // Reset
            CHNLS[Hndl-1].MonitorEventCount = 0;    
            // If there is Callback String - destroy it
            if(CHNLS[Hndl-1].MonitorCBString)
            {   mxFree(CHNLS[Hndl-1].MonitorCBString); 
                CHNLS[Hndl-1].MonitorCBString =NULL;
            }
                
          
        break;
          
        case 300: // MCACACHE Get Cached values of a monitored PV
            for(i=0;i<nrhs-1;i++)
            {   Hndl = (int)mxGetScalar(prhs[1+i]);
                // if(Hndl<1 || Hndl>HandlesUsed || !CHNLS[Hndl-1].CACHE)
                if(Hndl<1 || Hndl>HandlesUsed)
                    plhs[i] = mxCreateDoubleMatrix(0,0,mxREAL);
                else
                    {   plhs[i] = mxDuplicateArray(CHNLS[Hndl-1].CACHE);
                        CHNLS[Hndl-1].MonitorEventCount = 0;
                    }
            }       
          
        break;
        
        case 500: // MCAMON Info on installed monitors
            L = 0;
            HndlArray = (int*)mxCalloc(HandlesUsed,sizeof(int));
            
            for(i=0;i<HandlesUsed;i++) // Count installed monitors
            {   if(CHNLS[i].EVID)
                HndlArray[L++]=i+1;
            }       
            
            if(L>0)
            {   plhs[0] = mxCreateDoubleMatrix(1,L,mxREAL);
                myDblPr = mxGetPr(plhs[0]);
                plhs[1] = mxCreateCellMatrix(1,L);
                for(i=0;i<L;i++)
                {   myDblPr[i] = (double)HndlArray[i];
                    mxSetCell(plhs[1],i,mxCreateString(CHNLS[HndlArray[i]-1].MonitorCBString));
                }
            }
            else
            {   plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
                plhs[1] = mxCreateCellMatrix(0,0);
            }
            
        break;
        
        case 510: // MCAMONEVENTS Event count fot monitors
                       
            plhs[0] = mxCreateDoubleMatrix(1,HandlesUsed,mxREAL);
            myDblPr = mxGetPr(plhs[0]);
            for(i=0;i<HandlesUsed;i++)
                myDblPr[i]=(double)(CHNLS[i].MonitorEventCount);
            
        break;
        
        case 1000: // print timeout settings
            plhs[0] = mxCreateDoubleMatrix(3,1,mxREAL);
            mexPrintf("MCA timeout settings\n:");
            mexPrintf("mcaopen\t%f [s]\n",  MCA_SEARCH_TIMEOUT );
            mexPrintf("mcaget\t%f [s]\n",  MCA_GET_TIMEOUT ); 
            mexPrintf("mcaput\t%f [s]\n",  MCA_PUT_TIMEOUT );

            myDblPr = mxGetPr(plhs[0]);
            myDblPr[0] = MCA_SEARCH_TIMEOUT;
            myDblPr[1] = MCA_GET_TIMEOUT;
            myDblPr[2] = MCA_PUT_TIMEOUT;

            
        break;
        
        
        case 1001: // set MCA_SEARCH_TIMEOUT
            // return delay value
            MCA_SEARCH_TIMEOUT = mxGetScalar(prhs[1]);
            plhs[0] = mxCreateScalarDouble(MCA_SEARCH_TIMEOUT);
        break;
        
        case 1002: // set MCA_GET_TIMEOUT
            // return delay value
            MCA_GET_TIMEOUT = mxGetScalar(prhs[1]);
            plhs[0] = mxCreateScalarDouble(MCA_GET_TIMEOUT);
        break;
        
        case 1003: // set MCA_PUT_TIMEOUT
            // return delay value
            MCA_PUT_TIMEOUT = mxGetScalar(prhs[1]);
            plhs[0] = mxCreateScalarDouble(MCA_PUT_TIMEOUT);
        break;

    } 
}
コード例 #3
0
void update_phi_n(mxArray *retptr, double *sstopicwordptr, double *sstopicptr, const mxArray *phi_n, const double *windexn, const double *wcountn, const mxArray *model, const mxArray *data, const double *psigammaptr, const int n, const int phase, const double *annotations, int option)
{
    int ndistWords, nK, k1, k2, V, N, tempind, i, j, y, C2, Y; // number of words, maximum number of topics, maximum number of observed topics
    double logsum1, logsum2, minval, val, epsilon;
    mxArray *tmp;
    double *tmpptr, *tmp1, *log_beta, *mu, *eta, *classlabels;
    double *nwordspdoc = mxGetPr(mxGetField(data,0,"nwordspdoc"));
    
    minval = mxGetScalar(mxGetField(model,0,"MINVALUE"));
    ndistWords = mxGetM(phi_n);
    nK     = mxGetN(phi_n);
    tmp    = mxCreateDoubleMatrix(ndistWords,nK,mxREAL);
    tmpptr = mxGetPr(tmp);
    log_beta = mxGetPr(mxGetField(model,0,"log_beta"));
    
    V      = mxGetScalar(mxGetField(model,0,"V"));
    N      = mxGetScalar(mxGetField(model,0,"N"));
    
    //mexPrintf("till here ok1\n");
    if(option>=3)
    {
        classlabels = mxGetPr(mxGetField(data,0,"classlabels"));
        if(phase==1)
        {// use the dual variable only in training phase; no dual variable in test phase
            mu     = mxGetPr(mxGetField(model,0,"mu"));
        }
        eta     = mxGetPr(mxGetField(model,0,"eta"));
        C2 = (int)mxGetScalar(mxGetField(model,0,"C2"));
        Y  = (int)mxGetScalar(mxGetField(model,0,"Y"));
        if(option>=4)
        {
            k1 = mxGetScalar(mxGetField(model,0,"k1"));
            k2 = mxGetScalar(mxGetField(model,0,"k2"));
            epsilon = mxGetScalar(mxGetField(model,0,"epsilon"));
            //mexPrintf("\nY: %d\n",Y);
        }
    }
    
    int lowlimit, uplimit;
    if(option==5) // DSLDA-NSLT
    {
        lowlimit = k1 + ((int)classlabels[n]-1)*(k2/Y);
        uplimit  = k1 + ((int)classlabels[n])*(k2/Y)-1;
        //mexPrintf("%d %d %d %d %d %d\n", n, k1, k2, lowlimit, uplimit, (int)classlabels[n]);
    }
    //mexPrintf("\t %d acajcjac %d",n, ndistWords);
    for (i=0; i<ndistWords; i++)
    {
        logsum1 = 0;
        logsum2 = 0;
        tmp1 = Malloc(double,nK);
        //mexPrintf("%d %d %d %d till here ok2\n", n, i, windexn[i], ndistWords);
        
        for (j=0; j<nK; j++)
        {
            tempind = j + ((int)(windexn[i])-1)*nK;
            //mexPrintf("\n%d %d %d %d %f\n",n, i,j, nK, log_beta[tempind]);
            val = 0;
            if(phase==1 && (int)classlabels[n]>=1)   // use the dual variable only in training phase only when label is present; no dual variable in test phase;
            {
                for (y=0; y<Y; y++)
                    val = val + mu[y*N+n]*(eta[j*Y+ (int)classlabels[n]-1] - eta[j*Y+y]);
                val =  val/nwordspdoc[n];
            }
            
            //mexPrintf("\n%d %d %d %d %f\n",n, i,j, nK, log_beta[tempind]);
            if(option>=3)
                *(tmp1+j) = psigammaptr[j*N+n] + log_beta[tempind] + val;  // access (j,i) th element from gamma
            
            if(option==1 || option==2)
                *(tmp1+j) = psigammaptr[j*N+n] + log_beta[tempind];  // access (j,i) th element from gamma
            
            if(option!=1 && option!=3 && ((option>=4 && j<k1) || (option==2 && j<nK)))
            {
                // supervised topics for options other than 1(LDA) and 3(MedLDA); for option 2(LLDA), all the topics are supervised, so we need an extra clause
                if(phase==1) // in training phase
                {
                    //if condition says when to ignore phi's for supervised topics in training phase
                    if(option==2 && *(annotations+j*N+n)==0); // LLDA
                    else if (option==4 && j<k1 && *(annotations+j*N+n)==0);  // DSLDA
                    else if (option==5 && ((j<k1 && *(annotations+j*N+n)==0) || (j>=k1 && !(j>=lowlimit && j<=uplimit)))); // DSLDA-NSLT1
                    else if (option==7 && (j<k1 && *(annotations+j*N+n)==0)); // DSLDA-OSST
                    else
                        logsum1    = log_sum(*(tmp1+j),logsum1);
                }
                else // in test phase
                    logsum1    = log_sum(*(tmp1+j),logsum1);
            }
            else  // unsupervised topics (training and test phases are identical except for DSLDA-NSLT)
            {
                if(phase==1 && (int)classlabels[n]>=1 && option==5 && !(j>=lowlimit && j<=uplimit)); // skip in DSLDA-NSLT's training phase;
                //only if the class label is present
                else
                    logsum2    = log_sum(*(tmp1+j),logsum2);
            }
        }
        
        // conversion from log space to real number
        for (j=0; j<nK; j++)
        {
            if(option!=1 && option!=3 && ((option>=4 && j<k1) || (option==2 && j<nK)))
            {
                // supervised topics for options other than 1(LDA) and 3(MedLDA); for option 2(LLDA), all the topics are supervised, so we need an extra clause
                if(phase==1)
                {
                    //if condition says when to ignore phi's for supervised topics in training phase
                    if(option==2 && *(annotations+j*N+n)==0)
                        tmpptr[j*ndistWords+i] = 0; // LLDA
                    else if (option==4 && j<k1 && *(annotations+j*N+n)==0)
                        tmpptr[j*ndistWords+i] = 0; // DSLDA
                    else if (option==5 && j<k1 && *(annotations+j*N+n)==0)
                        tmpptr[j*ndistWords+i] = 0; // DSLDA-NSLT
                    else if (option==7 && (j<k1 && *(annotations+j*N+n)==0))
                        tmpptr[j*ndistWords+i] = 0; // DSLDA-OSST
                    else if(logsum1 - *(tmp1+j)>100)
                        tmpptr[j*ndistWords+i] = minval;                                //(j,i) th element
                    else if(logsum1 - *(tmp1+j)<100)
                        tmpptr[j*ndistWords+i] = epsilon*exp(*(tmp1+j)-logsum1)+minval; //(j,i) th element
                    else; // do nothing
                }
                else  // in test phase for supervised topics
                {
                    if(logsum1 - *(tmp1+j)>100)
                        tmpptr[j*ndistWords+i] = minval;                                //(j,i) th element
                    else if(logsum1 - *(tmp1+j)<100)
                        tmpptr[j*ndistWords+i] = epsilon*exp(*(tmp1+j)-logsum1)+minval; //(j,i) th element
                    else; // do nothing
                }
            }
            else  // unsupervised topics
            {
                if(phase==1 && (int)classlabels[n]>=1 && option==5 && !(j>=lowlimit && j<=uplimit)) // DSLDA-NSLT skip in training phase only if the class label is present
                    tmpptr[j*ndistWords+i] = 0;
                else // no distinction between training and test phase except for DSLDA-NSLT
                {
                    if(logsum2 - *(tmp1+j)>100)
                        tmpptr[j*ndistWords+i] = minval;                        //(j,i) th element
                    if(logsum2 - *(tmp1+j)<100)
                        if(option>=4)
                            tmpptr[j*ndistWords+i] = (1-epsilon)*exp(*(tmp1+j)-logsum2)+minval; //(j,i) th element
                        else
                            tmpptr[j*ndistWords+i] = exp(*(tmp1+j)-logsum2)+minval; //(j,i) th element
                }
            }
        }
        free(tmp1);
    }
    
    // update sufficient statistics
    for (j = 0; j < nK; j++)
        for (i = 0; i < ndistWords; i++) {
        int index = j + ((int)windexn[i]-1)*nK;    // (j,i)th element
        double value = wcountn[i]*tmpptr[i+j*ndistWords];
        if(index>=nK*V)
        {
            mexPrintf("\n %f %d %d %d ERROR !! \n", windexn[i], j, i, index);
            break;
        }
        sstopicwordptr[index] += value;
        //mexPrintf("%d\t", sstopicwordptr[index], index);
        sstopicptr[j] += value;
        }
    
    mxSetCell (retptr, n, tmp);
    return;
}
コード例 #4
0
ファイル: message.cpp プロジェクト: casro/rosmatlab
mxArray *message_constructor(const MessagePtr& message, int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  mxArray *result = 0;

  // parse inputs
  if (nrhs > 0 && Options::isString(prhs[0])) {
    std::string option = Options::getString(prhs[0]);
    if (nrhs == 1 && boost::algorithm::iequals(option, "definition")) {
      result = mxCreateString(message->getDefinition());
      return result;
    }
    if (nrhs == 1 && boost::algorithm::iequals(option, "md5sum")) {
      result = mxCreateString(message->getMD5Sum());
      return result;
    }
    if (nrhs == 1 && boost::algorithm::iequals(option, "fields")) {
      result = mxCreateCellMatrix(1, message->getFieldNames().size());
      for(std::size_t i = 0; i < message->getFieldNames().size(); ++i) {
        mxSetCell(result, i, mxCreateString(message->getFieldNames().at(i)));
      }
      return result;
    }
    if ((nrhs == 1 || nrhs == 2) && boost::algorithm::iequals(option, "default")) {
      if (nrhs == 2) {
        const mxArray *default_options = prhs[1];
        Conversion::perMessageOptions(message).merge(ConversionOptions(1, &default_options));
      }
      return Conversion::perMessageOptions(message).toMatlab();
    }
  }

  // Check if a numeric argument (message count) has been given
  std::size_t count = 1;
  if (nrhs > 0 && (Options::isIntegerScalar(prhs[0]) || Options::isDoubleScalar(prhs[0]))) {
    count = Options::getIntegerScalar(prhs[0]);
    nrhs--; prhs++;
  }

  // Get conversion options
  ConversionOptions options;
  if (nrhs % 2 == 0) {
    options.init(nrhs, prhs);
  } else {
    options.init(nrhs - 1, prhs + 1);
  }

  // Is this a copy constructor?
  if (nrhs % 2 != 0) {
    Conversion conversion(message, options);
    V_Message copy(conversion.numberOfInstances(prhs[0]));

    for(std::size_t j = 0; j < copy.size(); j++) {
      copy[j] = conversion.fromMatlab(prhs[0], j);
      // std::cout << "Constructed a new " << copy[j]->getDataType() << " message: " << *boost::shared_static_cast<MessageType const>(copy[j]->getConstInstance()) << std::endl;
      result = Conversion(conversion, copy[j]).toMatlab(result, j, copy.size());
    }

  // otherwise construct a new message
  } else {
    MessagePtr m = message->introspect(message->createInstance());
    // std::cout << "Constructed a new " << m->getDataType() << " message: " << *boost::shared_static_cast<MessageType const>(m->getConstInstance()) << std::endl;
    Conversion conversion(m, options);
    result = conversion.toMatlab();
  }

  // copy the contents of result if count > 1
  if (count > 1) {
    // This seems to be a bit hacky. Is there a better solution?
    mxArray *repmatrhs[] = { result, mxCreateDoubleScalar(1), mxCreateDoubleScalar(count) };
    mxArray *repmatlhs[] = { 0 };
    mexCallMATLAB(1, repmatlhs, 3, repmatrhs, "repmat");
    mxDestroyArray(repmatrhs[0]);
    mxDestroyArray(repmatrhs[1]);
    mxDestroyArray(repmatrhs[2]);
    result = repmatlhs[0];
  }

  return result;
}
コード例 #5
0
static void dispatch(int n, int m, double *x_ptr, double *c_ptr, double *d_ptr, int nlhs, mxArray *plhs[])
{
  // Read parameters
  typename KDTree<K, double>::points_type X;
  
  typename KDTree<K, double>::point_type v;
  
  for (int i = 0; i < n; ++i)
    {
      for (unsigned k = 0; k < K; ++k)
	v[k] = x_ptr[i + (n * k)];
      X.push_back(v);
    }

  typename KDTree<K, double>::points_type C;

  std::vector<double> R;

  for (int i = 0; i < m; ++i)
    {
      for (unsigned k = 0; k < K; ++k)
	v[k] = c_ptr[i + (m * k)];
      C.push_back(v);
      R.push_back(d_ptr[i]);
    }

  // Build kd-tree
  KDTree<K, double> kdtree(X);

  // Compute queries
  std::list<typename KDTree<K, double>::set_type > res_list;
  typename KDTree<K, double>::set_type res;
	
  for (int i = 0; i < m; ++i)
    {
      kdtree.ball_query(C[i], R[i], res);

      res_list.push_back(res);
			
      res.clear();
    }

  // Write output
  if (nlhs > 0)
    {
      const mwSize size[2] = {res_list.size(), 1};
      plhs[0] = mxCreateCellArray(2, size);
			
      int cnt = 0;
      for (typename std::list<typename KDTree<K, double>::set_type>::const_iterator it = res_list.begin(); it != res_list.end(); ++it, ++cnt)
	{
	  if (it->size())
	    {
	      mxArray * pArray = mxCreateDoubleMatrix(it->size(), 1, mxREAL);
	      double * p = mxGetPr(pArray);
				
	      for (typename KDTree<K, double>::set_type::const_iterator it2 = it->begin(); it2 != it->end(); ++it2)
		*p++ = it2->second + 1;
				
	      mxSetCell(plhs[0], cnt, pArray);
	    }
	}
    }

  if (nlhs > 1)
    {
      const mwSize size[2] = {res_list.size(), 1};
      plhs[1] = mxCreateCellArray(2, size);
			
      int cnt = 0;
      for (typename std::list<typename KDTree<K, double>::set_type>::const_iterator it = res_list.begin(); it != res_list.end(); ++it, ++cnt)
	{
	  if (it->size())
	    {
	      mxArray * pArray = mxCreateDoubleMatrix(it->size(), 1, mxREAL);
	      double * p = mxGetPr(pArray);
				
	      for (typename KDTree<K, double>::set_type::const_iterator it2 = it->begin(); it2 != it->end(); ++it2)
		*p++ = it2->first;
				
	      mxSetCell(plhs[1], cnt, pArray);
	    }
	}
    }
}
コード例 #6
0
ファイル: sql_select.c プロジェクト: wrrnsmith/sqlite4m
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
  mwSize subs[2];
  mxArray *trowmajor;
  char *zsql, *strbuf;
  int i, j, k, iret, istep, irow=0, nrow_alloc=0, ncol, kval, nval, kk, iargbind=4;
  int isnumeric=1,  ldestroy=1, coltyp, classid;

  int n_par_tobind=0, n_val_tobind=1;
  const mxArray *mxBindPar=NULL;

  strcat(errmsgstr1, "select:");

/* check for proper number of arguments */
  if( nrhs<2)
    ERRABORT("nrhs", "at least two input arguments are needed.");

  /* Make sure that input arguments 2...2nd last are strings: */
  for( k=2; k<nrhs-1; k++ )
    if( !mxIsChar(prhs[k]) )
      ERRABORT("notChar", "After the 2nd argument only string input is expected.");

/* if the first argument is a string, then open a database connection  */
  if( mxIsChar(prhs[0]) ) {
    mexCallMATLAB(1, &mxppDb, 1, (mxArray **) &prhs[0], "sql_open");
    ppDb = *((sqlite3 **) mxGetData(mxppDb));
  } else
    ppDb = *((sqlite3 **) mxGetData(prhs[0]));

  zsql = getzsql(nrhs, prhs, &iargbind);
  /* mexPrintf("zsql = %s\n", zsql); */

  /* Prepare the SQL library for the select statement: */
  iret = sqlite3_prepare_v2(ppDb, zsql, strlen(zsql), &ppStmt, NULL);
  /* mexPrintf("sqlite3_prepare_v2 returned %d\n", iret); */

  /* Return the statement in the second optional output argument*/
  if( nlhs>=2 )
    plhs[1] = mxCreateString(zsql);
  else
    mxFree(zsql);

  if( iret!=SQLITE_OK ) {
    char errmsgbuf[strlen(sqlite3_errmsg(ppDb))+1];
    strcpy(errmsgbuf, sqlite3_errmsg(ppDb));
    CLOSE_DB;
    ERRABORT("prepare", errmsgbuf);
  }

  /* If there are parameters to bind, check the matlab variables
     and find out how many parameters/values: */
  bind_m2sql(ppStmt, iargbind, prhs, &n_par_tobind, &n_val_tobind);

  /* How many columns? */
  ncol = sqlite3_column_count(ppStmt);
  /* mexPrintf("sqlite3_column_count returned %d\n", ncol); */

  /* The numbers of rows is not known at this point. Therefore
     the elements are first stored row-by-row in a temporary cell array,
     so that memory can be reallocated as database rows are added. */
  trowmajor = mxCreateCellMatrix(ncol, 0);

  /* Loop over the values that need to be bound to parameters, 
     if no parameters to bind n_val_tobind=1 and the loop is executed once: */
  for( kval=0; kval<n_val_tobind; kval++ ) {
    BIND_MATPAR(MEXFUN)

    /* Step along the selected rows: */
    while( (istep = sqlite3_step(ppStmt))==SQLITE_ROW ) {
      /* A row is available,
	 if needed then enlarge the output cell array: */
      if( irow>=nrow_alloc ) {
	/* mexPrintf("irow = %d, nrow_alloc = %d\n", irow, nrow_alloc);*/
	if( nrow_alloc==0 )  /* The first row is found */
	  nrow_alloc++;
	else
	  nrow_alloc *= 2;
	mxSetData(trowmajor,
		  mxRealloc(mxGetData(trowmajor),
			    sizeof(mxArray *)*nrow_alloc*ncol));
	/* mexPrintf("%d bytes reallocated\n", sizeof(mtype)*nrow_alloc*ncol); */
      }
      /* Increment the nr of columns of the output matrix by one: */ 
      mxSetN(trowmajor, mxGetN(trowmajor)+1);
      /* mexPrintf("plhs enlarged to %d %d\n",
	 mxGetM(trowmajor), mxGetN(trowmajor)); */
      
      subs[1] = irow++;
      for( k=0; k<ncol; k++ ) {
	subs[0] = k;
	coltyp = sqlite3_column_type(ppStmt, k);
	/* mexPrintf("subs = %d %d, coltyp = %d, mxCalcSingleSubscript = %d\n",
		  subs[0], subs[1], coltyp,
		  mxCalcSingleSubscript(trowmajor, 2, subs)); */
	
	switch( coltyp) {
	  mxArray *rnum;
	  int nblob;
	case SQLITE_NULL: /* NULL values are mapped in Matlab to empty cells: */
	  /* mexPrintf("NULL selected at ncol = %d and irow %d\n", subs[0], subs[1]); */
	  rnum = mxCreateDoubleMatrix(0, 1, mxREAL);
	  mxSetCell(trowmajor, 
		    mxCalcSingleSubscript(trowmajor, 2, subs), rnum);
	  isnumeric = 0;
	  break;
	case SQLITE_TEXT:
	  mxSetCell(trowmajor, 
		    mxCalcSingleSubscript(trowmajor, 2, subs),
		    mxCreateString(sqlite3_column_text(ppStmt, k)));
	  isnumeric = 0;
	  break;
	case SQLITE_BLOB:
	  nblob = sqlite3_column_bytes(ppStmt, k);
	  mxArray *blob = mxCreateNumericMatrix(1, nblob, mxUINT8_CLASS, mxREAL);
	  memcpy(mxGetPr(blob), sqlite3_column_blob(ppStmt, k), nblob);
	  mxSetCell(trowmajor, 
		    mxCalcSingleSubscript(trowmajor, 2, subs), blob);
	  isnumeric = 0;
	  break;
	case SQLITE_FLOAT:
	  rnum = mxCreateDoubleMatrix(1, 1, mxREAL);
	  *mxGetPr(rnum) = sqlite3_column_double(ppStmt, k);
	  mxSetCell(trowmajor, 
		    mxCalcSingleSubscript(trowmajor, 2, subs), rnum);
	  break;
	default:
	  sqlite3_finalize(ppStmt);
	  CLOSE_DB;
	  ERRABORT("column_type", "db should not have this column type");
	}
      }
    }
    /* mexPrintf("last return from sqlite3_step was %d\n", istep); */
    if( istep!=SQLITE_DONE ) {
      char errmsgbuf[strlen(sqlite3_errmsg(ppDb))+1];
      strcpy(errmsgbuf, sqlite3_errmsg(ppDb));
      sqlite3_finalize(ppStmt);
      CLOSE_DB;
      ERRABORT("done", sqlite3_errmsg(ppDb));
    }

    iret = sqlite3_reset(ppStmt);
    if( iret!=SQLITE_OK )
      mexWarnMsgIdAndTxt("Sqlite4m:sql_insert:reset", sqlite3_errmsg(ppDb));
  }
  TRY_SQLFUN(sqlite3_finalize(ppStmt), select, finalize);
  /* Release memory to the actual nr of db rows/matlab columns: */
  mxSetData(trowmajor,
	    mxRealloc(mxGetData(trowmajor),
		      sizeof(mxArray *)*mxGetN(trowmajor)*ncol));
  /* mexPrintf("final allocation is %d bytes\n", sizeof(mtype)*mxGetN(plhs[0])*ncol); */

  /* if the first argument was a string, then close the database connection  */
  CLOSE_DB;

  /* Transpose the row-by-row cell array into a double matrix
     if all elements are numeric: */
  /* if( isnumeric ) { */
  /*   plhs[0] = mxCreateDoubleMatrix(mxGetN(trowmajor), */
  /* 				   mxGetM(trowmajor), mxREAL); */
  /*   /\* Traverse the temporary row major array column by column, */
  /*      then the output array can be filled linearly: *\/ */
  /*   k = 0; */
  /*   for( i=0; i<mxGetM(trowmajor); i++ ) { */
  /*     subs[0] = i; */
  /*     for( j=0; j<mxGetN(trowmajor); j++ ) { */
  /* 	subs[1] = j; */
  /* 	mxGetPr(plhs[0])[k++] = */
  /* 	  *mxGetPr(mxGetCell(trowmajor, */
  /* 			     mxCalcSingleSubscript(trowmajor, 2, subs))); */
  /*     } */
  /*   } */
  /*   mxDestroyArray(trowmajor); */
  /* /\*  or else use Matlab transpose to copy into the output cell array, */
  /*       if at least one element is text or a blob: *\/ */
  /* } else */
    mexCallMATLAB(1, plhs, 1, &trowmajor, "transpose");
}
コード例 #7
0
void mexFunction(	int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{	
	int m, n;
	double *r_in;   
	double  *pr1, *pr2, *pt1, *pt2 , le, kv; 
	mxArray *tmpmxptr;
	

	if(nrhs)
	{
	
	/* ALLOCATE memory for the output array of the same size as the input */
	m = mxGetM(prhs[1]);
	n = mxGetN(prhs[1]);
	if(m!=6) 
		{mexErrMsgTxt("Second argument must be a 6 x N matrix");}	
	
	/* Required Fields */
	
	tmpmxptr = mxGetField(prhs[0],0,"Length");
	if(tmpmxptr)
	    le = mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'Length' was not found in the element data structure"); 
	    
	
	tmpmxptr = mxGetField(prhs[0],0,"K");
	if(tmpmxptr)
	    kv = mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'K' was not found in the element data structure"); 
	
	
	/* Optionnal arguments */    
	tmpmxptr = mxGetField(prhs[0],0,"R1");
	if(tmpmxptr)
	    pr1 = mxGetPr(tmpmxptr);
	else
	    pr1=NULL; 
	    
	tmpmxptr = mxGetField(prhs[0],0,"R2");
	if(tmpmxptr)
	    pr2 = mxGetPr(tmpmxptr);
	else
	    pr2=NULL; 

	tmpmxptr = mxGetField(prhs[0],0,"T1");

	
	if(tmpmxptr)
	    pt1=mxGetPr(tmpmxptr);
	else
	    pt1=NULL;

	tmpmxptr = mxGetField(prhs[0],0,"T2");
	if(tmpmxptr)
	    pt2=mxGetPr(tmpmxptr);
	else
	    pt2=NULL;  


	plhs[0] = mxDuplicateArray(prhs[1]);
	r_in = mxGetPr(plhs[0]);
	QuadLinearPass(r_in, le, kv, pt1, pt2, pr1, pr2, n);
	}
	else
	{   /* return list of required fields */
	    plhs[0] = mxCreateCellMatrix(2,1);
	    mxSetCell(plhs[0],0,mxCreateString("Length"));
	    mxSetCell(plhs[0],1,mxCreateString("K"));
	    
	    if(nlhs>1) /* Required and optional fields */ 
	    {   plhs[1] = mxCreateCellMatrix(4,1);
	        mxSetCell(plhs[1],0,mxCreateString("T1"));
	        mxSetCell(plhs[1],1,mxCreateString("T2"));
	        mxSetCell(plhs[1],2,mxCreateString("R1"));
	        mxSetCell(plhs[1],3,mxCreateString("R2"));
	    }
	}
}
コード例 #8
0
ファイル: mexSLOAD.cpp プロジェクト: NBT-Analytics/Biosig
void mexFunction(
    int           nlhs,           /* number of expected outputs */
    mxArray       *plhs[],        /* array of pointers to output arguments */
    int           nrhs,           /* number of inputs */
    const mxArray *prhs[]         /* array of pointers to input arguments */
)

{
	size_t 		k,k1;
	const mxArray	*arg;
	mxArray		*HDR;
	HDRTYPE		*hdr;
	CHANNEL_TYPE*	cp; 
	size_t 		count;
	time_t 		T0;
	char 		*FileName=NULL;  
	int 		status; 
	int		CHAN = 0;
	int		TARGETSEGMENT = 1; 
	double		*ChanList=NULL;
	int		NS = -1;
	char		FlagOverflowDetection = 1, FlagUCAL = 0;
	int		argSweepSel = -1;
	
#ifdef CHOLMOD_H
	cholmod_sparse RR,*rr=NULL;
	double dummy;
#endif 

// ToDO: output single data 
//	mxClassId	FlagMXclass=mxDOUBLE_CLASS;
	

	if (nrhs<1) {
#ifdef mexSOPEN
		mexPrintf("   Usage of mexSOPEN:\n");
		mexPrintf("\tHDR = mexSOPEN(f)\n");
		mexPrintf("   Input:\n\tf\tfilename\n");
		mexPrintf("   Output:\n\tHDR\theader structure\n\n");
#else
		mexPrintf("   Usage of mexSLOAD:\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f)\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan)\n\t\tchan must be sorted in ascending order\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,ReRef)\n\t\treref is a (sparse) matrix for rerefencing\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'...')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'OVERFLOWDETECTION:ON')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'OVERFLOWDETECTION:OFF')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'UCAL:ON')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'UCAL:OFF')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'OUTPUT:SINGLE')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'TARGETSEGMENT:<N>')\n");
		mexPrintf("\t[s,HDR]=mexSLOAD(f,chan,'SWEEP',[NE, NG, NS])\n");
		mexPrintf("   Input:\n\tf\tfilename\n");
		mexPrintf("\tchan\tlist of selected channels; 0=all channels [default]\n");
		mexPrintf("\tUCAL\tON: do not calibrate data; default=OFF\n");
//		mexPrintf("\tOUTPUT\tSINGLE: single precision; default='double'\n");
		mexPrintf("\tOVERFLOWDETECTION\tdefault = ON\n\t\tON: values outside dynamic range are not-a-number (NaN)\n");
		mexPrintf("\tTARGETSEGMENT:<N>\n\t\tselect segment <N> in multisegment files (like Nihon-Khoden), default=1\n\t\tIt has no effect for other data formats.\n");
		mexPrintf("\t[NE, NG, NS] are the number of the experiment, the series and the sweep, resp. for sweep selection in HEKA/PatchMaster files. (0 indicates all)\n");
		mexPrintf("\t\t examples: [1,2,3] the 3rd sweep from the 2nd series of experiment 1; [1,3,0] selects all sweeps from experiment=1, series=3. \n\n");
		mexPrintf("   Output:\n\ts\tsignal data, each column is one channel\n");
		mexPrintf("\tHDR\theader structure\n\n");
#endif
		return; 
	}

/*
 	improve checks for input arguments
*/
	/* process input arguments */
	for (k = 0; k < nrhs; k++) {	
		arg = prhs[k];
		if (mxIsEmpty(arg) && (k>0)) {
#ifdef DEBUG		
			mexPrintf("arg[%i] Empty\n",k);
#endif
		}
		else if ((k==0) && mxIsCell(arg) && mxGetNumberOfElements(arg)==1 && mxGetCell(arg,0) && mxIsChar(mxGetCell(arg,0))) {
			FileName = mxArrayToString(mxGetCell(arg,0));
#ifdef DEBUG		
			mexPrintf("arg[%i] IsCell\n",k);
#endif
		}
		else if ((k==0) && mxIsStruct(arg)) {
			FileName = mxArrayToString(mxGetField(prhs[k],0,"FileName"));
#ifdef DEBUG		
			mexPrintf("arg[%i] IsStruct\n",k);
#endif
		}
#ifdef CHOLMOD_H
		else if ((k==1) && mxIsSparse(arg)) {
			rr = sputil_get_sparse(arg,&RR,&dummy,0);
		}
#endif 
		else if ((k==1) && mxIsNumeric(arg)) {
#ifdef DEBUG		
			mexPrintf("arg[%i] IsNumeric\n",k);
#endif
			ChanList = (double*)mxGetData(prhs[k]);
			NS = mxGetNumberOfElements(prhs[k]);
		}	
		else if (mxIsChar(arg)) {
#ifdef DEBUG		
			mexPrintf("arg[%i]=%s \n",k,mxArrayToString(prhs[k]));
#endif
			if (k==0)			
				FileName = mxArrayToString(prhs[k]);
			else if (!strcmp(mxArrayToString(prhs[k]), "CNT32"))
				; // obsolete - supported for backwards compatibility
			else if (!strcmp(mxArrayToString(prhs[k]), "OVERFLOWDETECTION:ON"))
				FlagOverflowDetection = 1;
			else if (!strcmp(mxArrayToString(prhs[k]), "OVERFLOWDETECTION:OFF"))
				FlagOverflowDetection = 0;
			else if (!strcmp(mxArrayToString(prhs[k]), "UCAL:ON")) 
				FlagUCAL = 1;
			else if (!strcmp(mxArrayToString(prhs[k]), "UCAL:OFF"))
				FlagUCAL = 0;
//			else if (!strcmp(mxArrayToString(prhs[k]),"OUTPUT:SINGLE"))
//				FlagMXclass = mxSINGLE_CLASS;
			else if (!strncmp(mxArrayToString(prhs[k]),"TARGETSEGMENT:",14))
				TARGETSEGMENT = atoi(mxArrayToString(prhs[k])+14);
			else if (!strcasecmp(mxArrayToString(prhs[k]), "SWEEP") && (prhs[k+1] != NULL) && mxIsNumeric(prhs[k+1]))
				argSweepSel = ++k;
		}
		else {
#ifndef mexSOPEN
			mexPrintf("mexSLOAD: argument #%i is invalid.",k+1);	
			mexErrMsgTxt("mexSLOAD failes because of unknown parameter\n");	
#else
			mexPrintf("mexSOPEN: argument #%i is invalid.",k+1);	
			mexErrMsgTxt("mexSOPEN fails because of unknown parameter\n");	
#endif
		}
	}

	if (VERBOSE_LEVEL>7) 
		mexPrintf("110: input arguments checked\n");

	hdr = constructHDR(0,0);

#ifdef __LIBBIOSIG2_H__

	unsigned flags = (!!FlagOverflowDetection)*BIOSIG_FLAG_OVERFLOWDETECTION + (!!FlagUCAL)*BIOSIG_FLAG_UCAL;
#ifdef CHOLMOD_H
	flags += (rr!=NULL)*BIOSIG_FLAG_ROW_BASED_CHANNELS;
#else
	biosig_reset_flag(hdr, BIOSIG_FLAG_ROW_BASED_CHANNELS);
#endif
	biosig_set_flag(hdr, flags);

	biosig_set_targetsegment(hdr, TARGETSEGMENT);

	// sweep selection for Heka format
	if (argSweepSel>0) {
		double *SZ     = (double*) mxGetData(prhs[argSweepSel]);
		k = 0;
		while (k < mxGetNumberOfElements(prhs[argSweepSel]) && k < 5) {
			biosig_set_segment_selection(hdr, k+1, (uint32_t)SZ[k]);
			k++;
		}
	}

#else //__LIBBIOSIG2_H__


	hdr->FLAG.OVERFLOWDETECTION = FlagOverflowDetection; 
	hdr->FLAG.UCAL = FlagUCAL;
#ifdef CHOLMOD_H
	hdr->FLAG.ROW_BASED_CHANNELS = (rr!=NULL); 
#else 	
	hdr->FLAG.ROW_BASED_CHANNELS = 0; 
#endif 
	hdr->FLAG.TARGETSEGMENT = TARGETSEGMENT;

	// sweep selection for Heka format 
	if (argSweepSel>0) { 				
		double *SZ     = (double*) mxGetData(prhs[argSweepSel]);
		k = 0;
		while (k < mxGetNumberOfElements(prhs[argSweepSel]) && k < 5) { 
			hdr->AS.SegSel[k] = (uint32_t)SZ[k];
			k++;
		}
	}


#endif // __LIBBIOSIG2_H__ : TODO: below, nothing is converted to level-2 interface, yet


	if (VERBOSE_LEVEL>7) 
		mexPrintf("120: going to sopen\n");

	hdr = sopen(FileName, "r", hdr);
/*
#ifdef WITH_PDP 
	if (hdr->AS.B4C_ERRNUM) {
		hdr->AS.B4C_ERRNUM = 0;
		sopen_pdp_read(hdr);
	}	
#endif
*/
	if (VERBOSE_LEVEL>7) 
		mexPrintf("121: sopen done\n");

	if ((status=serror2(hdr))) {

		const char* fields[]={"TYPE","VERSION","FileName","FLAG","ErrNum","ErrMsg"};
		HDR = mxCreateStructMatrix(1, 1, 6, fields);
#ifdef __LIBBIOSIG2_H__
		mxSetField(HDR,0,"FileName",mxCreateString(biosig_get_filename(hdr)));
		const char *FileTypeString = GetFileTypeString(biosig_get_filetype(hdr));
		mxSetField(HDR,0,"VERSION",mxCreateDoubleScalar(biosig_get_version(hdr)));
#else
		mxSetField(HDR,0,"FileName",mxCreateString(hdr->FileName));
		const char *FileTypeString = GetFileTypeString(hdr->TYPE);
		mxSetField(HDR,0,"VERSION",mxCreateDoubleScalar(hdr->VERSION));
#endif
		mxArray *errnum = mxCreateNumericMatrix(1,1,mxUINT8_CLASS,mxREAL);
		*(uint8_t*)mxGetData(errnum) = (uint8_t)status;
		mxSetField(HDR,0,"ErrNum",errnum);
		
#ifdef HAVE_OCTAVE
		// handle bug in octave: mxCreateString(NULL) causes segmentation fault
		// Octave 3.2.3 causes a seg-fault in mxCreateString(NULL)
		if (FileTypeString) FileTypeString="\0";
#endif
		mxSetField(HDR,0,"TYPE",mxCreateString(FileTypeString));


		char *msg = (char*)malloc(72+23+strlen(FileName)); // 72: max length of constant text, 23: max length of GetFileTypeString()
		if (msg == NULL) 
			mxSetField(HDR,0,"ErrMsg",mxCreateString("Error mexSLOAD: Cannot open file\n"));
		else {	
		    if (status==B4C_CANNOT_OPEN_FILE)
			sprintf(msg,"Error mexSLOAD: file %s not found.\n",FileName);		/* Flawfinder: ignore *** sufficient memory is allocated above */
		    else if (status==B4C_FORMAT_UNKNOWN)
			sprintf(msg,"Error mexSLOAD: Cannot open file %s - format %s not known.\n",FileName,FileTypeString);	/* Flawfinder: ignore *** sufficient memory is allocated above */
		    else if (status==B4C_FORMAT_UNSUPPORTED)
			sprintf(msg,"Error mexSLOAD: Cannot open file %s - format %s not supported [%s].\n", FileName, FileTypeString, hdr->AS.B4C_ERRMSG);	/* Flawfinder: ignore *** sufficient memory is allocated above */
		    else 	
			sprintf(msg,"Error %i mexSLOAD: Cannot open file %s - format %s not supported [%s].\n", status, FileName, FileTypeString, hdr->AS.B4C_ERRMSG); 	/* Flawfinder: ignore *** sufficient memory is allocated above */
			
		    mxSetField(HDR,0,"ErrMsg",mxCreateString(msg));
		    free(msg);
		}    

	if (VERBOSE_LEVEL>7) 
		mexPrintf("737: abort mexSLOAD - sopen failed\n");

		destructHDR(hdr);

	if (VERBOSE_LEVEL>7) 
		mexPrintf("757: abort mexSLOAD - sopen failed\n");

#ifdef mexSOPEN
		plhs[0] = HDR; 
#else
		plhs[0] = mxCreateDoubleMatrix(0,0, mxREAL);
		plhs[1] = HDR; 
#endif 		 
	if (VERBOSE_LEVEL>7) 
		mexPrintf("777: abort mexSLOAD - sopen failed\n");

		return; 
	}

#ifdef CHOLMOD_H
	RerefCHANNEL(hdr,rr,2);
#endif

	if (hdr->FLAG.OVERFLOWDETECTION != FlagOverflowDetection)
		mexPrintf("Warning mexSLOAD: Overflowdetection not supported in file %s\n",hdr->FileName);
	if (hdr->FLAG.UCAL != FlagUCAL)
		mexPrintf("Warning mexSLOAD: Flag UCAL is %i instead of %i (%s)\n",hdr->FLAG.UCAL,FlagUCAL,hdr->FileName);


	if (VERBOSE_LEVEL>7) 
		fprintf(stderr,"[112] SOPEN-R finished NS=%i %i\n",hdr->NS,NS);

//	convert2to4_eventtable(hdr); 
		
#ifdef CHOLMOD_H
	if (hdr->Calib != NULL) {
		NS = hdr->Calib->ncol;
	}
	else 
#endif
	if ((NS<0) || ((NS==1) && (ChanList[0] == 0.0))) { 	// all channels
		for (k=0, NS=0; k<hdr->NS; ++k) {
			if (hdr->CHANNEL[k].OnOff) NS++; 
		}	
	}		
	else {		
		for (k=0; k<hdr->NS; ++k)
			hdr->CHANNEL[k].OnOff = 0; 	// reset
		for (k=0; k<NS; ++k) {
			int ch = (int)ChanList[k];
			if ((ch < 1) || (ch > hdr->NS)) 
				mexPrintf("Invalid channel number CHAN(%i) = %i!\n",k+1,ch); 
			else 	
				hdr->CHANNEL[ch-1].OnOff = 1;  // set
		}		
	}
	
	if (VERBOSE_LEVEL>7) 
		fprintf(stderr,"[113] NS=%i %i\n",hdr->NS,NS);

#ifndef mexSOPEN
	if (hdr->FLAG.ROW_BASED_CHANNELS)
		plhs[0] = mxCreateDoubleMatrix(NS, hdr->NRec*hdr->SPR, mxREAL);
	else
		plhs[0] = mxCreateDoubleMatrix(hdr->NRec*hdr->SPR, NS, mxREAL);

	count = sread(mxGetPr(plhs[0]), 0, hdr->NRec, hdr);
	hdr->NRec = count; 
#endif
	sclose(hdr);
#ifdef CHOLMOD_H
        if (hdr->Calib && hdr->rerefCHANNEL) {
		hdr->NS = hdr->Calib->ncol; 
                free(hdr->CHANNEL);
                hdr->CHANNEL = hdr->rerefCHANNEL;
                hdr->rerefCHANNEL = NULL; 
                hdr->Calib = NULL; 
        }                
#endif 
	if ((status=serror2(hdr))) return;  

	if (VERBOSE_LEVEL>7) 
		fprintf(stderr,"\n[129] SREAD/SCLOSE on %s successful [%i,%i] [%i,%i] %i.\n",hdr->FileName,(int)hdr->data.size[0],(int)hdr->data.size[1],(int)hdr->NRec,(int)count,(int)NS);


//	hdr2ascii(hdr,stderr,4);	

#ifndef mexSOPEN 

	if (nlhs>1) { 
#endif

		char* mexFileName = (char*)mxMalloc(strlen(hdr->FileName)+1); 

		mxArray *tmp, *tmp2, *Patient, *Manufacturer, *ID, *EVENT, *Filter, *Flag, *FileType;
		uint16_t numfields;
		const char *fnames[] = {"TYPE","VERSION","FileName","T0","tzmin","FILE","Patient",\
		"HeadLen","NS","SPR","NRec","SampleRate", "FLAG", \
		"EVENT","Label","LeadIdCode","PhysDimCode","PhysDim","Filter",\
		"PhysMax","PhysMin","DigMax","DigMin","Transducer","Cal","Off","GDFTYP","TOffset",\
		"LowPass","HighPass","Notch","ELEC","Impedance","fZ","AS","Dur","REC","Manufacturer",NULL};

		for (numfields=0; fnames[numfields++] != NULL; );
		HDR = mxCreateStructMatrix(1, 1, --numfields, fnames);

		mxSetField(HDR,0,"TYPE",mxCreateString(GetFileTypeString(hdr->TYPE)));
		mxSetField(HDR,0,"HeadLen",mxCreateDoubleScalar(hdr->HeadLen));
		mxSetField(HDR,0,"VERSION",mxCreateDoubleScalar(hdr->VERSION));
		mxSetField(HDR,0,"NS",mxCreateDoubleScalar(NS));
		mxSetField(HDR,0,"SPR",mxCreateDoubleScalar(hdr->SPR));
		mxSetField(HDR,0,"NRec",mxCreateDoubleScalar(hdr->NRec));
		mxSetField(HDR,0,"SampleRate",mxCreateDoubleScalar(hdr->SampleRate));
		mxSetField(HDR,0,"Dur",mxCreateDoubleScalar(hdr->SPR/hdr->SampleRate));
		mxSetField(HDR,0,"FileName",mxCreateString(hdr->FileName));
                
		mxSetField(HDR,0,"T0",mxCreateDoubleScalar(ldexp(hdr->T0,-32)));
		mxSetField(HDR,0,"tzmin",mxCreateDoubleScalar(hdr->tzmin));

		/* Channel information */ 
#ifdef CHOLMOD_H
/*
        	if (hdr->Calib == NULL) { // is refering to &RR, do not destroy
		        mxArray *Calib = mxCreateDoubleMatrix(hdr->Calib->nrow, hdr->Calib->ncol, mxREAL);

        	}
*/
#endif
		mxArray *LeadIdCode  = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *PhysDimCode = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *GDFTYP      = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *PhysMax     = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *PhysMin     = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *DigMax      = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *DigMin      = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Cal         = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Off         = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Toffset     = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *ELEC_POS    = mxCreateDoubleMatrix(NS,3, mxREAL);
/*
		mxArray *ELEC_Orient = mxCreateDoubleMatrix(NS,3, mxREAL);
		mxArray *ELEC_Area   = mxCreateDoubleMatrix(NS,1, mxREAL);
*/
		mxArray *LowPass     = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *HighPass    = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Notch       = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Impedance   = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *fZ          = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *SPR         = mxCreateDoubleMatrix(1,NS, mxREAL);
		mxArray *Label       = mxCreateCellMatrix(NS,1);
		mxArray *Transducer  = mxCreateCellMatrix(NS,1);
		mxArray *PhysDim1    = mxCreateCellMatrix(NS,1);

		for (k=0,k1=0; k1<NS; ++k) 
		if (hdr->CHANNEL[k].OnOff) {
			*(mxGetPr(LeadIdCode)+k1)	= (double)hdr->CHANNEL[k].LeadIdCode;
			*(mxGetPr(PhysDimCode)+k1)	= (double)hdr->CHANNEL[k].PhysDimCode;
			*(mxGetPr(GDFTYP)+k1)		= (double)hdr->CHANNEL[k].GDFTYP;
			*(mxGetPr(PhysMax)+k1)		= (double)hdr->CHANNEL[k].PhysMax;
			*(mxGetPr(PhysMin)+k1)		= (double)hdr->CHANNEL[k].PhysMin;
			*(mxGetPr(DigMax)+k1)		= (double)hdr->CHANNEL[k].DigMax;
			*(mxGetPr(DigMin)+k1)		= (double)hdr->CHANNEL[k].DigMin;
			*(mxGetPr(Toffset)+k1)		= (double)hdr->CHANNEL[k].TOffset;
			*(mxGetPr(Cal)+k1) 		= (double)hdr->CHANNEL[k].Cal;
			*(mxGetPr(Off)+k1) 		= (double)hdr->CHANNEL[k].Off;
			*(mxGetPr(SPR)+k1) 		= (double)hdr->CHANNEL[k].SPR;
			*(mxGetPr(LowPass)+k1) 		= (double)hdr->CHANNEL[k].LowPass;
			*(mxGetPr(HighPass)+k1) 	= (double)hdr->CHANNEL[k].HighPass;
			*(mxGetPr(Notch)+k1) 		= (double)hdr->CHANNEL[k].Notch;
			*(mxGetPr(Impedance)+k1)	= (double)hdr->CHANNEL[k].Impedance;
			*(mxGetPr(fZ)+k1)		= (double)hdr->CHANNEL[k].fZ;
			*(mxGetPr(ELEC_POS)+k1)    	= (double)hdr->CHANNEL[k].XYZ[0];
			*(mxGetPr(ELEC_POS)+k1+NS)	= (double)hdr->CHANNEL[k].XYZ[1];
			*(mxGetPr(ELEC_POS)+k1+NS*2)	= (double)hdr->CHANNEL[k].XYZ[2];
/*
			*(mxGetPr(ELEC_Orient)+k1)	= (double)hdr->CHANNEL[k].Orientation[0];
			*(mxGetPr(ELEC_Orient)+k1+NS)	= (double)hdr->CHANNEL[k].Orientation[1];
			*(mxGetPr(ELEC_Orient)+k1+NS*2)	= (double)hdr->CHANNEL[k].Orientation[2];
			*(mxGetPr(ELEC_Area)+k1)	= (double)hdr->CHANNEL[k].Area;
*/
			mxSetCell(Label,k1,mxCreateString(hdr->CHANNEL[k].Label));
			mxSetCell(Transducer,k1,mxCreateString(hdr->CHANNEL[k].Transducer));
			
			mxSetCell(PhysDim1,k1,mxCreateString(PhysDim3(hdr->CHANNEL[k].PhysDimCode)));
			k1++;
		} 

		mxSetField(HDR,0,"LeadIdCode",LeadIdCode);
		mxSetField(HDR,0,"PhysDimCode",PhysDimCode);
		mxSetField(HDR,0,"GDFTYP",GDFTYP);
		mxSetField(HDR,0,"PhysMax",PhysMax);
		mxSetField(HDR,0,"PhysMin",PhysMin);
		mxSetField(HDR,0,"DigMax",DigMax);
		mxSetField(HDR,0,"DigMin",DigMin);
		mxSetField(HDR,0,"TOffset",Toffset);
		mxSetField(HDR,0,"Cal",Cal);
		mxSetField(HDR,0,"Off",Off);
		mxSetField(HDR,0,"Impedance",Impedance);
		mxSetField(HDR,0,"fZ",fZ);
		mxSetField(HDR,0,"Off",Off);
		mxSetField(HDR,0,"PhysDim",PhysDim1);
		mxSetField(HDR,0,"Transducer",Transducer);
		mxSetField(HDR,0,"Label",Label);

		const char* field[] = {"XYZ","Orientation","Area","GND","REF",NULL};
		for (numfields=0; field[numfields++] != 0; );
		tmp = mxCreateStructMatrix(1, 1, --numfields, field);
		mxSetField(tmp,0,"XYZ",ELEC_POS);
/*
		mxSetField(tmp,0,"Orientation",ELEC_Orient);
		mxSetField(tmp,0,"Area",ELEC_Area);
*/
		mxSetField(HDR,0,"ELEC",tmp);

		const char* field2[] = {"SPR",NULL};
		for (numfields=0; field2[numfields++] != 0; );
		tmp2 = mxCreateStructMatrix(1, 1, --numfields, field2);
		mxSetField(tmp2,0,"SPR",SPR);
		if (hdr->AS.bci2000!=NULL) {
			mxAddField(tmp2, "BCI2000");
			mxSetField(tmp2,0,"BCI2000",mxCreateString(hdr->AS.bci2000));
		}
		if (hdr->TYPE==Sigma) {	
			mxAddField(tmp2, "H1");
			mxSetField(tmp2,0,"H1",mxCreateString((char*)hdr->AS.Header));
		}	
		mxSetField(HDR,0,"AS",tmp2);
				
		/* FLAG */
		const char* field3[] = {"UCAL","OVERFLOWDETECTION","ROW_BASED_CHANNELS",NULL};
		for (numfields=0; field3[numfields++] != 0; );
		Flag = mxCreateStructMatrix(1, 1, --numfields, field3);
#ifdef MX_API_VER
//#if 1
                // Matlab, Octave 3.6.1 
       		mxSetField(Flag,0,"UCAL",mxCreateLogicalScalar(hdr->FLAG.UCAL));
        	mxSetField(Flag,0,"OVERFLOWDETECTION",mxCreateLogicalScalar(hdr->FLAG.OVERFLOWDETECTION));
        	mxSetField(Flag,0,"ROW_BASED_CHANNELS",mxCreateLogicalScalar(hdr->FLAG.ROW_BASED_CHANNELS));
#else 
                // mxCreateLogicalScalar are not included in Octave 3.0 
	        mxSetField(Flag,0,"UCAL",mxCreateDoubleScalar(hdr->FLAG.UCAL));
       		mxSetField(Flag,0,"OVERFLOWDETECTION",mxCreateDoubleScalar(hdr->FLAG.OVERFLOWDETECTION));
       		mxSetField(Flag,0,"ROW_BASED_CHANNELS",mxCreateDoubleScalar(hdr->FLAG.ROW_BASED_CHANNELS));
#endif
		mxSetField(HDR,0,"FLAG",Flag);

		/* Filter */ 
		const char *filter_fields[] = {"HighPass","LowPass","Notch",NULL};
		for (numfields=0; filter_fields[numfields++] != 0; );
		Filter = mxCreateStructMatrix(1, 1, --numfields, filter_fields);
		mxSetField(Filter,0,"LowPass",LowPass);
		mxSetField(Filter,0,"HighPass",HighPass);
		mxSetField(Filter,0,"Notch",Notch);
		mxSetField(HDR,0,"Filter",Filter);

		/* annotation, marker, event table */
		const char *event_fields[] = {"SampleRate","TYP","POS","DUR","CHN","Desc",NULL};
		
		if (hdr->EVENT.DUR == NULL)
			EVENT = mxCreateStructMatrix(1, 1, 3, event_fields);
		else {	
			EVENT = mxCreateStructMatrix(1, 1, 5, event_fields);
			mxArray *DUR = mxCreateDoubleMatrix(hdr->EVENT.N,1, mxREAL);
			mxArray *CHN = mxCreateDoubleMatrix(hdr->EVENT.N,1, mxREAL);
			for (k=0; k<hdr->EVENT.N; ++k) {
				*(mxGetPr(DUR)+k) = (double)hdr->EVENT.DUR[k];
				*(mxGetPr(CHN)+k) = (double)hdr->EVENT.CHN[k];  // channels use a 1-based index, 0 indicates all channels
			} 
			mxSetField(EVENT,0,"DUR",DUR);
			mxSetField(EVENT,0,"CHN",CHN);
		}

		if (hdr->EVENT.CodeDesc != NULL) {
			mxAddField(EVENT, "CodeDesc");
			mxArray *CodeDesc = mxCreateCellMatrix(hdr->EVENT.LenCodeDesc-1,1);
			for (k=1; k < hdr->EVENT.LenCodeDesc; ++k) {
				mxSetCell(CodeDesc,k-1,mxCreateString(hdr->EVENT.CodeDesc[k]));
			} 
			mxSetField(EVENT,0,"CodeDesc",CodeDesc);
		}	

		mxArray *TYP = mxCreateDoubleMatrix(hdr->EVENT.N,1, mxREAL);
		mxArray *POS = mxCreateDoubleMatrix(hdr->EVENT.N,1, mxREAL);

		for (k=0; k<hdr->EVENT.N; ++k) {
			*(mxGetPr(TYP)+k) = (double)hdr->EVENT.TYP[k];
			*(mxGetPr(POS)+k) = (double)hdr->EVENT.POS[k]+1;   // conversion from 0-based to 1-based indexing 
		} 
		mxSetField(EVENT,0,"TYP",TYP);
		mxSetField(EVENT,0,"POS",POS);

#if (BIOSIG_VERSION >= 10500)
		if (hdr->EVENT.TimeStamp) {
			mxArray *TimeStamp = mxCreateDoubleMatrix(hdr->EVENT.N,1, mxREAL);
			for (k=0; k<hdr->EVENT.N; ++k) {
				*(mxGetPr(TimeStamp)+k) = ldexp(hdr->EVENT.TimeStamp[k],-32);
			} 
			mxAddField(EVENT, "TimeStamp");
			mxSetField(EVENT,0,"TimeStamp",TimeStamp);
		}	
#endif
		mxSetField(EVENT,0,"SampleRate",mxCreateDoubleScalar(hdr->EVENT.SampleRate));
		mxSetField(HDR,0,"EVENT",EVENT);

		/* Record identification */ 
		const char *ID_fields[] = {"Recording","Technician","Hospital","Equipment","IPaddr",NULL};
		for (numfields=0; ID_fields[numfields++] != 0; );
		ID = mxCreateStructMatrix(1, 1, --numfields, ID_fields);
		mxSetField(ID,0,"Recording",mxCreateString(hdr->ID.Recording));
		mxSetField(ID,0,"Technician",mxCreateString(hdr->ID.Technician));
		mxSetField(ID,0,"Hospital",mxCreateString(hdr->ID.Hospital));
		mxSetField(ID,0,"Equipment",mxCreateString((char*)&hdr->ID.Equipment));
		int len = 4; 
		uint8_t IPv6=0;
		for (k=4; k<16; k++) IPv6 |= hdr->IPaddr[k];
		if (IPv6) len=16; 
		mxArray *IPaddr = mxCreateNumericMatrix(1,len,mxUINT8_CLASS,mxREAL);
		memcpy(mxGetData(IPaddr),hdr->IPaddr,len);
		mxSetField(ID,0,"IPaddr",IPaddr); 
		mxSetField(HDR,0,"REC",ID);

		/* Patient Information */ 
		const char *patient_fields[] = {"Sex","Handedness","Id","Name","Weight","Height","Birthday",NULL};
		for (numfields=0; patient_fields[numfields++] != 0; );
		Patient = mxCreateStructMatrix(1, 1, --numfields, patient_fields);
		const char *strarray[1];
#ifdef __LIBBIOSIG2_H__
		strarray[0] = biosig_get_patient_name(hdr);
		if (strarray[0]) {
			mxSetField(Patient,0,"Name",mxCreateCharMatrixFromStrings(1,strarray));
		}	
		strarray[0] = biosig_get_patient_id(hdr);
		if (strarray[0]) {
			mxSetField(Patient,0,"Id",mxCreateCharMatrixFromStrings(1,strarray));
		}	
#else
		strarray[0] = hdr->Patient.Name;
		if (strarray[0]) {
			mxSetField(Patient,0,"Name",mxCreateCharMatrixFromStrings(1,strarray));
		}
		strarray[0] = hdr->Patient.Id;
		if (strarray[0]) {
			mxSetField(Patient,0,"Id",mxCreateCharMatrixFromStrings(1,strarray));
		}
#endif
		mxSetField(Patient,0,"Handedness",mxCreateDoubleScalar(hdr->Patient.Handedness));

		mxSetField(Patient,0,"Sex",mxCreateDoubleScalar(hdr->Patient.Sex));
		mxSetField(Patient,0,"Weight",mxCreateDoubleScalar((double)hdr->Patient.Weight));
		mxSetField(Patient,0,"Height",mxCreateDoubleScalar((double)hdr->Patient.Height));
		mxSetField(Patient,0,"Birthday",mxCreateDoubleScalar(ldexp(hdr->Patient.Birthday,-32)));

		double d;
		if (hdr->Patient.Weight==0)		d = NAN;	// not-a-number		
		else if (hdr->Patient.Weight==255)	d = INFINITY;	// Overflow
		else					d = (double)hdr->Patient.Weight;
		mxSetField(Patient,0,"Weight",mxCreateDoubleScalar(d));
			
		if (hdr->Patient.Height==0)		d = NAN;	// not-a-number		
		else if (hdr->Patient.Height==255)	d = INFINITY;	// Overflow
		else					d = (double)hdr->Patient.Height;
		mxSetField(Patient,0,"Height",mxCreateDoubleScalar(d));
	
		/* Manufacturer Information */ 
		const char *manufacturer_fields[] = {"Name","Model","Version","SerialNumber",NULL};
		for (numfields=0; manufacturer_fields[numfields++] != 0; );
		Manufacturer = mxCreateStructMatrix(1, 1, --numfields, manufacturer_fields);

#ifdef __LIBBIOSIG2_H__
		strarray[0] = biosig_get_manufacturer_name(hdr);
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"Name",mxCreateCharMatrixFromStrings(1,strarray));
		}	
		strarray[0] = biosig_get_manufacturer_model(hdr);
		if (strarray[0]) {
			biosig_get_manufacturer_model(hdr);
			mxSetField(Manufacturer,0,"Model",mxCreateCharMatrixFromStrings(1,strarray));
		}	
		strarray[0] = biosig_get_manufacturer_version(hdr);
		if (strarray[0]) {
			biosig_get_manufacturer_version(hdr);
			mxSetField(Manufacturer,0,"Version",mxCreateCharMatrixFromStrings(1,strarray));
		}	
		strarray[0] = biosig_get_manufacturer_serial_number(hdr);
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"SerialNumber",mxCreateCharMatrixFromStrings(1,strarray));
		}
#else
		strarray[0] = hdr->ID.Manufacturer.Name;
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"Name",mxCreateCharMatrixFromStrings(1,strarray));
		}
		strarray[0] = hdr->ID.Manufacturer.Model;
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"Model",mxCreateCharMatrixFromStrings(1,strarray));
		}
		strarray[0] = hdr->ID.Manufacturer.Version;
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"Version",mxCreateCharMatrixFromStrings(1,strarray));
		}
		strarray[0] = hdr->ID.Manufacturer.SerialNumber;
		if (strarray[0]) {
			mxSetField(Manufacturer,0,"SerialNumber",mxCreateCharMatrixFromStrings(1,strarray));
		}
#endif
		mxSetField(HDR,0,"Manufacturer",Manufacturer);


	if (VERBOSE_LEVEL>7) 
		fprintf(stdout,"[148] going for SCLOSE\n");

		mxSetField(HDR,0,"Patient",Patient);

#ifndef mexSOPEN
		plhs[1] = HDR; 
	}
#else
	plhs[0] = HDR; 
#endif

	if (VERBOSE_LEVEL>7) fprintf(stdout,"[151] going for SCLOSE\n");
#ifdef CHOLMOD_H
	hdr->Calib = NULL; // is refering to &RR, do not destroy
#endif
	if (VERBOSE_LEVEL>7) fprintf(stdout,"[156] SCLOSE finished\n");
	destructHDR(hdr);
	hdr = NULL; 
	if (VERBOSE_LEVEL>7) fprintf(stdout,"[157] SCLOSE finished\n");
};
コード例 #9
0
ファイル: amplmex.c プロジェクト: jonathancurrie/OPTI
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    //Possible Inputs
    char fpath[FLEN];
    char msg[FLEN];
    char cmd[FLEN]; //user commmand 
    int sp = 0;
    
    //Outputs
    const char *fnames[15] = {"H","f","lb","ub","A","cl","cu","Q","l","qcind","x0","v0","sense","objbias","conlin"};
    double *sizes;
    
    //Internal Vars
    int ii; size_t i,j,k;       //indexing vars
    char *what, **whatp;        //error message vars
    static FILE *nl;            //file handle
    ASL *asl = cur_ASL;         //Current ASL instance
    int icmd = ASLCMD_ERROR;    //Command Integer
    double *sense;              //Objective sense
    double *objbias;            //Objective bias
    int obj_lin;                //linearity of the objectiuve (see ASL_DEGREE_ defines)
    double *con_lin;            //linearity of the constraints (see ASL_DEGREE_ defines)  
    double *isopen;             //Is ASL open
    bool nlcon = false;         //indicates whether any constraint is nonlinear
    double *x;                  //Evaluation point
    double *f, *g, *c = NULL;   //Return pointers
    int nerror;                 //eval errors

    //Sparse Indexing
    mwIndex *Ir, *Jc;
    double *Pr;

    //QP Checking Vars
    int nqpz = 0;               //number of nzs in quadratic objective
    int nqc_con = 0;            //number of quadratic constraints
    int *QP_ir, *QP_jc;         //Pointers used when calling nqpcheck
    double *QP_pr;
    double *pqi;                //pointer to quadratic index vector
    ograd *og;                  //objective gradient structure
            
    //Jacobian Vars
    static double *J = NULL;        //Memory to store intermediate Jacobian Values when using Dense Mode
    static double *J1 = NULL;       //Memory to store Jacobian Values 
    cgrad *cg, **cgp, **cgpe;       //constraint gradient structures
    int *cs;                        //Column starts
    
    //Hessian Vars
    static double *Hsp = NULL;      //Memory to store Hessian Values
    static int nhnz;                //Number of Hessian nz
    double *s, *v;                  //Sigma, Lambda
	int *hcs, *hr;                  //Hessian column starts, row indexs
	double *H, *He,  *W;    	      
    
    //Error catching
    Jmp_buf err_jmp0;
    
    //If no inputs, just return info
    if(nrhs < 1) 
    {
        if (nlhs >= 1)
        {
            sprintf(msgbuf,"%s %s",__TIME__,__DATE__);
            plhs[0] = mxCreateString(msgbuf);
            plhs[1] = mxCreateDoubleScalar(OPTI_VER);
        }
        else
        {
            printUtilityInfo();
        }
        return;
    }
        
    //Get User Command
    icmd = getCommand(prhs[0]);
    
    //Switch Yard for Command
    switch(icmd)
    {
        case ASLCMD_ISOPEN:
            isopen = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));
            if(asl)
                *isopen = 1;
            else
                *isopen = 0;
            break;
        
        case ASLCMD_OPEN:
            //Check for Errors
            if(nrhs < 2)
                mexErrMsgTxt("Expected two arguments to open a file! [x0,v0,lb,ub,cl,cu,sense,sizes] = asl('open','file path')\n");
            if(!mxIsChar(prhs[1]))
                mexErrMsgTxt("File path must be a char array!");
            //Get String
            CHECK(mxGetString(prhs[1], fpath, FLEN) == 0,"error reading file path!");
            //Clear any existing objects
            if (cur_ASL)
                ASL_free(&cur_ASL);
            //Set MEX exit function
            mexAtExit(mexExit);
            
            //Open file for LP/QP/QCQP checking
            asl = ASL_alloc(ASL_read_fg);               //allocate for qp read
            return_nofile = 1;                          //return 0 if stub doesn't exist
            nl = jac0dim(fpath,(ftnlen)strlen(fpath));  //read in passed file
            //Check we got the file
            if(!nl) {
                sprintf(msgbuf, "Can't open (or error opening) %s\n", fpath);
                mexErrMsgTxt(msgbuf);
			}
            //Allocate Vector Memory
            pPROB = mxCreateStructMatrix(1,1,15,fnames);
            mxSetField(pPROB,0,fnames[eX0],mxCreateDoubleMatrix(n_var,1, mxREAL));      
            mxSetField(pPROB,0,fnames[eV0],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eLB],mxCreateDoubleMatrix(n_var, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eUB],mxCreateDoubleMatrix(n_var, 1, mxREAL));            
            mxSetField(pPROB,0,fnames[eCL],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eCU],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eSENSE],mxCreateDoubleMatrix(1, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eOBJBIAS],mxCreateDoubleMatrix(1, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eCONLIN],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            //Get Fields (ASL will fill)       
            X0 = mxGetPr(mxGetField(pPROB,0,fnames[eX0]));   
            pi0 = mxGetPr(mxGetField(pPROB,0,fnames[eV0]));  
            LUv = mxGetPr(mxGetField(pPROB,0,fnames[eLB]));  
            Uvx = mxGetPr(mxGetField(pPROB,0,fnames[eUB]));              
            LUrhs = mxGetPr(mxGetField(pPROB,0,fnames[eCL]));  
            Urhsx = mxGetPr(mxGetField(pPROB,0,fnames[eCU]));  
            sense = mxGetPr(mxGetField(pPROB,0,fnames[eSENSE])); 
            objbias = mxGetPr(mxGetField(pPROB,0,fnames[eOBJBIAS]));
            con_lin = mxGetPr(mxGetField(pPROB,0,fnames[eCONLIN]));  
            //Other Output Args
            sizes = mxGetPr(pSIZE = mxCreateDoubleMatrix(16, 1, mxREAL));
                     
            //Check for complementarity problems
            if(n_cc)
                mexWarnMsgTxt("Ignoring Complementarity Constraints!");
            //Assign asl problem sizes
            sizes[0] = (double)n_var; sizes[1] = (double)n_con; sizes[2] = (double)nzc;
            sizes[3] = (double)lnc; sizes[4] = (double)nbv; sizes[5] = (double)niv;
            sizes[6] = (double)nlc; sizes[7] = (double)nlnc; sizes[8] = (double)nlo;
            sizes[9] = (double)nlvb; sizes[10] = (double)nlvc; sizes[11] = (double)nlvo;
            sizes[12] = (double)nlvbi; sizes[13] = (double)nlvci; sizes[14] = (double)nlvoi;
            sizes[15] = (double)nwv; 
            //Read In For QP Checking
            qp_read(nl,0); 
            //Assign sense
            if(objtype[0] == 1)
                *sense = -1; //max
            else
                *sense = 1; //min  
                      
            //Determine Objective Linearity
            obj_lin = linCheck(asl, 0);
            //Determine Constraints Linearity
            for(ii = 0; ii < n_con; ii++) {
                con_lin[ii] = linCheck(asl, -(ii+1));
                //Check if nonlinear or quadratic
                if(con_lin[ii] >= ASL_DEGREE_NLIN)
                    nlcon = true;
                else if(con_lin[ii] == ASL_DEGREE_QUAD)
                {
                    //con_lin indicates quadratic constraint, ensure is inequality
                    if(LUrhs[ii] != Urhsx[ii])
                        nqc_con++;
                    else
                        nlcon = true; //quadratic equalities not currently handled by any explicit QCQP solver (I know of), make nl
                }                    
            }
    
            //Check to force to read as nonlinear problem
            if(nrhs > 2 && *mxGetPr(prhs[2])==1)
                nlcon = true;
            
            //If objective or any constraint is nonlinear, then we have to process as an NLP
            if(obj_lin == ASL_DEGREE_NLIN || nlcon) {
                //Free the QP read memory
                ASL_free(&asl);
                //Re-open for full NLP read
                asl = ASL_alloc(ASL_read_pfgh);                 //allocate memory for pfgh read
                nl = jac0dim(fpath,(ftnlen)strlen(fpath));      //read passed file (full nl read)
                //Allocate Jacobian Memory [note use M1alloc to let ASL clean it up if multiple instances opened]
                J = (double*)M1alloc(nzc*sizeof(double));       //Memory to store Jacobian nzs  
                //Assign memory for saving obj + con x
                objx = (double*)M1alloc(n_var*sizeof(double));
                conx = (double*)M1alloc(n_var*sizeof(double));
                //Read File (f + g + H)
                pfgh_read(nl, ASL_findgroups); 
                //Assign Hessian Memory
                nhnz = sphsetup(1, 1, n_con > 0, 0);            //one obj, use sigma, optionally use lambda, full hessian
                Hsp = (double*)M1alloc(nhnz*sizeof(double));    //memory to store hessian nzs
            }
            //Otherwise we can process as a LP, QP or QCQP
            else {                
                //Assign objective bias
                *objbias = objconst(0);
                //Check for quadratic objective
                if(obj_lin == ASL_DEGREE_QUAD) {
                    //Capture Pointers
                    nqpz = nqpcheck(0, &QP_ir, &QP_jc, &QP_pr); //check objective for qp
                    //Create QP H
                    mxSetField(pPROB,0,fnames[eH],mxCreateSparse(n_var,n_var,nqpz,mxREAL));                   
                    //Copy in Objective Quadratic Elements (copy-cast where appropriate)
                    memcpy(mxGetPr(mxGetField(pPROB,0,fnames[eH])),QP_pr,nqpz*sizeof(double));
                    Jc = mxGetJc(mxGetField(pPROB,0,fnames[eH]));
                    Ir = mxGetIr(mxGetField(pPROB,0,fnames[eH]));
                    for(i = 0; i <= n_var; i++)
                        Jc[i] = (mwIndex)QP_jc[i];
                    for(i = 0; i < nqpz; i++)
                        Ir[i] = (mwIndex)QP_ir[i];                       
                }
                else //create an empty sparse matrix
                    mxSetField(pPROB,0,fnames[eH],mxCreateSparse(n_var,n_var,0,mxREAL));
                
                //Create QP f
                mxSetField(pPROB,0,fnames[eF],mxCreateDoubleMatrix(n_var,1,mxREAL));
                Pr = mxGetPr(mxGetField(pPROB,0,fnames[eF]));
                //Copy in Objective Linear Elements
                for( og = Ograd[0]; og; og = og->next )
                    Pr[og->varno] = og->coef;
                
                //Create A (linear constraints)
                mxSetField(pPROB,0,fnames[eA],mxCreateSparse(n_con, n_var, nzc, mxREAL));
                if(n_con) {
                    Pr = mxGetPr(mxGetField(pPROB,0,fnames[eA]));
                    Ir = mxGetIr(mxGetField(pPROB,0,fnames[eA]));;                    
                    //Fill in A (will double on quadratic linear sections, but easier to remove once in MATLAB)
                    for(Jc = mxGetJc(mxGetField(pPROB,0,fnames[eA])), cs = A_colstarts, i = 0; i <= n_var; ++i)
                        Jc[i] = (mwIndex)cs[i];
                    cgp = Cgrad;
                    for(i = 0; i < n_con; i++)
                        for(cg = *cgp++; cg; cg = cg->next) {
                            Ir[cg->goff] = (mwIndex)i; 
                            Pr[cg->goff] = cg->coef;
                        }
                }
                
                //Add quadratic constraints if present
                if(nqc_con) {
                    //Allocate a Cell Array to store the quadratic constraint Qs, and vector to store indices
                    mxSetField(pPROB,0,fnames[eQ],mxCreateCellMatrix(nqc_con,1)); //Q
                    mxSetField(pPROB,0,fnames[eL],mxCreateDoubleMatrix(n_var, nqc_con,mxREAL)); //l
                    mxSetField(pPROB,0,fnames[eQCIND],mxCreateDoubleMatrix(nqc_con,1,mxREAL)); //ind                   
                    pqi = mxGetPr(mxGetField(pPROB,0,fnames[eQCIND]));
                    //Fill In Constraints
                    for(ii=0,j=0;ii<n_con;ii++) {
                        //Quadratic Constraints
                        if(con_lin[ii] == ASL_DEGREE_QUAD) {
                            //Create index
                            pqi[j] = ii+1; //increment for matlab index
                            //Capture Pointers
                            nqpz = nqpcheck(-(ii+1), &QP_ir, &QP_jc, &QP_pr); //check constraint for qp;
                            if(nqpz <= 0)
                                mexErrMsgTxt("Error reading quadratic constraints. Assumed constraint was quadratic based on prescan, now appears not?");
                            //Create QC Q
                            mxSetCell(mxGetField(pPROB,0,fnames[eQ]),j,mxCreateSparse(n_var,n_var,nqpz,mxREAL));                   
                            //Copy in Constraint Quadratic Elements (copy-cast where appropriate)
                            Pr = mxGetPr(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            Jc = mxGetJc(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            Ir = mxGetIr(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            for(k = 0; k <= n_var; k++)
                                Jc[k] = (mwIndex)QP_jc[k];
                            for(k = 0; k < nqpz; k++) {
                                Ir[k] = (mwIndex)QP_ir[k];
                                Pr[k] = 0.5*QP_pr[k];  //to QP form
                            }
                            //Create QC l (not sure why we can't extract this from Jacobian, values are wrong)
                            Pr = mxGetPr(mxGetField(pPROB,0,fnames[eL]));
                            for( cg = Cgrad[ii]; cg; cg = cg->next )
                                Pr[j*n_var + cg->varno] = cg->coef;
                            //Increment for next cell / col
                            j++;
                        }
                    } 
                }
                //Put back into function eval mode (just in case)
                qp_opify();
                
            }
            break;
            
        case ASLCMD_CLOSE:
            //Check for Errors
            CHECKASL(asl);
            //Call Exit Function
            mexExit();          
            break;                    
            
        case ASLCMD_FUN:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);             
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var); 
            //Save x
            if(objx) memcpy(objx,x,n_var*sizeof(double));                   
            //Create objective val memory and get it from ASL       
            SETERRJMP(); what = "objective";            
			f = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));            
			*f = objval(0, x, &nerror);        
            break;
            
        case ASLCMD_GRAD:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);            
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(objx) memcpy(objx,x,n_var*sizeof(double));            
            //Create objective grad memory and get it from ASL     
            SETERRJMP(); what = "gradient";            
			g = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, n_var, mxREAL));            
			objgrd(0, x, g, &nerror);            
            break;
            
        case ASLCMD_CON:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);            
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(conx) memcpy(conx,x,n_var*sizeof(double));                        
            //Create constraint memory and get it from ASL  
            SETERRJMP(); what = "constraints";
			c = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_con, 1, mxREAL));   
            if(n_con)
                conval(x, c, &nerror);            
            break;
            
        case ASLCMD_JAC:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);   
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(conx) memcpy(conx,x,n_var*sizeof(double));            
            //Create constraint jac memory and get it from ASL
            SETERRJMP(); what = "Jacobian";            
            //Check for sparsity
            if(nrhs > 2 && *mxGetPr(prhs[2])) {
                sp = 1;
                J1 = mxGetPr(plhs[0] = mxCreateSparse(n_con, n_var, nzc, mxREAL));
            }
            else {
                sp = 0;
                J1 = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_con, n_var, mxREAL));
            }        
            //Evaluate if we have constraints
            if (n_con) {                
                //Sparse
                if(sp) {
                    jacval(x, J1, &nerror);
                    Ir = mxGetIr(plhs[0]);
                    for(Jc = mxGetJc(plhs[0]), cs = A_colstarts, i = 0; i <= n_var; ++i)
                        Jc[i] = (mwIndex)cs[i];
                    cgp = Cgrad;
                    for(i = 0; i < n_con; i++)
                        for(cg = *cgp++; cg; cg = cg->next)
                            Ir[cg->goff] = (mwIndex)i;  
                }
                //Dense
                else {      
                    jacval(x, J, &nerror);
                    cgp = Cgrad;
                    for(cgpe = cgp + n_con; cgp < cgpe; J1++)
                        for(cg = *cgp++; cg; cg = cg->next)
                            J1[n_con*cg->varno] = J[cg->goff];
                }
            }                        
            break;
            
        case ASLCMD_JACSTR:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,1);            
            //Create constraint jacstr memory and get it from ASL
            SETERRJMP(); what = "Jacobian Structure)";                       
            J1 = mxGetPr(plhs[0] = mxCreateSparse(n_con, n_var, nzc, mxREAL));
            //Fill In Structure
            for(i=0;i<nzc;i++)
                J1[i] = 1.0;
            for(Jc = mxGetJc(plhs[0]), cs = A_colstarts, i = 0; i <= n_var; ++i)
                Jc[i] = (mwIndex)cs[i];
            cgp = Cgrad;
            Ir = mxGetIr(plhs[0]);
            for(i = 0; i < n_con; i++)
                for(cg = *cgp++; cg; cg = cg->next)
                    Ir[cg->goff] = (mwIndex)i;                
            break;
            
        case ASLCMD_HES:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,4); //assume hess(x,sigma,lambda) and optionally sparse            
            //Check dimensions & get args
            x = sizechk(prhs[1],"x",n_var);
            s = sizechk(prhs[2],"sigma",1);
            v = sizechk(prhs[3],"lambda",n_con);
            
            //Check for sparsity
            if(nrhs > 4 && *mxGetPr(prhs[4])) {
                sp = 1;
                W = mxGetPr(plhs[0] = mxCreateSparse(n_var, n_var, nhnz, mxREAL));
            }
            else {
                sp = 0;    
                W = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_var, n_var, mxREAL));
            }
            //Check if we need to recalculate objective / constraints
            if(!comp_x(objx,x,n_var)) {
                //Setup Error Catching
                SETERRJMP(); what = "Objective for Hessian";                
                //Re-evaluate Objective
                objval(0, x, &nerror);                
            }            
            if(!comp_x(conx,x,n_var)){
                if(!c)
                    c = mxGetPr(mxCreateDoubleMatrix(n_con, 1, mxREAL));                
                //Setup Error Catching
                SETERRJMP(); what = "Constraints for Hessian";                
                //Re-evaluate Constraints
                conval(x, c, &nerror);
            }            
            //Setup Error Catching
            SETERRJMP(); what = "Hessian";
            
            //Sparse
            if(sp) {
                //This function returns the full (symmetric) Hessian as setup above
                sphes(H = Hsp, 1, s, v);                
                Ir = mxGetIr(plhs[0]);
                Jc = mxGetJc(plhs[0]);
                hcs = sputinfo->hcolstarts;
                hr = sputinfo->hrownos;
                for(i = 0; i <= n_var; i++)
                    Jc[i] = (mwIndex)hcs[i];
                He = H + hcs[n_var];
                while(H < He) {
                    *W++ = *H++;
                    *Ir++ = (mwIndex)*hr++;
                }	
            }
            //Dense
            else
                fullhes(W, n_var, 1, s, v);            
            break;
            
        case ASLCMD_HESSTR:
            //mexPrintf("CMD: Get Hessian Structure\n");
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,1);            
            //Create hessianstr memory and get it from ASL
            SETERRJMP(); what = "Hessian Structure";
            W = mxGetPr(plhs[0] = mxCreateSparse(n_var, n_var, nhnz, mxREAL));
            Ir = mxGetIr(plhs[0]);
            Jc = mxGetJc(plhs[0]);
            //Get Sparse Info
            hcs = sputinfo->hcolstarts;
            hr = sputinfo->hrownos;
            //Assign col starts
            for(i = 0; i <= n_var; i++)
                Jc[i] = (mwIndex)hcs[i];
            //Assign rows + 1.0 for nz positions
            H = Hsp;                //Start of nz Hsp elements
            He = H + hcs[n_var];    //End of nz Hsp elements
            while(H < He) {
                *W++ = 1.0;                
                *Ir++ = (mwIndex)*hr++;
                *H++; //increment nz element position
            }	                        
            break;           
            
        case ASLCMD_WRITESOL:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2); //asl('writesol',msg,x)            
            //Get Input Args
            CHECK(mxGetString(prhs[1], msg, FLEN) == 0,"error reading message!");
            x = sizechk(prhs[2],"x",n_var);            
            //Write to solution stub file
            write_sol(msg,x,NULL,NULL);
            break;
            
        default:
            mexExit(); //clean up
            mxGetString(prhs[0], cmd, FLEN);
            sprintf(msgbuf, "ASL Command Error! Unknown Command: '%s'\n", cmd);
            mexErrMsgTxt(msgbuf);
            break;
    }
}
コード例 #10
0
/* entry point */
void mexFunction(int nlhs, mxArray *plhs[], 
                 int nrhs, const mxArray *prhs[])                
{
    int ind, i, x, y, o, dataDim, j, bytes_to_copy, nGaborFilter;
    const mxArray *f;
    const mxArray *pAS1Map;
    mxArray *outPA;
    mwSize ndim;
    const mwSize* dims;
    mwSize dimsOutput[2];
    void* start_of_pr;
    mxClassID datatype;

	/*
	 * input variable 0: nGaborOri
	 */
	nGaborOri = (int)mxGetScalar(prhs[0]);
 
    /*
	 * input variable 1: S1 maps
	 */
    pAS1Map = prhs[1];
    dims = mxGetDimensions(pAS1Map);
    nGaborFilter = dims[0] * dims[1];
    nGaborScale = nGaborFilter / nGaborOri;
 
    S1Map = (const float**)mxCalloc( nGaborFilter, sizeof(*S1Map) );   /* SUM1 maps */
    for (i=0; i<nGaborFilter; ++i)
    {
        f = mxGetCell(pAS1Map, i);
        datatype = mxGetClassID(f);
        if (datatype != mxSINGLE_CLASS)
            mexErrMsgTxt("warning !! single precision required.");
        S1Map[i] = (const float*)mxGetPr(f);    /* get the pointer to cell content */
        height = mxGetM(f);    /* overwriting is ok, since it is constant */
        width = mxGetN(f);
    }
    
    /*
     * input variable 2: location shift radius
     */
    locationPerturb = (int)mxGetScalar(prhs[2]);
    
    /*
     * input variable 3: orientation shift radius
     */
    orientationPerturb = (int)mxGetScalar(prhs[3]);
    
    /*
     * input variable 4: sub sample step length
     */
    subsample = (int)mxGetScalar(prhs[4]);

    StoreShift();
    Compute();
    
    /* =============================================
     * Handle output variables.
     * ============================================= 
     */
    
    /*
     * output variable 0: M1 map
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[0] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxSINGLE_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (float*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Map[i], bytes_to_copy );
        mxSetCell( plhs[0], i, outPA );
    }
    
    /*
     * output variable 1: M1 trace
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[1] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Trace[i], bytes_to_copy );
        mxSetCell( plhs[1], i, outPA );
    }
    
    /*
     * output variable 2: stored Gabor shifts : row shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[2] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, rowShift[i], bytes_to_copy );
        mxSetCell( plhs[2], i, outPA );
    }
    
    /*
     * output variable 3: stored Gabor shifts : col shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[3] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, colShift[i], bytes_to_copy );
        mxSetCell( plhs[3], i, outPA );
    }
    
    /*
     * output variable 4: stored Gabor shifts : orientation shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[4] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, orientShift[i], bytes_to_copy );
        mxSetCell( plhs[4], i, outPA );
    }
}
コード例 #11
0
ファイル: matwrap.hpp プロジェクト: Alienfeel/graphlab
 void set_cell_index2d(const size_t i, const size_t j,
                       matwrap contents) {
   safe_assert(array != NULL, "dereferenced null mxArray");
   mxSetCell(array, i + j*rows(), contents.array);    
 }
コード例 #12
0
ファイル: buffer_gethdr.c プロジェクト: KoraST/ft_BIU-1
void addChunksToMatrix(mxArray *S, const char *buf, int bufsize, int numChannels) {
	int bufpos = 0;
	int numBlobs = 0;
	mxArray *blobs[MAX_NUM_BLOBS];
	mxArray *keyval = NULL;
	mxArray *A;
	int field;

	while (bufpos + sizeof(ft_chunkdef_t) <= bufsize) {
		ft_chunk_t *chunk = (ft_chunk_t *) (buf + bufpos);
				
		/* "chunk" now points to the right location, make sure it has a valid size definition */
		if (bufpos + sizeof(ft_chunkdef_t) + chunk->def.size > bufsize) {
			printf("Invalid chunk size (%i) in Fieldtrip header detected. Stopping to parse.\n", chunk->def.size);
			break;
		}
				
		switch (chunk->def.type) {
			case FT_CHUNK_CHANNEL_NAMES:
				field = addIfNew(S, "channel_names");
				if (field < 0) break;
				A  = channelNames2Cell(chunk->data, chunk->def.size, numChannels);
				mxSetFieldByNumber(S, 0, field, A);
				break;
			case FT_CHUNK_NIFTI1:
				if (chunk->def.size != SIZE_NIFTI_1) {
					mexWarnMsgTxt("Invalid NIFTI-1 chunk detected. Skipping.");
					break;
				}
				field = addIfNew(S, "nifti_1");
				if (field < 0) break;
				/* pass on as 348 bytes (uint8), should be decoded on Matlab level (?) */
				A  = mxCreateNumericMatrix(1, SIZE_NIFTI_1, mxUINT8_CLASS, mxREAL);
				memcpy(mxGetData(A), chunk->data, SIZE_NIFTI_1);
				mxSetFieldByNumber(S, 0, field, A);
				break;
			case FT_CHUNK_SIEMENS_AP:
				field = addIfNew(S, "siemensap");
				if (field < 0) break;
				/* pass on as uint8, should be decoded on Matlab level (?) */
				A  = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL);
				memcpy(mxGetData(A), chunk->data, chunk->def.size);
				mxSetFieldByNumber(S, 0, field, A);
				break;
			case FT_CHUNK_CTF_RES4:
				field = addIfNew(S, "ctf_res4");
				if (field < 0) break;
				/* pass on as uint8, should be decoded on Matlab level (?) */
				A  = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL);
				memcpy(mxGetData(A), chunk->data, chunk->def.size);
				mxSetFieldByNumber(S, 0, field, A);
				break;
			case FT_CHUNK_RESOLUTIONS:
				field = addIfNew(S, "resolutions");
				if (field >=0) {
					int nc = chunk->def.size / sizeof(double);
					/*  If the chunk is buggy and there are less resolution values present,
						we only fill in those we have. If there are more, we only fill in numChannels.
						So the returned 'resolutions' field will always match the number of channels in the buffer.
					*/
					if (nc>numChannels) nc = numChannels;
					A = mxCreateDoubleMatrix(numChannels, 1, mxREAL);
					memcpy(mxGetPr(A), chunk->data, nc*sizeof(double));
				}
				break;
			case FT_CHUNK_UNSPECIFIED:
			default:
				if (numBlobs < MAX_NUM_BLOBS) {
					/* pass on the binary(?) blob as an uint8 matrix */
					A = mxCreateNumericMatrix(chunk->def.size, (chunk->def.size>0)?1:0, mxUINT8_CLASS, mxREAL);
					memcpy(mxGetData(A), chunk->data, chunk->def.size);
					blobs[numBlobs++] = A;
				} else {
					mexWarnMsgTxt("Encountered too many unspecified chunks in header. Skipping this one.");
				}
		}
		/* jump to next chunk */
		bufpos += chunk->def.size + sizeof(ft_chunkdef_t);
	}
	
	if (numBlobs > 0) {
		int i;
		
		field = addIfNew(S, "unspecified_blob");
		if (field < 0) return;
		
		A = mxCreateCellMatrix(numBlobs,1);
		for (i=0;i<numBlobs;i++) {
			mxSetCell(A, i, blobs[i]);
		}
		mxSetFieldByNumber(S, 0, field, A);
	}
}
コード例 #13
0
static void 
read_path(FILE *fob, mxArray **data, double dbu_to_uu) 
{
   mxArray *pstruct;
   mxArray *pprop = NULL;
   mxArray *pc;
   tList xylist;
   uint16_t rtype, rlen;
   int nprop = 0;
   int nle, k;
   element_t path;
   const char *fields[] = {"internal", "xy", "prop"};


   /* initialize element */
   init_element(&path, GDS_PATH);

   /* output data structure */
   pstruct = mxCreateStructMatrix(1,1, 3, fields);

   /* create a list for the XY data record(s) */
   if ( create_list(&xylist) == -1 )
      mexErrMsgTxt("gds_read_element (path) :  could not create list for XY records.");

   /* read element properties */
   while (1) {
      
      if ( read_record_hdr(fob, &rtype, &rlen) )
	 mexErrMsgTxt("gds_read_element (path) :  could not read record header.");

      if (rtype == ENDEL)
	 break;

      switch (rtype) {

         case XY:
	    if ( list_insert(xylist, read_xy(fob, rlen, dbu_to_uu), AFTER) == -1)
	       mexErrMsgTxt("gds_read_element (path) :  list insertion failed.");
	    break;

         case LAYER:
	    path.layer = read_layer(fob);
	    break;

         case PATHTYPE:
	    path.ptype = read_type(fob);
	    path.has |= HAS_PTYPE;
	    break;

         case WIDTH:
	    path.width = dbu_to_uu * (double)read_width(fob);
	    path.has |= HAS_WIDTH;
	    break;

         case BGNEXTN:
	    path.bgnextn = dbu_to_uu * read_extn(fob);
	    path.has |= HAS_BGNEXTN;
	    break;

         case ENDEXTN:
	    path.endextn = dbu_to_uu * read_extn(fob);
	    path.has |= HAS_ENDEXTN;
	    break;

         case DATATYPE:
	    path.dtype = read_type(fob);
	    break;

         case ELFLAGS:
	    path.elflags = read_elflags(fob);
	    path.has |= HAS_ELFLAGS;
	    break;

         case PLEX:
	    path.plex = read_plex(fob);
	    path.has |= HAS_PLEX;
	    break;

         case PROPATTR:
	    pprop = resize_property_structure(pprop, nprop+1);
	    mxSetFieldByNumber(pprop, nprop, 0, read_propattr(fob));
	    break;

         case PROPVALUE:
 	    mxSetFieldByNumber(pprop, nprop, 1, read_propvalue(fob,rlen));
	    nprop += 1;
	    break;

         default:
	    mexPrintf("Unknown record id: 0x%x\n", rtype);
	    mexErrMsgTxt("PATH :  found unknown element property.");
      }
   }

   /* cell array with XY records */
   nle = list_entries(xylist);
   if ( !nle )
      mexErrMsgTxt("gds_read_element (path) :  element has no XY record.");
   pc = mxCreateCellMatrix(1, nle);
   list_head(xylist);
   for (k=0; k<nle; k++)
      mxSetCell(pc, k, (mxArray *)get_current_entry(xylist, NULL));
   mxSetFieldByNumber(pstruct, 0, 1, pc);

   /* set prop field */
   if ( nprop ) {
      mxSetFieldByNumber(pstruct, 0, 2, pprop);
   }
   else {
      mxSetFieldByNumber(pstruct, 0, 2, empty_matrix());
   }

   /* store structure with element data */
   mxSetFieldByNumber(pstruct, 0, 0, copy_element_to_array(&path));

   /* return data */
   *data = pstruct;
}
コード例 #14
0
//=========================================================================
//=========================================================================
void initialize_unique_objects(unsigned char *js,mxArray *plhs[], struct sdata *slog){
    //
    //  This code will initialize unique objects (structures) with keys, 
    //  based on already having identified unique objects earlier.
    //
    //  This function populates
    //  -----------------------
    //  objects : cell array of empty structs with fields
    
    
    int n_unique_objects = slog->obj__n_unique_objects;
    
    if (n_unique_objects == 0){
        return;
    }
    
    int *d1 = get_int_field_by_number(plhs[0],E_d1);
    
    mxArray *object_info = plhs[0];
    
    int *child_count_object = get_int_field_by_number(object_info,E_obj__child_count_object);    
    int *unique_object_first_md_indices = get_int_field_by_number(object_info,E_obj__unique_object_first_md_indices);
    
    int max_keys_in_object = slog->obj__max_keys_in_object;
    
    if (max_keys_in_object == 0){
        //We have at least one objects, but none of the objects have keys
        //Create a single unique object with no fields ...
        mxArray *all_objects = mxCreateCellMatrix(1,1);
        mxArray *s = mxCreateStructMatrix(1,0,0,0);
        mxSetCell(all_objects, 0, s);
        mxSetFieldByNumber(object_info,0,E_obj__objects,all_objects);
        return;
    }
    
    //TODO: Define this here ...
    int *object_ids = get_int_field_by_number(object_info,E_obj__object_ids);
     
    mxArray *key_info = plhs[0];
    mxArray *temp_key_p = mxGetFieldByNumber(key_info,0,E_key__key_p);
    
    unsigned char **key_p = (unsigned char **)mxGetData(temp_key_p);
    
    
    int *key_sizes = get_int_field_by_number(key_info,E_key__key_sizes);
    int *next_sibling_index_key = get_int_field_by_number(key_info,E_key__next_sibling_index_key);
    
    //Note, Matlab does a deep copy of this field, so we are only
    //allocating a temporary array, note the final values.
    const char **fieldnames = mxMalloc(max_keys_in_object*sizeof(char *));
    
    //This is the output, stored in our output structure as "objects"
    mxArray *all_objects = mxCreateCellMatrix(1, n_unique_objects);
     
    mxArray *s;
    
    unsigned char *cur_key_p;
    int cur_key_md_index;
    int cur_key_data_index;
    int cur_key_size;
    int temp_key_index;
    
    int cur_object_md_index;
    int cur_object_data_index;
    int n_keys_in_object;
    
    //  For each unique object, get an example object and grab the fields
    //  of that object.
    
    for (int iObj = 0; iObj < n_unique_objects; iObj++){   
        cur_object_md_index = unique_object_first_md_indices[iObj];
        cur_object_data_index = d1[cur_object_md_index]; 
        n_keys_in_object = child_count_object[cur_object_data_index];

        cur_key_md_index = cur_object_md_index + 1;
        cur_key_data_index = d1[cur_key_md_index];
                
        for (int iKey = 0; iKey < n_keys_in_object; iKey++){
            cur_key_p = key_p[cur_key_data_index];
            cur_key_size = key_sizes[cur_key_data_index];
                        
            //JAH Notes 2018-09
            //1) This is modifying the original the JSON string
            //   which should be documented ...
            //      - we could fix this by writing the " back in
            //      - "my_string" => "my_string\0 => "my_string"
            //      - Matlab is deep copying the strings in
            //        mxCreateStructMatrix
            //2) We are not parsing for UTF-8, Matlab only supports
            //   ASCII for fields, this should be documented
            
            //At a minimum, we'll zero out the key to specify length
            //for Matlab. Matlab takes in an array of pointers to 
            //null-terminated strings rather than allowing us to specify
            //the size. So here we add null termination into the string.
            //Note that we are always zeroing a terminating quote symbol.
            *(cur_key_p + cur_key_size) = 0;
            
            fieldnames[iKey] = cur_key_p;
            
            //TODO: It is not obvious how the next sibling behaves at the
            //end - comment on this here ...
            cur_key_md_index = next_sibling_index_key[cur_key_data_index];
            cur_key_data_index = d1[cur_key_md_index];            
        }
        
        //We'll initialize as empty here, because we don't get much of 
        //an advantage of preinitializing if we are going to chop this up later
        //Initialing to zero still logs the field names
        //Any advantage of 1,0 vs 0,0?, vs even 1,1?
        //1,1 might be good if we only have 1 example, then we could
        //just use it later ... - this would require counting how many
        //objects take on this value ...
        s = mxCreateStructMatrix(1,0,n_keys_in_object,fieldnames);
        mxSetCell(all_objects, iObj, s);
    }
    
    mxFree(fieldnames);
    mxSetFieldByNumber(object_info,0,E_obj__objects,all_objects);
    
}
コード例 #15
0
void mexFunction(	int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{	int m,n;
	double *r_in;
	double le, *A, *B;  
	int max_order, num_int_steps;
	double  *pr1, *pr2, *pt1, *pt2, *ka;  
	mxArray *tmpmxptr;
	double E0;		/* Design energy [eV]  */


    if(nrhs)
    {
    /* ALLOCATE memory for the output array of the same size as the input */
	m = mxGetM(prhs[1]);
	n = mxGetN(prhs[1]);
	if(m!=6) 
		mexErrMsgTxt("Second argument must be a 6 x N matrix");
	
	
	
	tmpmxptr =mxGetField(prhs[0],0,"PolynomA");
	if(tmpmxptr)
	    A = mxGetPr(tmpmxptr);
	else
		mexErrMsgTxt("Required field 'PolynomA' was not found in the element data structure"); 
				    
	tmpmxptr =mxGetField(prhs[0],0,"PolynomB");
	if(tmpmxptr)   
	    B = mxGetPr(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'PolynomB' was not found in the element data structure");
					    
	tmpmxptr = mxGetField(prhs[0],0,"MaxOrder");
	if(tmpmxptr)
	    max_order = (int)mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'MaxOrder' was not found in the element data structure");
				        
	tmpmxptr = mxGetField(prhs[0],0,"NumIntSteps");
	if(tmpmxptr)   
	    num_int_steps = (int)mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'NumIntSteps' was not found in the element data structure");    
				    
	tmpmxptr = mxGetField(prhs[0],0,"Length");
	if(tmpmxptr)
	    le = mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'Length' was not found in the element data structure");    
	
	/* Kicks from multipole elements can be specified as angles. This handles the
	case where corrector coils are used in sextupoles and used for orbit
	correction. */
	tmpmxptr = mxGetField(prhs[0],0,"KickAngle");
	if(tmpmxptr)
	    ka = mxGetPr(tmpmxptr);
	else
            ka = NULL;
		
	tmpmxptr = mxGetField(prhs[0],0,"Energy");
	if(tmpmxptr)
	    E0 = mxGetScalar(tmpmxptr);
	else
	    mexErrMsgTxt("Required field 'Energy' was not found in the element data structure");  
				    
	tmpmxptr=mxGetField(prhs[0],0,"R1");
	if(tmpmxptr)
            pr1 = mxGetPr(tmpmxptr);
	else
	    pr1 = NULL; 
				
					    
	tmpmxptr=mxGetField(prhs[0],0,"R2");
	if(tmpmxptr)
            pr2 = mxGetPr(tmpmxptr);
	else
	    pr2 = NULL; 

	tmpmxptr=mxGetField(prhs[0],0,"T1");
	if(tmpmxptr)
	    pt1 = mxGetPr(tmpmxptr);
    	else
	    pt1 = NULL; 

	tmpmxptr=mxGetField(prhs[0],0,"T2");
	if(tmpmxptr)
            pt2 = mxGetPr(tmpmxptr);
	else
	    pt2 = NULL;
	

	if(ka!=NULL)
	{
	    /* Positive angle must correspond to -ve B field since +ve B field corresponds
	       to a bend with the same curvature as the bend magnets.
	    */
	    B[0] -= sin(ka[0])/le;
	    A[0] += sin(ka[1])/le;
	}

	plhs[0] = mxDuplicateArray(prhs[1]);
	r_in = mxGetPr(plhs[0]);
	
	StrMPoleSymplectic4RadPass(r_in, le, A, B, max_order, num_int_steps, 
											pt1, pt2, pr1, pr2, E0, n);
    
	if(ka!=NULL)
	{
	    B[0] -= sin(ka[0])/le;
	    A[0] -= sin(ka[1])/le;
	}
    

	}
	else
	{   /* return list of required fields */
	    plhs[0] = mxCreateCellMatrix(6,1);
	    mxSetCell(plhs[0],0,mxCreateString("Length"));
	    mxSetCell(plhs[0],1,mxCreateString("PolynomA"));
	    mxSetCell(plhs[0],2,mxCreateString("PolynomB"));
	    mxSetCell(plhs[0],3,mxCreateString("MaxOrder"));
            mxSetCell(plhs[0],4,mxCreateString("NumIntSteps"));
            mxSetCell(plhs[0],5,mxCreateString("Energy"));
	    
        if(nlhs>1) /* Required and optional fields */ 
	    {   plhs[1] = mxCreateCellMatrix(4,1);
	        mxSetCell(plhs[1],0,mxCreateString("T1"));
	        mxSetCell(plhs[1],1,mxCreateString("T2"));
	        mxSetCell(plhs[1],2,mxCreateString("R1"));
	        mxSetCell(plhs[1],3,mxCreateString("R2"));
	        mxSetCell(plhs[1],4,mxCreateString("KickAngle"));
	    }
    }



}
コード例 #16
0
ファイル: findnearest.C プロジェクト: ayinde07/dw
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[]) {



    /* Check for proper number of arguments. */
    if (nrhs != 3) {
        mexErrMsgTxt("Three inputs required.");
    }

    //the first argument is the array of vectors used to build the tree
    /*
      int nelements=mxGetNumberOfFields(prhs[0]);
    if(nelements!=1) {
      mexErrMsgTxt("Input should have one element.");
    }
    */

    //the second argument is the struct returned by covertree
    int nfields = mxGetNumberOfFields(prhs[1]);
    if(nfields!=8) {
        mexErrMsgTxt("Second input should have 8 fields.");
    }

    //the third argument is the struct whose first member is the array of
    //vectors being studied;
    //whose second member is the distance;
    //whose third member is the depth
    nfields = mxGetNumberOfFields(prhs[2]);
    if(nfields!=2) {
        mexErrMsgTxt("Third input should have two fields.");
    }

    const mxArray* tmp=0;

    //Check for proper number of return arguments; [D] or [D E] or [D E F]
    //Return argument one is a cell array D
    //D{i}=indices of A.vectors within distance of A.vectors(:,i) at right level
    //If two or more return arguments, E{i} is corresponding distances
    //F is diagnostics

    bool dist_flag=false;
    bool diag_flag=false;
    if(nlhs==3) {
        dist_flag=true;
        diag_flag=true;
    } else if (nlhs=3) {
        dist_flag=true;
    } else {
        if(nlhs!=1) {
            mexErrMsgTxt("One, two or three return arguments required\n");
        }
    }

    //Extract appropriate members from first input;
    //this is what what was passed to covertree

    tmp=prhs[0];
    mwSize ndims_in=mxGetNumberOfDimensions(tmp);
    const mwSize* dims_in=mxGetDimensions(tmp);

    int N=dims_in[ndims_in-1];
    int n=1;
    for(int i=0; i<ndims_in-1; i++) {
        n*=dims_in[i];
    }

    mexPrintf("n=%d N=%d\n",n,N);


    double* X=(double*)mxGetData(tmp);

    Vectors vectors(n,N,X);

    // Extract appropriate members from second input;
    //this is what was returned from covertree

    tmp=mxGetField(prhs[1],0,cover_in[0]);
    double* ptheta=(double*)mxGetData(tmp);
    double theta=*ptheta;

    tmp=mxGetField(prhs[1],0,cover_in[1]);
    int* params=(int*)mxGetData(tmp);

    tmp=mxGetField(prhs[1],0,cover_in[2]);
    int* lp=(int*)mxGetData(tmp);

    tmp=mxGetField(prhs[1],0,cover_in[3]);
    int* pchildren=(int*)mxGetData(tmp);
    DisjointLists children(N,pchildren,false);


    int* pdescend_list=(int*)mxMalloc(2*N*sizeof(int));
    int* pdist_flags=(int*)mxMalloc(N*sizeof(int));
    int* pindices_to_dist_flags=(int*)mxMalloc(N*sizeof(int));
    double* pdistances=(double*)mxMalloc(N*sizeof(double));
    int* pcurrent_child_flags=(int*)mxMalloc(N*sizeof(int));
    int* pindices_to_current_child_flags=(int*)mxMalloc(N*sizeof(int));
    int* pcurrent_children=(int*)mxMalloc(N*sizeof(int));

//Get third input

    //tmp=prhs[2];
    tmp=mxGetField(prhs[2],0,nearest_in[0]);
    ndims_in=mxGetNumberOfDimensions(tmp);
    dims_in=mxGetDimensions(tmp);


    int N2=dims_in[ndims_in-1];
    int n2=1;
    for(int i=0; i<ndims_in-1; i++) {
        n2*=dims_in[i];
    }

    mexPrintf("N2=%d\n",N2);

    if(n2!=n) {
        mexPrintf("n2=%d must equal n=%d\n",n2,n);
    }

    double* Y=(double*)mxGetData(tmp);

    tmp=mxGetField(prhs[2],0,nearest_in[1]);
    int* pk=(int*)mxGetData(tmp);
    int k=*pk;

    Cover cover(theta,
                params,
                &vectors,
                lp,children,
                pdescend_list,
                pdist_flags,pindices_to_dist_flags,
                pdistances,
                pcurrent_child_flags,pindices_to_current_child_flags,
                pcurrent_children);

    ndims=2;
    dims[0]=1;
    dims[1]=N2;

    mxArray* pointer0=mxCreateCellArray(ndims,dims);
    mxArray* pointer1=0;
    //Cover::DescendList* pdescendlist=0;
    if(dist_flag) {
        pointer1= mxCreateCellArray(ndims,dims);
        //pdescendlist=(Cover::DescendList*)&cover.getDescendList();
    }

    int* indices=(int*)mxMalloc(N*sizeof(int));
    double* d=(double*)mxMalloc(N*sizeof(double));
    int* Indices=(int*)mxMalloc(N*sizeof(int));
    double* D=(double*)mxMalloc(N*sizeof(double));

    for(int i=0; i<N2; i++) {
        //mexPrintf("loop i=%d\n",i);
        Vector v(n,Y+i*n);
        int K=cover.findNearest(&v,k,indices,d);
        dims[1]=K;
        mxArray* fout=mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
        int* arr=(int*)mxGetData(fout);
        for(int j=0; j<K; j++) {
            arr[j]=indices[j];
        }

        /*
        bool test=cover.checkFindNearest(&v,k,K,indices,d,Indices,D);
        if(test) {
          mexPrintf("checkFindWithin passed\n");
        } else {
          mexPrintf("checkFindWithin failed\n");
        }
        mexPrintf("after mxSetCell i=%d\n",i);
        */

        mxSetCell(pointer0,i,fout);
        if(dist_flag) {
            fout=mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
            double* dist=(double*)mxGetData(fout);
            for(int j=0; j<K; j++) {
                //dist[i]=pdescendlist->getDist(&v,arr[i]);
                dist[j]=d[j];
            }
            mxSetCell(pointer1,i,fout);
        }
        cover.clearDescendList();
    }

    plhs[0]=pointer0;
    if(dist_flag) {
        plhs[1]=pointer1;
    }

    if(diag_flag) {
        double* p=0;
        plhs[2]= mxCreateStructMatrix(1, 1, 4, fnames_out_2);
        ndims=2;
        dims[0]=1;
        dims[1]=1;

        mxArray* fout=0;
        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[0],fout);
        p[0]=cover.getDistNCallsToGet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[1],fout);
        p[0]=cover.getDistNCallsToSet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[2],fout);
        p[0]=cover.getChildrenNCallsToGet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[3],fout);
        p[0]=cover.getChildrenNCallsToSet();
    }

    mxFree(pdescend_list);
    mxFree(pdist_flags);
    mxFree(pindices_to_dist_flags);
    mxFree(pdistances);
    mxFree(pcurrent_child_flags);
    mxFree(pindices_to_current_child_flags);
    mxFree(pcurrent_children);

    mxFree(indices);
    mxFree(d);
    mxFree(Indices);
    mxFree(D);

}
コード例 #17
0
ファイル: lcaGetEnumStrings.c プロジェクト: Sangil-Lee/Work
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
PVs     pvs = { {0} };
int     i,j,ij,n;
LcaError theErr;
MultiArgRec	args[1];
enum_states *strbuf MAY_ALIAS = 0;
mxArray *tmp;

	lcaErrorInit(&theErr);

	LHSCHECK(nlhs, plhs);

	if ( nlhs > 1 ) {
		lcaSetError(&theErr, EZCA_INVALIDARG, "Too many output args");
		goto cleanup;
	}

	if ( nrhs < 1 || nrhs > 1 ) {
		lcaSetError(&theErr, EZCA_INVALIDARG, "Expected 1 rhs argument");
		goto cleanup;
	}

	if ( buildPVs(prhs[0], &pvs, &theErr) )
		goto cleanup;

	MSetArg(args[0], sizeof(*strbuf), 0, &strbuf);

	if ( !multi_ezca_get_misc(pvs.names, pvs.m, (MultiEzcaFunc)ezcaGetEnumStrings, NumberOf(args), args, &theErr) )
		goto cleanup;

	n = EZCA_ENUM_STATES;

	/* convert string array to a matlab cell array of matlab strings */
	if ( !(plhs[0] = mxCreateCellMatrix(pvs.m, n)) ) {
		lcaSetError(&theErr, EZCA_FAILEDMALLOC, "Not enough memory");
		goto cleanup;
	}
	ij = 0;
	for ( j = 0; j < n; j++ ) {
		for ( i = 0; i < pvs.m; i++ ) {
			if ( !(tmp = mxCreateString(strbuf[i][j])) ) {
				for ( j=0; j<ij; j++ ) {
					mxDestroyArray(mxGetCell(plhs[0],ij));
				}
				mxDestroyArray(plhs[0]);
				plhs[0] = 0;
				lcaSetError(&theErr, EZCA_FAILEDMALLOC, "Not enough memory");
				goto cleanup;
			}
			mxSetCell(plhs[0], ij, (mxArray*)tmp);
			ij++;
		}
	}

	nlhs = 0;

cleanup:
	if ( strbuf )
		lcaFree( strbuf );
	releasePVs(&pvs);
	/* do this LAST (in case mexErrMsgTxt is called) */
	ERR_CHECK(nlhs, plhs, &theErr);
}
コード例 #18
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  /* field data */
  LSMLIB_REAL *phi;
  LSMLIB_REAL *mask;
  LSMLIB_REAL **source_fields;
  LSMLIB_REAL *distance_function;
  LSMLIB_REAL **extension_fields;
  int num_ext_fields;
 
  /* grid data */
  const int *grid_dims = mxGetDimensions(PHI);
  double *dX = mxGetPr(DX);
  LSMLIB_REAL dX_matlab_order[2];

  /* numerical parameters */
  int spatial_discretization_order;

  /* auxilliary variables */
  int i;
  int error_code;
  mxArray* tmp_mxArray;

  /* Check for proper number of arguments */
  if (nrhs < 3) {
    mexErrMsgTxt(
      "Insufficient number of input arguments (3 required; 2 optional)");
  } else if (nrhs > 5) {
    mexErrMsgTxt("Too many input arguments (3 required; 2 optional)");
  } else if (nlhs > 2) {
    mexErrMsgTxt("Too many output arguments.");
  }

  /* Check that the inputs have the correct floating-point precision */
#ifdef LSMLIB_DOUBLE_PRECISION
    if (!mxIsDouble(PHI)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but phi is single-precision");
    }
#else
    if (!mxIsSingle(PHI)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but phi is double-precision");
    }
#endif

  /* Get mask */
  if ( (nrhs < 4) || (mxIsEmpty(MASK)) ) {
    mask = 0;  /* NULL mask ==> all points are in interior of domain */
  } else {

#ifdef LSMLIB_DOUBLE_PRECISION
    if (!mxIsDouble(MASK)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but mask is single-precision");
    }
#else
    if (!mxIsSingle(MASK)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but mask is double-precision");
    }
#endif

    mask = (LSMLIB_REAL*) mxGetPr(MASK);
  }

  /* Get spatial derivative order */
  if (nrhs < 5) {
    spatial_discretization_order = 2;
  } else {
    spatial_discretization_order = mxGetPr(SPATIAL_DERIVATIVE_ORDER)[0];
  }

  /* Assign pointers for phi and extension field data */
  phi = (LSMLIB_REAL*) mxGetPr(PHI);
  num_ext_fields = mxGetNumberOfElements(SOURCE_FIELDS);
  source_fields = (LSMLIB_REAL**) mxMalloc(num_ext_fields*sizeof(LSMLIB_REAL*));
  for (i = 0; i < num_ext_fields; i++) {
    tmp_mxArray = mxGetCell(SOURCE_FIELDS,i);

#ifdef LSMLIB_DOUBLE_PRECISION
    if (!mxIsDouble(tmp_mxArray)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but one of the source fields is single-precision");
    }
#else
    if (!mxIsSingle(tmp_mxArray)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but one of the source fields is double-precision");
    }
#endif

    source_fields[i] = (LSMLIB_REAL*) mxGetPr(tmp_mxArray);
  }


  /* Create distance function and extension field data */
#ifdef LSMLIB_DOUBLE_PRECISION
  DISTANCE_FUNCTION = mxCreateDoubleMatrix(grid_dims[0], grid_dims[1], mxREAL);
#else
  DISTANCE_FUNCTION = mxCreateNumericMatrix(grid_dims[0], grid_dims[1],
                                            mxSINGLE_CLASS, mxREAL);
#endif                                
  distance_function = (LSMLIB_REAL*) mxGetPr(DISTANCE_FUNCTION);
  num_ext_fields = mxGetNumberOfElements(SOURCE_FIELDS);
  EXTENSION_FIELDS = mxCreateCellArray(1, &num_ext_fields);
  extension_fields = 
    (LSMLIB_REAL**) mxMalloc(num_ext_fields*sizeof(LSMLIB_REAL*)); 
  for (i = 0; i < num_ext_fields; i++) {
#ifdef LSMLIB_DOUBLE_PRECISION
    tmp_mxArray = mxCreateDoubleMatrix(grid_dims[0], grid_dims[1], mxREAL);
#else
    tmp_mxArray= mxCreateNumericMatrix(grid_dims[0], grid_dims[1],
                                       mxSINGLE_CLASS, mxREAL);
#endif                                
    mxSetCell(EXTENSION_FIELDS, i, tmp_mxArray);
    extension_fields[i] = (LSMLIB_REAL*) mxGetPr(tmp_mxArray);
  }

  /* Change order of dX to be match MATLAB meshgrid() order for grids. */
  dX_matlab_order[0] = dX[1];
  dX_matlab_order[1] = dX[0];

  LSMLIB_REAL *extension_mask_dummy;	/* ipa.n */
  
  /* Carry out FMM calculation */
  error_code = computeExtensionFields2d(
                 distance_function,
                 extension_fields,
                 phi,
                 mask,
                 source_fields,
		          extension_mask_dummy,	/* ipa.n */
                 num_ext_fields,
                 spatial_discretization_order,
                 (int*) grid_dims,
                 dX_matlab_order);

  if (error_code) {
    mexErrMsgTxt("computeExtensionFields2d failed...");
  }

  /* Clean up memory */
  mxFree(source_fields); 
  mxFree(extension_fields);

  return;
}
コード例 #19
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){

  int dims [2];
  int i, j, k, m, n;
  long index;
  double * G_pr;
  double * stage_pr;
  double * answer_G_pr, * fill_ins_pr;
  double * matlab_clique_pr;
  mxArray * matlab_clique;
  Elimination e;
  float ** adj_mat;
  int ** order = (int **) NULL;
  Iterator iter, iter2;
  word w, w2;
  int ** fill_ins;
  Map cliques;
  Map clique;
  mxArray * fill_ins_mat;
  int * nodes;
  mxArray * full;

// (original)  full = mlfFull((mxArray *) prhs[0]);
  full = (mxArray *) mlfFull((mxArray *) prhs[0]);  // added typecasting
  /* Obtain graph matrix information. */
  m = mxGetM(full);
  n = mxGetN(full);
  G_pr = mxGetPr(full);

  if(n < 1 || m < 1){
    return;
  }

  /* Allocate and populate the log weight adjacency matrix corresponding
     to the input graph. */
  adj_mat = (float **) malloc(sizeof(float *) * m);
  adj_mat[0] = (float *) malloc(sizeof(float) * m * n);
  for(i = 1; i < m; i++){
    adj_mat[i] = adj_mat[i - 1] + n;
  }
  /* We no longer have log weight info, but we have a (total) ordering on
     the nodes already, so we do not need this information. */
  for(i = 0; i < m; i++){
    for(j = 0; j < n; j++){
      index = j * m + i;
      if(G_pr[index] > 0){
        adj_mat[i][j] = 1;
      } else {
        adj_mat[i][j] = 0;
      }
    }
  }

  /* Convert the total elimination ordering into a partial order argument
     for the elimination routine.  The elimination routine's purpose in this
     mode of operation is to return cliques and fill-in edges. */
  if(nrhs > 1){
    order = (int **) malloc(sizeof(int *) * m);
    order[0] = (int *) malloc(sizeof(int) * m * n);
    for(i = 1; i < m; i++){
      order[i] = order[i - 1] + n;
    }
    for(i = 0; i < m; i++){
      for(j = 0; j < n; j++){
        order[i][j] = 0;
      }
    }
    stage_pr = mxGetPr(prhs[1]);
    for(i = 0; i < mxGetN(prhs[1]) - 1; i++){
      order[(int) stage_pr[i] - 1][(int) stage_pr[i + 1] - 1] = 1;
    }
  }

  /* Find the elimination ordering. */
  e = find_elim(n, adj_mat, order, -1);

  /* Allocate memory for the answer, and set the answer. */
  plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);
  answer_G_pr = mxGetPr(plhs[0]);
  cliques = get_cliques(e);
/* 
  dims[0] = 1;
  dims[1] = get_size_Map(cliques);
  plhs[1] = mxCreateCellArray(2, (const int *) dims);*/
  plhs[1] = mxCreateCellMatrix(get_size_Map(cliques), 1);
  fill_ins = get_fill_ins(e);
  fill_ins_mat = mxCreateDoubleMatrix(m, n, mxREAL);
  fill_ins_pr = mxGetPr(fill_ins_mat);

  for(i = 0; i < n; i++){
    for(j = 0; j < m; j++){
      index = j * m + i;
      answer_G_pr[index] = G_pr[index];
      if(fill_ins[i][j] > 0){
        answer_G_pr[index] = 1;
        fill_ins_pr[index] = 1;
      }
    }
  }
  mxDestroyArray(full);
// (original)  plhs[2] = mlfSparse(fill_ins_mat, NULL, NULL, NULL, NULL, NULL);
  plhs[2] = (mxArray *) mlfSparse(fill_ins_mat, NULL, NULL, NULL, NULL, NULL); // added typecasting
  mxDestroyArray(fill_ins_mat);
  nodes = (int *) malloc(sizeof(int) * n);
  k = 0;
  iter = get_Iterator(cliques);
  while(!is_empty(iter)){
    w = next_key(iter);
    clique = (Map) w.v;
    matlab_clique = mxCreateDoubleMatrix(1, get_size_Map(clique), mxREAL);
    matlab_clique_pr = mxGetPr(matlab_clique);
    for(i = 0; i < n; i++){
      nodes[i] = 0;
    }
    iter2 = get_Iterator(clique);
    while(!is_empty(iter2)){
      w2 = next_key(iter2);
      nodes[w2.i] = w2.i + 1;
    }
    j = 0;
    for(i = 0; i < n; i++){
      if(nodes[i] > 0){
        matlab_clique_pr[j++] = nodes[i];
      }
    }
    mxSetCell(plhs[1], k++, matlab_clique);
  }
  free(nodes);

  /* Finally, free the allocated memory. */
  destroy_Elimination(e);
  if(adj_mat){
    if(adj_mat[0]){
      free(adj_mat[0]);
    }
    free(adj_mat);
  }
  if(order){
    if(order[0]){
      free(order[0]);
    }
    free(order);
  }
}
コード例 #20
0
ファイル: JoinNodes2.cpp プロジェクト: py3ams/vertex_model
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	
// 	printf("start of file \n");
	
	//	Get array_sizes
	const mxArray* mx_array_sizes = mexGetVariablePtr("global", "array_sizes");
	if (mx_array_sizes == NULL) {
		mexErrMsgTxt("array_sizes not defined");
	}
	unsigned array_sizes = (unsigned)mxGetScalar(mx_array_sizes);
	
	//	Get iteration
	const mxArray* mx_iteration = mexGetVariablePtr("caller", "iteration");
	if (mx_iteration == NULL) {
		mexErrMsgTxt("iteration not defined");
	}
	double iteration = mxGetScalar(mx_iteration);
	
	//	Get protection_time
	const mxArray* mx_protection_time = mexGetVariablePtr("caller", "protection_time");
	if (mx_protection_time == NULL) {
		mexErrMsgTxt("protection_time not defined");
	}
	double protection_time = mxGetScalar(mx_protection_time);
	
	//	Get join_probability
	const mxArray* mx_join_probability = mexGetVariablePtr("caller", "join_probability");
	if (mx_join_probability == NULL) {
		mexErrMsgTxt("join_probability not defined");
	}
	double join_probability = mxGetScalar(mx_join_probability);
	
	//	Get threshold_join_nodes
	const mxArray* mx_threshold_join_nodes = mexGetVariablePtr("caller", "threshold_join_nodes");
	if (mx_threshold_join_nodes == NULL) {
		mexErrMsgTxt("threshold_join_nodes not defined");
	}
	double threshold_join_nodes = mxGetScalar(mx_threshold_join_nodes);
	
	//	Get time
	const mxArray* mx_time = mexGetVariablePtr("global", "time");
	if (mx_time == NULL) {
		mexErrMsgTxt("time not defined");
	}
	double time = mxGetScalar(mx_time);
	
	unsigned width_cell_store = mxGetN(prhs[1]);
	unsigned no_cells = mxGetM(prhs[2]);
	unsigned no_FEM_elements = mxGetM(prhs[5]);
	unsigned length_FEM_node_positions = mxGetM(prhs[6]);
	
	double* initial_cell_store = mxGetPr(prhs[1]);
	double* initial_cells_per_node = mxGetPr(prhs[3]);
	double* initial_Dpp = mxGetPr(prhs[4]);
	double* initial_FEM_elements = mxGetPr(prhs[5]);
	double* initial_previous_FEM_node_positions = mxGetPr(prhs[6]);
	double* initial_node_positions = mxGetPr(prhs[7]);
	double* initial_time_nodes_created = mxGetPr(prhs[8]);
	
	plhs[0] = mxCreateCellMatrix(no_cells, 1);
	plhs[1] = mxCreateDoubleMatrix(array_sizes, width_cell_store, mxREAL);
	plhs[2] = mxCreateCellMatrix(no_cells, 1);
	plhs[3] = mxCreateDoubleMatrix(array_sizes, 1, mxREAL);
	plhs[4] = mxCreateDoubleMatrix(length_FEM_node_positions, 1, mxREAL);
	plhs[5] = mxCreateDoubleMatrix(no_FEM_elements, 3, mxREAL);
	plhs[6] = mxCreateDoubleMatrix(length_FEM_node_positions, 2, mxREAL);
	plhs[7] = mxCreateDoubleMatrix(array_sizes, 2, mxREAL);
	plhs[8] = mxCreateDoubleMatrix(array_sizes, 1, mxREAL);
	plhs[9] = mxCreateDoubleMatrix(1, 1, mxREAL);
	
	double* final_cell_store = mxGetPr(plhs[1]);
	double* final_cells_per_node = mxGetPr(plhs[3]);
	double* final_Dpp = mxGetPr(plhs[4]);
	double* final_FEM_elements = mxGetPr(plhs[5]);
	double* final_previous_FEM_node_positions = mxGetPr(plhs[6]);
	double* final_node_positions = mxGetPr(plhs[7]);
	double* final_time_nodes_created = mxGetPr(plhs[8]);
	double* no_join_nodes_this_iteration = mxGetPr(plhs[9]);
	
	*no_join_nodes_this_iteration = 0;
	
	// set output matrices equal to input matrices
	for(unsigned current_node=0;current_node<array_sizes;current_node++){
		final_cells_per_node[current_node] = initial_cells_per_node[current_node];
		final_time_nodes_created[current_node] = initial_time_nodes_created[current_node];
		for(unsigned dim=0;dim<2;dim++){
			final_node_positions[current_node+array_sizes*dim] = initial_node_positions[current_node+array_sizes*dim];
		}
		for(unsigned i=0;i<width_cell_store;i++){
			final_cell_store[current_node+i*array_sizes] = initial_cell_store[current_node+i*array_sizes];
		}
	}
	
	for(unsigned current_element=0;current_element<no_FEM_elements;current_element++){
		for(unsigned i=0;i<3;i++){
			final_FEM_elements[current_element+no_FEM_elements*i] =
					  initial_FEM_elements[current_element+no_FEM_elements*i];
		}
	}
	
	for(unsigned current_FEM_node=0;current_FEM_node<length_FEM_node_positions;current_FEM_node++){
		final_Dpp[current_FEM_node] = initial_Dpp[current_FEM_node];
		for(unsigned dim=0;dim<2;dim++){
			final_previous_FEM_node_positions[current_FEM_node+length_FEM_node_positions*dim] =
					  initial_previous_FEM_node_positions[current_FEM_node+length_FEM_node_positions*dim];
		}
	}
	
	// set output cells equal to input cells
	for(unsigned current_cell=0; current_cell<no_cells; current_cell++) {
		
		mxArray* mx_initial_cell_nodes = mxGetCell(prhs[2], current_cell);
		
		unsigned no_cell_nodes = mxGetN(mx_initial_cell_nodes);
		
		double* initial_cell_nodes = mxGetPr(mx_initial_cell_nodes);
		
		mxArray* mx_final_cell_nodes = mxCreateDoubleMatrix(1, no_cell_nodes, mxREAL);
		double* final_cell_nodes = mxGetPr(mx_final_cell_nodes);
		
		mxArray* mx_initial_cell_elements = mxGetCell(prhs[0], current_cell);
		double* initial_cell_elements = mxGetPr(mx_initial_cell_elements);
		
		mxArray* mx_final_cell_elements = mxCreateDoubleMatrix(1, no_cell_nodes, mxREAL);
		double* final_cell_elements = mxGetPr(mx_final_cell_elements);
		
		for(unsigned i=0; i<no_cell_nodes;i++){
			final_cell_nodes[i] = initial_cell_nodes[i];
			final_cell_elements[i] = initial_cell_elements[i];
		}
		
		mxSetCell(plhs[2], current_cell, mx_final_cell_nodes);
		mxSetCell(plhs[0], current_cell, mx_final_cell_elements);
		
	}
	
	bool join_logical;
	
	// loop over all cells
	for(unsigned current_cell_ci=0; current_cell_ci<no_cells; current_cell_ci++) {
		
		join_logical = false;
		
// 		printf("start of main loop \n");
		
		unsigned current_cell_mi = current_cell_ci+1;
		
		mxArray* mx_cell_nodes = mxGetCell(plhs[2], current_cell_ci);
		double* cell_nodes = mxGetPr(mx_cell_nodes);
		
		unsigned no_cell_nodes = mxGetN(mx_cell_nodes);
		
		// only proceed if there are more than 3 cell nodes
		if(no_cell_nodes > 3){
			
			// loop over the nodes of the current cell
			for(unsigned current_node_local=0; current_node_local<no_cell_nodes; current_node_local++) {
				
				double rand_number = rand()/((double)RAND_MAX);
				
				// only proceed with p(join_probability)
				if(rand_number < join_probability){
					
					// find current node and clockwise node in matlab and c indicies
					unsigned current_node_global_mi = (unsigned)cell_nodes[current_node_local];
					unsigned current_node_global_ci = current_node_global_mi-1;
					
					unsigned clockwise_node_local = (current_node_local+1)%no_cell_nodes;
					
					unsigned clockwise_node_global_mi = (unsigned)cell_nodes[clockwise_node_local];
					unsigned clockwise_node_global_ci = clockwise_node_global_mi - 1;
					
					// extract the positions of the current node and clockwise node from the node positions matrix
					double current_node_position[2], clockwise_node_position[2];
					
					for(unsigned dim=0;dim<2;dim++) {
						
						current_node_position[dim] = final_node_positions[current_node_global_ci + dim*array_sizes];
						clockwise_node_position[dim] = final_node_positions[clockwise_node_global_ci + dim*array_sizes];
					}
					
					// find the current edge length
					double current_edge_length = findStraightLineDistanceBetweenTwoNodes(current_node_position,
							  clockwise_node_position);
					
					// only proceed if edge length is less than threshold, and nodes have not been created very
					// recently
					if(current_edge_length < threshold_join_nodes &&
							  (time-final_time_nodes_created[current_node_global_ci])>protection_time &&
							  (time-final_time_nodes_created[clockwise_node_global_ci])>protection_time){
						
// 						printf("hello \n");
						
						// look for a cell that shares the edge - we need this for a T1 swap
						bool cell_with_same_edge_found = false;
						int cell_with_same_edge_mi = -1;
						
						unsigned counter_1 = 0;
						// loop over all cells containing current_node_global
						for(unsigned i=0;i<final_cells_per_node[current_node_global_ci];i++){
							
							unsigned temp_cell_1_mi = (unsigned)final_cell_store[current_node_global_ci + i*array_sizes];
							
							// if not current_cell, loop over all cells containing clockwise_node_global
							if(temp_cell_1_mi != current_cell_mi && !cell_with_same_edge_found){
								for(unsigned j=0;j<final_cells_per_node[clockwise_node_global_ci];j++){
									
									unsigned temp_cell_2_mi = (unsigned)final_cell_store[clockwise_node_global_ci + j*array_sizes];
									
									// if cell containing clockwise_node_global is also a cell containing current_node_global,
									// but not current_cell, then it is cell_with_same_edge;
									if(temp_cell_2_mi == temp_cell_1_mi){
										cell_with_same_edge_mi = temp_cell_1_mi;
										cell_with_same_edge_found = true;
										break;
									}
								}
							}
							
						}
						
						if(!cell_with_same_edge_found){
							
							join_logical = true;
							(*no_join_nodes_this_iteration)++;
							
// 							printf("doing a join \n");
							
							double new_node_position[2];
							for(unsigned dim=0;dim<2;dim++) {
								new_node_position[dim] = (current_node_position[dim] +
										  clockwise_node_position[dim])/2;
							}
							
							// find two unused nodes to put new nodes in
							unsigned new_node_ci = 0;
							while(final_cells_per_node[new_node_ci]>0){
								new_node_ci++;
							}
							unsigned new_node_mi = new_node_ci+1;
							
							assert(new_node_mi <= array_sizes);
							
							// store new node position
							for(unsigned dim=0;dim<2;dim++){
								final_node_positions[new_node_ci+dim*array_sizes] =
										  new_node_position[dim];
							}
							
							// set time new nodes created to current time
							final_time_nodes_created[new_node_ci] = time;
							
							// edit current cell nodes to contain new node instead of previous two nodes
							mxArray* mx_cell_nodes_edited = mxCreateDoubleMatrix(1, no_cell_nodes-1, mxREAL);
							double* cell_nodes_edited = mxGetPr(mx_cell_nodes_edited);
							
							int temp_counter = -1;
							for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes;temp_current_node_local++){
								
								unsigned temp_current_node_global_mi = (unsigned)cell_nodes[temp_current_node_local];
								
								if(temp_current_node_global_mi==current_node_global_mi){
									temp_counter++;
									cell_nodes_edited[temp_counter]=new_node_mi;
								}
								else if(temp_current_node_global_mi==clockwise_node_global_mi){}
								else{
									temp_counter++;
									cell_nodes_edited[temp_counter]=temp_current_node_global_mi;
								}
							}
							mxSetCell(plhs[2], current_cell_ci, mx_cell_nodes_edited);
							
// 							printf("edited current cell \n");
							
							final_cells_per_node[new_node_ci] = 1;
							final_cell_store[new_node_ci] = current_cell_mi;
							
							if(final_cells_per_node[current_node_global_ci] > 1.1){
								
								for(unsigned i=0;i<final_cells_per_node[current_node_global_ci];i++){
									
									unsigned temp_cell_mi = (unsigned)final_cell_store[current_node_global_ci + i*array_sizes];
									
									if(temp_cell_mi!=current_cell_mi){
										
										unsigned temp_cell_ci = temp_cell_mi-1;
										
										mxArray* mx_cell_nodes_temp_cell = mxGetCell(plhs[2], temp_cell_ci);
										double* cell_nodes_temp_cell = mxGetPr(mx_cell_nodes_temp_cell);
										unsigned no_cell_nodes_temp_cell = mxGetN(mx_cell_nodes_temp_cell);
										
										mxArray* mx_cell_nodes_temp_cell_edited = mxCreateDoubleMatrix(1, no_cell_nodes_temp_cell, mxREAL);
										double* cell_nodes_temp_cell_edited = mxGetPr(mx_cell_nodes_temp_cell_edited);
										
										for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes_temp_cell;temp_current_node_local++){
											
											unsigned temp_current_node_global_mi = (unsigned)cell_nodes_temp_cell[temp_current_node_local];
											
											if(temp_current_node_global_mi==current_node_global_mi){
												cell_nodes_temp_cell_edited[temp_current_node_local] = new_node_mi;
											}
											else{
												cell_nodes_temp_cell_edited[temp_current_node_local] = temp_current_node_global_mi;
											}
										}
										
										mxSetCell(plhs[2], temp_cell_ci, mx_cell_nodes_temp_cell_edited);
										
										final_cells_per_node[new_node_ci]++;
										unsigned matrix_index = (unsigned)(new_node_ci+array_sizes*(final_cells_per_node[new_node_ci]-1));
										final_cell_store[matrix_index] = temp_cell_mi;
									}
								}
// 								printf("edited cells with node 1 \n");
							}
							
							if(final_cells_per_node[clockwise_node_global_ci] > 1.1){
								
								for(unsigned i=0;i<final_cells_per_node[clockwise_node_global_ci];i++){
									
									unsigned temp_cell_mi = (unsigned)final_cell_store[clockwise_node_global_ci + i*array_sizes];
									
									if(temp_cell_mi!=current_cell_mi){
										
										unsigned temp_cell_ci = temp_cell_mi-1;
										
										// edit stretch cell 1 by adding in two new nodes in place of current node global
										mxArray* mx_cell_nodes_temp_cell = mxGetCell(plhs[2], temp_cell_ci);
										double* cell_nodes_temp_cell = mxGetPr(mx_cell_nodes_temp_cell);
										unsigned no_cell_nodes_temp_cell = mxGetN(mx_cell_nodes_temp_cell);
										
										mxArray* mx_cell_nodes_temp_cell_edited = mxCreateDoubleMatrix(1, no_cell_nodes_temp_cell, mxREAL);
										double* cell_nodes_temp_cell_edited = mxGetPr(mx_cell_nodes_temp_cell_edited);
										
										for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes_temp_cell;temp_current_node_local++){
											
											unsigned temp_current_node_global_mi = (unsigned)cell_nodes_temp_cell[temp_current_node_local];
											
											if(temp_current_node_global_mi==clockwise_node_global_mi){
												cell_nodes_temp_cell_edited[temp_current_node_local] = new_node_mi;
											}
											else{
												cell_nodes_temp_cell_edited[temp_current_node_local] = temp_current_node_global_mi;
											}
										}
										
										mxSetCell(plhs[2], temp_cell_ci, mx_cell_nodes_temp_cell_edited);
										
										// add stretch cell 1 to cells_per_node and cell_store for new_node and new_node_2
										final_cells_per_node[new_node_ci]++;
										unsigned matrix_index = (unsigned)(new_node_ci+array_sizes*(final_cells_per_node[new_node_ci]-1));
										final_cell_store[matrix_index] = temp_cell_mi;
										
									}
								}
								printf("edited cells with node 2 \n");
								
							}
							
							// reset cells per node and cell store for current_node_global and clockwise_node_global.
							// they should no longer be part of any cells, unless something has gone horribly wrong.
							final_cells_per_node[current_node_global_ci] = 0;
							final_cells_per_node[clockwise_node_global_ci] = 0;
							
							for(unsigned i=0;i<width_cell_store;i++){
								final_cell_store[current_node_global_ci+i*array_sizes] = 0;
								final_cell_store[clockwise_node_global_ci+i*array_sizes] = 0;
							}
							
							for(unsigned dim=0;dim<2;dim++){
								final_node_positions[current_node_global_ci+dim*array_sizes] = 0;
								final_node_positions[clockwise_node_global_ci+dim*array_sizes] = 0;
							}
						}
					}
				}
				if(join_logical){break;}
			}
		}
		if(join_logical){break;}
	}
}
コード例 #21
0
void LTFAT_NAME(ltfatMexFnc)( int UNUSED(nlhs), mxArray *plhs[],
                              int UNUSED(nrhs), const mxArray *prhs[] )
{

    static int atExitFncRegistered = 0;
    if(!atExitFncRegistered)
    {
        LTFAT_NAME(ltfatMexAtExit)(LTFAT_NAME(fftblMexAtExitFnc));
        atExitFncRegistered = 1;
    }

    const mxArray* mxF = prhs[0];
    const mxArray* mxG = prhs[1];
    double* foffDouble = (double*) mxGetData(prhs[2]);
    double* a = (double*) mxGetData(prhs[3]);
    double* realonlyDouble = (double*) mxGetData(prhs[4]);

    // input data length
    mwSize L = mxGetM(mxF);
    // number of channels
    mwSize W = mxGetN(mxF);
    // filter number
    mwSize M = mxGetNumberOfElements(mxG);

    //
    mwSize acols = mxGetN(prhs[3]);

    double afrac[M];
    memcpy(afrac,a,M*sizeof*a);
    if(acols>1)
    {
        for(mwIndex m=0; m<M; m++)
        {
            afrac[m] = afrac[m]/a[M+m];
        }
    }

    // output lengths
    mwSize outLen[M];
    // Frequency offsets
    mwSignedIndex foff[M];
    // realonly
    int realonly[M];

    // POINTER TO THE INPUT
    LTFAT_COMPLEX* FPtr = mxGetData(prhs[0]);

    // POINTER TO THE FILTERS
    const LTFAT_COMPLEX* GPtrs[M];
    // filter lengths
    mwSize Gl[M];
    // POINTER TO OUTPUTS
    LTFAT_COMPLEX* cPtrs[M]; // C99 feature

    plhs[0] = mxCreateCellMatrix(M, 1);

    if(M!=LTFAT_NAME(oldM) || W != LTFAT_NAME(oldW))
    {
        LTFAT_NAME(fftblMexAtExitFnc)();
        LTFAT_NAME(oldM) = M;
        LTFAT_NAME(oldW) = W;
        LTFAT_NAME(oldLc) = ltfat_calloc(M,sizeof(mwSize));
        LTFAT_NAME(oldPlans) =  ltfat_calloc(M,sizeof*LTFAT_NAME(oldPlans));
    }

    for(mwIndex m=0; m<M; ++m)
    {
        foff[m] = (mwSignedIndex) foffDouble[m];
        realonly[m] = (realonlyDouble[m]>1e-3);
        outLen[m] = (mwSize) floor( L/afrac[m] +0.5);
        GPtrs[m] = mxGetData(mxGetCell(mxG, m));
        Gl[m] = mxGetNumberOfElements(mxGetCell(mxG, m));
        mxSetCell(plhs[0], m, ltfatCreateMatrix(outLen[m], W,
                                  LTFAT_MX_CLASSID,mxCOMPLEX));
        cPtrs[m] = mxGetData(mxGetCell(plhs[0],m));

        if(LTFAT_NAME(oldLc)[m]!=outLen[m])
        {
            LTFAT_NAME(oldLc)[m] = outLen[m];
            LTFAT_NAME(convsub_fftbl_plan) ptmp =
            LTFAT_NAME(convsub_fftbl_init)( L, Gl[m], W, afrac[m], cPtrs[m]);

            if(LTFAT_NAME(oldPlans)[m]!=0)
            {
                 LTFAT_NAME(convsub_fftbl_done)(LTFAT_NAME(oldPlans)[m]);
            }
            LTFAT_NAME(oldPlans)[m]=ptmp; 
        }

    }


    LTFAT_NAME(filterbank_fftbl_execute)( LTFAT_NAME(oldPlans),FPtr, GPtrs, M,
                                 foff, realonly, cPtrs);
}
コード例 #22
0
void LTFAT_NAME(ltfatMexFnc)( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] )
{
  #ifdef _DEBUG
  static int atExitFncRegistered = 0;
  if(!atExitFncRegistered)
  {
     LTFAT_NAME(ltfatMexAtExit)(LTFAT_NAME(tdMexAtExitFnc));
     atExitFncRegistered = 1;
  }
  #endif

  const mxArray* mxf = prhs[0];
  const mxArray* mxg = prhs[1];
  double* a = (double*) mxGetData(prhs[2]);
  double* offset = (double*) mxGetData(prhs[3]);
  char* ext = mxArrayToString(prhs[4]);


  // input data length
  mwSize L = mxGetM(mxf);
  // number of channels
  mwSize W = mxGetN(mxf);
  // filter number
  mwSize M = mxGetNumberOfElements(mxg);
  // filter lengths
  mwSize filtLen[M];
  //mwSize* filtLen = mxMalloc(M*sizeof(mwSize));
  for(unsigned int m=0;m<M;m++)
  {
     filtLen[m] = (mwSize) mxGetNumberOfElements(mxGetCell(mxg,m));
  }

  // output lengths
  mwSize outLen[M];
  //mwSize* outLen = mxMalloc(M*sizeof(mwSize));
  if(!strcmp(ext,"per"))
  {
     for(unsigned int m = 0; m < M; m++)
     {
        outLen[m] = (mwSize) ceil( L/a[m] );
     }
  }
  else if(!strcmp(ext,"valid"))
  {
     for(unsigned int m = 0; m < M; m++)
     {
        outLen[m] = (mwSize) ceil( (L-(filtLen[m]-1))/a[m] );
     }
  }
  else
  {
     for(unsigned int m = 0; m < M; m++)
     {
        outLen[m] = (mwSize) ceil( (L + filtLen[m] - 1 + offset[m] )/a[m] );
     }
  }

     // POINTER TO THE INPUT
     LTFAT_TYPE* fPtr = (LTFAT_TYPE*) mxGetData(prhs[0]);

     // POINTER TO THE FILTERS
     LTFAT_TYPE* gPtrs[M];
     // LTFAT_TYPE** gPtrs = (LTFAT_TYPE**) mxMalloc(M*sizeof(LTFAT_TYPE*));
     for(mwIndex m=0;m<M;m++)
     {
        gPtrs[m] = (LTFAT_TYPE*) mxGetPr(mxGetCell(mxg, m));
     }

     // POINTER TO OUTPUTS
     LTFAT_TYPE* cPtrs[M]; // C99 feature
     //LTFAT_TYPE** cPtrs = (LTFAT_TYPE**) mxMalloc(M*sizeof(LTFAT_TYPE*));
     plhs[0] = mxCreateCellMatrix(M, 1);
     for(mwIndex m=0;m<M;++m)
     {
        mxSetCell(plhs[0], m, ltfatCreateMatrix(outLen[m], W,LTFAT_MX_CLASSID,LTFAT_MX_COMPLEXITY));
        cPtrs[m] = (LTFAT_TYPE*) mxGetData(mxGetCell(plhs[0],m));
        memset(cPtrs[m],0,outLen[m]*W*sizeof(LTFAT_TYPE));
     }

     // over all channels
   //  #pragma omp parallel for private(m)

        for(mwIndex m =0; m<M; m++)
        {
          for(mwIndex w =0; w<W; w++)
          {
           // Obtain pointer to w-th column in input
           LTFAT_TYPE *fPtrCol = fPtr + w*L;
           // Obtaing pointer to w-th column in m-th element of output cell-array
           LTFAT_TYPE *cPtrCol = cPtrs[m] + w*outLen[m];
           //conv_td_sub(fPtrCol,L,&cPtrCol,outLen[m],(const double**)&gPtrs[m],filtLen[m],1,a[m],skip[m],ltfatExtStringToEnum(ext),0);
           LTFAT_NAME(convsub_td)(fPtrCol,L,cPtrCol,outLen[m],gPtrs[m],filtLen[m],a[m],-offset[m],ltfatExtStringToEnum(ext));
          }
        }
}
コード例 #23
0
ファイル: read_qt.c プロジェクト: cabeen/mat-qt
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {

  if (nlhs < 0) { mexErrMsgTxt("Too few output arguments."); return; }
  if (nlhs > 1) { mexErrMsgTxt("Too many output arguments."); return; }
  if (nrhs < 1) { mexErrMsgTxt("Too few input arguments."); return; }
  if (nrhs > 3) { mexErrMsgTxt("Too many input arguments."); return; }

  TimeValue duration;
  TimeRecord myTimeRecord;
  Rect bounds;
  OSErr result = 0;
  short resRefNum = -1;
  short actualResId = DoTheRightThing;
  FSSpec theFSSpec;
  GWorldPtr offWorld;
  Movie theMovie = nil;
  MovieController thePlayer = nil;
  MovieDrawingCompleteUPP myDrawCompleteProc;
  long frame_end;
  long myStep = 1;
  char location[PATH_BUFFER_SIZE];
  long frame_count;
  mwSize cdims[2];

  mxGetString(prhs[0], location, PATH_BUFFER_SIZE);

  if (nrhs > 2) {
    frame_start = rint(mxGetScalar(prhs[1]));
    frame_end = rint(mxGetScalar(prhs[2]));
  } else if (nrhs > 1) {
    frame_start = 1;
    frame_end = rint(mxGetScalar(prhs[1]));
  } else {
    frame_start = 1;
    frame_end = 0;
  }

  if (frame_start < 1) {
    mexErrMsgTxt("Error: the starting frame must be positive\n"); 
    return; 
  }

  if (frame_end < 0) {
    mexErrMsgTxt("Error: the ending frame must be positive\n"); 
    return; 
  }

  if (frame_end != 0 && frame_end < frame_start) {
    mexErrMsgTxt("Error: the ending frame must not be less than the starting frame\n"); 
    return; 
  }

  myDrawCompleteProc = NewMovieDrawingCompleteUPP(DrawCompleteProc);

  EnterMovies();            

  if (NativePathNameToFSSpec(location, &theFSSpec, 0) ||
      OpenMovieFile(&theFSSpec, &resRefNum, 0) ||
      NewMovieFromFile(&theMovie, resRefNum, &actualResId, 0, 0, 0)) {
    mexErrMsgTxt("Error: failed to open movie\n"); 
    return; 
  }

  if (resRefNum != -1) CloseMovieFile(resRefNum);

  GetMovieBox(theMovie, &bounds);
  QTNewGWorld(&offWorld, k32ARGBPixelFormat, &bounds, NULL, NULL, 0);
  LockPixels(GetGWorldPixMap(offWorld));
  SetGWorld(offWorld, NULL);

  thePlayer = NewMovieController(theMovie, &bounds, mcTopLeftMovie | mcNotVisible);
  SetMovieGWorld(theMovie, offWorld, NULL);
  SetMovieActive(theMovie, true);
  SetMovieDrawingCompleteProc(theMovie, movieDrawingCallWhenChanged, myDrawCompleteProc, (long) offWorld);
  GetMovieTime(theMovie, &myTimeRecord);
  duration = GetMovieDuration(theMovie);

  // Compute the number of frames for allocation of output structure
  frame_count = 0;
  while ((frame_end == 0 || frame_count < frame_end) && GetMovieTime(theMovie, NULL) < duration) {
    frame_count++;
    MCDoAction(thePlayer, mcActionStep, (Ptr) myStep);
  }
  SetMovieTime(theMovie, &myTimeRecord);
  
  // Ignore frames greater than those in the file
  if (frame_end == 0 || frame_count < frame_end) frame_end = frame_count;
  
  cdims[0] = frame_end - frame_start + 1; // Indices are one-based
  cdims[1] = 1; 

  plhs[0] = mxCreateCellArray(2, cdims);

  // Step through the movie and save the frame when in the chosen interval
  // Note: the step size seems to be handled as a short internally. 
  //       Using anything greater than 32758 will seek to an incorrect frame
  frame_num = 1;
  while (frame_num <= frame_end) {
    MCDoAction(thePlayer, mcActionStep, (Ptr) myStep);
    if (frame_num >= frame_start) {
      MCIdle(thePlayer);
      mxSetCell(plhs[0], frame_num - frame_start, framedata);
    }
    frame_num++;
  }

  UnlockPixels(GetGWorldPixMap (offWorld));
  DisposeGWorld(offWorld);
  DisposeMovieController (thePlayer);
  DisposeMovie(theMovie);
  DisposeMovieDrawingCompleteUPP(myDrawCompleteProc);
  ExitMovies();

  return;
}
コード例 #24
0
void
mexFunction(int nout, mxArray *out[], 
            int nin, const mxArray *in[])
{
  uint8* img;
  
  enum {img_i=0, minLength_i} ;
  enum {c_edgeGroups_i=0, imgEdge_i} ;


  // int i =cvUseOptimized(1);
  // printf("optimized -> %d\n", i);
  /* ------------------------------------------------------------------
  **                                                Check the arguments
  ** --------------------------------------------------------------- */ 
  if (nin != 2) {
    mexErrMsgTxt("At least 1 input arguments required");
  } 
  if (nout > 2) {
    mexErrMsgTxt("Too many output arguments");
  }

  img = (uint8*) mxGetData(in[img_i]) ;
  uint minLength = (uint) mxGetScalar(in[minLength_i]);

  int imgHeight = mxGetM(in[img_i]) ;
  int imgWidth  = mxGetN(in[img_i]) ;

  //copy image to OPENCV format
  IplImage* iplImg = cvCreateImage (cvSize(imgWidth, imgHeight),
				    8, 1);
  Image<uint8> iplImgT(iplImg);

  for (int x = 0; x < imgWidth; x++)
    for (int y = 0; y < imgHeight; y++)
      iplImgT[y][x] =  getColor(img,imgHeight, x,y);

  //get edge map
  cv::Mat mat_img(iplImg);
  cv::Mat m_edge;
  
  cv::Canny(mat_img,m_edge,CANNY_THRESH,CANNY_THRESH*4,CANNY_MASK);
  IplImage* iplEdge = new IplImage(m_edge);
  //get edgelist
  //printf("Computing\n");
  std::vector< std::vector <CvPoint> > vComp = getEdgeGroup(iplEdge, minLength);

  //copy to cell
  mxArray* vCell = (mxArray*) mxCreateCellMatrix(1,vComp.size() );

  //printf("Copying data\n");
  for (uint i=0; i<vComp.size();i++)
    {
      std::vector<CvPoint> vPt = vComp[i];
      int nbPt = vPt.size();
	    
      mxArray* mxMat = (mxArray*) mxCreateDoubleMatrix(nbPt,2,mxREAL) ; //arrange un columns
      double* mat = (double*) mxGetPr(mxMat);

      for (int p=0; p<nbPt;p++)
      	{
      	  mat[p]     = vPt[p].y;
      	  mat[p+nbPt]= vPt[p].x;
	  
      	}
      mxSetCell(vCell, i, mxMat);

    }
  out[c_edgeGroups_i] = vCell;

  if (nout >= 2) //return edge image, mostly for debugging
    {
      mxArray* mxImgEdge = (mxArray*) mxCreateNumericMatrix(imgHeight,imgWidth,mxUINT8_CLASS,mxREAL);
      uint8* imgEdge = (uint8*) mxGetPr(mxImgEdge); 
      
      Image<uint8> iplEdgeT(iplEdge);
      for (int x = 0; x < imgWidth; x++)
	for (int y = 0; y < imgHeight; y++)
	  setColor(imgEdge,imgHeight, x,y, iplEdgeT[y][x]);
      
      out[imgEdge_i] = mxImgEdge;
    }

  
  delete iplEdge;
  cvReleaseImage(&iplImg);
}
コード例 #25
0
/* 
 * [type,num_constraint,constraint_val,dconstraint_val,constraint_name,lower_bound,upper_bound] = testSingleTimeKinCnstmex(kinCnst_ptr,q,t)
 * @param kinCnst_ptr           A pointer to a SingleTimeKinematicConstraint object
 * @param q                     A nqx1 double vector
 * @param t                     A double scalar, the time to evaluate constraint value, bounds and name. This is optional.
 * @retval type                 The type of the constraint
 * @retval num_constraint       The number of constraint active at time t
 * @retval constraint_val       The value of the constraint at time t
 * @retval dconstraint_val      The gradient of the constraint w.r.t q at time t
 * @retval constraint_name      The name of the constraint at time t
 * @retval lower_bound          The lower bound of the constraint at time t
 * @retval upper_bound          The upper bound of the constraint at time t
 * */
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
  if((nrhs!=3 && nrhs != 2)||nlhs != 7)
  {
    mexErrMsgIdAndTxt("Drake:testSingleTimeKinCnstmex:BadInputs","Usage [type, num_cnst,cnst_val,dcnst_val,cnst_name,lb,ub] = testSingleTimeKinKinCnstmex(kinCnst,q,t)");
  }
  SingleTimeKinematicConstraint* cnst = (SingleTimeKinematicConstraint*) getDrakeMexPointer(prhs[0]);
  double* t_ptr;
  if(nrhs == 2)
  {
    t_ptr = nullptr;
  }
  else
  {
    int num_t = mxGetNumberOfElements(prhs[2]);
    if(num_t == 0)
    {
      t_ptr = nullptr;
    }
    if(num_t == 1)
    {
      t_ptr = mxGetPrSafe(prhs[2]);
    }
    if(num_t>1)
    {
      mexErrMsgIdAndTxt("Drake:testSingleTimeKinCnstmex:BadInputs","t must be either empty or a single number");
    }
  }
  int type = cnst->getType();
  int num_cnst = cnst->getNumConstraint(t_ptr);
  //mexPrintf("num_cnst = %d\n",num_cnst);
  int nq = cnst->getRobotPointer()->num_positions;
  Map<VectorXd> q(mxGetPrSafe(prhs[1]), nq);
  VectorXd v = VectorXd::Zero(0);
  cnst->getRobotPointer()->doKinematics(q, v);
  VectorXd c(num_cnst);
  MatrixXd dc(num_cnst,nq);
  cnst->eval(t_ptr,c,dc);
  //mexPrintf("get c,dc\n");
  VectorXd lb(num_cnst);
  VectorXd ub(num_cnst);
  cnst->bounds(t_ptr,lb,ub);
  //mexPrintf("get lb, ub\n");
  std::vector<std::string> cnst_names;
  cnst->name(t_ptr,cnst_names);
  //mexPrintf("get name\n");
  int retvec_size;
  if(num_cnst == 0)
  {
    retvec_size = 0;
  }
  else
  {
    retvec_size = 1;
  }
  plhs[0] = mxCreateDoubleScalar((double) type);
  plhs[1] = mxCreateDoubleScalar((double) num_cnst);
  plhs[2] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[2]),c.data(),sizeof(double)*num_cnst);
  plhs[3] = mxCreateDoubleMatrix(num_cnst,nq,mxREAL);
  memcpy(mxGetPrSafe(plhs[3]),dc.data(),sizeof(double)*num_cnst*nq);
  int name_ndim = 1;
  mwSize name_dims[] = {(mwSize) num_cnst};
  plhs[4] = mxCreateCellArray(name_ndim,name_dims);
  mxArray *name_ptr;
  for(int i = 0;i<num_cnst;i++)
  {
    name_ptr = mxCreateString(cnst_names[i].c_str());
    mxSetCell(plhs[4],i,name_ptr);
  }
  plhs[5] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  plhs[6] = mxCreateDoubleMatrix(num_cnst,retvec_size,mxREAL);
  memcpy(mxGetPrSafe(plhs[5]),lb.data(),sizeof(double)*num_cnst);
  memcpy(mxGetPrSafe(plhs[6]),ub.data(),sizeof(double)*num_cnst);
}
コード例 #26
0
ファイル: update_zeta.cpp プロジェクト: aacharya/DSLDA2
void update_zeta_i(mxArray *retptr, double *sstopicwordptr, double *ssfeatures, double *zetai, double *windexi, double *wcounti, const mxArray *model, const mxArray *data, const double *Esticks, const double *Eloglambda, const double *Eloggamma, const double *smallphi, const int ndistWords, const int i, double *count2, double *option)
{
    int index, nK1, nK2, t, k, k1, T, K1, K2, V, N, tempind1, tempind2, j, y, C2, Y, phase;
    double logsum, logsum1, logsum2, minval, val1, val2, val3, value, epsilon, valtemp;
    double *tmpptr, *tmp1, *log_beta, *dmu, *r, *annotations, *classlabels, *nwordspdoc;
    mxArray *tmp;
    
    minval      = mxGetScalar(mxGetField(model,0,"MINVALUE"));
    phase       = mxGetScalar(mxGetField(model,0,"phase"));
    classlabels = (double*)mxGetPr(mxGetField(data,0,"classlabels"));
    nwordspdoc  = (double*)mxGetPr(mxGetField(data,0,"nwordspdoc"));
    annotations = (double*)mxGetPr(mxGetField(data,0,"annotations"));
    
    r       = mxGetPr(mxGetField(model,0,"r"));
    V       = mxGetScalar(mxGetField(model,0,"V"));
    N       = mxGetScalar(mxGetField(model,0,"N"));
    C2      = mxGetScalar(mxGetField(model,0,"C2"));
    Y       = mxGetScalar(mxGetField(data,0,"Y"));
    T       = mxGetScalar(mxGetField(model,0,"T"));
    K1      = mxGetScalar(mxGetField(model,0,"K1"));
    K2      = mxGetScalar(mxGetField(model,0,"K2"));
    epsilon = mxGetScalar(mxGetField(model,0,"epsilon"));
    
    if((int)option[0]==1)
    {
        nK1 = (T+K2);
        nK2 = (K1+K2);
    }
    else
    {
        nK1 = T;
        nK2 = K1;
    }
    
    if(phase==1)
    {
        // use the dual variable only in training phase; no dual variable in test phase
        dmu     = (double*)mxGetPr(mxGetField(model,0,"dmu"));
    }
    
    tmp    = mxCreateDoubleMatrix(ndistWords,nK1,mxREAL);
    tmpptr = mxGetPr(tmp);
    
    for (j=0; j<ndistWords; j++)  // loop over (distinct) words
    {
        logsum  = 0;
        logsum1 = 0;
        logsum2 = 0;
        
        tmp1 = Malloc(double,nK1);
        
        for (k=0; k<nK1; k++)     // loop over third dimension
        {
            tempind1 = k + ((int)(windexi[j])-1)*nK2;
            val1     = 0;
            
            ////////////////////////////////////////////////////////////////////////////////////////////
            // terms from document level supervision
            if(phase==1 && (int)classlabels[i]>=1)   // use the dual variable only in training phase only when label is present; no dual variable in test phase;
            {
                if(k<T)          // for unsupervised topics
                {
                    for (y=0; y<Y; y++)
                    {
                        valtemp = 0;
                        for (k1=0; k1<K1; k1++)
                        {
                            valtemp = valtemp + (r[k1*Y+ (int)classlabels[i]-1] - r[k1*Y+y])*smallphi[i+k*N+k1*N*T];
                        }
                        val1 = val1 + dmu[i+y*N]*valtemp;
                    }
                }
                else   // for NPDSLDA
                    if((int)option[0]==1)// for supervised topics
                    {
                    for (y=0; y<Y; y++)
                    {
                        val1 = val1 + dmu[i+y*N]*(r[(int)classlabels[i]-1 + (k-T+K1)*Y] - r[y + (k-T+K1)*Y]);
                    }
                    val1 =  val1/nwordspdoc[i];
                    }
            }
            
            ////////////////////////////////////////////////////////////////////////////////////////////
            // for other terms
            if(k<T) // for unsupersvised topics
            {
                val2 = 0;
                for(k1=0; k1<K1; k1++)
                {
                    tempind2 = k1 + ((int)(windexi[j])-1)*nK2;
                    val2     = val2 + smallphi[i+k*N+k1*N*T]*Eloglambda[tempind2];
                }
                val3 = Esticks[i+k*N];
                *(tmp1+k) = val1 + val2 + val3;
            }
            else    // for supersvised topics
                if((int)option[0]==1)  // for NPDSLDA
                {
                *(tmp1+k) = Eloggamma[i+k*N] + Eloglambda[tempind1] + val1;
                }
            
            
            if(phase==1) // only in training phase; no need to have any clause for test phase
            {
                if((int)option[0]==1) // NPDSLDA
                {
                    if (k<T)    // unsupervised topics
                        logsum1 = log_sum(*(tmp1+k),logsum1);
                    else        // supervised topics
                    {
                        if(*(annotations+(k-T)*N+i)==0);  //if condition says when to ignore phi's
                        else
                            logsum2 = log_sum(*(tmp1+k),logsum2);
                    }
                }
                else                  // NPLDA
                    logsum = log_sum(*(tmp1+k),logsum);
            }
        }
        
        // conversion from log space to real number
        for (k=0; k<nK1; k++)
        {
            if((int)option[0]==1) // NPDSLDA
            {
                if(k<T)     // unsupervised topics
                {
                    if(logsum1 - *(tmp1+k)>10000)
                        tmpptr[k*ndistWords+j] = minval;
                    if(logsum1 - *(tmp1+k)<10000)
                        tmpptr[k*ndistWords+j] = (1-epsilon)*exp(*(tmp1+k) - logsum1) + minval;
                }
                else        // supervised topics
                {
                    if(logsum2 - *(tmp1+k)>10000)
                        tmpptr[k*ndistWords+j] = minval;
                    if(logsum2 - *(tmp1+k)<10000)
                        tmpptr[k*ndistWords+j] = epsilon*exp(*(tmp1+k) - logsum2) + minval;
                    if (phase==1 && k>=T && *(annotations+(k-T)*N+i)==0) // only in training phase
                    {
                        tmpptr[k*ndistWords+j] = 0;  // DSLDA
                        //mexPrintf("%d %d %d hey here!\n", i, j, k);
                    }
                }
            }
            else  // NPLDA
            {
                if(logsum - *(tmp1+k)>10000)
                    tmpptr[k*ndistWords+j] = minval;
                if(logsum - *(tmp1+k)<10000)
                    tmpptr[k*ndistWords+j] = exp(*(tmp1+k) - logsum) + minval;
            }
        }
        
        free(tmp1);
    }
    
    // update sufficient statistics -- for both unsupervised and supervised topics
    for (k = 0; k < nK2; k++)
    {
        for (j = 0; j < ndistWords; j++)
        {
            value = 0;
            if(k<K1)  // unsupervised topics
            {
                for (t = 0; t < T; t++) // loop over topics
                {
                    //mexPrintf("hey here1! %d %d %d %d %f\n", k, i, ndistWords, t, windexi[j]);
                    value += smallphi[i+t*N+k*N*T]*tmpptr[j+t*ndistWords]; // smallphi{ntk1}*zeta{nmt}
                }
                value = wcounti[j]*value;
            }
            else    // for NPDSLDA
                if((int)option[0]==1)// supervised topics
                {
                value = wcounti[j]*tmpptr[j+(k-K1+T)*ndistWords]; // zeta{nmk2}
                }
            index = k + ((int)windexi[j]-1)*nK2;
            sstopicwordptr[index] += value;
            ssfeatures[i+k*N] += value;
        }
    }
    
    mxSetCell (retptr, i, tmp);
    
    return;
}
コード例 #27
0
void mcaMonitorEventHandler(struct event_handler_args arg)
{   union db_access_val *pBuf;
    struct mca_channel* PCHNL = (struct mca_channel*)arg.usr;
    double *myDblPr;
    chtype RequestType;
    int i,Cnt;
    mxArray* mymxArray;
    pBuf = (union db_access_val *)arg.dbr;
    
    //mexPrintf("MCA Monitor Event Handler Called\n");
    
    PCHNL->MonitorEventCount++;
    
    Cnt = ca_element_count(arg.chid);  
    RequestType = dbf_type_to_DBR(ca_field_type(arg.chid)); // Closest to the native 
    
    if(RequestType==DBR_STRING)
    {   if(Cnt==1)
        {   mxDestroyArray(PCHNL->CACHE); // clear mxArray that pointed to by PCHNL->CACHE
            PCHNL->CACHE = mxCreateString((char*)((pBuf)->strval)); // Create new array with current string value
            mexMakeArrayPersistent(PCHNL->CACHE);
        }
        else
        {   for(i=0;i<Cnt;i++)
            {   mymxArray = mxGetCell(PCHNL->CACHE,i);
                mxDestroyArray(mymxArray);
                mymxArray = mxCreateString(  (char*)   (&(pBuf->strval)+i)   );
                mexMakeArrayPersistent(mymxArray);
                mxSetCell(PCHNL->CACHE,i,mymxArray);
            }
        }
    }
    else
    {   myDblPr = mxGetPr(PCHNL->CACHE);
        
        switch(RequestType)
        {   case DBR_INT: // As defined in db_access.h DBR_INT = DBR_SHORT = 1
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->intval)+i));
            break;    
            
            case DBR_FLOAT:
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->fltval)+i));
            break;
                
            case DBR_ENUM:
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->enmval)+i));
            break;
                
            case DBR_CHAR:
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->charval)+i));
            break;
                    
            case DBR_LONG:
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->longval)+i));
            break;
                    
            case DBR_DOUBLE:
            for (i = 0; i<Cnt;i++)
                myDblPr[i]= (double)(*(&((pBuf)->doubleval)+i));
            break;
        }
    }
    
    if(PCHNL->MonitorCBString)
    {   
        mexEvalString(PCHNL->MonitorCBString);
    }
}
コード例 #28
0
ファイル: directbin.c プロジェクト: Field-Lab/matlab
/**
 * @brief Interfaces C and Matlab data.
 * This function is the MEX-file gateway routine. Please see the Matlab
 * MEX-file documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f43721.html)
 * for more information.
 */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{

  /* allocate variables */
  struct input *X;
  struct options_direct *opts;
  int m,p,n,z;
  int p_total,P_total;
  int W;
  int *P_vec;
  mxArray *mxbinned;
  int **binned,*binned_temp;
  int cur_P;
  int status;
  int temp_N;

  /* check number of inputs (nargin) and outputs (nargout) */
  if((nrhs<1) | (nrhs>2))
    mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 input arguments required.");
  if((nlhs<1) | (nlhs>2))
    mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 output arguments required.");

  X = ReadInput(prhs[0]);

  /* get or set options */
  if(nrhs<2)
    opts = ReadOptionsDirect(mxCreateEmptyStruct());
  else if(mxIsEmpty(prhs[1]))
    opts = ReadOptionsDirect(mxCreateEmptyStruct());
  else
    opts = ReadOptionsDirect(prhs[1]);

  /* Read in time range */
  ReadOptionsDirectTimeRange(opts,X);
  
  /* check options */
  if(opts->Delta_flag==0)
    {
      opts[0].Delta = (*opts).t_end-(*opts).t_start;
      opts[0].Delta_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter counting_bin_size. Using default value end_time-start_time=%f.\n",opts[0].Delta);
    }
  
  if(opts->Delta <= 0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","counting_bin_size must be positive. It is currently set to %f.\n",opts[0].Delta);
    }

  if(opts->words_per_train_flag==0)
    {
      opts[0].words_per_train = (int)DEFAULT_WORDS_PER_TRAIN;
      opts[0].words_per_train_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter words_per_train. Using default value %d.\n",opts[0].words_per_train);
    }

  if(opts->words_per_train <= 0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","words_per_train must be positive. It is currently set to %d.\n",opts[0].words_per_train);
    }

 if(opts->legacy_binning_flag==0)
    {
      opts[0].legacy_binning = (int)DEFAULT_LEGACY_BINNING;
      opts[0].legacy_binning_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter legacy_binning. Using default value %d.\n",opts[0].legacy_binning);
    }

  if((opts->legacy_binning!=0) & (opts->legacy_binning!=1))
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option legacy_binning set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",opts[0].legacy_binning);
    }

 if(opts->letter_cap_flag==0)
    {
      opts[0].letter_cap = (int)DEFAULT_LETTER_CAP;
      opts[0].letter_cap_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter letter_cap. Using default value %d.\n",opts[0].letter_cap);
    }

  if(opts->letter_cap<0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option letter_cap set to an invalid value. Must be a positive integer or Inf. It is currently set to %d.\n",opts[0].letter_cap);
    }

  if((*X).N>1)
    {
      if(opts->sum_spike_trains_flag==0)
	{
	  opts[0].sum_spike_trains = (int)DEFAULT_SUM_SPIKE_TRAINS;
	  opts[0].sum_spike_trains_flag=1;
	  mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter sum_spike_trains. Using default value %d.\n",opts[0].sum_spike_trains);
	}

      if((opts->sum_spike_trains!=0) & (opts->sum_spike_trains!=1))
        {
          mxFree(opts);
          mxFreeInput(X); 
	  mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option sum_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).sum_spike_trains);
        }
      
      if(opts->permute_spike_trains_flag==0)
	{
	  opts[0].permute_spike_trains = (int)DEFAULT_PERMUTE_SPIKE_TRAINS;
	  opts[0].permute_spike_trains_flag=1;
	  mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter permute_spike_trains. Using default value %d.\n",opts[0].permute_spike_trains);
	}

      if((opts->permute_spike_trains!=0) & (opts->permute_spike_trains!=1))
        {
          mxFree(opts);
          mxFreeInput(X); 
	  mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option permute_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).permute_spike_trains);
        }
    }

  P_total = GetNumTrials(X);
  /* W is the number of letters in a word */
  W=GetWindowSize(opts);

  /* Allocate memory for pointers to pointers */
  if(opts[0].sum_spike_trains)
    temp_N = 1;
  else
    temp_N = X[0].N;
  binned = mxMatrixInt((*opts).words_per_train*P_total,temp_N*W);

  /* Allocate memory for P_vec */
  P_vec = (int *)mxMalloc((*X).M*sizeof(int));

  /* Do computation */
  status = DirectBinComp(X,opts,(*opts).words_per_train*P_total,W,P_vec,binned);
  if(status==EXIT_FAILURE)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mxFreeMatrixInt(binned);
      mxFree(P_vec);
      mexErrMsgIdAndTxt("STAToolkit:directbin:failure","directbin failed.");
    }

  /* Create binned cell array */
  plhs[0] = mxCreateCellMatrix((*X).M,(*opts).words_per_train);
  p_total = 0;

  for(m=0;m<(*X).M;m++)
    {
      cur_P = (*X).categories[m].P;
      for(z=0;z<(*opts).words_per_train;z++)
	{
	  /* vectorize and transpose this matrix */
	  binned_temp = (int *)mxMalloc(W*temp_N*cur_P*sizeof(int));
	  
	  for(p=0;p<cur_P;p++)
	    for(n=0;n<temp_N*W;n++)
	      binned_temp[n*cur_P + p]=binned[p_total+p][n];
	  
	  p_total += cur_P;
      
	  mxbinned = mxCreateNumericMatrix(cur_P,temp_N*W,mxINT32_CLASS,mxREAL);
	  memcpy(mxGetData(mxbinned),binned_temp,cur_P*temp_N*W*sizeof(int));

	  mxSetCell(plhs[0],z*(*X).M+m,mxbinned);
	  
	  mxFree(binned_temp);
	}
    }

  /* output options used */
  if(nrhs<2)
    plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts);
  else if(mxIsEmpty(prhs[1]))
    plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts);
  else
    plhs[1] = WriteOptionsDirect(prhs[1],opts);

  /* free memory */
  mxFreeInput(X); 
  mxFreeMatrixInt(binned);
  mxFree(P_vec);

  return;
}
コード例 #29
0
ファイル: matlab_cell_io.hpp プロジェクト: caomw/partapp
  bool mat_save_multi_array_vec2(MATFile *f, QString qsVarName, const std::vector<std::vector<Array> > &vvA)
  {
    assert(f != 0);
    
    mwSize cell_ndim = 2;
    mwSize cell_dims[2];
    
    assert(vvA.size() > 0);
    uint N1 = vvA.size();
    uint N2 = vvA[0].size();

    cell_dims[0] = N1;
    cell_dims[1] = N2;

    mxArray *CA = mxCreateCellArray(cell_ndim, cell_dims);
    assert(CA != 0);

    for (uint i1 = 0; i1 < N1; ++i1) {
      assert(vvA.size() > i1);
      assert(vvA[i1].size() == N2);

      for (uint i2 = 0; i2 < N2; ++i2) {

        /* init shape array */
        const typename Array::size_type *shape_ptr = vvA[i1][i2].shape();
        assert(shape_ptr != 0);

        boost::array<typename Array::size_type, Array::dimensionality> array_shape;
        for (uint i = 0; i < Array::dimensionality; ++i) 
          array_shape[i] = shape_ptr[i];

        /* create array of the same shape as initial array with data stored in fortran storage order */
        Array B(array_shape, boost::fortran_storage_order());  
        B = vvA[i1][i2];  
    
        const typename Array::element *data2 = B.data();
        assert(data2 != 0);

        /* shape again, this time as mwSize array */
        mwSize dims[Array::dimensionality];
        for (uint i = 0; i < Array::dimensionality; ++i) 
          dims[i] = array_shape[i];

        mxArray *E = mxCreateNumericArray(Array::dimensionality, dims, mxSINGLE_CLASS, mxREAL);    
        assert(E != 0);
    
        /* copy elements to matlab array */
        size_t nElements = vvA[i1][i2].num_elements();
        if (nElements > 0) {
          float *pE = (float *)mxGetPr(E);
          assert(pE != 0);
          for (uint idx = 0; idx < nElements; ++idx) {
            *pE = *(data2 + idx);
            ++pE;
          }
        }

        /* add element to cell array */
        mwIndex subs[2];
        subs[0] = i1;
        subs[1] = i2;
        mwIndex cell_idx = mxCalcSingleSubscript(CA, cell_ndim, subs);
        //std::cout << "cell index: " << cell_idx << std::endl;
        mxSetCell(CA, cell_idx, E);
      }
    }

    matPutVariable(f, qsVarName.toStdString().c_str(), CA);
    
    mxDestroyArray(CA);
    return true;
  }
コード例 #30
0
ファイル: mex_lpqp.cpp プロジェクト: ppletscher/lpqp
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    MatlabCPPInitialize(false);

    // Check for proper number of arguments
    if ( (nrhs < NR_IN) || (nrhs > NR_IN + NR_IN_OPT) || \
            (nlhs < NR_OUT) || (nlhs > NR_OUT + NR_OUT_OPT) ) {
        mexErrMsgTxt("Wrong number of arguments.");
    }

    // fetch the input (we support matrices and cell arrays)
    std::vector< Eigen::VectorXd > theta_unary;
    std::vector< Eigen::VectorXd > theta_pair;

    if (!mxIsCell(THETA_UNARY_IN)) {
        GetMatlabPotentialFromMatrix(THETA_UNARY_IN, theta_unary);
        GetMatlabPotentialFromMatrix(THETA_PAIR_IN, theta_pair);
    }
    else {
        GetMatlabPotential(THETA_UNARY_IN, theta_unary);
        GetMatlabPotential(THETA_PAIR_IN, theta_pair);
    }
    
    Eigen::MatrixXi edges;
    GetMatlabMatrix(EDGES_IN, edges);

    // decomposition: cell array of edge index vectors
    std::vector< std::vector<size_t> > decomposition;
    if (nrhs >= 5) {
        size_t num = mxGetNumberOfElements(DECOMPOSITION_IN);
        decomposition.resize(num);
        for (size_t d_idx=0; d_idx<num; d_idx++) {
            const mxArray* v = mxGetCell(DECOMPOSITION_IN, d_idx);
            size_t num_edges = mxGetM(v);
            decomposition[d_idx].resize(num_edges);
	        const double* ptr = mxGetPr(v);
            for (size_t e_idx=0; e_idx<num_edges; e_idx++) {
                decomposition[d_idx][e_idx] = static_cast<size_t>(ptr[e_idx]);
            }
        }
    }
    
    // parse options
    MexLPQPOptions options;
    if (nrhs >= 4) {
        bool opts_parsed = options.parse(OPTIONS_IN);
        if (!opts_parsed) {
            MatlabCPPExit();
            return;
        }
    }

    LPQP* lpqp;
    if (nrhs < 5) {
        lpqp = new LPQPNPBP(theta_unary, theta_pair, edges);
    }
    else {
        lpqp = new LPQPSDD(theta_unary, theta_pair, edges, decomposition, options.solver_sdd);
    }

    lpqp->setRhoStart(options.rho_start);
    lpqp->setRhoEnd(options.rho_end);
    lpqp->setEpsilonEntropy(options.eps_entropy);
    lpqp->setEpsilonKullbackLeibler(options.eps_dkl);
    lpqp->setEpsilonObjective(options.eps_obj);
    lpqp->setEpsilonMP(options.eps_mp);
    lpqp->setMaximumNumberOfIterationsDC(options.num_max_iter_dc);
    lpqp->setMaximumNumberOfIterationsMP(options.num_max_iter_mp);
    lpqp->setRhoScheduleConstant(options.rho_schedule_constant);
    lpqp->setInitialLPActive(options.initial_lp_active);
    lpqp->setInitialLPImprovmentRatio(options.initial_lp_improvement_ratio);
    lpqp->setInitialLPRhoStart(options.initial_lp_rho_start);
    lpqp->setInitialRhoSimilarValues(options.initial_rho_similar_values);
    lpqp->setInitialRhoFactorKLSmaller(options.initial_rho_factor_kl_smaller);
    lpqp->setSkipIfIncrease(options.skip_if_increase);

    lpqp->run();
    
    if (options.do_round) {
        double curr_qp_obj = lpqp->computeQPValue();

        lpqp->roundSolution();

        double qp_obj_after_rounding = lpqp->computeQPValue();
        printf("QP objective before rounding: %f after rounding: %f\n",curr_qp_obj, qp_obj_after_rounding);
    }

    // return marginals (if input was provided as a matrix, also return
    // marginals in a matrix)
    std::vector< Eigen::VectorXd >& mu_unary = lpqp->getUnaryMarginals();
    if (!mxIsCell(THETA_UNARY_IN)) {
        size_t num_states = mxGetM(THETA_UNARY_IN);
        size_t num_vars = mxGetN(THETA_UNARY_IN);
        MARGINALS_UNARY_OUT = mxCreateNumericMatrix(
                                num_states, 
                                num_vars,
                                mxDOUBLE_CLASS, mxREAL);
        double* mu_res_p = mxGetPr(MARGINALS_UNARY_OUT);
        for (size_t v_idx=0; v_idx<mu_unary.size(); v_idx++) {
            for (size_t idx=0; idx<mu_unary[v_idx].size(); idx++) {
                mu_res_p[v_idx*num_states+idx] = mu_unary[v_idx](idx);
            }
        }
    }
    else {
        mwSize dim_0 = static_cast<mwSize>(mu_unary.size());
        MARGINALS_UNARY_OUT = mxCreateCellArray(1, &dim_0);
        for (size_t v_idx=0; v_idx<mu_unary.size(); v_idx++) {
            mxArray* m = mxCreateNumericMatrix(
                            static_cast<int>(mu_unary[v_idx].size()),
                            1,
                            mxDOUBLE_CLASS, mxREAL);
            double* mu_res_p = mxGetPr(m);
            for (size_t idx=0; idx<mu_unary[v_idx].size(); idx++) {
                mu_res_p[idx] = mu_unary[v_idx](idx);
            }

            mxSetCell(MARGINALS_UNARY_OUT, v_idx, m);
        }
    }
    
    // return history
    if (nlhs > 1) {
        std::vector<double>& history_obj = lpqp->getHistoryObjective();
        std::vector<double>& history_obj_qp = lpqp->getHistoryObjectiveQP();
        std::vector<double>& history_obj_lp = lpqp->getHistoryObjectiveLP();
        std::vector<double>& history_obj_decoded = lpqp->getHistoryObjectiveDecoded();
        std::vector<size_t>& history_iteration = lpqp->getHistoryIteration();
        std::vector<double>& history_rho = lpqp->getHistoryRho();
        //std::vector< Eigen::VectorXi > history_decoded = lpqp.getHistoryDecoded();

        //const char *field_names[] = {"obj", "obj_qp", "obj_lp", "obj_decoded", "iteration", "beta", "decoded"};
        const char *field_names[] = {"obj", "obj_qp", "obj_lp", "obj_decoded", "iteration", "rho"};
        mwSize dims[2];
        dims[0] = 1;
        dims[1] = history_obj.size();
        HISTORY_OUT = mxCreateStructArray(2, dims, sizeof(field_names)/sizeof(*field_names), field_names);

        int field_obj, field_obj_qp, field_obj_lp, field_obj_decoded, field_iteration, field_rho;
        //int field_decoded;
        field_obj = mxGetFieldNumber(HISTORY_OUT, "obj");
        field_obj_qp = mxGetFieldNumber(HISTORY_OUT, "obj_qp");
        field_obj_lp = mxGetFieldNumber(HISTORY_OUT, "obj_lp");
        field_obj_decoded = mxGetFieldNumber(HISTORY_OUT, "obj_decoded");
        field_iteration = mxGetFieldNumber(HISTORY_OUT, "iteration");
        field_rho = mxGetFieldNumber(HISTORY_OUT, "rho");
        //field_decoded = mxGetFieldNumber(HISTORY_OUT, "decoded");

        for (size_t i=0; i<history_obj.size(); i++) {
            mxArray *field_value;

            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_qp[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_qp, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_lp[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_lp, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_decoded[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_decoded, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = static_cast<double>(history_iteration[i]);
            mxSetFieldByNumber(HISTORY_OUT, i, field_iteration, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_rho[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_rho, field_value);
            
            //if (options.with_decoded_history) {
            //    field_value = mxCreateDoubleMatrix(history_decoded[i].size(),1,mxREAL);
            //    double* decoded_res_p = mxGetPr(field_value);
            //    for (size_t idx=0; idx<history_decoded[i].size(); idx++) {
            //        decoded_res_p[idx] = static_cast<double>(history_decoded[i][idx]);
            //    }
            //    mxSetFieldByNumber(HISTORY_OUT, i, field_decoded, field_value);
            //}
        }
    }

    delete lpqp;

    MatlabCPPExit();
}