BinaryMatrix *BinaryMatrix::CreateVectorFromBinaryData(byte *data, int bitLen) { BinaryMatrix *matrix = CreateVector(bitLen); int byteLen = ByteUtil::GetByteLenForDataLen(bitLen); for (int i = 0; i < byteLen; i++) { byte b = data[i]; for (int j = 0; j < BYTE_BIT_LEN; j++) { int itemIndex = i * BYTE_BIT_LEN + j; if (itemIndex < bitLen) { byte bitByte = ByteUtil::GetOnlyBitByte(b, j); if (bitByte != 0) { matrix->SetItem(0, itemIndex, true); } } } } return matrix; };
/* VQNodeScore: compute VQNodeScore between v and n, smallest score is best. */ float VQNodeScore(VQNode n, Vector v, int size, CovKind ck) { Vector m,iv,crow,vx; TriMat ic; float x,sum; int i,j; m = n->mean; switch(ck){ case NULLC: sum = 0.0; for (i=1; i<=size; i++){ x = v[i]-m[i]; sum += x*x; } return n->gconst+sum; case INVDIAGC: iv = (Vector)n->cov.var; sum = 0.0; for (i=1; i<=size; i++){ x = v[i]-m[i]; sum += x*x*iv[i]; } return n->gconst+sum; case FULLC: ic = (TriMat)n->cov.inv; vx = CreateVector(&gstack,size); for (i=1;i<=size;i++) vx[i] = v[i] - m[i]; sum = 0.0; for (i=2;i<=size;i++) { crow = ic[i]; for (j=1; j<i; j++) sum += vx[i]*vx[j]*crow[j]; } sum *= 2; for (i=1;i<=size;i++) sum += vx[i] * vx[i] * ic[i][i]; FreeVector(&gstack,vx); return n->gconst+sum; default: HError(6172,"VQNodeScore: bad kind %d",ck); } return 0; /* to keep compiler happy */ }
/* EXPORT->CreateBoNGram: Allocate and create basic NGram structures */ NGramLM *CreateBoNGram(LModel *lm,int vocSize, int counts[NSIZE]) { lmId ndx[NSIZE]; int i,k; NGramLM *nglm; nglm = (NGramLM *) New(lm->heap, sizeof(NGramLM)); lm->data.ngram = nglm; nglm->heap = lm->heap; for (i=0;i<=NSIZE;i++) nglm->counts[i]=0; for (i=1;i<=NSIZE;i++) if (counts[i]==0) break; else nglm->counts[i]=counts[i]; nglm->nsize=i-1; /* Don't count final layer */ for (k=0,i=1;i<nglm->nsize;i++) k+=nglm->counts[i]; /* Then use total to guess NEntry hash size */ if (k<25000) nglm->hashsize=NGHSIZE1; else if (k<250000) nglm->hashsize=NGHSIZE2; else nglm->hashsize=NGHSIZE3; nglm->hashtab=(NEntry **) New(lm->heap,sizeof(NEntry*)*nglm->hashsize); for (i=0; i<nglm->hashsize; i++) nglm->hashtab[i]=NULL; nglm->vocSize = vocSize; nglm->unigrams = CreateVector(lm->heap,nglm->vocSize); nglm->wdlist = (LabId *) New(lm->heap,nglm->vocSize*sizeof(LabId)); nglm->wdlist--; for (i=1;i<=nglm->vocSize;i++) nglm->wdlist[i]=NULL; for (i=0;i<NSIZE;i++) ndx[i]=0; GetNEntry(nglm,ndx,TRUE); return(nglm); }
Object findLocationOf(State *state, Object obj) { int args[6], findOpByName(ConcreteType, char *); ConcreteType bcct = BuiltinInstCT(BITCHUNKI); Bitchunk bc; ConcreteType ct; OID oid; static int lookupfn = 0; bc = (Bitchunk)CreateVector(bcct, sizeof(OID)); oid = OIDOf(obj); memmove(bc->d.data, &oid, sizeof(OID)); args[0] = (int)JNIL; args[1] = (int)JNIL; args[2] = (int)bc; args[3] = (int)bcct; args[4] = (int)OIDFetch(thisnode->node); args[5] = (int)BuiltinInstCT(NODEI); ct = CODEPTR(locsrv->flags); if (!lookupfn) lookupfn = findOpByName(ct, "lookup"); upcall(locsrv, lookupfn, 0, 2, 1, args); return (Object)args[0]; }
/* Durbins recursion to get LP coeffs for auto values */ static float Durbin(Vector k, Vector thisA, Vector r, float E, int order) { Vector newA; float ki; /* Current Reflection Coefficient */ int i,j; newA = CreateVector(&gstack,order); for (i=1;i<=order;i++) { ki = r[i]; /* Calc next reflection coef */ for (j=1;j<i;j++) ki = ki + thisA[j] * r[i - j]; ki = ki / E; if (k!=NULL) k[i] = ki; E *= 1 - ki*ki; /* Update Error */ newA[i] = -ki; /* Calc new filter coef */ for (j=1;j<i;j++) newA[j] = thisA[j] - ki * thisA[i - j]; for (j=1;j<=i;j++) thisA[j] = newA[j]; } FreeVector(&gstack,newA); return (E); }
static void CheckFunctionDeclarator(AstFunctionDeclarator dec) { AstFunctionDeclarator funcDec = (AstFunctionDeclarator)dec; CheckDeclarator(funcDec->dec); ALLOC(funcDec->sig); funcDec->sig->hasProto = funcDec->paramTyList != NULL; funcDec->sig->hasEllipse = 0; funcDec->sig->params = CreateVector(4); if (funcDec->sig->hasProto) { CheckParameterTypeList(funcDec); } else if (funcDec->partOfDef) { char *id; FOR_EACH_ITEM(char*, id, funcDec->ids) AddParameter(funcDec->sig->params, id, NULL, 0, &funcDec->coord); ENDFOR }
/* CloneStream: return a clone of given stream */ MixtureVector CloneStream(HMMSet *hset, StreamElem *ste, Boolean sharing) { int m,M; MixtureElem *sme,*tme; MixtureVector mv; M = ste->nMix; if (hset->hsKind == PLAINHS || hset->hsKind == SHAREDHS){ tme = (MixtureElem *)New(hset->hmem,M*sizeof(MixtureElem)); mv.cpdf = tme-1; sme = ste->spdf.cpdf + 1; for (m=1; m<=M; m++,sme++,tme++){ tme->weight = sme->weight; tme->mpdf = (tme->weight>MINMIX)?CloneMixPDF(hset,sme->mpdf,sharing):NULL; } } else if (hset->hsKind == TIEDHS) { mv.tpdf = CreateVector(hset->hmem,M); CopyVector(ste->spdf.tpdf,mv.tpdf); } else { mv.dpdf = CreateShortVec(hset->hmem,M); CopyShortVec(ste->spdf.dpdf,mv.dpdf); } return mv; }
int main(int argc, char *argv[]) { vector *Xdb, *strain, *stress, *Pc, *phi, *aw, *xf; double Xmin = .05, Xmax = .29, Xi = .33, T, n = 100; matrix *output; int i; oswin *o; if(argc != 2) { puts("Usage: calc-stress <T>"); puts(" <T>: Temperature in Kelvins"); exit(0); } T = atof(argv[1]); o = CreateOswinData(); Xdb = linspaceV(Xmin, Xmax, n); strain = CreateVector(n); stress = CreateVector(n); phi = CreateVector(n); aw = CreateVector(n); Pc = CreateVector(n); xf = CreateVector(n); for(i=0; i<n; i++) { setvalV(strain, i, linear_strain(Xi, valV(Xdb, i), T)); setvalV(stress, i, valV(strain, i)*EaLaura(T, valV(Xdb, i))); setvalV(Pc, i, EffPorePress(Xi, valV(Xdb, i), T)); setvalV(aw, i, OswinInverse(o, valV(Xdb, i), T)); setvalV(xf, i, solidfrac(Xi, T, valV(strain, i))); setvalV(phi, i, porosity(Xi, valV(Xdb, i), T, valV(strain, i))); } output = CatColVector(7, Xdb, strain, stress, Pc, aw, xf, phi); mtxprntfilehdr(output, "stress.csv", "Xdb,strain,stress,Pc,aw,solidfrac,porosity\n"); }
CClosure *CLispEng::CreateClosure(size_t len) { return (CClosure*)CreateVector(len); }
/** * @brief Used to create and initialise a new instance of the Matrix3d struct * @return A pointer to the new Matrix3d* instance */ Matrix3d* CreateMatrix() { return NewMatrix(CreateVector(), CreateVector(), CreateVector()); }
/* LoadFile: load whole file or segments and accumulate variance */ void LoadFile(char *fn) { ParmBuf pbuf; BufferInfo info; char labfn[80]; Transcription *trans; long segStIdx,segEnIdx; int i,s,j,ncas,nObs=0; LLink p; if (segId == NULL) { /* load whole parameter file */ if((pbuf=OpenBuffer(&iStack, fn, 0, dff, FALSE_dup, FALSE_dup))==NULL) HError(2550,"LoadFile: Config parameters invalid"); GetBufferInfo(pbuf,&info); CheckData(fn,info); nObs = ObsInBuffer(pbuf); for (i=0; i<nObs; i++) { for(s=1;s<=swidth[0];s++) obs.fv[s] = CreateVector(&dStack,swidth[s]); ReadAsTable(pbuf,i,&obs); for(s=1;s<=swidth[0];s++) StoreItem(dSeq[s],(Ptr)obs.fv[s]); } CloseBuffer(pbuf); } else { /* load segment of parameter file */ MakeFN(fn,labDir,labExt,labfn); trans = LOpen(&iStack,labfn,lff); ncas = NumCases(trans->head,segId); if ( ncas > 0) { if((pbuf=OpenBuffer(&iStack, fn, 0, dff, FALSE_dup, FALSE_dup))==NULL) HError(2550,"LoadFile: Config parameters invalid"); GetBufferInfo(pbuf,&info); CheckData(fn,info); for (i=1,nObs=0; i<=ncas; i++) { p = GetCase(trans->head,segId,i); segStIdx= (long) (p->start/info.tgtSampRate); segEnIdx = (long) (p->end/info.tgtSampRate); if (trace&T_SEGS) printf(" loading seg %s [%ld->%ld]\n", segId->name,segStIdx,segEnIdx); if (segEnIdx >= ObsInBuffer(pbuf)) segEnIdx = ObsInBuffer(pbuf)-1; if (segEnIdx >= segStIdx) { for (j=segStIdx;j<=segEnIdx;j++) { /* SJY: The HInit code I copied this from had no */ /* SJY: CreateVector call here -- a bug? */ for(s=1;s<=swidth[0];s++) obs.fv[s] = CreateVector(&dStack,swidth[s]); ReadAsTable(pbuf,j,&obs); for(s=1;s<=swidth[0];s++) StoreItem(dSeq[s],(Ptr)obs.fv[s]); ++nObs; } } } CloseBuffer(pbuf); } } ResetHeap(&iStack); if (trace&T_LOAD) { printf(" %5d obs loaded from %s, streams: ",nObs,fn); for(s=1;s<=swidth[0];s++) printf("[%d]" ,swidth[s]); printf("\n"); fflush(stdout); } }
void CXYZGradient::SetNumberOfAtoms(int numofatoms) { Comment = NULL; CreateVector(numofatoms); }
/* InitMgeTrnInfo: Initialize all info struct for MGE training */ static void InitMgeTrnInfo() { int i, p, nWin; /* setup GenInfo */ genInfo->genMem = &genStack; genInfo->hset = &hset; genInfo->maxStates = MaxStatesInSet(&hset); genInfo->MSDthresh = MSDthresh; genInfo->frameRate = frameRate; genInfo->stateAlign = TRUE; CheckGenSetUp(); /* setup MTStatInfo */ statInfo->order = GetTotalOrder(mtInfo->genInfo); for (p = 1; p <= genInfo->nPdfStream[0]; p++) { statInfo->initErrAcc[p] = CreateDVector(&gstack, genInfo->pst[p].order * 2); statInfo->prevErrAcc[p] = CreateDVector(&gstack, genInfo->pst[p].order * 2); statInfo->currErrAcc[p] = CreateDVector(&gstack, genInfo->pst[p].order * 2); ZeroDVector(statInfo->initErrAcc[p]); ZeroDVector(statInfo->prevErrAcc[p]); ZeroDVector(statInfo->currErrAcc[p]); } nWin = mtInfo->genInfo->pst[1].win.num; for (p = 1; p <= genInfo->nPdfStream[0]; p++) { statInfo->pnMeanFloor[p] = (IMatrix *) New(&gstack, statInfo->order * sizeof(IMatrix *)); statInfo->pnMeanFloor[p]--; statInfo->pnVarFloor[p] = (IMatrix *) New(&gstack, statInfo->order * sizeof(IMatrix *)); statInfo->pnVarFloor[p]--; for (i = 1; i <= statInfo->order; i++) { statInfo->pnMeanFloor[p][i] = CreateIMatrix(&gstack, nWin, 2); /* 2: High & Low floor */ ZeroIMatrix(statInfo->pnMeanFloor[p][i]); statInfo->pnVarFloor[p][i] = CreateIMatrix(&gstack, nWin, 2); /* 2: High & Low floor */ ZeroIMatrix(statInfo->pnVarFloor[p][i]); } } /* setup MgeTrnInfo */ mtInfo->nBoundAdjWin = nBoundAdjWin; mtInfo->fGVDistWght = fGVDistWght; mtInfo->uFlags = uFlags; mtInfo->funcType = funcType; for (p = 1; p <= genInfo->nPdfStream[0]; p++) { mtInfo->SRMean[p] = CreateVector(&gstack, genInfo->pst[p].order); mtInfo->SRVar[p] = CreateVector(&gstack, genInfo->pst[p].order); mtInfo->DWght[p] = CreateVector(&gstack, genInfo->pst[p].order); ZeroVector(mtInfo->SRMean[p]); ZeroVector(mtInfo->SRVar[p]); ZeroVector(mtInfo->DWght[p]); } if (scalefn != NULL) { LoadScaleRate(scalefn); mtInfo->bMScale = TRUE; } else mtInfo->bMScale = FALSE; CheckMTInfoSetUp(); return; }
/* ----------------------------------------- main() ----------------------------------------- */ int main(void) { FILE* hFileInVectors; char text[MAX_CHARS] = {0}; int nQuit = FALSE; int nVector; int iResult; float fDistance; float fAngle; struct vector_t vectors[MAX_VECTORS]; WSADATA wsaData; struct addrinfo *result = NULL, *ptr = NULL, hints; SOCKET UdpSocket = INVALID_SOCKET; printf("BUILD: coordinates.c %s, %s\n", __DATE__, __TIME__); // -------------- CODE ----------- // open input file to get command vectors sprintf(text, "%s%s", FILE_DIR, INPUT_FILE); if ( (hFileInVectors = fopen(text,"r")) == NULL ) { ErrorExit("fopen() could not open vectors file."); } // initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if ( iResult != 0) { sprintf(text, "WSAStartup() failed with error: %d\n", iResult); fclose(hFileInVectors); ErrorExit(text); } ZeroMemory(&hints, sizeof (hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; // Resolve the local address and port to be used by the server iResult = getaddrinfo(DEFAULT_IP, DEFAULT_PORT, &hints, &result); if (iResult != 0) { sprintf(text, "getaddrinfo() failed with error: %d\n", iResult); fclose(hFileInVectors); WSACleanup(); ErrorExit(text); } // Create a SOCKET for the server UdpSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (UdpSocket == INVALID_SOCKET) { sprintf(text, "socket() falied with error: %ld\n", WSAGetLastError()); fclose(hFileInVectors); freeaddrinfo(result); WSACleanup(); ErrorExit(text); } // Setup the TCP listening socket -- don't need to bind for UDP //iResult = bind( UdpSocket, result->ai_addr, (int) result->ai_addrlen); //if (iResult == SOCKET_ERROR) //{ // sprintf(text, "bind() failed with error: %d\n", WSAGetLastError()); // freeaddrinfo(result); // closesocket(UdpSocket); // WSACleanup(); // ErrorExit(text); //} ClearVector(&vectors[0]); printf(" [#] ( t , r ) tSum dX dY X Y | R t align\n"); printf(" ---- ----------- ---- --- --- --- --- | --- --- -----\n"); nVector = 1; while ( !feof(hFileInVectors) && !nQuit && nVector < MAX_VECTORS ) { text[0] = '\0'; fgets(text, MAX_CHARS, hFileInVectors); if ( text[0] != '#' ) { sscanf(text, "%g %g", &fAngle, &fDistance); CreateVector(fAngle, fDistance, &vectors[nVector], &vectors[nVector-1]); printf(" [%d] (%+.2f,%+.2f) %+.2f %+.2f %+.2f %+.2f %+.2f | %+.2f %+.2f %+.2f\n", nVector, fAngle, fDistance, vectors[nVector].fAngleSum, vectors[nVector].fDx, vectors[nVector].fDy, vectors[nVector].fX, vectors[nVector].fY, vectors[nVector].fOriginLength, vectors[nVector].fOriginAngle, vectors[nVector].fRealignAngle); GetHomeCommand(&vectors[nVector], &fAngle, &fDistance); printf(" get home: [%+.2f,%+.2f]\n", fAngle, fDistance); sprintf(text, "vector,%+.2f,%+.2f,%+.2f,%+.2f", vectors[nVector-1].fX, vectors[nVector-1].fY, vectors[nVector].fX, vectors[nVector].fY); // Echo the buffer to the client iResult = sendto(UdpSocket, text, strlen(text), 0, result->ai_addr, (int) result->ai_addrlen); if (iResult == SOCKET_ERROR) { sprintf(text, "sendto() failed with error: %d\n", WSAGetLastError()); fclose(hFileInVectors); closesocket(UdpSocket); WSACleanup(); ErrorExit(text); } sprintf(text, "obstacle,%+.2f,%+.2f", vectors[nVector].fX, vectors[nVector].fY); // Echo the buffer to the client iResult = sendto(UdpSocket, text, strlen(text), 0, result->ai_addr, (int) result->ai_addrlen); if (iResult == SOCKET_ERROR) { sprintf(text, "sendto() failed with error: %d\n", WSAGetLastError()); fclose(hFileInVectors); closesocket(UdpSocket); WSACleanup(); ErrorExit(text); } Sleep(500); nVector++; } } // vector position and error calculation // close all open handles fclose(hFileInVectors); freeaddrinfo(result); closesocket(UdpSocket); WSACleanup(); return 0; }
/* WriteParms: write generated parameter vector sequences */ void WriteParms(char *labfn, GenInfo * genInfo) { int p, t, v, k; char ext[MAXSTRLEN], fn[MAXFNAMELEN]; float ig; Vector igvec; TriMat igtm; FILE *parmfp = NULL, *pdffp = NULL; Boolean isPipe1, isPipe2; PdfStream *pst; /* get ignore value for MSD */ ig = ReturnIgnoreValue(); /* save generated parameters */ for (p = 1; p <= genInfo->nPdfStream[0]; p++) { /* p-th PdfStream */ pst = &(genInfo->pst[p]); /* create ignore value vector/triangular matrix */ igvec = CreateVector(&genStack, pst->vSize); igtm = CreateTriMat(&genStack, pst->vSize); for (v = 1; v <= pst->vSize; v++) { igvec[v] = ig; for (k = 1; k <= v; k++) igtm[v][k] = ig; } /* open file pointer for saving generated parameters */ MakeFN(labfn, genDir, pst->ext, fn); if ((parmfp = FOpen(fn, NoOFilter, &isPipe1)) == NULL) HError(9911, "WriteParms: Cannot create ouput file %s", fn); /* open file pointer for saving pdf parameters */ if (outPdf) { sprintf(ext, "%s_%s", pst->ext, pdfExt); MakeFN(labfn, genDir, ext, fn); if ((pdffp = FOpen(fn, NoOFilter, &isPipe2)) == NULL) HError(9911, "WriteParms: Cannot create output file %s", fn); } /* output generated parameter sequence */ for (t = pst->t = 1; t <= genInfo->tframe; t++) { if (pst->ContSpace[t]) { /* output generated parameters */ WriteVector(parmfp, pst->C[pst->t], inBinary); /* output pdfs */ if (outPdf) { WriteVector(pdffp, pst->mseq[pst->t], inBinary); if (pst->fullCov) WriteTriMat(pdffp, pst->vseq[pst->t].inv, inBinary); else WriteVector(pdffp, pst->vseq[pst->t].var, inBinary); } pst->t++; } else { /* output ignoreValue symbol for generated parameters */ WriteFloat(parmfp, &igvec[1], pst->order, inBinary); /* output ignoreValue symbol for pdfs */ if (outPdf) { WriteVector(pdffp, igvec, inBinary); if (pst->fullCov) WriteTriMat(pdffp, igtm, inBinary); else WriteVector(pdffp, igvec, inBinary); } } } /* close file pointer */ if (outPdf) FClose(pdffp, isPipe2); FClose(parmfp, isPipe1); /* free igvec */ FreeVector(&genStack, igvec); } return; }
/* WriteStateDurations: output state duration to file */ void WriteStateDurations(char *labfn, GenInfo * genInfo) { char fn[MAXFNAMELEN]; int i, j, k, s, cnt, nState, modeldur; float modelMean; Label *label; FILE *durfp; Vector mean = NULL; Boolean isPipe; /* open file pointer for saving state durations */ MakeFN(labfn, genDir, durExt, fn); if ((durfp = FOpen(fn, NoOFilter, &isPipe)) == NULL) HError(9911, "WriteStateDurations: Cannot create output file %s", fn); /* prepare mean vector */ mean = CreateVector(genInfo->genMem, genInfo->maxStates); for (i = 1; i <= genInfo->labseqlen; i++) { label = GetLabN(genInfo->labseq->head, i); nState = genInfo->hmm[i]->numStates - 2; /* compose mean vector of the i-th state duration model */ for (s = cnt = 1; s <= genInfo->dset->swidth[0]; s++) { for (k = 1; k <= genInfo->dset->swidth[s]; k++, cnt++) mean[cnt] = genInfo->dm[i]->svec[2].info->pdf[s].info->spdf.cpdf[1].mpdf->mean[k]; } modeldur = 0; modelMean = 0.0; for (j = 1; genInfo->sindex[i][j] != 0; j++) { /* output state duration */ fprintf(durfp, "%s.state[%d]: duration=%d (frame), mean=%e\n", label->labid->name, genInfo->sindex[i][j], genInfo->durations[i][j], mean[genInfo->sindex[i][j] - 1]); fflush(durfp); if (trace & T_DUR) { printf("%s.state[%d]: duration=%d (frame), mean=%e\n", label->labid->name, genInfo->sindex[i][j], genInfo->durations[i][j], mean[genInfo->sindex[i][j] - 1]); fflush(stdout); } modeldur += genInfo->durations[i][j]; modelMean += mean[genInfo->sindex[i][j] - 1]; } fprintf(durfp, "%s: duration=%d (frame), mean=%e\n", label->labid->name, modeldur, modelMean); fflush(durfp); if (trace & T_DUR) { printf("%s: duration=%d (frame), mean=%e\n", label->labid->name, modeldur, modelMean); fflush(stdout); } } /* dispose mean vector */ FreeVector(genInfo->genMem, mean); /* close file pointer for saving state durations */ FClose(durfp, isPipe); return; }
/* EXPORT->InitFBank: Initialise an FBankInfo record */ FBankInfo InitFBank(MemHeap *x, int frameSize, long sampPeriod, int numChans, float lopass, float hipass, Boolean usePower, Boolean takeLogs, Boolean doubleFFT, float alpha, float warpLowCut, float warpUpCut) { FBankInfo fb; float mlo,mhi,ms,melk; int k,chan,maxChan,Nby2; /* Save sizes to cross-check subsequent usage */ fb.frameSize = frameSize; fb.numChans = numChans; fb.sampPeriod = sampPeriod; fb.usePower = usePower; fb.takeLogs = takeLogs; /* Calculate required FFT size */ fb.fftN = 2; while (frameSize>fb.fftN) fb.fftN *= 2; if (doubleFFT) fb.fftN *= 2; Nby2 = fb.fftN / 2; fb.fres = 1.0E7/(sampPeriod * fb.fftN * 700.0); maxChan = numChans+1; /* set lo and hi pass cut offs if any */ fb.klo = 2; fb.khi = Nby2; /* apply lo/hi pass filtering */ mlo = 0; mhi = Mel(Nby2+1,fb.fres); if (lopass>=0.0) { mlo = 1127*log(1+lopass/700.0); fb.klo = (int) ((lopass * sampPeriod * 1.0e-7 * fb.fftN) + 2.5); if (fb.klo<2) fb.klo = 2; } if (hipass>=0.0) { mhi = 1127*log(1+hipass/700.0); fb.khi = (int) ((hipass * sampPeriod * 1.0e-7 * fb.fftN) + 0.5); if (fb.khi>Nby2) fb.khi = Nby2; } if (trace&T_MEL){ printf("FFT passband %d to %d out of 1 to %d\n",fb.klo,fb.khi,Nby2); printf("Mel passband %f to %f\n",mlo,mhi); } /* Create vector of fbank centre frequencies */ fb.cf = CreateVector(x,maxChan); ms = mhi - mlo; for (chan=1; chan <= maxChan; chan++) { if (alpha == 1.0) { fb.cf[chan] = ((float)chan/(float)maxChan)*ms + mlo; } else { /* scale assuming scaling starts at lopass */ float minFreq = 700.0 * (exp (mlo / 1127.0) - 1.0 ); float maxFreq = 700.0 * (exp (mhi / 1127.0) - 1.0 ); float cf = ((float)chan / (float) maxChan) * ms + mlo; cf = 700 * (exp (cf / 1127.0) - 1.0); fb.cf[chan] = 1127.0 * log (1.0 + WarpFreq (warpLowCut, warpUpCut, cf, minFreq, maxFreq, alpha) / 700.0); } } /* Create loChan map, loChan[fftindex] -> lower channel index */ fb.loChan = CreateShortVec(x,Nby2); for (k=1,chan=1; k<=Nby2; k++){ melk = Mel(k,fb.fres); if (k<fb.klo || k>fb.khi) fb.loChan[k]=-1; else { while (fb.cf[chan] < melk && chan<=maxChan) ++chan; fb.loChan[k] = chan-1; } } /* Create vector of lower channel weights */ fb.loWt = CreateVector(x,Nby2); for (k=1; k<=Nby2; k++) { chan = fb.loChan[k]; if (k<fb.klo || k>fb.khi) fb.loWt[k]=0.0; else { if (chan>0) fb.loWt[k] = ((fb.cf[chan+1] - Mel(k,fb.fres)) / (fb.cf[chan+1] - fb.cf[chan])); else fb.loWt[k] = (fb.cf[1]-Mel(k,fb.fres))/(fb.cf[1] - mlo); } } /* Create workspace for fft */ fb.x = CreateVector(x,fb.fftN); return fb; }
/* 初始化词法分析用到的数据 */ void SetupLexer (void) { int i; InLink = CreateVector (1); for (i = 0; i < END_OF_FILE + 1; i++) { if ( IsLetter (i) ) { /* 在字母开始的位置挂载标示符处理函数 */ Scanners[i] = ScanIdentifier; } else if ( IsDigit (i) ) { /* 在数字或点开始的位置挂载常数处理函数 */ Scanners[i] = ScanNumericLiteral; } else { /* 挂载处理处理非法字符的函数 */ Scanners[i] = ScanBadChar; } } /* 下边覆盖上边部分挂在的错误处理函数 */ /* 挂在文件扫描结束时的处理函数 */ Scanners[END_OF_FILE] = ScanEOF; Scanners['\''] = ScanCharLiteral; Scanners['"'] = ScanStringLiteral; Scanners['+'] = ScanPlus; Scanners['-'] = ScanMius; Scanners['*'] = ScanStar; Scanners['/'] = ScanSlash; Scanners['%'] = ScanPercent; Scanners['<'] = ScanLess; Scanners['>'] = ScanGreat; Scanners['!'] = ScanExclamation; Scanners['='] = ScanEqual; Scanners['|'] = ScanBar; Scanners['&'] = ScanAmpersand; Scanners['^'] = ScanCaret; Scanners['.'] = ScanDot; Scanners['{'] = ScanLBRACE; Scanners['}'] = ScanRBRACE; Scanners['['] = ScanLBRACKET; Scanners[']'] = ScanRBRACKET; Scanners['('] = ScanLPAREN; Scanners[')'] = ScanRPAREN; Scanners[','] = ScanCOMMA; Scanners[';'] = ScanSEMICOLON; Scanners['~'] = ScanCOMP; Scanners['?'] = ScanQUESTION; Scanners[':'] = ScanCOLON; Scanners['\\'] = ScanBacklash; /* 外部关键字关键字 */ if (ExtraKeywords) { char *str; struct keyword *p; FOR_EACH_ITEM (char*, str, ExtraKeywords) for (p = keywords_; p->name; p++) { if (!strcmp (str, p->name)) { p->len = strlen (str); break; } } ENDFOR } }
/* ReadBigram: load a bigram from given file */ static void ReadMatBigram(LModel *lm,char *fn) { Vector vec; char buf[132]; int P,p,j; float sum,x; LabId id; MatBiLM *matbi; if (trace&T_TIO) printf("\nMB "),fflush(stdout); if(InitSource(fn,&source,LangModFilter)<SUCCESS) HError(8110,"ReadMatBigram: Can't open file %s", fn); vec = CreateVector(&gcheap,MAX_LMID); ReadLMWord(buf);SkipWhiteSpace(&source); id=GetLabId(buf,TRUE); P = ReadRow(vec); if (P<=0 || P >MAX_LMID) HError(8151,"ReadMatBigram: First row invalid (%d entries)",P); matbi=CreateMatBigram(lm,P); matbi->wdlist[1] = id; for (p=1;p<=P;p++) matbi->bigMat[1][p]=vec[p]; id->aux=(Ptr) 1; Dispose(&gcheap,vec); for (sum=0.0, j=1; j<=P; j++) { x = matbi->bigMat[1][j]; if (x<0) HError(8151,"ReadMatBigram: In bigram, entry %d for %s is -ve (%e)", j,buf,x); sum += x; matbi->bigMat[1][j]=((x<MINLARG)?LZERO:log(x)); } if (sum < 0.99 || sum > 1.01) HError(-8151,"ReadMatBigram: Row %d of bigram %s adds up to %f",1,fn,sum); for (p=2; ReadLMWord(buf); p++) { if (trace&T_TIO) { if ((p%25)==0) printf(". "),fflush(stdout); if ((p%800)==0) printf("\n "),fflush(stdout); } if (p>P) HError(8150,"ReadMatBigram: More rows than columns in bigram %s",fn); id=GetLabId(buf,TRUE); if ((int)id->aux != 0) HError(8150,"ReadMatBigram: Duplicated name %s in bigram %s",buf,fn); id->aux = (Ptr) p; matbi->wdlist[p] = id; SkipWhiteSpace(&source); if (ReadRow(matbi->bigMat[p])!=P) HError(8150,"ReadMatBigram: Wrong number of items in row %d",p); for (sum=0.0, j=1; j<=P; j++) { x = matbi->bigMat[p][j]; if (x<0) HError(8151,"ReadMatBigram: In bigram, entry %d for %s is -ve (%e)", j,buf,x); sum += x; matbi->bigMat[p][j]=((x<MINLARG)?LZERO:log(x)); } if (sum < 0.99 || sum > 1.01) HError(-8151,"ReadMatBigram: Row %d of bigram %s adds up to %f",p,fn,sum); } if (P>p) HError(8150,"ReadMatBigram: More columns than rows in bigram %s",fn); if (trace&T_TIO) printf("\n"),fflush(stdout); CloseSource(&source); }
CP CLispEng::CreateString(RCString s) { size_t size = s.length(); CArrayValue *av = CreateVector(size, ELTYPE_CHARACTER); memcpy(av->m_pData, (const String::value_type*)s, size*sizeof(String::value_type)); return FromSValue(av); }
/* Initialise: load HMMs and create accumulators */ static void Initialise(void) { int s,V; Boolean eSep; char base[MAXSTRLEN]; char path[MAXSTRLEN]; char ext[MAXSTRLEN]; /* Load HMM defs */ if(MakeOneHMM(&hset,BaseOf(hmmfn,base))<SUCCESS) HError(2028,"Initialise: MakeOneHMM failed"); if(LoadHMMSet(&hset,PathOf(hmmfn,path),ExtnOf(hmmfn,ext))<SUCCESS) HError(2028,"Initialise: LoadHMMSet failed"); SetParmHMMSet(&hset); if (hset.hsKind==DISCRETEHS || hset.hsKind==TIEDHS) HError(2030,"Initialise: HCompV only uses continuous models"); /* Create a heap to store the input data */ /*CreateHeap(&iStack,"InBuf", MSTAK, 1, 0.5, 100000, LONG_MAX);*/ /* Get a pointer to the physical HMM */ hmmId = GetLabId(base,FALSE); macroLink = FindMacroName(&hset,'h',hmmId); if (macroLink==NULL) HError(2020,"Initialise: cannot find hmm %s in hset",hmmfn); hmmLink = (HLink)macroLink->structure; /* Find out for which streams full covariance is needed */ CheckVarianceKind( ); /* Create accumulators for the mean and variance */ for (s=1;s<=hset.swidth[0]; s++){ V = hset.swidth[s]; accs[s].meanSum=CreateVector(&gstack,V); ZeroVector(accs[s].meanSum); if (fullcNeeded[s]) { accs[s].squareSum.inv=CreateSTriMat(&gstack,V); accs[s].fixed.inv=CreateSTriMat(&gstack,V); ZeroTriMat(accs[s].squareSum.inv); } else { accs[s].squareSum.var=CreateSVector(&gstack,V); accs[s].fixed.var=CreateSVector(&gstack,V); ZeroVector(accs[s].squareSum.var); } } /* Create an object to hold the input parameters */ SetStreamWidths(hset.pkind,hset.vecSize,hset.swidth,&eSep); obs=MakeObservation(&gstack,hset.swidth,hset.pkind,FALSE,eSep); if(segLab != NULL) { segId = GetLabId(segLab,TRUE); } if (trace&T_TOP) { printf("Calculating Fixed Variance\n"); printf(" HMM Prototype: %s\n",hmmfn); printf(" Segment Label: %s\n",(segLab==NULL)?"None":segLab); printf(" Num Streams : %d\n",hset.swidth[0]); printf(" UpdatingMeans: %s\n",(meanUpdate)?"Yes":"No"); printf(" Target Direct: %s\n",(outDir==NULL)?"Current":outDir); } }
// Creates a sphere Mesh* CreateSphere(int subdivisions) { nextIndex = 0; // TODO: calc how many items in the arrays we need vertices = new Vertex[100000]; vertexCurrentIndex = 0; indices = new USHORT[100000]; indexCurrentIndex = 0; AddBaseTriangle(CreateVector(0, 0, 1), CreateVector(1, 0, 0), CreateVector(0, 1, 0)); AddBaseTriangle(CreateVector(1, 0, 0), CreateVector(0, 0, -1), CreateVector(0, 1, 0)); AddBaseTriangle(CreateVector(0, 0, -1), CreateVector(-1, 0, 0), CreateVector(0, 1, 0)); AddBaseTriangle(CreateVector(-1, 0, 0), CreateVector(0, 0, 1), CreateVector(0, 1, 0)); AddBaseTriangle(CreateVector(1, 0, 0), CreateVector(0, 0, 1), CreateVector(0, -1, 0)); AddBaseTriangle(CreateVector(0, 0, -1), CreateVector(1, 0, 0), CreateVector(0, -1, 0)); AddBaseTriangle(CreateVector(-1, 0, 0), CreateVector(0, 0, -1), CreateVector(0, -1, 0)); AddBaseTriangle(CreateVector(0, 0, 1), CreateVector(-1, 0, 0), CreateVector(0, -1, 0)); for (int division = 1; division < subdivisions; division++) Divide(); Mesh* mesh = new Mesh(); mesh->Set(vertices, vertexCurrentIndex, indices, indexCurrentIndex); // Free allocated arrays delete [] vertices; delete [] indices; return mesh; }
HRESULT CFoundationExemplars::TMchInstall(IModule* pModule) { // Array of methods for transaction machine CMethodInfo rgMethod[] = { { METHOD_SERVER, "OnCreate", "TMchOnCreate", PSBIT_NONE, PS_EXEMPLARDEFAULTMETHOD }, { METHOD_CLIENT, "UpdateCurrentIndex", "TMchUpdateCurrentIndex", PSBIT_NONE, PS_ALLEXECUTEMETHOD }, { METHOD_CLIENT, "SetCurrentIndex", "TMchSetCurrentIndex", PSBIT_NONE, PS_ALLEXECUTEMETHOD }, { METHOD_CLIENT, "OnCurrentIndexChanged", "TMchOnCurrentIndexChanged", PSBIT_NONE, PS_ALLEXECUTEMETHOD }, { METHOD_CLIENT, "GetCurrentItem", "TMchGetCurrentItem", PSBIT_NONE, PS_ALLEXECUTEMETHOD }, { METHOD_SERVER, "CreateAndDispenseObject", "TMchCreateAndDispenseObject", PSBIT_NONE, PS_ALLEXECUTEMETHOD } }; int cMethod = sizeof(rgMethod)/sizeof(rgMethod[0]); int iMethod; HRESULT hr = S_OK; CComPtr<IThing> pTransMachineEx; CComPtr<IVector> pVector; CComPtr<IPropertyList> pItemList; CComPtr<IPropertyList> pMenu; CComPtr<IPropertyList> pMenuEx; CComPtr<IMenuItem> pMenuItem; CComPtr<IThing> pPrevBtnEx; CComPtr<IThing> pNextBtnEx; CComPtr<IThing> pSelectBtnEx; CComPtr<IThing> pDisplayEx; CComBSTR bstrName; CComBSTR bstrNameInternal; static CComBSTR bstrGeometryName("GeometryName"); // Create the transaction machine exemplar if (FAILED(hr = m_pWorld->CreateExemplarEx(CComBSTR("Transaction Machine Exemplar"), CComBSTR("TransactionMachine"), CComVariant(CComBSTR("Artifact")), &pTransMachineEx))) goto ERROR_ENCOUNTERED; // Set the description string if (FAILED(hr = pTransMachineEx->put_Description(CComBSTR("A transaction machine which dispenses goods")))) goto ERROR_ENCOUNTERED; // Create a geometry for it if (FAILED(hr = pTransMachineEx->put_String(bstrGeometryName, CComBSTR("Client/Exemplar/Vending/Hvend.x")))) goto ERROR_ENCOUNTERED; // Set contents (buttons, display) to be visible if (FAILED(hr = pTransMachineEx->put_BOOL(CComBSTR("IsContentsVisible"), VARIANT_TRUE))) goto ERROR_ENCOUNTERED; // Add properties if (FAILED(hr = pTransMachineEx->AddPropertyExt(CComBSTR("Display"), CComVariant((IDispatch *) NULL), PSBIT_EXEMPLARDEFAULTPROPERTY, PS_EXEMPLARDEFAULTPROPERTY, VT_DISPATCH, IID_IThing, NULL))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pTransMachineEx->AddPropertyExt(CComBSTR("CurrentIndex"), CComVariant((short) 0), PSBIT_EXEMPLARDEFAULTPROPERTY, PS_ALLACCESSPROPERTY, VT_I2, IID_IDispatch, NULL))) goto ERROR_ENCOUNTERED; if (FAILED(hr = CreatePropertyList(m_pWorld, &pItemList))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pTransMachineEx->AddPropertyExt(CComBSTR("ItemList"), CComVariant((IDispatch *) pItemList), PSBIT_EXEMPLARDEFAULTPROPERTY, PS_EXEMPLARDEFAULTCOLLECTION, VT_DISPATCH, IID_IPropertyList, NULL))) goto ERROR_ENCOUNTERED; pItemList.Release(); // Create "sub" exemplars with geometry for previous/next buttons, select button, & display // Previous Button if (FAILED(hr = m_pWorld->CreateExemplarEx(CComBSTR("Previous Button Exemplar"), CComBSTR("PreviousButton"), CComVariant(CComBSTR("Artifact")), &pPrevBtnEx))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pPrevBtnEx->put_String(bstrGeometryName, CComBSTR("Client/Exemplar/Vending/VButLeft.x")))) goto ERROR_ENCOUNTERED; if (FAILED(hr = CreateVector(m_pWorld, 0.0, 0.0, 0.0, &pVector))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pPrevBtnEx->put_ObjectProperty(CComBSTR("Position"), pVector))) goto ERROR_ENCOUNTERED; pVector.Release(); if (FAILED(hr = pPrevBtnEx->put_BOOL(CComBSTR("IsNoticeable"), VARIANT_TRUE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pPrevBtnEx->put_BOOL(CComBSTR("IsTakeable"), VARIANT_FALSE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pPrevBtnEx->CreateAndAddMethodExt(METHOD_CLIENT, pModule, CComBSTR("TMchPreviousButton_OnLButtonDown"), CComBSTR("OnLButtonDown"), PSBIT_NONE, PS_ALLEXECUTEMETHOD))) goto ERROR_ENCOUNTERED; // Next Button if (FAILED(hr = m_pWorld->CreateExemplarEx(CComBSTR("Next Button Exemplar"), CComBSTR("NextButton"), CComVariant(CComBSTR("Artifact")), &pNextBtnEx))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pNextBtnEx->put_String(bstrGeometryName, CComBSTR("Client/Exemplar/Vending/VBuRight.x")))) goto ERROR_ENCOUNTERED; if (FAILED(hr = CreateVector(m_pWorld, 0.0, 0.0, 0.0, &pVector))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pNextBtnEx->put_ObjectProperty(CComBSTR("Position"), pVector))) goto ERROR_ENCOUNTERED; pVector.Release(); if (FAILED(hr = pNextBtnEx->put_BOOL(CComBSTR("IsNoticeable"), VARIANT_TRUE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pNextBtnEx->put_BOOL(CComBSTR("IsTakeable"), VARIANT_FALSE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pNextBtnEx->CreateAndAddMethodExt(METHOD_CLIENT, pModule, CComBSTR("TMchNextButton_OnLButtonDown"), CComBSTR("OnLButtonDown"), PSBIT_NONE, PS_ALLEXECUTEMETHOD))) goto ERROR_ENCOUNTERED; // Select Button if (FAILED(hr = m_pWorld->CreateExemplarEx(CComBSTR("Select Button Exemplar"), CComBSTR("SelectButton"), CComVariant(CComBSTR("Artifact")), &pSelectBtnEx))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pSelectBtnEx->put_String(bstrGeometryName, CComBSTR("Client/Exemplar/Vending/VButBuy.x")))) goto ERROR_ENCOUNTERED; if (FAILED(hr = CreateVector(m_pWorld, 0.0, 0.0, 0.0, &pVector))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pSelectBtnEx->put_ObjectProperty(CComBSTR("Position"), pVector))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pSelectBtnEx->put_BOOL(CComBSTR("IsNoticeable"), VARIANT_TRUE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pSelectBtnEx->put_BOOL(CComBSTR("IsTakeable"), VARIANT_FALSE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pSelectBtnEx->CreateAndAddMethodExt(METHOD_CLIENT, pModule, CComBSTR("TMchSelectButton_OnLButtonDown"), CComBSTR("OnLButtonDown"), PSBIT_NONE, PS_ALLEXECUTEMETHOD))) goto ERROR_ENCOUNTERED; // Display if (SUCCEEDED(hr = m_pWorld->CreateExemplarEx(CComBSTR("Display Exemplar"), CComBSTR("Display"), CComVariant(CComBSTR("Artifact")), &pDisplayEx))) { CComBSTR bstrGeomFile("worlds/plazas/commons/filerock.gif"); CComVariant varFile(bstrGeomFile); CComDISPPARAMS dpInitGraphics(10, varFile, CComVariant(0.0f), CComVariant(0.45f), CComVariant(0.0f), CComVariant(0.0f), CComVariant(0.0f), CComVariant(1.0f), CComVariant(0.25f), CComVariant(0.25f), CComVariant(0.25f)); pDisplayEx->InvokeMethodExt(CComBSTR("InitializeSpriteGraphics"), (DISPPARAMS *) dpInitGraphics, NULL); } else goto ERROR_ENCOUNTERED; if (FAILED(hr = pDisplayEx->put_BOOL(CComBSTR("IsNoticeable"), VARIANT_TRUE))) goto ERROR_ENCOUNTERED; if (FAILED(hr = pDisplayEx->put_BOOL(CComBSTR("IsTakeable"), VARIANT_FALSE))) goto ERROR_ENCOUNTERED; // SetGraphic must be server-side so that we have the proper security context if (FAILED(hr = pDisplayEx->CreateAndAddMethodExt(METHOD_SERVER, pModule, CComBSTR("TMchDisplay_SetGraphic"), CComBSTR("SetGraphic"), PSBIT_NONE, PS_ALLEXECUTEMETHOD))) goto ERROR_ENCOUNTERED; // Add in the methods for (iMethod=0; iMethod<cMethod; iMethod++) { bstrName = rgMethod[iMethod].pszName; if (rgMethod[iMethod].pszNameInternal == NULL) bstrNameInternal = bstrName; else bstrNameInternal = rgMethod[iMethod].pszNameInternal; if (FAILED(hr = pTransMachineEx->CreateAndAddMethodExt( rgMethod[iMethod].lFlags, pModule, bstrNameInternal, bstrName, rgMethod[iMethod].psbits, rgMethod[iMethod].permissions))) goto ERROR_ENCOUNTERED; } // Add menu items here return S_OK; ERROR_ENCOUNTERED: return hr; }