void exit_with_help() { mexPrintf( "Usage: libsvmwrite('filename', label_vector, instance_matrix);\n" ); }
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 */ ) { int 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; char FLAG_CNT32 = 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,'CNT32')\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("\tCNT32: needed to read 32bit CNT files \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")) FLAG_CNT32 = 1; 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 (!strcmpi(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); hdr->FLAG.OVERFLOWDETECTION = FlagOverflowDetection; hdr->FLAG.UCAL = FlagUCAL; hdr->FLAG.CNT32 = FLAG_CNT32; #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++; } } if (VERBOSE_LEVEL>7) mexPrintf("120: going to sopen\n"); hdr = sopen(FileName, "r", hdr); /* #ifdef WITH_PDP if (B4C_ERRNUM) { B4C_ERRNUM = 0; sopen_pdp_read(hdr); } #endif */ if (VERBOSE_LEVEL>7) mexPrintf("121: sopen done\n"); if ((status=serror())) { const char* fields[]={"TYPE","VERSION","FileName","FLAG","ErrNum","ErrMsg"}; HDR = mxCreateStructMatrix(1, 1, 6, fields); mxSetField(HDR,0,"FileName",mxCreateString(hdr->FileName)); 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) { const char *p = GetFileTypeString(hdr->TYPE); if (p) mxSetField(HDR,0,"TYPE",mxCreateString(p)); } #else mxSetField(HDR,0,"TYPE",mxCreateString(GetFileTypeString(hdr->TYPE))); #endif mxSetField(HDR,0,"VERSION",mxCreateDoubleScalar(hdr->VERSION)); char msg[1024]; if (status==B4C_CANNOT_OPEN_FILE) sprintf(msg,"Error mexSLOAD: file %s not found.\n",FileName); else if (status==B4C_FORMAT_UNKNOWN) sprintf(msg,"Error mexSLOAD: Cannot open file %s - format %s not known.\n",FileName,GetFileTypeString(hdr->TYPE)); else if (status==B4C_FORMAT_UNSUPPORTED) sprintf(msg,"Error mexSLOAD: Cannot open file %s - format %s not supported [%s].\n", FileName, GetFileTypeString(hdr->TYPE), B4C_ERRMSG); else sprintf(msg,"Error %i mexSLOAD: Cannot open file %s - format %s not supported [%s].\n", status, FileName, GetFileTypeString(hdr->TYPE), B4C_ERRMSG); mxSetField(HDR,0,"ErrMsg",mxCreateString(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=serror())) return; if (VERBOSE_LEVEL>7) fprintf(stderr,"\n[129] SREAD/SCLOSE on %s successful [%i,%i] [%Li,%i] %i.\n",hdr->FileName,hdr->data.size[0],hdr->data.size[1],hdr->NRec,count,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","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(hdr->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",mxCreateCharMatrixFromStrings(1,&hdr->FileName)); mxSetField(HDR,0,"T0",mxCreateDoubleScalar(ldexp(hdr->T0,-32))); /* 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,hdr->NS, mxREAL); mxArray *PhysDimCode = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *GDFTYP = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *PhysMax = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *PhysMin = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *DigMax = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *DigMin = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Cal = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Off = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Toffset = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *ELEC_POS = mxCreateDoubleMatrix(hdr->NS,3, mxREAL); mxArray *ELEC_Orient = mxCreateDoubleMatrix(hdr->NS,3, mxREAL); mxArray *ELEC_Area = mxCreateDoubleMatrix(hdr->NS,1, mxREAL); mxArray *LowPass = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *HighPass = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Notch = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Impedance = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *fZ = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *SPR = mxCreateDoubleMatrix(1,hdr->NS, mxREAL); mxArray *Label = mxCreateCellMatrix(hdr->NS,1); mxArray *Transducer = mxCreateCellMatrix(hdr->NS,1); mxArray *PhysDim1 = mxCreateCellMatrix(hdr->NS,1); for (size_t k=0; k<hdr->NS; ++k) { *(mxGetPr(LeadIdCode)+k) = (double)hdr->CHANNEL[k].LeadIdCode; *(mxGetPr(PhysDimCode)+k) = (double)hdr->CHANNEL[k].PhysDimCode; *(mxGetPr(GDFTYP)+k) = (double)hdr->CHANNEL[k].GDFTYP; *(mxGetPr(PhysMax)+k) = (double)hdr->CHANNEL[k].PhysMax; *(mxGetPr(PhysMin)+k) = (double)hdr->CHANNEL[k].PhysMin; *(mxGetPr(DigMax)+k) = (double)hdr->CHANNEL[k].DigMax; *(mxGetPr(DigMin)+k) = (double)hdr->CHANNEL[k].DigMin; *(mxGetPr(Toffset)+k) = (double)hdr->CHANNEL[k].TOffset; *(mxGetPr(Cal)+k) = (double)hdr->CHANNEL[k].Cal; *(mxGetPr(Off)+k) = (double)hdr->CHANNEL[k].Off; *(mxGetPr(SPR)+k) = (double)hdr->CHANNEL[k].SPR; *(mxGetPr(LowPass)+k) = (double)hdr->CHANNEL[k].LowPass; *(mxGetPr(HighPass)+k) = (double)hdr->CHANNEL[k].HighPass; *(mxGetPr(Notch)+k) = (double)hdr->CHANNEL[k].Notch; *(mxGetPr(Impedance)+k) = (double)hdr->CHANNEL[k].Impedance; *(mxGetPr(fZ)+k) = (double)hdr->CHANNEL[k].fZ; *(mxGetPr(ELEC_POS)+k) = (double)hdr->CHANNEL[k].XYZ[0]; *(mxGetPr(ELEC_POS)+k+hdr->NS) = (double)hdr->CHANNEL[k].XYZ[1]; *(mxGetPr(ELEC_POS)+k+hdr->NS*2) = (double)hdr->CHANNEL[k].XYZ[2]; /* *(mxGetPr(ELEC_Orient)+k) = (double)hdr->CHANNEL[k].Orientation[0]; *(mxGetPr(ELEC_Orient)+k+hdr->NS) = (double)hdr->CHANNEL[k].Orientation[1]; *(mxGetPr(ELEC_Orient)+k+hdr->NS*2) = (double)hdr->CHANNEL[k].Orientation[2]; *(mxGetPr(ELEC_Area)+k) = (double)hdr->CHANNEL[k].Area; */ mxSetCell(Label,k,mxCreateString(hdr->CHANNEL[k].Label)); mxSetCell(Transducer,k,mxCreateString(hdr->CHANNEL[k].Transducer)); char p[MAX_LENGTH_PHYSDIM+1]; PhysDim(hdr->CHANNEL[k].PhysDimCode,p); mxSetCell(PhysDim1,k,mxCreateString(p)); } 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 // Matlab 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 (size_t 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 (size_t 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 (size_t 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); 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 (uint8_t 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]; if (hdr->Patient.Name) { strarray[0] = hdr->Patient.Name; mxSetField(Patient,0,"Name",mxCreateCharMatrixFromStrings(1,strarray)); } if (hdr->Patient.Id) { strarray[0] = hdr->Patient.Id; mxSetField(Patient,0,"Id",mxCreateCharMatrixFromStrings(1,strarray)); } 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 = 0.0/0.0; // not-a-number else if (hdr->Patient.Weight==255) d = 1.0/0.0; // Overflow else d = (double)hdr->Patient.Weight; mxSetField(Patient,0,"Weight",mxCreateDoubleScalar(d)); if (hdr->Patient.Height==0) d = 0.0/0.0; // not-a-number else if (hdr->Patient.Height==255) d = 1.0/0.0; // 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); if (hdr->ID.Manufacturer.Name) { strarray[0] = hdr->ID.Manufacturer.Name; mxSetField(Manufacturer,0,"Name",mxCreateCharMatrixFromStrings(1,strarray)); } if (hdr->ID.Manufacturer.Model) { strarray[0] = hdr->ID.Manufacturer.Model; mxSetField(Manufacturer,0,"Model",mxCreateCharMatrixFromStrings(1,strarray)); } if (hdr->ID.Manufacturer.Version) { strarray[0] = hdr->ID.Manufacturer.Version; mxSetField(Manufacturer,0,"Version",mxCreateCharMatrixFromStrings(1,strarray)); } if (hdr->ID.Manufacturer.SerialNumber) { strarray[0] = hdr->ID.Manufacturer.SerialNumber; mxSetField(Manufacturer,0,"SerialNumber",mxCreateCharMatrixFromStrings(1,strarray)); } mxSetField(HDR,0,"Manufacturer",Manufacturer); if (VERBOSE_LEVEL>8) 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"); };
int read_problem_sparse(const mxArray *label_vec, const mxArray *instance_mat) { int i, j, k, low, high; mwIndex *ir, *jc; int elements, max_index, num_samples, label_vector_row_num; double *samples, *labels; mxArray *instance_mat_col; // instance sparse matrix in column format prob.x = NULL; prob.y = NULL; x_space = NULL; if(col_format_flag) instance_mat_col = (mxArray *)instance_mat; else { // transpose instance matrix mxArray *prhs[1], *plhs[1]; prhs[0] = mxDuplicateArray(instance_mat); if(mexCallMATLAB(1, plhs, 1, prhs, "transpose")) { mexPrintf("Error: cannot transpose training instance matrix\n"); return -1; } instance_mat_col = plhs[0]; mxDestroyArray(prhs[0]); } // the number of instance prob.l = (int) mxGetN(instance_mat_col); label_vector_row_num = (int) mxGetM(label_vec); if(label_vector_row_num!=prob.l) { mexPrintf("Length of label vector does not match # of instances.\n"); return -1; } // each column is one instance labels = mxGetPr(label_vec); samples = mxGetPr(instance_mat_col); ir = mxGetIr(instance_mat_col); jc = mxGetJc(instance_mat_col); num_samples = (int) mxGetNzmax(instance_mat_col); elements = num_samples + prob.l*2; max_index = (int) mxGetM(instance_mat_col); prob.y = Malloc(double, prob.l); prob.x = Malloc(struct feature_node*, prob.l); x_space = Malloc(struct feature_node, elements); prob.bias=bias; j = 0; for(i=0;i<prob.l;i++) { prob.x[i] = &x_space[j]; prob.y[i] = labels[i]; low = (int) jc[i], high = (int) jc[i+1]; for(k=low;k<high;k++) { x_space[j].index = (int) ir[k]+1; x_space[j].value = samples[k]; j++; } if(prob.bias>=0) { x_space[j].index = max_index+1; x_space[j].value = prob.bias; j++; } x_space[j++].index = -1; } if(prob.bias>=0) prob.n = max_index+1; else prob.n = max_index; return 0; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { float *y; mwSize m,n,curn; if (first) { mexPrintf("fastsoftmax using NUM_THREADS=%u\n",NUM_THREADS); first=0; } switch (nrhs) { case 2: if (! mxIsSingle(SHIFT_PARAMETER_IN)) { mexErrMsgTxt("Single precision shift argument required."); return; } if (mxGetN(SHIFT_PARAMETER_IN) != 1 && mxGetM(SHIFT_PARAMETER_IN) != 1) { mexErrMsgTxt("Shift needs to be a vector."); return; } if (mxGetN(SHIFT_PARAMETER_IN) * mxGetM(SHIFT_PARAMETER_IN) != mxGetN(MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Shift has incompatible shape."); return; } if (! mxIsSingle(MATRIX_PARAMETER_IN)) { mexErrMsgTxt("Single precision matrix argument required."); return; } break; default: mexErrMsgTxt("Incorrect number of input arguments provided."); return; } m = mxGetM(MATRIX_PARAMETER_IN); n = mxGetN(MATRIX_PARAMETER_IN); /* Cheat ... do things in place */ RESULT_OUT = mxCreateNumericMatrix(1, 1, mxSINGLE_CLASS, mxREAL); float* outptr = (float*) mxGetPr(RESULT_OUT); *outptr = 1.0; /* Assign pointers to the various parameters */ y = (float*) mxGetPr(MATRIX_PARAMETER_IN); std::thread t[NUM_THREADS]; float* shiftptr = (float*) mxGetPr(SHIFT_PARAMETER_IN); mwSize quot = (n/NUM_THREADS); for (int i = 0; i + 1 < NUM_THREADS; ++i) { t[i] = std::thread(mexsoftmax, y + i * m * quot, shiftptr + i * quot, quot, m); } mexsoftmax (y + (NUM_THREADS - 1) * m * quot, shiftptr + (NUM_THREADS - 1) * quot, n - (NUM_THREADS - 1) * quot, m); for (int i = 0; i + 1 < NUM_THREADS; ++i) { t[i].join (); } return; }
void sCVB0(double ALPHA, double BETA, int W, int J, int D, int NN, int OUTPUT, int ntokens, int *d, int *w, double *phi, double *theta, double *mu, int startcond) { int wi, di, i, ii, j, topic, rp, temp, iter; double totprob, *thetad, *phitot, xitot = 0.0, JALPHA = (double) (J*ALPHA), WBETA = (double) (W*BETA), r, max, perp = 0.0; thetad = dvec(D); phitot = dvec(J); if (startcond == 1) { /* start from previously saved state */ for (i=0; i<ntokens; i++) { wi = w[i]; di = d[i]; xitot++; thetad[di]++; for (j=0; j<J; j++) { phi[ wi*J + j ] += mu[i*J + j]; // increment phi count matrix theta[ di*J + j ] += mu[i*J + j]; // increment theta count matrix phitot[ j ] += mu[i*J + j]; // increment phitot matrix } } } if (startcond == 0) { /* random initialization */ for (i=0; i<ntokens; i++) { wi = w[ i ]; di = d[ i ]; xitot++; thetad[di]++; // pick a random topic 0..J-1 topic = (int) (J*drand()); phi[ wi*J + topic ]++; // increment phi count matrix theta[ di*J + topic ]++; // increment theta count matrix phitot[ topic ]++; // increment phitot matrix mu[i*J + topic] = (double) 1; } } for (iter=0; iter<NN; iter++) { if (((iter % 10)==0) && (iter != 0)) { /* calculate perplexity */ perp = (double) 0; for (i=0; i<ntokens; i++) { wi = w[i]; // current word index di = d[i]; // current document index totprob = (double) 0; for (j=0; j<J; j++) { totprob += ((double) phi[wi*J + j] + (double) BETA)/ ((double) phitot[j]+ (double) WBETA)* ((double) theta[di*J + j] + (double) ALPHA)/ ((double) thetad[di] + (double) JALPHA); } perp -= log(totprob); } mexPrintf("\tIteration %d of %d:\t%f\n", iter, NN, exp(perp/xitot)); if ((iter % 10)==0) mexEvalString("drawnow;"); } for (i=0; i<ntokens; i++) { wi = w[i]; // current word index di = d[i]; // current document index totprob = (double) 0; for (j=0; j<J; j++) { mu[i*J + j] = ((double) phi[ wi*J+j ] - (double) mu[i*J + j] + (double) BETA)/ ( (double) phitot[j] - (double) mu[i*J + j] + (double) WBETA)* ( (double) theta[ di*J + j ] - (double) mu[i*J + j] + (double) ALPHA ); totprob += mu[i*J + j]; } for (j = 0; j < J; j++) { mu[i*J + j] /= totprob; } } for (i=0; i<J*W; i++) phi[i] = (double) 0; for (i=0; i<J*D; i++) theta[i] = (double) 0; for (j=0; j<J; j++) phitot[j] = (double) 0; for (i=0; i<ntokens; i++) { wi = w[i]; // current word index di = d[i]; // current document index for (j=0; j<J; j++) { phi[wi*J + j] += mu[i*J + j]; // and update counts theta[di*J + j] += mu[i*J + j]; phitot[j] += mu[i*J + j]; } } } }
/* nrhs should be 3 */ int parse_command_line(int nrhs, const mxArray *prhs[], char *model_file_name) { int i, argc = 1; char cmd[CMD_LEN]; char *argv[CMD_LEN/2]; void (*print_func)(const char *) = NULL; /* default printing to stdout */ /* default values */ param.svm_type = C_SVC; param.kernel_type = RBF; param.degree = 3; param.gamma = 0; /* 1/num_features */ param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; cross_validation = 0; if(nrhs <= 1) return 1; if(nrhs > 2) { /* put options in argv[] */ mxGetString(prhs[2], cmd, mxGetN(prhs[2]) + 1); if((argv[argc] = strtok(cmd, " ")) != NULL) while((argv[++argc] = strtok(NULL, " ")) != NULL) ; } /* parse options */ for(i=1;i<argc;i++) { if(argv[i][0] != '-') break; ++i; if(i>=argc && argv[i-1][1] != 'q') /* since option -q has no parameter */ return 1; switch(argv[i-1][1]) { case 's': param.svm_type = atoi(argv[i]); break; case 't': param.kernel_type = atoi(argv[i]); break; case 'd': param.degree = atoi(argv[i]); break; case 'g': param.gamma = atof(argv[i]); break; case 'r': param.coef0 = atof(argv[i]); break; case 'n': param.nu = atof(argv[i]); break; case 'm': param.cache_size = atof(argv[i]); break; case 'c': param.C = atof(argv[i]); break; case 'e': param.eps = atof(argv[i]); break; case 'p': param.p = atof(argv[i]); break; case 'h': param.shrinking = atoi(argv[i]); break; case 'b': param.probability = atoi(argv[i]); break; case 'q': print_func = &print_null; i--; break; case 'v': cross_validation = 1; nr_fold = atoi(argv[i]); if(nr_fold < 2) { mexPrintf("n-fold cross validation: n must >= 2\n"); return 1; } break; case 'w': ++param.nr_weight; param.weight_label = (int *)realloc(param.weight_label,sizeof(int)*param.nr_weight); param.weight = (double *)realloc(param.weight,sizeof(double)*param.nr_weight); param.weight_label[param.nr_weight-1] = atoi(&argv[i-1][2]); param.weight[param.nr_weight-1] = atof(argv[i]); break; default: mexPrintf("Unknown option -%c\n", argv[i-1][1]); return 1; } } svm_set_print_string_function(print_func); return 0; }
/* Interface function of matlab now assume prhs[0]: label prhs[1]: features */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { const char *error_msg; /* fix random seed to have same results for each run (for cross validation and probability estimation) */ srand(1); /* Transform the input Matrix to libsvm format */ if(nrhs > 1 && nrhs < 4) { int err; if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) { mexPrintf("Error: label vector and instance matrix must be double\n"); fake_answer(plhs); return; } if(parse_command_line(nrhs, prhs, NULL)) { exit_with_help(); svm_destroy_param(¶m); fake_answer(plhs); return; } if(mxIsSparse(prhs[1])) { if(param.kernel_type == PRECOMPUTED) { /* precomputed kernel requires dense matrix, so we make one */ mxArray *rhs[1], *lhs[1]; rhs[0] = mxDuplicateArray(prhs[1]); if(mexCallMATLAB(1, lhs, 1, rhs, "full")) { mexPrintf("Error: cannot generate a full training instance matrix\n"); svm_destroy_param(¶m); fake_answer(plhs); return; } err = read_problem_dense(prhs[0], lhs[0]); mxDestroyArray(lhs[0]); mxDestroyArray(rhs[0]); } else err = read_problem_sparse(prhs[0], prhs[1]); } else err = read_problem_dense(prhs[0], prhs[1]); /* svmtrain's original code */ error_msg = svm_check_parameter(&prob, ¶m); if(err || error_msg) { if (error_msg != NULL) mexPrintf("Error: %s\n", error_msg); svm_destroy_param(¶m); free(prob.y); free(prob.x); free(x_space); fake_answer(plhs); return; } if(cross_validation) { double *ptr; plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); ptr = mxGetPr(plhs[0]); ptr[0] = do_cross_validation(); } else { int nr_feat = (int)mxGetN(prhs[1]); const char *error_msg; model = svm_train(&prob, ¶m); error_msg = model_to_matlab_structure(plhs, nr_feat, model); if(error_msg) mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg); svm_free_and_destroy_model(&model); } svm_destroy_param(¶m); free(prob.y); free(prob.x); free(x_space); } else { exit_with_help(); fake_answer(plhs); return; } }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { DOUBLE *prof,*wc, *sg, *Scratch; unsigned int ncolumns,nsamples,nn; int L,J,EntType; int D,nlevel; mxArray *Temp; /* Check for proper number of arguments */ if (nrhs != 5) { mexErrMsgTxt("FastEntProfile requires five input arguments."); } else if (nlhs != 1) { mexErrMsgTxt("FastEntProfile requires one output argument."); } /* Create a matrix for the return argument */ nsamples = mxGetM(WC_IN); ncolumns = mxGetN(WC_IN); if(nsamples == 1){ nsamples = ncolumns; ncolumns = 1; } J = 0; for( nn = 1; nn < nsamples; nn *= 2 ) J ++; if( nn != nsamples){ mexErrMsgTxt("FastEntProfile requires dyadic length"); } L = (int) floor(*(mxGetPr(L_IN)) + .5); if(L >= J || L <= 3) mexErrMsgTxt("FastEntProfile requires 3 <= J <= log_2(n)"); D = (int) floor(*(mxGetPr(D_IN)) + .5); if(D < 2 || D % 2) mexErrMsgTxt("FastEntProfile requires D >= 2 even"); EntType = (int) floor(*(mxGetPr(ET_IN)) + .5); if( EntType != 1 && EntType !=2 ) mexErrMsgTxt("FastEntProfile Requires EntType ==1 or 2"); /* create output array */ nlevel = (J - L); ncolumns = nlevel * (D+1); if(mxGetM(SG_IN) != nsamples ) mexErrMsgTxt("FastEntProfile requires that WC and SG agree in size"); if(mxGetN(SG_IN) != ncolumns ) mexErrMsgTxt("FastEntProfile: the D and J parameters don't agree with shape of SG par"); Prof_OUT = mxCreateDoubleMatrix(nsamples,1,mxREAL); /* create temporary array */ Temp = mxCreateDoubleMatrix(nsamples,3,mxREAL); /* Assign pointers to the various parameters */ prof = mxGetPr(Prof_OUT); sg = mxGetPr(SG_IN); wc = mxGetPr(WC_IN); Scratch = mxGetPr(Temp); mexPrintf("nsamples =%d,nlevel=%d,EntType=%d,D=%d\n", (int) nsamples,nlevel,EntType,D); /* Do the actual computations in a subroutine */ fastprof(wc,(int) nsamples,J,sg,nlevel,L,(int) ncolumns,D,prof,EntType,Scratch); /* remove temporary array */ mxDestroyArray(Temp); }
void mexFunction( const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { /* Check for proper number of arguments. */ if (nrhs != 1) { mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumInputs", "One input required."); } else if (nlhs > 1) { mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumOutputs", "At most one output is allowed."); } const mxArray *numberOfNodesArray = mxGetProperty(prhs[0], 0, "numberOfNodes"); if (!mxIsNumeric(numberOfNodesArray) || mxGetNumberOfElements(numberOfNodesArray) != 1) { mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumberOfNodes", "Number of nodes is not numeric scalar."); } const int numberOfNodes = mxGetScalar(numberOfNodesArray); if (numberOfNodes < 1) { mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:emptyGraph", "Graph is empty."); } const mxArray *pAdjacencyMatrix = mxGetProperty(prhs[0], 0, "pAdjacencyMatrix"); if (!mxIsLogical(pAdjacencyMatrix) || mxGetN(pAdjacencyMatrix) != numberOfNodes || mxGetM(pAdjacencyMatrix) != numberOfNodes) { mexErrMsgIdAndTxt("MATLAB:Graph:IsConnected:invalidAdjacencyMatrix", "Adjacency matrix is not logical square matrix"); } const bool *adjacencyMatrix = mxGetLogicals(pAdjacencyMatrix); const mxArray *pIsDirectedArray = mxGetProperty(prhs[0], 0, "pIsDirected"); if (!mxIsLogicalScalar(pIsDirectedArray)) { mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidIsDirected", "Direction is not logical scalar"); } const bool isDirected = mxIsLogicalScalarTrue(pIsDirectedArray); bool *reachable = new bool[numberOfNodes]; if (mxIsSparse(pAdjacencyMatrix)) { // Sparse adjacency matrix std::vector<std::vector<mwIndex> > graph(numberOfNodes), rgraph(numberOfNodes); const mwIndex* row = mxGetIr(pAdjacencyMatrix); const mwIndex* col = mxGetJc(pAdjacencyMatrix); const size_t nz = col[mxGetN(pAdjacencyMatrix)]; mwIndex c = 0; for(size_t i = 0; i<nz; ++i) { while(col[c+1]<=i) ++c; if(adjacencyMatrix[i]) { graph[row[i]].push_back(c); rgraph[c].push_back(row[i]); } } memset(reachable, false, numberOfNodes * sizeof(bool)); reachable[0] = true; int nReachable = 1; std::queue<int> nodeQueue; nodeQueue.push(0); while(!nodeQueue.empty() && nReachable < numberOfNodes) { const int i = nodeQueue.front(); nodeQueue.pop(); std::vector<mwIndex>::const_iterator it = graph[i].begin(); for (; it != graph[i].end(); ++it) { if(!reachable[*it]) { reachable[*it] = true; nReachable++; nodeQueue.push(*it); } } } if (!isDirected || nReachable != numberOfNodes) { plhs[0] = mxCreateLogicalScalar(nReachable == numberOfNodes); } else { memset(reachable, false, numberOfNodes * sizeof(bool)); reachable[0] = true; int nReachable2 = 1; nodeQueue = std::queue<int>(); // Clear queue nodeQueue.push(0); while(!nodeQueue.empty() && nReachable2 < numberOfNodes) { const int i = nodeQueue.front(); nodeQueue.pop(); std::vector<mwIndex>::const_iterator it = rgraph[i].begin(); for (; it != rgraph[i].end(); ++it) { if(!reachable[*it]) { mexPrintf("Reachable 2 is %lu\n", *it); reachable[*it] = true; nReachable2++; nodeQueue.push(*it); } } } plhs[0] = mxCreateLogicalScalar(nReachable2 == numberOfNodes); } } else { // Full adjacency matrix memset(reachable, false, numberOfNodes * sizeof(bool)); reachable[0] = true; int nReachable = 1; std::queue<int> nodeQueue; nodeQueue.push(0); while(!nodeQueue.empty() && nReachable < numberOfNodes) { const int i = nodeQueue.front(); nodeQueue.pop(); for (int j=0; j<numberOfNodes; ++j) { if(adjacencyMatrix[i*numberOfNodes+j] && !reachable[j]) { reachable[j] = true; nReachable++; nodeQueue.push(j); } } } if (!isDirected || nReachable != numberOfNodes) { plhs[0] = mxCreateLogicalScalar(nReachable == numberOfNodes); } else { memset(reachable, false, numberOfNodes * sizeof(bool)); reachable[0] = true; int nReachable2 = 1; nodeQueue = std::queue<int>(); // Clear queue nodeQueue.push(0); while(!nodeQueue.empty() && nReachable2 < numberOfNodes) { const int i = nodeQueue.front(); nodeQueue.pop(); for (int j=0; j<numberOfNodes; ++j) { if(adjacencyMatrix[j*numberOfNodes+i] && !reachable[j]) { reachable[j] = true; nReachable2++; nodeQueue.push(j); } } } plhs[0] = mxCreateLogicalScalar(nReachable2 == numberOfNodes); } } delete [] reachable; }
/* * This ist the Entry Function of this Mex-DLL */ void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[]) { mexAtExit(CloseDBs); /* * Get the current Language */ if (Language == -1) { #ifdef _WIN32 switch(PRIMARYLANGID(GetUserDefaultLangID())) { case LANG_GERMAN: Language = 1; break; default: Language = 0; } #else Language = 0; #endif } /* * Print Version Information */ if (! FirstStart) { FirstStart = true; mexPrintf (MSG_HELLO, sqlite3_libversion()); } int db_id = 0; int CommandPos = 0; int NumArgs = nrhs; int i; /* * Check if the first argument is a number, then we have to use * this number as an database id. */ if (nrhs >= 1 && mxIsNumeric(prhs[0])) { db_id = getinteger(prhs[0]); if (db_id < 0 || db_id > MaxNumOfDbs) { mexPrintf(MSG_INVALIDDBHANDLE); mexErrMsgTxt(MSG_IMPOSSIBLE); } db_id --; CommandPos ++; NumArgs --; } /* * no argument -> fail */ if (NumArgs < 1) { mexPrintf(MSG_USAGE); mexErrMsgTxt(MSG_INVALIDARG); } /* * The next (or first if no db number available) is the command, * it has to be a string. * This fails also, if the first arg is a db-id and there is no * further argument */ if (! mxIsChar(prhs[CommandPos])) { mexPrintf(MSG_USAGE); mexErrMsgTxt(MSG_INVALIDARG); } /* * Get the command string */ char *command = getstring(prhs[CommandPos]); /* * Adjust the Argument pointer and counter */ int FirstArg = CommandPos +1; NumArgs --; if (! strcmp(command, "open")) { /* * open a database. There has to be one string argument, * the database filename */ if (NumArgs != 1 || !mxIsChar(prhs[FirstArg])) { mexPrintf(MSG_NOOPENARG, mexFunctionName()); mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } // TODO: possible Memoryleak 'command not freed' when getstring fails char* dbname = getstring(prhs[FirstArg]); /* * Is there an database ID? The close the database with the same id */ if (db_id > 0 && g_dbs[db_id]) { sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; } /* * If there isn't an database id, then try to get one */ if (db_id < 0) { for (i = 0; i < MaxNumOfDbs; i++) { if (g_dbs[i] == 0) { db_id = i; break; } } } /* * no database id? sorry, database id table full */ if (db_id < 0) { plhs[0] = mxCreateDoubleScalar((double) 0); mexPrintf(MSG_NOFREESLOT); mxFree(command); mxFree(dbname); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * Open the database */ int rc = sqlite3_open(dbname, &g_dbs[db_id]); if (rc) { /* * Anything wrong? free the database id and inform the user */ mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id])); sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; plhs[0] = mxCreateDoubleScalar((double) 0); mxFree(command); mxFree(dbname); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * Set Default Busytimeout */ rc = sqlite3_busy_timeout(g_dbs[db_id], DEFAULT_BUSYTIMEOUT); if (rc) { /* * Anything wrong? free the database id and inform the user */ mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id])); sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; plhs[0] = mxCreateDoubleScalar((double) 0); mxFree(command); mxFree(dbname); mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL); } /* * return value will be the used database id */ plhs[0] = mxCreateDoubleScalar((double) db_id +1); mxFree(dbname); } else if (! strcmp(command, "close")) { /* * close a database */ /* * There should be no Argument to close */ if (NumArgs > 0) { mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } /* * if the database id is < 0 than close all open databases */ if (db_id < 0) { for (i = 0; i < MaxNumOfDbs; i++) { if (g_dbs[i]) { sqlite3_close(g_dbs[i]); g_dbs[i] = 0; } } } else { /* * If the database is open, then close it. Otherwise * inform the user */ if (! g_dbs[db_id]) { mxFree(command); mexErrMsgTxt(MSG_DBNOTOPEN); } else { sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; } } } else if (! strcmp(command, "status")) { /* * There should be no Argument to status */ if (NumArgs > 0) { mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } for (i = 0; i < MaxNumOfDbs; i++) { mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED"); } } else if (! _strcmpi(command, "setbusytimeout")) { /* * There should be one Argument, the Timeout in ms */ if (NumArgs != 1 || !mxIsNumeric(prhs[FirstArg])) { mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } if (! g_dbs[db_id]) { mxFree(command); mexErrMsgTxt(MSG_DBNOTOPEN); } else { /* * Set Busytimeout */ int TimeoutValue = getinteger(prhs[FirstArg]); int rc = sqlite3_busy_timeout(g_dbs[db_id], TimeoutValue); if (rc) { /* * Anything wrong? free the database id and inform the user */ mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id])); sqlite3_close(g_dbs[db_id]); g_dbs[db_id] = 0; plhs[0] = mxCreateDoubleScalar((double) 0); mxFree(command); mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL); } } } else { /* * database id < 0? Thats an error... */ if (db_id < 0) { mexPrintf(MSG_INVALIDDBHANDLE); mxFree(command); mexErrMsgTxt(MSG_IMPOSSIBLE); } /* * database not open? -> error */ if (!g_dbs[db_id]) { mxFree(command); mexErrMsgTxt(MSG_DBNOTOPEN); } /* * Every unknown command is treated as an sql query string */ const char* query = command; /* * a query shuld have no arguments */ if (NumArgs > 0) { mxFree(command); mexErrMsgTxt(MSG_INVALIDARG); } /* * emulate the "show tables" sql query */ if (! _strcmpi(query, "show tables")) { query = "SELECT name as tablename FROM sqlite_master " "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' " "UNION ALL " "SELECT name as tablename FROM sqlite_temp_master " "WHERE type IN ('table','view') " "ORDER BY 1"; } /* * complete the query */ if (sqlite3_complete(query)) { mxFree(command); mexErrMsgTxt(MSG_INVQUERY); } sqlite3_stmt *st; /* * and prepare it * if anything is wrong with the query, than complain about it. */ if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0)) { if (st) sqlite3_finalize(st); mxFree(command); mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id])); } /* * Any results? */ int ncol = sqlite3_column_count(st); if (ncol > 0) { char **fieldnames = new char *[ncol]; /* Column names */ Values* allrows = 0; /* All query results */ Values* lastrow = 0; /* pointer to the last result row */ int rowcount = 0; /* number of result rows */ /* * Get the column names of the result set */ for(i=0; i<ncol; i++) { const char *cname = sqlite3_column_name(st, i); fieldnames[i] = new char [strlen(cname) +1]; strcpy (fieldnames[i], cname); /* * replace invalid chars by '_', so we can build * valid MATLAB structs */ char *mk_c = fieldnames[i]; while (*mk_c) { if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?')) *mk_c = '_'; mk_c++; } } /* * get the result rows from the engine * * We cannot get the number of result lines, so we must * read them in a loop and save them into an temporary list. * Later, we can transfer this List into an MATLAB array of structs. * This way, we must allocate enough memory for two result sets, * but we save time by allocating the MATLAB Array at once. */ for(;;) { /* * Advance to teh next row */ int step_res = sqlite3_step(st); /* * no row left? break out of the loop */ if (step_res != SQLITE_ROW) break; /* * get new memory for the result */ Values* RecordValues = new Values(ncol); Value *v = RecordValues->m_Values; for (int j = 0; j < ncol; j++, v++) { int fieldtype = sqlite3_column_type(st,j); v->m_Type = fieldtype; v->m_Size = 0; switch (fieldtype) { case SQLITE_NULL: v->m_NumericValue = g_NaN; break; case SQLITE_INTEGER: v->m_NumericValue = (double) sqlite3_column_int(st, j); break; case SQLITE_FLOAT: v->m_NumericValue = (double) sqlite3_column_double(st, j); break; case SQLITE_TEXT: v->m_StringValue = strnewdup((const char*) sqlite3_column_text(st, j)); break; case SQLITE_BLOB: { v->m_Size = sqlite3_column_bytes(st,j); if (v->m_Size > 0) { v->m_StringValue = new char[v->m_Size]; memcpy(v->m_StringValue, sqlite3_column_blob(st,j), v->m_Size); } else { v->m_Size = 0; } } break; default: mxFree(command); mexErrMsgTxt(MSG_UNKNWNDBTYPE); } } /* * and add this row to the list of all result rows */ if (! lastrow) { allrows = lastrow = RecordValues; } else { lastrow->m_NextValues = RecordValues; lastrow = lastrow->m_NextValues; } /* * we have one more... */ rowcount ++; } /* * end the sql engine */ sqlite3_finalize(st); /* * got nothing? return an empty result to MATLAB */ if (rowcount == 0 || ! allrows) { if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) )) { mxFree(command); mexErrMsgTxt(MSG_CANTCREATEOUTPUT); } } else { /* * Allocate an array of MATLAB structs to return as result */ int ndims[2]; ndims[0] = rowcount; ndims[1] = 1; if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0) { mxFree(command); mexErrMsgTxt(MSG_CANTCREATEOUTPUT); } /* * transfer the result rows from the temporary list into the result array */ lastrow = allrows; i = 0; while(lastrow) { Value* recordvalue = lastrow->m_Values; for (int j = 0; j < ncol; j++, recordvalue++) { if (recordvalue -> m_Type == SQLITE_TEXT) { mxArray* c = mxCreateString(recordvalue->m_StringValue); mxSetFieldByNumber(plhs[0], i, j, c); } else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN) { mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL); mxSetFieldByNumber(plhs[0], i, j, out_double); } else if (recordvalue -> m_Type == SQLITE_BLOB) { if (recordvalue->m_Size > 0) { int BytePos; int NumDims[2]={1,1}; NumDims[1]=recordvalue->m_Size; mxArray*out_uchar8=mxCreateNumericArray(2, NumDims, mxUINT8_CLASS, mxREAL); unsigned char *v = (unsigned char *) mxGetData(out_uchar8); memcpy(v, recordvalue->m_StringValue, recordvalue->m_Size); mxSetFieldByNumber(plhs[0], i, j, out_uchar8); } else { // empty BLOB mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL); mxSetFieldByNumber(plhs[0], i, j, out_double); } } else { mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue); mxSetFieldByNumber(plhs[0], i, j, out_double); } } allrows = lastrow; lastrow = lastrow->m_NextValues; delete allrows; i++; } } for(int i=0; i<ncol; i++) delete [] fieldnames[i]; delete [] fieldnames; } else { /* * no result, cleanup the sqlite engine */ int res = sqlite3_step(st); sqlite3_finalize(st); if (!( plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL) )) { mexErrMsgTxt(MSG_CANTCREATEOUTPUT); } if (res != SQLITE_DONE) { mxFree(command); mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id])); } } } mxFree(command); }
void mexFunction( int mlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { /* Declare */ short *dlsch_llr; unsigned char mcs; unsigned int *ret; unsigned char mod_order; unsigned char num_pdcch_symbols; unsigned char harq_pid; unsigned char subframe; unsigned char Kmimo; unsigned char Mdlharq; unsigned char abstraction_flag; LTE_UE_DLSCH_t* dlsch; LTE_DL_FRAME_PARMS *frame_parms; PHY_VARS_UE *phy_vars_ue; extern int *pi2tab16[188],*pi5tab16[188],*pi4tab16[188],*pi6tab16[188]; unsigned long *ptr_td; //Specific Modification for 64bit int *tmp[1]; /* Allocate input */ dlsch_llr = (short*) mxGetData(prhs[0]); /* Create new dlsch */ Kmimo = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"Kmimo")); Mdlharq = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"Mdlharq")); abstraction_flag = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"abstraction_flag")); mcs = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"mcs")); #ifdef DEBUG_DLSCH_DECODING mexPrintf("Kmimo %d\n",Kmimo); mexPrintf("Mdlharq %d\n",Mdlharq); mexPrintf("abstraction_flag %d\n",abstraction_flag); mexPrintf("mcs %d\n",mcs); #endif /* Create new dlsch */ dlsch = new_ue_dlsch(Kmimo,Mdlharq,8,25,abstraction_flag); // Init CRC tables crcTableInit(); // init_td(); // copy the pointers to memory allocated in dlsch_decoding_init ptr_td = (unsigned int*) mxGetData(mxGetField(prhs[1],0,"ptr_td")); #ifdef DEBUG_DLSCH_DECODING mexPrintf("ptr_td0 %p\n",ptr_td[0]); mexPrintf("ptr_td1 %p\n",ptr_td[1]); mexPrintf("ptr_td2 %p\n",ptr_td[2]); mexPrintf("ptr_td3 %p\n",ptr_td[3]); #endif memcpy(&tmp[0], &ptr_td[0], sizeof(ptr_td[0])); memcpy(&pi2tab16[0], tmp[0], 188*sizeof(pi2tab16[0])); memcpy(&tmp[0], &ptr_td[1], sizeof(ptr_td[1])); memcpy(&pi4tab16[0], tmp[0], 188*sizeof(pi4tab16[0])); memcpy(&tmp[0], &ptr_td[2], sizeof(ptr_td[2])); memcpy(&pi5tab16[0], tmp[0], 188*sizeof(pi5tab16[0])); memcpy(&tmp[0], &ptr_td[3], sizeof(ptr_td[3])); memcpy(&pi6tab16[0], tmp[0], 188*sizeof(pi6tab16[0])); harq_pid = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"harq_pid")); dlsch->current_harq_pid = harq_pid; dlsch->harq_processes[harq_pid]->rvidx = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"rvidx")); dlsch->harq_processes[harq_pid]->Nl = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"Nl")); //dlsch->harq_processes[harq_pid]->Ndi = (unsigned char) mxGetScalar(mxGetField(prhs[2],0,"Ndi")); dlsch->harq_processes[harq_pid]->mcs = mcs; dlsch->harq_processes[harq_pid]->rb_alloc[0] = (unsigned int) mxGetScalar(mxGetField(prhs[1],0,"rb_alloc")); dlsch->harq_processes[harq_pid]->nb_rb = (unsigned short) mxGetScalar(mxGetField(prhs[1],0,"nb_rb")); dlsch->harq_processes[harq_pid]->TBS = dlsch_tbs25[get_I_TBS(mcs)][dlsch->harq_processes[harq_pid]->nb_rb-1]; num_pdcch_symbols = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"num_pdcch_symbols")); subframe = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"subframe")); phy_vars_ue = calloc(1,sizeof(PHY_VARS_UE)); // Create a LTE_DL_FRAME_PARMS structure and assign required params frame_parms = calloc(1,sizeof(LTE_DL_FRAME_PARMS)); frame_parms->N_RB_DL = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"nb_rb")); frame_parms->frame_type = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"frame_type")); frame_parms->mode1_flag = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"mode1_flag")); frame_parms->Ncp = (unsigned char) mxGetScalar(mxGetField(prhs[1],0,"Ncp")); mod_order = get_Qm(dlsch->harq_processes[harq_pid]->mcs); dlsch->harq_processes[harq_pid]->G = get_G(frame_parms,dlsch->harq_processes[harq_pid]->nb_rb,dlsch->harq_processes[harq_pid]->rb_alloc,mod_order,dlsch->harq_processes[harq_pid]->Nl,num_pdcch_symbols,0,subframe); #ifdef DEBUG_DLSCH_DECODING mexPrintf("TBS %d\n",dlsch->harq_processes[harq_pid]->TBS); mexPrintf("nb_rb %d\n",dlsch->harq_processes[harq_pid]->nb_rb); mexPrintf("ncs %d\n",dlsch->harq_processes[harq_pid]->mcs); mexPrintf("num_pdcch_symbols %d\n",num_pdcch_symbols); mexPrintf("subframe %d\n",subframe); mexPrintf("G %d\n",dlsch->harq_processes[harq_pid]->G); #endif if (dlsch->harq_processes[harq_pid]->G != mxGetM(prhs[0])) { free_ue_dlsch(dlsch); free(frame_parms); free(phy_vars_ue); mexErrMsgTxt("Length of the LLR vector is incorrect."); } /* Allocate Output */ plhs[0] = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL); ret = (unsigned int*) mxGetPr(plhs[0]); /* Algo */ *ret = dlsch_decoding(phy_vars_ue, dlsch_llr, frame_parms, dlsch, dlsch->harq_processes[harq_pid], subframe, dlsch->current_harq_pid, 1,0); /* free dlsch */ free_ue_dlsch(dlsch); free(frame_parms); free(phy_vars_ue); // free_td(); }
// -------------------------------------------------- Print some fancy help static void PrintHelp(void) { mexPrintf("(MX) little cms ColorSpace conversion tool - v0.3 BETA\n\n"); mexPrintf("usage: icctrans (mVar, flags)\n\n"); mexPrintf("mVar : Matlab array.\n"); mexPrintf("flags: a string containing one or more of following options.\n\n"); mexPrintf("\t%cv - Verbose\n", SW); mexPrintf("\t%ci<profile> - Input profile (defaults to sRGB)\n", SW); mexPrintf("\t%co<profile> - Output profile (defaults to sRGB)\n", SW); mexPrintf("\t%cl<profile> - Transform by device-link profile\n", SW); mexPrintf("\t%cm<profiles> - Apply multiprofile chain\n", SW); mexPrintf("\t%ct<0,1,2,3> - Intent (0=Perceptual, 1=Colorimetric, 2=Saturation, 3=Absolute)\n", SW); mexPrintf("\t%cb - Black point compensation\n", SW); mexPrintf("\t%cc<0,1,2,3> - Precalculates transform (0=Off, 1=Normal, 2=Hi-res, 3=LoRes) [defaults to 0]\n", SW); mexPrintf("\t%cp<profile> - Soft proof profile\n", SW); mexPrintf("\t%cr<0,1,2,3> - Soft proof intent\n", SW); mexPrintf("\nYou can use following built-ins as profiles:\n\n"); mexPrintf("\t'*sRGB' -> IEC6 1996-2.1 sRGB\n"); mexPrintf("\t'*Lab' -> D50 based Lab\n"); mexPrintf("\t'*LabD65' -> D65 based Lab\n"); mexPrintf("\t'*XYZ' -> XYZ (D50)\n"); mexPrintf("\t'*Gray22' -> D50 gamma 2.2 grayscale.\n\n"); mexPrintf("For suggestions, comments, bug reports etc. send mail to\n" "[email protected] or [email protected]\n\n"); }
static void OpenTransforms(int argc, char *argv[]) { DWORD dwIn, dwOut, dwFlags; if (lMultiProfileChain) { int i; cmsHTRANSFORM hTmp; nProfiles = argc - xoptind; for (i=0; i < nProfiles; i++) { hProfiles[i] = OpenProfile(argv[i+xoptind]); } // Create a temporary devicelink hTmp = cmsCreateMultiprofileTransform(hProfiles, nProfiles, 0, 0, Intent, GetFlags()); hInput = cmsTransform2DeviceLink(hTmp, 0); hOutput = NULL; cmsDeleteTransform(hTmp); InputColorSpace = cmsGetColorSpace(hInput); OutputColorSpace = cmsGetPCS(hInput); lIsDeviceLink = TRUE; } else if (lIsDeviceLink) { hInput = cmsOpenProfileFromFile(cInProf, "r"); hOutput = NULL; InputColorSpace = cmsGetColorSpace(hInput); OutputColorSpace = cmsGetPCS(hInput); } else { hInput = OpenProfile(cInProf); hOutput = OpenProfile(cOutProf); InputColorSpace = cmsGetColorSpace(hInput); OutputColorSpace = cmsGetColorSpace(hOutput); if (cmsGetDeviceClass(hInput) == icSigLinkClass || cmsGetDeviceClass(hOutput) == icSigLinkClass) FatalError("Use %cl flag for devicelink profiles!\n", SW); } if (Verbose) { mexPrintf("From: %s\n", cmsTakeProductName(hInput)); if (hOutput) mexPrintf("To : %s\n\n", cmsTakeProductName(hOutput)); } OutputChannels = _cmsChannelsOf(OutputColorSpace); InputChannels = _cmsChannelsOf(InputColorSpace); dwIn = MakeFormatDescriptor(InputColorSpace, nBytesDepth); dwOut = MakeFormatDescriptor(OutputColorSpace, nBytesDepth); dwFlags = GetFlags(); if (cProofing != NULL) { hProof = OpenProfile(cProofing); dwFlags |= cmsFLAGS_SOFTPROOFING; } hColorTransform = cmsCreateProofingTransform(hInput, dwIn, hOutput, dwOut, hProof, Intent, ProofingIntent, dwFlags); }
void mexFunction(int nlhs, /* Num return vals on lhs */ mxArray *plhs[], /* Matrices on lhs */ int nrhs, /* Num args on rhs */ const mxArray *prhs[] /* Matrices on rhs */ ) { double *image,*filt, *temp, *result; int x_fdim, y_fdim, x_idim, y_idim; int x_rdim, y_rdim; int x_start = 1; int x_step = 1; int y_start = 1; int y_step = 1; int x_stop, y_stop; mxArray *arg; double *mxMat; char edges[15] = "reflect1"; if (nrhs<2) mexErrMsgTxt("requres at least 2 args."); /* ARG 1: IMAGE */ arg = prhs[0]; if notDblMtx(arg) mexErrMsgTxt("IMAGE arg must be a non-sparse double float matrix."); image = mxGetPr(arg); x_idim = (int) mxGetM(arg); /* X is inner index! */ y_idim = (int) mxGetN(arg); /* ARG 2: FILTER */ arg = prhs[1]; if notDblMtx(arg) mexErrMsgTxt("FILTER arg must be non-sparse double float matrix."); filt = mxGetPr(arg); x_fdim = (int) mxGetM(arg); y_fdim = (int) mxGetN(arg); if ((x_fdim > x_idim) || (y_fdim > y_idim)) { mexPrintf("Filter: [%d %d], Image: [%d %d]\n",x_fdim,y_fdim,x_idim,y_idim); mexErrMsgTxt("FILTER dimensions larger than IMAGE dimensions."); } /* ARG 3 (optional): EDGES */ if (nrhs>2) { if (!mxIsChar(prhs[2])) mexErrMsgTxt("EDGES arg must be a string."); mxGetString(prhs[2],edges,15); } /* ARG 4 (optional): STEP */ if (nrhs>3) { arg = prhs[3]; if notDblMtx(arg) mexErrMsgTxt("STEP arg must be a double float matrix."); if (mxGetM(arg) * mxGetN(arg) != 2) mexErrMsgTxt("STEP arg must contain two elements."); mxMat = mxGetPr(arg); x_step = (int) mxMat[0]; y_step = (int) mxMat[1]; if ((x_step<1) || (y_step<1)) mexErrMsgTxt("STEP values must be greater than zero."); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Get the command string char cmd[64]; if (nrhs < 1 || mxGetString(prhs[0], cmd, sizeof(cmd))) mexErrMsgTxt("First input should be a command string less than 64 characters long."); // New if (!strcmp("new", cmd)) { // Check parameters if (nlhs != 1) mexErrMsgTxt("New: One output expected."); // Return a handle to a new C++ instance //plhs[0] = convertPtr2Mat<dummy>(new dummy); plhs[0] = convertPtr2Mat<CK4Wv2OpenCVModule>(new CK4Wv2OpenCVModule()); return; } // Check there is a second input, which should be the class instance handle if (nrhs < 2) mexErrMsgTxt("Second input should be a class instance handle."); // Delete if (!strcmp("delete", cmd)) { // Destroy the C++ object destroyObject<CK4Wv2OpenCVModule>(prhs[1]); // Warn if other commands were ignored if (nlhs != 0 || nrhs != 2) mexWarnMsgTxt("Delete: Unexpected arguments ignored."); return; } // Get the class instance pointer from the second input CK4Wv2OpenCVModule *dummy_instance = convertMat2Ptr<CK4Wv2OpenCVModule>(prhs[1]); // Call the various class methods // Train if (!strcmp("InitializeKinectDevice", cmd)) { // Check parameters if (nlhs < 0 || nrhs < 2) mexErrMsgTxt("InitializeKinectDevice: Unexpected arguments."); // Call the method dummy_instance->InitializeKinectDevice(); //plhs[0] = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL);; //double * data = (double *)mxGetData(plhs[0]); //data[0] = *dummy_instance->dynamicData; return; } // Test if (!strcmp("UpdateData", cmd)) { // Check parameters if (nlhs < 0 || nrhs < 2) mexErrMsgTxt("UpdateData: Unexpected arguments."); // Call the method //dummy_instance->UpdateData(); return; } if (!strcmp("GrabDepth", cmd)) { // Check parameters if (nlhs < 0 || nrhs < 2) mexErrMsgTxt("GrabDepth: Unexpected arguments."); // Call the method if (persistent_array_ptr==NULL) { mexPrintf("MEX-file initializing, creating array\n"); persistent_array_ptr = mxCreateNumericMatrix(dummy_instance->DEPTH_FRAME_WIDTH, dummy_instance->DEPTH_FRAME_HEIGHT, mxUINT16_CLASS, mxREAL); mexMakeArrayPersistent(persistent_array_ptr); mexAtExit(exitFcn); } plhs[0] = persistent_array_ptr; UINT16 *dynamicData = (UINT16*)mxGetPr(plhs[0]); int nop = dummy_instance->DEPTH_FRAME_HEIGHT* dummy_instance->DEPTH_FRAME_WIDTH; dummy_instance->UpdateData(dynamicData); return; } // Got here, so command not recognized mexErrMsgTxt("Command not recognized."); }
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { int col, row, r_find , movie_length, traces_col, min_length, trace_length, r_integrate, fnumber_size, trace_number; double *movie, h_min, *p2Matrix, *cur_trace, *fnumber; std::vector< std::vector< std::vector<int> > > traces; std::vector< std::vector< std::vector<int> > > itraces; std::vector<int> framenumber; /* Check for proper number of arguments */ if (nrhs != 8 ) { mexErrMsgTxt ("append_traces requires: movie, traces, itraces, framenumbers, h_min, r_find, r_integrate, min_length"); } else if (nlhs != 2 ) { mexErrMsgTxt ("add returns list of traces "); } /* Get arguments from MATLAB */ // movie = mxGetPr(prhs[0]); //columns * rows * frame movie_length = (int) mxGetDimensions(prhs[0])[2]; //length of video = number of frames col = (int) mxGetDimensions(prhs[0])[0]; //number of columns row = (int) mxGetDimensions(prhs[0])[1]; //number of rows h_min = (mxGetScalar(prhs[4])); r_find = (int)(mxGetScalar(prhs[5])); r_integrate = (int)(mxGetScalar(prhs[6])); min_length = (int)(mxGetScalar(prhs[7])); //fill framenumbers fnumber = mxGetPr(prhs[3]); //columns * rows * frame for(int i=0; i< PeakProcessing::max(mxGetM(prhs[3]), mxGetN(prhs[3]) ); i++){ framenumber.push_back((int)fnumber[i]); } trace_number = mxGetM(prhs[1]); //fill traces for(int i=0; i<trace_number; i++){ cur_trace = mxGetPr(mxGetCell(prhs[1],i)); trace_length = mxGetM(mxGetCell(prhs[1],i)); std::vector< std::vector<int> > tmptrace; //loop through ith trace for(int j=0; j<trace_length; j++){ std::vector<int> addthis; addthis.push_back(cur_trace[trace_length*0+j]); //framenumber addthis.push_back(cur_trace[trace_length*1+j]); //x addthis.push_back(cur_trace[trace_length*2+j]); //y tmptrace.push_back(addthis); } traces.push_back(tmptrace); } trace_number = mxGetM(prhs[2]); //fill itraces for(int i=0; i<trace_number; i++){ cur_trace = mxGetPr(mxGetCell(prhs[2],i)); trace_length = mxGetM(mxGetCell(prhs[2],i)); std::vector< std::vector<int> > tmptrace; //loop through ith trace for(int j=0; j<trace_length; j++){ std::vector<int> addthis; addthis.push_back(cur_trace[trace_length*0+j]); //framenumber addthis.push_back(cur_trace[trace_length*1+j]); //x addthis.push_back(cur_trace[trace_length*2+j]); //y addthis.push_back(cur_trace[trace_length*3+j]); //intensity tmptrace.push_back(addthis); } itraces.push_back(tmptrace); } PeakProcessing::append_traces(movie, movie_length, col, row, &traces, &itraces, r_find, h_min, r_integrate, &framenumber); //delete short traces for(int i=0; i< traces.size(); i++){ if(traces[i].size() < min_length){ traces.erase(traces.begin()+i); itraces.erase(itraces.begin()+i); i--; } } mexPrintf("movie_length = %i \tImage = %i , %i \t", movie_length, col, row); mexPrintf("r_find = %i \t h_min = %.2f \t r_integrate = %i\t", r_find, h_min, r_integrate); mexPrintf("%i traces\n", traces.size()); //Allocate storage place for the result int dims[1]; dims[0]=(int) traces.size(); //number of traces plhs[0] = mxCreateCellArray(1, dims ); for(int i=0; i< traces.size(); i++){ traces_col = traces[i].size(); mxArray * tmp = mxCreateDoubleMatrix((int)traces[i].size(),3, mxREAL); //make mxArray to store the ith trace p2Matrix = mxGetPr(tmp); //fill this array for(int j=0; j<traces[i].size(); j++){ p2Matrix[traces_col*0+j] = traces[i][j][0]; //framenumber p2Matrix[traces_col*1+j] = traces[i][j][1]; //x p2Matrix[traces_col*2+j] = traces[i][j][2]; //y //mexPrintf("%i\t %i \t %i\n", traces[i][j][0], traces[i][j][1], traces[i][j][2]); } mxSetCell(plhs[0], i,tmp); } //Allocate storage place for the result dims[0]=(int) itraces.size(); //number of traces plhs[1] = mxCreateCellArray(1, dims ); for(int i=0; i< itraces.size(); i++){ traces_col = itraces[i].size(); mxArray * tmp = mxCreateDoubleMatrix((int)itraces[i].size(),4, mxREAL); //make mxArray to store the ith trace p2Matrix = mxGetPr(tmp); //fill this array for(int j=0; j<itraces[i].size(); j++){ p2Matrix[traces_col*0+j] = itraces[i][j][0]; //framenumber p2Matrix[traces_col*1+j] = itraces[i][j][1]; //x p2Matrix[traces_col*2+j] = itraces[i][j][2]; //y p2Matrix[traces_col*3+j] = itraces[i][j][3]; //y //mexPrintf("%i\t %i \t %i\n", traces[i][j][0], traces[i][j][1], traces[i][j][2]); } mxSetCell(plhs[1], i,tmp); } }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Declare Inputs*/ double *xCurr; double *parameters; double *timepoints; int numTimepts; /* Load input values from prhs */ xCurr = mxGetPr(prhs[0]); parameters = mxGetPr(prhs[1]); /* Get the program related options * from the structure. */ char *panicFileName = NULL; //char defaultPanicFileName[] = "panic_log.txt"; char *periodicFileName = NULL; //char defaultperiodicFileName[] = "periodic_log.txt"; long long unsigned *maxHistory = NULL; long long unsigned *period = NULL; bool assignedDefault[NUM_OF_FIELDS] = { false }; /* pointer to field names */ const char **fnames; int numFields; mwSize NStructElems; mxArray *fields[MAX_FIELDS]; const mxArray *struct_array = prhs[2]; mxClassID classIDflags[] = { mxCHAR_CLASS, mxCHAR_CLASS, mxUINT64_CLASS, mxUINT64_CLASS }; /* check if the input in struct_array is a structure */ if (mxIsStruct(struct_array) == false) { mexErrMsgIdAndTxt("SSA:programOptions:inputNotStruct", "Input must be a structure."); } /* get number of elements in structure */ numFields = mxGetNumberOfFields(struct_array); mexPrintf("Number of fields provided in structure %d \n", numFields); if (numFields != NUM_OF_FIELDS) { mexWarnMsgIdAndTxt("SSA:programOptions:NumOfStructElementMismatch", "The expected number of elements in structure does not match with the provided\n"); mexPrintf("Expected vs Provided : %d %d\n", NUM_OF_FIELDS, numFields); } NStructElems = mxGetNumberOfElements(struct_array); mexPrintf("Number of elements in structure %d \n", NStructElems); /* allocate memory for storing pointers */ fnames = (const char**) mxCalloc(numFields, sizeof(*fnames)); /* get field name pointers */ for (int i = 0; i < numFields; i++) { fnames[i] = mxGetFieldNameByNumber(struct_array, i); } /* get the panic file name*/ mxArray *panic_file = getFieldPointer(struct_array, 0, fnames[PANIC_FILE_INDEX], classIDflags[0]); if (panic_file != NULL) { panicFileName = mxArrayToString(panic_file); mexPrintf("panic file name %s \n", panicFileName); } else { int buflen = strlen(DEFAULT_PANIC_FILE) + 1; panicFileName = (char *) mxCalloc(buflen, sizeof(char)); strcpy(panicFileName, DEFAULT_PANIC_FILE); mexPrintf("default panic file name %s \n", panicFileName); assignedDefault[PANIC_FILE_INDEX] = true; } /* get the periodic file name*/ mxArray *periodic_file = getFieldPointer(struct_array, 0, fnames[PERIODIC_FILE_INDEX], classIDflags[1]); if (periodic_file != NULL) { periodicFileName = mxArrayToString(periodic_file); mexPrintf("periodic file name %s \n", periodicFileName); } else { int buflen = strlen(DEFAULT_PERIODIC_FILE) + 1; periodicFileName = (char *) mxCalloc(buflen, sizeof(char)); strcpy(periodicFileName, DEFAULT_PERIODIC_FILE); mexPrintf("default periodic file name %s \n", periodicFileName); assignedDefault[PERIODIC_FILE_INDEX] = true; } /* get the max history value */ mxArray *max_history_pointer = getFieldPointer(struct_array, 0, fnames[MAX_HISTORY_INDEX], classIDflags[2]); if (max_history_pointer != NULL) { maxHistory = (long long unsigned*) mxGetData(max_history_pointer); mexPrintf("max history value %llu \n", *maxHistory); } else { maxHistory = (long long unsigned *) mxCalloc(1, sizeof(long long unsigned)); *maxHistory = DEFAULT_MAX_HISTORY; mexPrintf("default max history value %llu \n", *maxHistory); assignedDefault[MAX_HISTORY_INDEX] = true; } /* get the period value */ mxArray *period_pointer = getFieldPointer(struct_array, 0, fnames[PERIOD_INDEX], classIDflags[3]); if (period_pointer != NULL) { period = (long long unsigned *) mxGetPr(period_pointer); mexPrintf("period value %llu \n", *period); } else { period = (long long unsigned *) mxCalloc(1, sizeof(long long unsigned)); *period = DEFAULT_PERIOD; mexPrintf("default period value %llu \n", *period); assignedDefault[PERIOD_INDEX] = true; } /* free the memory */ mxFree((void *) fnames); timepoints = mxGetPr(prhs[3]); numTimepts = (int) mxGetScalar(prhs[4]); /* Declare IMs*/ double cumProps[SSA_NumReactions]; int reactionIndex; int iTime; double tCurr; double tNext; /* Declare Outputs*/ double* timecourse; /* Create Outputs I */ plhs[0] = mxCreateDoubleMatrix(SSA_NumStates * numTimepts, 1, mxREAL); timecourse = mxGetPr(plhs[0]); #ifdef LOGGING /* Panic log file name */ std::string panic_file_name(panicFileName); std::ofstream panic_fstream; /* periodic log file */ std::string periodic_file_name(periodicFileName); std::ofstream periodic_fstream; openOutputStream(periodic_file_name, periodic_fstream); //std::cout<<"logging enabled...\n"<<std::endl; LOGLEVEL level; #ifdef LEVEL_ALL /* memory allocation of variables */ double logRandOne[MAX_HISTORY]; double logRandTwo[MAX_HISTORY]; double logTCurr[MAX_HISTORY]; double logTNext[MAX_HISTORY]; double logCurrentStates [MAX_HISTORY][SSA_NumStates]; double logPropensities [MAX_HISTORY][SSA_NumReactions]; double logChosenPropensity [MAX_HISTORY]; double logChosenReactionIndex [MAX_HISTORY]; /* set level */ level = ALL; #elif LEVEL_DEBUG /* memory allocation of variables */ double *logRandOne = NULL; double *logRandTwo = NULL; double logTCurr[MAX_HISTORY]; double logTNext[MAX_HISTORY]; double logCurrentStates [MAX_HISTORY][SSA_NumStates]; double logPropensities [MAX_HISTORY][SSA_NumReactions]; double *logChosenPropensity = NULL; double logChosenReactionIndex [MAX_HISTORY]; /* set level */ level = DEBUG; #elif LEVEL_INFO /* memory allocation of variables */ double *logRandOne = NULL; double *logRandTwo = NULL; double *logTCurr = NULL; double *logTNext = NULL; double logCurrentStates [MAX_HISTORY][SSA_NumStates]; double logPropensities [MAX_HISTORY][SSA_NumReactions]; double *logChosenPropensity = NULL; double logChosenReactionIndex [MAX_HISTORY]; /* set level */ level = INFO; #else /* memory allocation of variables */ double *logRandOne = NULL; double *logRandTwo = NULL; double *logTCurr = NULL; double *logTNext = NULL; double *logCurrentStates = NULL; double *logPropensities = NULL; double *logChosenPropensity = NULL; double *logChosenReactionIndex = NULL; /* set level */ level = OFF; /* As level is off disable the logging */ #endif /*definition of log levels */ /* INFO - { STATES,PROPENSITIES, REACTION_INDICIES} */ /* DEBUG - {T_CURR ,T_NEXT , CHOOSEN_PROPENSITY } + INFO */ /* ALL - {RAND_ONE , RAND_TWO } + DEBUG */ int log_level_of_var[NUM_VARS]; log_level_of_var[RAND_ONE] = 0; log_level_of_var[RAND_TWO] = 0; log_level_of_var[T_CURR] = 1; log_level_of_var[T_NEXT] = 1; log_level_of_var[STATES] = 2; log_level_of_var[PROPENSITIES] = 2; log_level_of_var[CHOSEN_PROPENSITY] = 1; log_level_of_var[REACTION_INDEX] = 2; /* initialize the logging flag for variables */ bool logging_flag_of_var[NUM_VARS]; initializeLoggingFlags(level,log_level_of_var,logging_flag_of_var); #endif /* Write initial conditions to output */ iTime = 0; for (int i = 0; i < SSA_NumStates; i++) { timecourse[iTime * SSA_NumStates + i] = xCurr[i]; } iTime++; tNext = timepoints[iTime]; /* Start iteration*/ tCurr = timepoints[0]; tNext = timepoints[iTime]; long long unsigned globalCounter = 0; long long unsigned historyCounts = 0; while (tCurr < timepoints[numTimepts - 1]) { // Debugging info - massive performance decrease double rand1 = std::max(1.0, (double) rand()) / (double) RAND_MAX; double rand2 = std::max(1.0, (double) rand()) / (double) RAND_MAX; /* Calculate cumulative propensities in one step*/ int retVal = calculateCumProps(cumProps, xCurr, parameters); //retVal = -1; if (retVal == -1) { #ifdef LOGGING if(level < OFF) { openOutputStream(panic_file_name, panic_fstream); writeLastNSteps(FILE_OUTPUT,panic_fstream, historyCounts, *maxHistory,level, logging_flag_of_var, logRandOne, logRandTwo, logTCurr,logTNext, logCurrentStates, logPropensities, logChosenPropensity, logChosenReactionIndex); } #endif mexErrMsgIdAndTxt("SSA:InvalidPropensity", "Propensity can not be negative"); } /* Sample reaction time*/ double temp = cumProps[SSA_NumReactions - 1] * log(1 / rand1); if (temp <= 0) { #ifdef LOGGING if(level < OFF) { openOutputStream(panic_file_name, panic_fstream); writeLastNSteps(FILE_OUTPUT,panic_fstream, historyCounts, *maxHistory,level, logging_flag_of_var, logRandOne, logRandTwo, logTCurr,logTNext, logCurrentStates, logPropensities, logChosenPropensity, logChosenReactionIndex); } #endif mexErrMsgIdAndTxt("SSA:InvalidTcurr", "Value of tCurr can not be negative"); } tCurr = tCurr + 1 / temp; /* If time > time out, write next datapoint to output*/ while (tCurr >= tNext && iTime < numTimepts) { // this will save the repeated calculation int cIndex = iTime * SSA_NumStates; for (int i = 0; i < SSA_NumStates; i++) { timecourse[cIndex + i] = xCurr[i]; // mexPrintf(" %d",xCurr[i]); } //mexPrintf("\n"); iTime++; tNext = timepoints[iTime]; } /* Sample reaction index*/ double chosenProp = rand2 * cumProps[SSA_NumReactions - 1]; reactionIndex = 1; for (int i = 1; cumProps[i - 1] <= chosenProp; i++) reactionIndex = i + 1; //std::cout<<"updating logs...\n"<<std::endl; globalCounter = globalCounter + 1; #ifdef LOGGING /* this call store the parameters of simulation which can used to print * at later stage in case of any error */ historyCounts = historyCounts + 1; if (historyCounts > *maxHistory) { historyCounts = 0; } if(level < OFF) { //std::cout<<"updating logs...\n"<<std::endl; update_logRotation(historyCounts,level, logging_flag_of_var, logRandOne, logRandTwo, logTCurr,logTNext, logCurrentStates, logPropensities, logChosenPropensity, logChosenReactionIndex, rand1, rand2, tCurr, tNext, xCurr, cumProps, chosenProp ,reactionIndex); } //std::cout<<"global count: "<<globalCounter<<"\n"; if (globalCounter % *period == 0) { //mexPrintf("printing logs.."); writeOneStep(FILE_OUTPUT,periodic_fstream,globalCounter, level, logging_flag_of_var, rand1, rand2, tCurr,tNext, xCurr,cumProps, chosenProp, reactionIndex); } #endif } #ifdef LOGGING panic_fstream.close(); periodic_fstream.close(); #endif /*free the allocated memory */ if (assignedDefault[PANIC_FILE_INDEX] == true) { mxFree((void*) panicFileName); } if (assignedDefault[PERIODIC_FILE_INDEX] == true) { mxFree((void*) periodicFileName); } if (assignedDefault[MAX_HISTORY_INDEX] == true) { mxFree((void*) maxHistory); } if (assignedDefault[PERIOD_INDEX] == true) { mxFree((void *) period); } }
/** * Main optimization loop. * Note: this version of code does NOT have special version for sequential * version. Sequential version is slightly lighter than parallel version because * it can use a more efficient operation to maintain the active set. In practice, this * has little effect. Also, it does not need to have a atomic array for maintaining Ax. * For the experiments in the paper, a special sequential code was used for fairness. */ void compute_logreg(shotgun_data * prob, double lambda, double term_threshold, int max_iter, int verbose, bool & all_zero) { all_zero = false; logregprob = prob; //double l1x, loglikelihood; int iterations = 0;//, t=0; long long int num_of_shoots = 0; std::vector<int> shuffled_indices; for(int j=0; j<logregprob->nx; j++) shuffled_indices.push_back(j); Gmax_old = 1e30; // Adjust threshold similarly as liblinear initialize_all(); term_threshold = term_threshold*std::min(pos_y,neg_y)/double(logregprob->ny); while(true) { int active_size = logregprob->nx; num_of_shoots += active_size; // Randomization if (shuffle) for(int j=0; j<active_size; j++) { int i = j+rand()%(active_size-j); swap(shuffled_indices[i], shuffled_indices[j]); } /* Main parallel loop */ #pragma omp parallel for for(int s=0; s<active_size; s++) { int x_i = shuffled_indices[s]; shoot_logreg(x_i, lambda); } /* Gmax handling */ Gmax_old = logregprob->Gmax[0]; if (iterations == 0) { Gmax_init = Gmax_old; } iterations++; //std::cout << Gmax.get_value() << " " << Gmax_init << " " << term_threshold*Gmax_init << std::endl; if (iterations > max_iter && max_iter>0) { mexPrintf("Exceeded max iterations: %d\n", max_iter); break; } for(int i=0; i<logregprob->nx; i++) shuffled_indices[i] = i; active_size = logregprob->nx; for(int s=0; s<active_size; s++) { int j = shuffled_indices[s]; if (!active[j]) { active_size--; swap(shuffled_indices[s], shuffled_indices[active_size]); s--; } } if (logregprob->Gmax[0] <= term_threshold*Gmax_init) { // std::cout << active_size << std::endl; if (active_size == logregprob->nx) { printf("Encountered all zero solution! try to decrease lambda\n"); all_zero = true; break; } else { Gmax_old = 1e30; for(int i=0; i<logregprob->nx; i++) active[i] = true; active_size=logregprob->nx; recompute_expAx(); //continue; } } if (verbose){ double l1x=0, loglikelihood=0; int l0=0; double obj = compute_objective_logreg(lambda, &l1x, &loglikelihood, &l0, NULL); printf("objective is: %g l1: %g loglikelihood %g l0: %d\n", obj, l1x, loglikelihood, l0); if (l1x == 0) all_zero = true; } }// end iterations if (!verbose){ double l1x=0, loglikelihood=0; int l0=0; double obj = compute_objective_logreg(lambda, &l1x, &loglikelihood, &l0, NULL); if (l1x == 0) all_zero = true; printf("objective is: %g l1: %g loglikelihood %g l0: %d\n", obj, l1x, loglikelihood, l0); } delete[] active; delete[] xjneg; mexPrintf("Finished Shotgun CDN in %d iterations\n", iterations); }
/* read in a problem (in svmlight format) */ int read_problem_dense(const mxArray *label_vec, const mxArray *instance_mat) { int i, j, k; int elements, max_index, sc, label_vector_row_num; double *samples, *labels; prob.x = NULL; prob.y = NULL; x_space = NULL; labels = mxGetPr(label_vec); samples = mxGetPr(instance_mat); sc = (int)mxGetN(instance_mat); elements = 0; /* the number of instance */ prob.l = (int)mxGetM(instance_mat); label_vector_row_num = (int)mxGetM(label_vec); if(label_vector_row_num!=prob.l) { mexPrintf("Length of label vector does not match # of instances.\n"); return -1; } if(param.kernel_type == PRECOMPUTED) elements = prob.l * (sc + 1); else { for(i = 0; i < prob.l; i++) { for(k = 0; k < sc; k++) if(samples[k * prob.l + i] != 0) elements++; /* count the '-1' element */ elements++; } } prob.y = Malloc(double,prob.l); prob.x = Malloc(struct svm_node *,prob.l); x_space = Malloc(struct svm_node, elements); max_index = sc; j = 0; for(i = 0; i < prob.l; i++) { prob.x[i] = &x_space[j]; prob.y[i] = labels[i]; for(k = 0; k < sc; k++) { if(param.kernel_type == PRECOMPUTED || samples[k * prob.l + i] != 0) { x_space[j].index = k + 1; x_space[j].value = samples[k * prob.l + i]; j++; } } x_space[j++].index = -1; } if(param.gamma == 0 && max_index > 0) param.gamma = 1.0/max_index; if(param.kernel_type == PRECOMPUTED) for(i=0;i<prob.l;i++) { if((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index) { mexPrintf("Wrong input format: sample_serial_number out of range\n"); return -1; } } return 0; }
/* The gateway routine */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ----------------- Variables ----------------- */ /* input variables */ /* mandatory input */ int startIdx; int endIdx; double * inReal; /* optional input */ int optInFastPeriod; double optInFastMA; int optInSlowPeriod; double optInSlowMA; int optInSignalPeriod; double optInSignalMA; /* output variables */ int outBegIdx; int outNbElement; double* outMACD; double* outMACDSignal; double* outMACDHist; /* input dimentions */ int inSeriesRows; int inSeriesCols; /* error handling */ TA_RetCode retCode; /* ----------------- input/output count ----------------- */ /* Check for proper number of arguments. */ if (nrhs < 1 || nrhs > 7) mexErrMsgTxt("#7 inputs possible #6 optional."); if (nlhs != 3) mexErrMsgTxt("#3 output required."); /* ----------------- INPUT ----------------- */ /* Create a pointer to the input matrix inReal. */ inReal = mxGetPr(prhs[0]); /* Get the dimensions of the matrix input inReal. */ inSeriesCols = mxGetN(prhs[0]); if (inSeriesCols != 1) mexErrMsgTxt("inReal only vector alowed."); inSeriesRows = mxGetM(prhs[0]); endIdx = inSeriesRows - 1; startIdx = 0; /* Process optional arguments */ if (nrhs >= 1+1) { if (!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || mxGetN(prhs[1])*mxGetM(prhs[1]) != 1) mexErrMsgTxt("Input optInFastPeriod must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInFastPeriod = (int) mxGetScalar(prhs[1]); } else { optInFastPeriod = 12; } if (nrhs >= 2+1) { if (!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || mxGetN(prhs[2])*mxGetM(prhs[2]) != 1) mexErrMsgTxt("Input optInFastMA must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInFastMA = mxGetScalar(prhs[2]); } else { optInFastMA = 0; } if (nrhs >= 3+1) { if (!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || mxGetN(prhs[3])*mxGetM(prhs[3]) != 1) mexErrMsgTxt("Input optInSlowPeriod must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInSlowPeriod = (int) mxGetScalar(prhs[3]); } else { optInSlowPeriod = 26; } if (nrhs >= 4+1) { if (!mxIsDouble(prhs[4]) || mxIsComplex(prhs[4]) || mxGetN(prhs[4])*mxGetM(prhs[4]) != 1) mexErrMsgTxt("Input optInSlowMA must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInSlowMA = mxGetScalar(prhs[4]); } else { optInSlowMA = 0; } if (nrhs >= 5+1) { if (!mxIsDouble(prhs[5]) || mxIsComplex(prhs[5]) || mxGetN(prhs[5])*mxGetM(prhs[5]) != 1) mexErrMsgTxt("Input optInSignalPeriod must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInSignalPeriod = (int) mxGetScalar(prhs[5]); } else { optInSignalPeriod = 9; } if (nrhs >= 6+1) { if (!mxIsDouble(prhs[6]) || mxIsComplex(prhs[6]) || mxGetN(prhs[6])*mxGetM(prhs[6]) != 1) mexErrMsgTxt("Input optInSignalMA must be a scalar."); /* Get the scalar input optInTimePeriod. */ optInSignalMA = mxGetScalar(prhs[6]); } else { optInSignalMA = 0; } /* ----------------- OUTPUT ----------------- */ outMACD = mxCalloc(inSeriesRows, sizeof(double)); outMACDSignal = mxCalloc(inSeriesRows, sizeof(double)); outMACDHist = mxCalloc(inSeriesRows, sizeof(double)); /* -------------- Invocation ---------------- */ retCode = TA_MACDEXT( startIdx, endIdx, inReal, optInFastPeriod, optInFastMA, optInSlowPeriod, optInSlowMA, optInSignalPeriod, optInSignalMA, &outBegIdx, &outNbElement, outMACD, outMACDSignal, outMACDHist); /* -------------- Errors ---------------- */ if (retCode) { mxFree(outMACD); mxFree(outMACDSignal); mxFree(outMACDHist); mexPrintf("%s%i","Return code=",retCode); mexErrMsgTxt(" Error!"); } // Populate Output plhs[0] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL); memcpy(((double *) mxGetData(plhs[0]))+outBegIdx, outMACD, outNbElement*mxGetElementSize(plhs[0])); mxFree(outMACD); plhs[1] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL); memcpy(((double *) mxGetData(plhs[1]))+outBegIdx, outMACDSignal, outNbElement*mxGetElementSize(plhs[1])); mxFree(outMACDSignal); plhs[2] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL); memcpy(((double *) mxGetData(plhs[2]))+outBegIdx, outMACDHist, outNbElement*mxGetElementSize(plhs[2])); mxFree(outMACDHist); } /* END mexFunction */
void printUsage() { mexPrintf("XonOmegaTranspose.c: usage is\n\t b = XonOmegaTranspose(U.',V.',omega)\n"); mexPrintf(" or b = XonOmegaTranspose(U.',V.',omega,cutoff)\n"); mexPrintf("where A = U*V' and b = A(omega)\n"); mexPrintf("\nAlternative usage is\n\t b = XonOmegaTranspose(U.',V.',omegaI,omegaJ),\n where [omegaI,omegaJ] = ind2sub(...,omega)\n"); mexPrintf("\nor b = XonOmegaTranspose(U',V',omegaI,omegaJ,cutoff)\n"); mexPrintf("\nAnother alternative usage is\n\t b = XonOmegaTranspose(U.',V.',OMEGA),\n where OMEGA is a sparse matrix with nonzeros on omega.\nThis will agree with the other forms of the command if omega is sorted\n"); mexPrintf("Can also call this as b = XonOmegaTranspose(U.',V.',OMEGA, cutoff)\n\n"); mexPrintf("'cutoff' affects how the computation is done\n"); mexPrintf("if length(omega) > cutoff*numel(A), then the entire A matrix is first formed\n"); mexPrintf("otherwise, A is never formed explicitly\n"); mexPrintf("If U and V are complex, then make sure A=U*V' and not A=U*V.'\n"); mexPrintf("If U and V are complex, make sure to pass in the variables U.' and V.',not U' and V''\n\n"); }
void printprofinfo(profdata *pd, int erroromp, int batchomp, int signum) { clock_t tottime; tottime = pd->DtX_time + pd->XtX_time + pd->DtR_time + pd->DtD_time + pd->compres_time + pd->maxabs_time + pd->Lchol_time + pd->compcoef_time + pd->update_DtR_time + pd->update_resnorm_time + pd->indexsort_time; mexPrintf("\n\n***** Profiling information for %s *****\n\n", erroromp? "OMP2" : "OMP"); mexPrintf("OMP mode: %s\n\n", batchomp? "Batch-OMP" : "OMP-Cholesky"); mexPrintf("Total signals processed: %d\n\n", signum); if (pd->DtX_time_counted) { mexPrintf("Compute DtX time: %7.3lf seconds\n", pd->DtX_time/(float)CLOCKS_PER_SEC); } if (pd->XtX_time_counted) { mexPrintf("Compute XtX time: %7.3lf seconds\n", pd->XtX_time/(float)CLOCKS_PER_SEC); } mexPrintf("Max abs time: %7.3lf seconds\n", pd->maxabs_time/(float)CLOCKS_PER_SEC); if (pd->DtD_time_counted) { mexPrintf("Compute DtD time: %7.3lf seconds\n", pd->DtD_time/(float)CLOCKS_PER_SEC); } mexPrintf("Lchol update time: %7.3lf seconds\n", pd->Lchol_time/(float)CLOCKS_PER_SEC); mexPrintf("Compute coef time: %7.3lf seconds\n", pd->compcoef_time/(float)CLOCKS_PER_SEC); if (pd->compres_time_counted) { mexPrintf("Compute R time: %7.3lf seconds\n", pd->compres_time/(float)CLOCKS_PER_SEC); } if (pd->DtR_time_counted) { mexPrintf("Compute DtR time: %7.3lf seconds\n", pd->DtR_time/(float)CLOCKS_PER_SEC); } if (pd->update_DtR_time_counted) { mexPrintf("Update DtR time: %7.3lf seconds\n", pd->update_DtR_time/(float)CLOCKS_PER_SEC); } if (pd->resnorm_time_counted) { mexPrintf("Update resnorm time: %7.3lf seconds\n", pd->update_resnorm_time/(float)CLOCKS_PER_SEC); } if (pd->indexsort_time_counted) { mexPrintf("Index sort time: %7.3lf seconds\n", pd->indexsort_time/(float)CLOCKS_PER_SEC); } mexPrintf("---------------------------------------\n"); mexPrintf("Total time: %7.3lf seconds\n\n", tottime/(float)CLOCKS_PER_SEC); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *px, cf, binwidth, reptime, cohc, cihc; int nrep, pxbins, lp, outsize[2], totalstim; double *pxtmp, *cftmp, *nreptmp, *binwidthtmp, *reptimetmp, *cohctmp, *cihctmp; double *ihcout; void SingleAN(double *, double, int, double, int, double, double, double *); /* Check for proper number of arguments */ if (nrhs != 7) { mexErrMsgTxt("catmodel_IHC requires 7 input arguments."); }; if (nlhs !=1) { mexErrMsgTxt("catmodel_IHC requires 1 output argument."); }; /* Assign pointers to the inputs */ pxtmp = mxGetPr(prhs[0]); cftmp = mxGetPr(prhs[1]); nreptmp = mxGetPr(prhs[2]); binwidthtmp = mxGetPr(prhs[3]); reptimetmp = mxGetPr(prhs[4]); cohctmp = mxGetPr(prhs[5]); cihctmp = mxGetPr(prhs[6]); /* Check with individual input arguments */ pxbins = mxGetN(prhs[0]); if (pxbins==1) mexErrMsgTxt("px must be a row vector\n"); cf = cftmp[0]; if ((cf<80)|(cf>40e3)) { mexPrintf("cf (= %1.1f Hz) must be between 80 Hz and 40 kHz\n",cf); mexErrMsgTxt("\n"); } nrep = (int)nreptmp[0]; if (nreptmp[0]!=nrep) mexErrMsgTxt("nrep must an integer.\n"); if (nrep<1) mexErrMsgTxt("nrep must be greater that 0.\n"); binwidth = binwidthtmp[0]; reptime = reptimetmp[0]; if (reptime<pxbins*binwidth) /* duration of stimulus = pxbins*binwidth */ mexErrMsgTxt("reptime should be equal to or longer than the stimulus duration.\n"); cohc = cohctmp[0]; /* impairment in the OHC */ if ((cohc<0)|(cohc>1)) { mexPrintf("cohc (= %1.1f) must be between 0 and 1\n",cohc); mexErrMsgTxt("\n"); } cihc = cihctmp[0]; /* impairment in the IHC */ if ((cihc<0)|(cihc>1)) { mexPrintf("cihc (= %1.1f) must be between 0 and 1\n",cihc); mexErrMsgTxt("\n"); } /* Calculate number of samples for total repetition time */ totalstim = (int)floor((reptime*1e3)/(binwidth*1e3)); outsize[0] = 1; outsize[1] = totalstim; px = (double*)mxCalloc(outsize[1],sizeof(double)); /* Put stimulus waveform into pressure waveform */ for (lp=0; lp<pxbins; lp++) px[lp] = pxtmp[lp]; /* Create an array for the return argument */ plhs[0] = mxCreateNumericArray(2, outsize, mxDOUBLE_CLASS, mxREAL); /* Assign pointers to the outputs */ ihcout = mxGetPr(plhs[0]); /* run the model */ SingleAN(px,cf,nrep,binwidth,totalstim,cohc,cihc,ihcout); mxFree(px); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ************** Inputs *******************/ double *v; // Vertices unsigned int *f; // Faces double factor1,factor2; // Parameters: Reduction Factor int interact; // whether or not to interact /* ************** Outputs *******************/ // Field data for output structure mxArray *out_verts, *out_faces; double *out_vertsptr, *out_facesptr; // field names for output structure const char *field_names[] = {"vertices", "faces"}; /* ************** Others ******************* */ unsigned int nV, nF, i, j; unsigned int n0,numscalars,numverts,numfaces,count,facecount,nidx; double pt[3]; int dims[2] = {1, 1},vert_field,face_field; // Initialize vtk variables vtkPolyData *surf = vtkPolyData::New(); vtkPoints *sverts = vtkPoints::New(); vtkCellArray *sfaces = vtkCellArray::New(); vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New(); //vtkDecimate *decimate = vtkDecimate::New(); vtkDecimatePro *decimate = vtkDecimatePro::New(); vtkPolyDataConnectivityFilter *connector = vtkPolyDataConnectivityFilter::New(); vtkPoints *pts; vtkCellArray *polys; vtkIdTypeArray *faces; /* Inputs */ v = mxGetPr(prhs[0]); f = (unsigned int*)mxGetPr(prhs[1]); factor1 = *mxGetPr(prhs[2]); factor2 = *mxGetPr(prhs[3]); nV = mxGetM(prhs[0]); nF = mxGetM(prhs[1]); if (nrhs==5) interact = (int)(*mxGetPr(prhs[4])); else interact = 0; // Load the point, cell, and data attributes. for (i=0; i<nV; i++) sverts->InsertPoint(i,v[i],v[nV+i],v[2*nV+i]); for (i=0; i<nF; i++) { sfaces->InsertNextCell(3); for(j=0;j<3;j++) sfaces->InsertCellPoint((vtkIdType(f[j*nF+i]-1))); } // We now assign the pieces to the vtkPolyData. surf->SetPoints(sverts); sverts->Delete(); surf->SetPolys(sfaces); sfaces->Delete(); // decimate the mesh //decimate->SetInput(skinExtractor->GetOutput()); decimate->SetInput(surf); decimate->SetPreserveTopology(int(factor2)); decimate->SetTargetReduction(factor1); //decimate->SetMaximumCost(factor1); //decimate->SetMaximumCollapsedEdges(int(factor2)); //decimate->SetInitialFeatureAngle(45); //decimate->SetMaximumIterations(20); //decimate->SetMaximumSubIterations(2); //decimate->PreserveEdgesOn(); //decimate->SetInitialError(.0002); //decimate->SetErrorIncrement(.0005); // smooth the mesh smoother->SetInput(decimate->GetOutput()); smoother->SetNumberOfIterations(10); smoother->SetRelaxationFactor(0.1); smoother->SetFeatureAngle(60); smoother->FeatureEdgeSmoothingOff(); smoother->BoundarySmoothingOff(); smoother->SetConvergence(0); //extract largest connected region to get a manifold surface connector->SetInput(smoother->GetOutput()); connector->SetExtractionModeToLargestRegion(); connector->Update(); // Get hold of vertices and faces // Vertices pts = connector->GetOutput()->GetPoints(); //pts = surf->GetPoints(); numverts = pts->GetNumberOfPoints(); out_verts = mxCreateDoubleMatrix(numverts,3,mxREAL); out_vertsptr = mxGetPr(out_verts); for(n0=0;n0<numverts;n0++) { pts->GetPoint(n0,pt); out_vertsptr[n0] = pt[0]; out_vertsptr[numverts+n0] = pt[1]; out_vertsptr[2*numverts+n0] = pt[2]; } // Faces polys = connector->GetOutput()->GetPolys(); //polys = surf->GetPolys(); faces = (vtkIdTypeArray*)polys->GetData(); numfaces = polys->GetNumberOfCells(); out_faces = mxCreateDoubleMatrix(numfaces,3,mxREAL); out_facesptr = mxGetPr(out_faces); count = 0; facecount = 0; nidx = 0; while(facecount<numfaces) { nidx = faces->GetValue(count++); for(n0=0;n0<nidx;n0++) if (n0<3) // Add one to the output as faces are indexed by 0..(n-1) out_facesptr[n0*numfaces+facecount] = faces->GetValue(count++)+1; else // Print warning if face contains more than 3 vertices (non-triangular) mexPrintf("Warning: Face[%d] has more than 3 vertices[%d].\n",facecount+1,count++); facecount++; } // Create the output structure plhs[0] = mxCreateStructArray(2, dims, NUMBER_OF_FIELDS, field_names); vert_field = mxGetFieldNumber(plhs[0],"vertices"); face_field = mxGetFieldNumber(plhs[0],"faces"); mxSetFieldByNumber(plhs[0],0,vert_field,out_verts); mxSetFieldByNumber(plhs[0],0,face_field,out_faces); // Clean up. Delete all vtk objects surf->Delete(); decimate->Delete(); smoother->Delete(); connector->Delete(); }
/* The gateway routine */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ----------------- Variables ----------------- */ /* input variables */ /* mandatory input */ int startIdx; int endIdx; double * open; double * high; double * low; double * close; /* optional input */ /* output variables */ int outBegIdx; int outNbElement; int* outInteger; /* input dimentions */ int inSeriesRows; int inSeriesCols; /* error handling */ TA_RetCode retCode; /* ----------------- input/output count ----------------- */ /* Check for proper number of arguments. */ if (nrhs < 4 || nrhs > 4) mexErrMsgTxt("#4 inputs possible #0 optional."); if (nlhs != 1) mexErrMsgTxt("#1 output required."); /* ----------------- INPUT ----------------- */ /* Create a pointer to the input matrix open. */ open = mxGetPr(prhs[0]); /* Get the dimensions of the matrix input open. */ inSeriesCols = mxGetN(prhs[0]); if (inSeriesCols != 1) mexErrMsgTxt("open only vector alowed."); /* Create a pointer to the input matrix high. */ high = mxGetPr(prhs[1]); /* Get the dimensions of the matrix input high. */ inSeriesCols = mxGetN(prhs[1]); if (inSeriesCols != 1) mexErrMsgTxt("high only vector alowed."); /* Create a pointer to the input matrix low. */ low = mxGetPr(prhs[2]); /* Get the dimensions of the matrix input low. */ inSeriesCols = mxGetN(prhs[2]); if (inSeriesCols != 1) mexErrMsgTxt("low only vector alowed."); /* Create a pointer to the input matrix close. */ close = mxGetPr(prhs[3]); /* Get the dimensions of the matrix input close. */ inSeriesCols = mxGetN(prhs[3]); if (inSeriesCols != 1) mexErrMsgTxt("close only vector alowed."); inSeriesRows = mxGetM(prhs[3]); endIdx = inSeriesRows - 1; startIdx = 0; /* Process optional arguments */ /* ----------------- OUTPUT ----------------- */ outInteger = mxCalloc(inSeriesRows, sizeof(int)); /* -------------- Invocation ---------------- */ retCode = TA_CDLLONGLINE( startIdx, endIdx, open, high, low, close, &outBegIdx, &outNbElement, outInteger); /* -------------- Errors ---------------- */ if (retCode) { mxFree(outInteger); mexPrintf("%s%i","Return code=",retCode); mexErrMsgTxt(" Error!"); } // Populate Output plhs[0] = mxCreateNumericMatrix(outBegIdx+outNbElement,1, mxINT32_CLASS, mxREAL); memcpy(((int *) mxGetData(plhs[0]))+outBegIdx, outInteger, outNbElement*mxGetElementSize(plhs[0])); mxFree(outInteger); } /* END mexFunction */
void exit_with_help(){ mexPrintf( "Number of Input/Output Argument is Wrong\n" ); }
// nrhs should be 3 int parse_command_line(int nrhs, const mxArray *prhs[], char *model_file_name) { int i, argc = 1; char cmd[CMD_LEN]; char *argv[CMD_LEN/2]; void (*print_func)(const char *) = print_string_matlab; // default printing to matlab display // default values param.solver_type = L2R_L2LOSS_SVC_DUAL; param.C = 1; param.eps = INF; // see setting below param.p = 0.1; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; cross_validation_flag = 0; col_format_flag = 0; bias = -1; if(nrhs <= 1) return 1; if(nrhs == 4) { mxGetString(prhs[3], cmd, mxGetN(prhs[3])+1); if(strcmp(cmd, "col") == 0) col_format_flag = 1; } // put options in argv[] if(nrhs > 2) { mxGetString(prhs[2], cmd, mxGetN(prhs[2]) + 1); if((argv[argc] = strtok(cmd, " ")) != NULL) while((argv[++argc] = strtok(NULL, " ")) != NULL) ; } // parse options for(i=1;i<argc;i++) { if(argv[i][0] != '-') break; ++i; if(i>=argc && argv[i-1][1] != 'q') // since option -q has no parameter return 1; switch(argv[i-1][1]) { case 's': param.solver_type = atoi(argv[i]); break; case 'c': param.C = atof(argv[i]); break; case 'p': param.p = atof(argv[i]); break; case 'e': param.eps = atof(argv[i]); break; case 'B': bias = atof(argv[i]); break; case 'v': cross_validation_flag = 1; nr_fold = atoi(argv[i]); if(nr_fold < 2) { mexPrintf("n-fold cross validation: n must >= 2\n"); return 1; } break; case 'w': ++param.nr_weight; param.weight_label = (int *) realloc(param.weight_label,sizeof(int)*param.nr_weight); param.weight = (double *) realloc(param.weight,sizeof(double)*param.nr_weight); param.weight_label[param.nr_weight-1] = atoi(&argv[i-1][2]); param.weight[param.nr_weight-1] = atof(argv[i]); break; case 'q': print_func = &print_null; i--; break; default: mexPrintf("unknown option\n"); return 1; } } set_print_string_function(print_func); if(param.eps == INF) { switch(param.solver_type) { case L2R_LR: case L2R_L2LOSS_SVC: param.eps = 0.01; break; case L2R_L2LOSS_SVR: param.eps = 0.001; break; case L2R_L2LOSS_SVC_DUAL: case L2R_L1LOSS_SVC_DUAL: case MCSVM_CS: case L2R_LR_DUAL: param.eps = 0.1; break; case L1R_L2LOSS_SVC: case L1R_LR: param.eps = 0.01; break; case L2R_L1LOSS_SVR_DUAL: case L2R_L2LOSS_SVR_DUAL: param.eps = 0.1; break; } } return 0; }
/* the gateway function */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { srslte_cell_t cell; srslte_refsignal_ul_t refs; srslte_refsignal_dmrs_pusch_cfg_t pusch_cfg; uint32_t sf_idx; if (nrhs != NOF_INPUTS) { help(); return; } if (mexutils_read_uint32_struct(UECFG, "NCellID", &cell.id)) { mexErrMsgTxt("Field NCellID not found in UE config\n"); return; } if (mexutils_read_uint32_struct(UECFG, "NULRB", &cell.nof_prb)) { mexErrMsgTxt("Field NCellID not found in UE config\n"); return; } cell.cp = SRSLTE_CP_NORM; cell.nof_ports = 1; if (mexutils_read_uint32_struct(UECFG, "NSubframe", &sf_idx)) { mexErrMsgTxt("Field NSubframe not found in UE config\n"); return; } bzero(&pusch_cfg, sizeof(srslte_refsignal_dmrs_pusch_cfg_t)); pusch_cfg.group_hopping_en = false; pusch_cfg.sequence_hopping_en = false; char *tmp = mexutils_get_char_struct(UECFG, "Hopping"); if (tmp) { if (!strcmp(tmp, "Group")) { pusch_cfg.group_hopping_en = true; } else if (!strcmp(tmp, "Sequence")) { pusch_cfg.sequence_hopping_en = true; } mxFree(tmp); } if (mexutils_read_uint32_struct(UECFG, "SeqGroup", &pusch_cfg.delta_ss)) { pusch_cfg.delta_ss = 0; } if (mexutils_read_uint32_struct(UECFG, "CyclicShift", &pusch_cfg.cyclic_shift)) { pusch_cfg.cyclic_shift = 0; } float *prbset; mxArray *p; p = mxGetField(PUSCHCFG, 0, "PRBSet"); if (!p) { mexErrMsgTxt("Error field PRBSet not found in PUSCH config\n"); return; } uint32_t nof_prb = mexutils_read_f(p, &prbset); uint32_t cyclic_shift_for_dmrs = 0; if (mexutils_read_uint32_struct(PUSCHCFG, "DynCyclicShift", &cyclic_shift_for_dmrs)) { cyclic_shift_for_dmrs = 0; } if (srslte_refsignal_ul_init(&refs, cell)) { mexErrMsgTxt("Error initiating srslte_refsignal_ul\n"); return; } mexPrintf("nof_prb: %d, ",nof_prb); mexPrintf("cyclic_shift: %d, ",pusch_cfg.cyclic_shift); mexPrintf("cyclic_shift_for_dmrs: %d, ", cyclic_shift_for_dmrs); mexPrintf("delta_ss: %d, ",pusch_cfg.delta_ss); cf_t *signal = srslte_vec_malloc(2*SRSLTE_NRE*nof_prb*sizeof(cf_t)); if (!signal) { perror("malloc"); return; } cf_t *sf_symbols = srslte_vec_malloc(SRSLTE_SF_LEN_RE(cell.nof_prb, cell.cp)*sizeof(cf_t)); if (!sf_symbols) { perror("malloc"); return; } bzero(sf_symbols, SRSLTE_SF_LEN_RE(cell.nof_prb, cell.cp)*sizeof(cf_t)); srslte_refsignal_ul_set_cfg(&refs, &pusch_cfg, NULL, NULL); //mexPrintf("Generating DRMS for ns=%d, nof_prb=%d\n", 2*sf_idx+i,pusch_cfg.nof_prb); srslte_refsignal_dmrs_pusch_gen(&refs, nof_prb, sf_idx, cyclic_shift_for_dmrs, signal); uint32_t n_prb[2]; n_prb[0] = prbset[0]; n_prb[1] = prbset[0]; srslte_refsignal_dmrs_pusch_put(&refs, signal, nof_prb, n_prb, sf_symbols); if (nlhs >= 1) { mexutils_write_cf(sf_symbols, &plhs[0], SRSLTE_SF_LEN_RE(cell.nof_prb, cell.cp), 1); } srslte_refsignal_ul_free(&refs); free(signal); free(prbset); return; }
// Interface function of matlab // now assume prhs[0]: label prhs[1]: features void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { const char *error_msg; // fix random seed to have same results for each run // (for cross validation) srand(1); if(nlhs > 1) { exit_with_help(); fake_answer(nlhs, plhs); return; } // Transform the input Matrix to libsvm format if(nrhs > 1 && nrhs < 5) { int err=0; if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) { mexPrintf("Error: label vector and instance matrix must be double\n"); fake_answer(nlhs, plhs); return; } if(parse_command_line(nrhs, prhs, NULL)) { exit_with_help(); destroy_param(¶m); fake_answer(nlhs, plhs); return; } if(mxIsSparse(prhs[1])) err = read_problem_sparse(prhs[0], prhs[1]); else { mexPrintf("Training_instance_matrix must be sparse; " "use sparse(Training_instance_matrix) first\n"); destroy_param(¶m); fake_answer(nlhs, plhs); return; } // train's original code error_msg = check_parameter(&prob, ¶m); if(err || error_msg) { if (error_msg != NULL) mexPrintf("Error: %s\n", error_msg); destroy_param(¶m); free(prob.y); free(prob.x); free(x_space); fake_answer(nlhs, plhs); return; } if(cross_validation_flag) { double *ptr; plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); ptr = mxGetPr(plhs[0]); ptr[0] = do_cross_validation(); } else { const char *error_msg; model_ = train(&prob, ¶m); error_msg = model_to_matlab_structure(plhs, model_); if(error_msg) mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg); free_and_destroy_model(&model_); } destroy_param(¶m); free(prob.y); free(prob.x); free(x_space); } else { exit_with_help(); fake_answer(nlhs, plhs); return; } }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { Zmat A; ZAMGlevelmat *PRE; ZILUPACKparam *param; integer n; const char **fnames; const mwSize *dims; mxClassID *classIDflags; mxArray *tmp, *fout, *A_input , *b_input, *x0_input, *options_input, *PRE_input, *options_output, *x_output; char *pdata, *input_buf, *output_buf; mwSize mrows, ncols, buflen, nnz, ndim; int ifield, status, nfields, ierr,i,j,k,l,m; size_t sizebuf; double dbuf, *A_valuesR, *A_valuesI, *convert, *sr, *pr, *pi; doublecomplex *sol, *rhs; mwIndex *irs, *jcs, *A_ja, /* row indices of input matrix A */ *A_ia; /* column pointers of input matrix A */ if (nrhs != 5) mexErrMsgTxt("five input arguments required."); else if (nlhs !=2) mexErrMsgTxt("Too many output arguments."); else if (!mxIsStruct(prhs[2])) mexErrMsgTxt("Third input must be a structure."); else if (!mxIsNumeric(prhs[0])) mexErrMsgTxt("First input must be a matrix."); /* The first input must be a square matrix.*/ A_input = (mxArray *) prhs [0] ; /* get size of input matrix A */ mrows = mxGetM (A_input) ; ncols = mxGetN (A_input) ; nnz = mxGetNzmax(A_input); if (mrows!=ncols) { mexErrMsgTxt("First input must be a square matrix."); } if (!mxIsSparse (A_input)) { mexErrMsgTxt ("ILUPACK: input matrix must be in sparse format.") ; } /* copy input matrix to sparse row format */ A.nc=A.nr=mrows; A.ia=(integer *) MAlloc((size_t)(A.nc+1)*sizeof(integer),"ZHERHPDilupacksolver"); A.ja=(integer *) MAlloc((size_t)nnz *sizeof(integer),"ZHERHPDilupacksolver"); A. a=(doublecomplex *) MAlloc((size_t)nnz *sizeof(doublecomplex), "ZHERHPDilupacksolver"); A_ja = (mwIndex *) mxGetIr (A_input) ; A_ia = (mwIndex *) mxGetJc (A_input) ; A_valuesR = (double *) mxGetPr(A_input); if (mxIsComplex(A_input)) A_valuesI = (double *) mxGetPi(A_input); /* -------------------------------------------------------------------- */ /* .. Convert matrix from 0-based C-notation to Fortran 1-based */ /* notation. */ /* -------------------------------------------------------------------- */ /* for (i = 0 ; i < ncols ; i++) for (j = A_ia[i] ; j < A_ia[i+1] ; j++) printf("i=%d j=%d A.real=%e\n", i+1, A_ja[j]+1, A_valuesR[j]); */ A.ia[0]=1; if (mxIsComplex(A_input)) { for (i = 0 ; i < ncols ; i++) { A.ia[i+1]=A.ia[i]; for (j = A_ia[i] ; j < A_ia[i+1] ; j++) { k=A_ja[j]; if (k>=i) { l=A.ia[i+1]-1; A.ja[l]=k+1; A.a [l].r= A_valuesR[j]; A.a [l].i=-A_valuesI[j]; A.ia[i+1]=l+2; } } } } else { for (i = 0 ; i < ncols ; i++) { A.ia[i+1]=A.ia[i]; for (j = A_ia[i] ; j < A_ia[i+1] ; j++) { k=A_ja[j]; if (k>=i) { l=A.ia[i+1]-1; A.ja[l]=k+1; A.a [l].r=A_valuesR[j]; A.a [l].i=0; A.ia[i+1]=l+2; } } } } /* for (i = 0 ; i < A.nr ; i++) for (j = A.ia[i]-1 ; j < A.ia[i+1]-1 ; j++) printf("i=%d j=%d A.real=%e A.imag=%e\n", i+1, A.ja[j], A.a[j].r, A.a[j].i); */ /* import pointer to the preconditioner */ PRE_input = (mxArray*) prhs [1] ; /* get number of levels of input preconditioner structure `PREC' */ /* nlev=mxGetN(PRE_input);*/ nfields = mxGetNumberOfFields(PRE_input); /* allocate memory for storing pointers */ fnames = mxCalloc(nfields, sizeof(*fnames)); for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(PRE_input,ifield); /* check whether `PREC.ptr' exists */ if (!strcmp("ptr",fnames[ifield])) { /* field `ptr' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(&PRE, pdata, (size_t)sizeof(size_t)); } else if (!strcmp("param",fnames[ifield])) { /* field `param' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(¶m, pdata, (size_t)sizeof(size_t)); } } mxFree(fnames); /* rescale input matrix */ /* obsolete for (i=0; i <A.nr; i++) { for (j=A.ia[i]-1; j<A.ia[i+1]-1; j++) { A.a[j].r*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; A.a[j].i*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; } } */ /* Get third input argument `options' */ options_input=(mxArray*)prhs[2]; nfields = mxGetNumberOfFields(options_input); /* Allocate memory for storing classIDflags */ classIDflags = (mxClassID *) mxCalloc((size_t)nfields+1, (size_t)sizeof(mxClassID)); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields+1, (size_t)sizeof(*fnames)); /* Get field name pointers */ j=-1; for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(options_input,ifield); /* check whether `options.niter' already exists */ if (!strcmp("niter",fnames[ifield])) j=ifield; } if (j==-1) fnames[nfields]="niter"; /* mexPrintf("search for niter completed\n"); fflush(stdout); */ /* import data */ for (ifield = 0; ifield < nfields; ifield++) { /* mexPrintf("%2d\n",ifield+1); fflush(stdout); */ tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = mxCalloc((size_t)buflen, sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); if (!strcmp("amg",fnames[ifield])) { if (strcmp(param->amg,input_buf)) { param->amg=(char *)MAlloc((size_t)buflen*sizeof(char),"ilupacksolver"); strcpy(param->amg,input_buf); } } else if (!strcmp("presmoother",fnames[ifield])) { if (strcmp(param->presmoother,input_buf)) { param->presmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->presmoother,input_buf); } } else if (!strcmp("postsmoother",fnames[ifield])) { if (strcmp(param->postsmoother,input_buf)) { param->postsmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->postsmoother,input_buf); } } else if (!strcmp("typecoarse",fnames[ifield])) { if (strcmp(param->typecoarse,input_buf)) { param->typecoarse=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typecoarse,input_buf); } } else if (!strcmp("typetv",fnames[ifield])) { if (strcmp(param->typetv,input_buf)) { param->typetv=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typetv,input_buf); } } else if (!strcmp("FCpart",fnames[ifield])) { if (strcmp(param->FCpart,input_buf)) { param->FCpart=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->FCpart,input_buf); } } else if (!strcmp("solver",fnames[ifield])) { if (strcmp(param->solver,input_buf)) { param->solver=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->solver,input_buf); } } else if (!strcmp("ordering",fnames[ifield])) { if (strcmp(param->ordering,input_buf)) { param->ordering=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->ordering,input_buf); } } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } else { if (!strcmp("elbow",fnames[ifield])) { param->elbow=*mxGetPr(tmp); } else if (!strcmp("lfilS",fnames[ifield])) { param->lfilS=*mxGetPr(tmp); } else if (!strcmp("lfil",fnames[ifield])) { param->lfil=*mxGetPr(tmp); } else if (!strcmp("maxit",fnames[ifield])) { param->maxit=*mxGetPr(tmp); } else if (!strcmp("droptolS",fnames[ifield])) { param->droptolS=*mxGetPr(tmp); } else if (!strcmp("droptolc",fnames[ifield])) { param->droptolc=*mxGetPr(tmp); } else if (!strcmp("droptol",fnames[ifield])) { param->droptol=*mxGetPr(tmp); } else if (!strcmp("condest",fnames[ifield])) { param->condest=*mxGetPr(tmp); } else if (!strcmp("restol",fnames[ifield])) { param->restol=*mxGetPr(tmp); } else if (!strcmp("npresmoothing",fnames[ifield])) { param->npresmoothing=*mxGetPr(tmp); } else if (!strcmp("npostmoothing",fnames[ifield])) { param->npostsmoothing=*mxGetPr(tmp); } else if (!strcmp("ncoarse",fnames[ifield])) { param->ncoarse=*mxGetPr(tmp); } else if (!strcmp("matching",fnames[ifield])) { param->matching=*mxGetPr(tmp); } else if (!strcmp("nrestart",fnames[ifield])) { param->nrestart=*mxGetPr(tmp); } else if (!strcmp("damping",fnames[ifield])) { param->damping.r=*mxGetPr(tmp); if (mxIsComplex(tmp)) param->damping.i=*mxGetPi(tmp); else param->damping.i=0; } else if (!strcmp("mixedprecision",fnames[ifield])) { param->mixedprecision=*mxGetPr(tmp); } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } } /* copy right hand side `b' */ b_input = (mxArray *) prhs [3] ; /* get size of input matrix A */ rhs=(doublecomplex*) MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZHERHPDilupacksolver:rhs"); pr=mxGetPr(b_input); if (!mxIsComplex(b_input)) { for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=0; } } else { pi=mxGetPi(b_input); for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=pi[i]; } } /* copy initial solution `x0' */ x0_input = (mxArray *) prhs [4] ; /* numerical solution */ sol=(doublecomplex *)MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZHERHPDilupacksolver:sol"); pr=mxGetPr(x0_input); if (!mxIsComplex(x0_input)) { for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=0; } } else { pi=mxGetPi(x0_input); for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=pi[i]; } } ierr=ZHERHPDAMGsolver(&A, PRE, param, rhs, sol); /* Create a struct matrices for output */ nlhs=2; if (j==-1) plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, (mwSize)nfields+1, fnames); else plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, nfields, fnames); if (plhs[1]==NULL) mexErrMsgTxt("Could not create structure mxArray\n"); options_output=plhs[1]; /* export data */ for (ifield = 0; ifield<nfields; ifield++) { tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { if (!strcmp("amg",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->amg)+1, (size_t)sizeof(char)); strcpy(output_buf,param->amg); fout = mxCreateString(output_buf); } else if (!strcmp("presmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->presmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->presmoother); fout = mxCreateString(output_buf); } else if (!strcmp("postsmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->postsmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->postsmoother); fout = mxCreateString(output_buf); } else if (!strcmp("typecoarse",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typecoarse)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typecoarse); fout = mxCreateString(output_buf); } else if (!strcmp("typetv",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typetv)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typetv); fout = mxCreateString(output_buf); } else if (!strcmp("FCpart",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->FCpart)+1, (size_t)sizeof(char)); strcpy(output_buf,param->FCpart); fout = mxCreateString(output_buf); } else if (!strcmp("solver",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->solver)+1, (size_t)sizeof(char)); strcpy(output_buf, param->solver); fout = mxCreateString(output_buf); } else if (!strcmp("ordering",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->ordering)+1, (size_t)sizeof(char)); strcpy(output_buf, param->ordering); fout = mxCreateString(output_buf); } else { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); output_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); sizebuf = (size_t)buflen*sizeof(char); memcpy(output_buf, input_buf, sizebuf); fout = mxCreateString(output_buf); } } else { /* real case */ if (mxGetPi(tmp)==NULL && strcmp("damping",fnames[ifield])) fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxREAL); else { /* complex case */ fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxCOMPLEX); } pdata = mxGetData(fout); sizebuf = mxGetElementSize(tmp); if (!strcmp("elbow",fnames[ifield])) { dbuf=param->elbow; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfilS",fnames[ifield])) { dbuf=param->lfilS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfil",fnames[ifield])) { dbuf=param->lfil; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("maxit",fnames[ifield])) { dbuf=param->maxit; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolS",fnames[ifield])) { dbuf=param->droptolS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolc",fnames[ifield])) { dbuf=param->droptolc; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptol",fnames[ifield])) { dbuf=param->droptol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("condest",fnames[ifield])) { dbuf=param->condest; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("restol",fnames[ifield])) { dbuf=param->restol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npresmoothing",fnames[ifield])) { dbuf=param->npresmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npostmoothing",fnames[ifield])) { dbuf=param->npostsmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("ncoarse",fnames[ifield])) { dbuf=param->ncoarse; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("matching",fnames[ifield])) { dbuf=param->matching; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("nrestart",fnames[ifield])) { dbuf=param->nrestart; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("damping",fnames[ifield])) { pr=mxGetPr(fout); pi=mxGetPi(fout); *pr=param->damping.r; *pi=param->damping.i; } else if (!strcmp("mixedprecision",fnames[ifield])) { dbuf=param->mixedprecision; memcpy(pdata, &dbuf, sizebuf); } else { memcpy(pdata, mxGetData(tmp), sizebuf); } } /* Set each field in output structure */ mxSetFieldByNumber(options_output, 0, ifield, fout); } /* store number of iteration steps */ if (j==-1) ifield=nfields; else ifield=j; fout=mxCreateDoubleMatrix(1,1, mxREAL); pr=mxGetPr(fout); *pr=param->ipar[26]; /* set each field in output structure */ mxSetFieldByNumber(options_output, 0, (mwIndex)ifield, fout); mxFree(fnames); mxFree(classIDflags); /* mexPrintf("options exported\n"); fflush(stdout); */ /* export approximate solution */ plhs[0] = mxCreateDoubleMatrix((mwSize)A.nr, (mwSize)1, mxCOMPLEX); x_output=plhs[0]; pr=mxGetPr(x_output); pi=mxGetPi(x_output); for (i=0; i<A.nr; i++) { pr[i]=sol[i].r; pi[i]=sol[i].i; } /* release right hand side */ free(rhs); /* release solution */ free(sol); /* release input matrix */ free(A.ia); free(A.ja); free(A.a); switch (ierr) { case 0: /* perfect! */ break; case -1: /* too many iteration steps */ mexPrintf("!!! ILUPACK Warning !!!\n"); mexPrintf("number of iteration steps exceeded its limit.\nEither increase `options.maxit'\n or recompute ILUPACK preconditioner using a smaller `options.droptol'"); break; case -2: /* weird, should not occur */ mexErrMsgTxt("not enough workspace provided."); plhs[0]=NULL; break; case -3: /* breakdown */ mexErrMsgTxt("iterative solver breaks down.\nMost likely you need to recompute ILUPACK preconditioner using a smaller `options.droptol'"); plhs[0]=NULL; break; default: /* zero pivot encountered at step number ierr */ mexPrintf("iterative solver exited with error code %d.\n",ierr); mexErrMsgTxt("break down."); plhs[0]=NULL; break; } /* end switch */ return; }