void create_phasevocoder(struct FFTSound *fftsound,int windowsize){ /* INITIALIZE PHASE VOCODER */ /* FFT length */ fftsound->N=windowsize; if ((fftsound->N!=512) && (fftsound->N!=1024) && (fftsound->N!=2048) && (fftsound->N!=4096)) { printf("Illegal value for N. Selected 1024.\n"); fftsound->N=1024; } fftsound->overlap=CONFIG_getInt("overlap_factor"); if (fftsound->overlap<1) fftsound->overlap=1; if (fftsound->overlap>32) fftsound->overlap=32; fftsound->Nw=fftsound->N; /* Window size */ fftsound->Dn=fftsound->Nw/fftsound->overlap; /* Decimation factor */ fftsound->I=(int)(fftsound->Dn * CONFIG_getDouble("time_stretch_factor")); /* Interpolationi factor */ fftsound->N2=fftsound->N>>1; theheight=fftsound->N2; fftsound->P=CONFIG_getDouble("pitch_shift"); /* Oscbank pitch factor */ fftsound->Pinc = fftsound->P*8192./fftsound->R; if (fftsound->P>1.){ fftsound->NP=fftsound->N2/fftsound->P; }else{ fftsound->NP=fftsound->N2; } fftsound->synt=CONFIG_getDouble("threshold")/fftsound->N; /* Synthesis threshold */ fftsound->binfreq = (double)fftsound->R/fftsound->N; fftsound->Nw2=fftsound->Nw>>1; fftsound->numchannels=fftsound->N/2+1; areaf2=fftsound->numchannels; fvec(fftsound->Wanal, fftsound->Nw); fvec(fftsound->Wsyn, fftsound->Nw); /* fvec(input, fftsound->Nw); fvec(buffer, fftsound->N); fvec(channel, fftsound->N+2); */ // init_again(); // fvec(tempamp,fftsound->numchannels); }
void triPack2polygons(coOutputPort **packageOutPort, coDoPolygons **package, trivec &triangles) { int tsize = triangles.size(); int num_coord = 3 * tsize; f2ten coord = f2ten(3); coord[0] = fvec(num_coord, 0.0); coord[1] = fvec(num_coord, 0.0); coord[2] = fvec(num_coord, 0.0); int num_conn = num_coord; ivec conn = ivec(num_conn); int num_poly = tsize; ivec poly = ivec(num_poly); int i = 0; for (; i < num_poly; i++) { poly[i] = 3 * i; } for (i = 0; i < num_conn; i++) { conn[i] = i; } for (i = 0; i < tsize; i++) { f2ten points = f2ten(2); points[0] = fvec(3, 0.0); points[1] = fvec(3, 0.0); points = (triangles[i]).getC2d(); int j = 0; for (; j < 3; j++) { coord[0][3 * i + j] = points[0][j]; coord[1][3 * i + j] = points[1][j]; } } //(*package) (*package) = new coDoPolygons((*packageOutPort)->getObjName(), num_coord, &coord[0][0], &coord[1][0], &coord[2][0], num_conn, &conn[0], num_poly, &poly[0]); (*packageOutPort)->setCurrentObject(*package); (*package)->addAttribute("vertexOrder", "2"); }
void *sampling_p(void *pargs) { int i; float *p = fvec(ddN.T * 4); D_MiSi_t dD; D_pargs_p *par =(D_pargs_p *) pargs; clock_t t1 = clock(); if ( PCTL_BURSTY() ) misi_init(&ddM,&dD); /* * sampling */ par->thislp = 0; par->thisNd = 0; while ( (i=atomic_incr(*par->doc)-1)<ddN.DT ) { if ( PCTL_BURSTY() ) misi_build(&dD,i,0); par->thislp += gibbs_lda(GibbsNone, i, ddD.N_dT[i], p, &dD); par->thisNd += ddD.N_dT[i]; if ( par->dots>0 && i>0 && (i%par->dots==0) ) yap_message("."); if ( PCTL_BURSTY() ) misi_unbuild(&dD,i,0); } free(p); if ( PCTL_BURSTY() ) misi_free(&dD); par->tot_time = (double)(clock() - t1) / CLOCKS_PER_SEC; return NULL; }
void Hypergraph::loadLayout(const QString &fileName) { ifstream layoutFile (fileName.toStdString().c_str(), ios::binary); layoutFile.read((char*)&_layoutDim, sizeof(int)); layoutFile.read((char*)&_nVertices, sizeof(int)); setNumOfVertices(_nVertices); int nEdges; layoutFile.read((char*)&nEdges, sizeof(int)); _edges.clear(); for (int i=0; i<nEdges; ++i) { int edgeSize; layoutFile.read((char*)&edgeSize, sizeof(int)); HyperEdge e (edgeSize); for (int j=0; j<edgeSize; ++j) { layoutFile.read((char*)&(e[j]), sizeof(int)); } _edges.push_back(e); } _layout.resize(_nVertices+nEdges); for(int i=0; i<_nVertices+nEdges; ++i) { _layout[i] = fvec(_layoutDim); layoutFile.read((char*)_layout[i].memptr(), _layoutDim*sizeof(float)); } layoutFile.close(); }
/* * global probability for topic: * taken from data if exists; * else from ddP.alphapr * else is 0 */ static float *globalprop() { float *vec = fvec(ddN.T); double tot = 0; int k; if ( !vec) return NULL; if ( ddS.Nwt ) { for (k=0; k<ddN.T; k++) { tot += vec[k] = ddS.NWt[k]; } } else if ( ddS.Ndt ) { /* have to total from Ndt */ int d; uint32_t *uvec = u32vec(ddN.T); for (d=0; d<ddN.DT; d++) { for (k=0; k<ddN.T; k++) uvec[k] += ddS.Ndt[d][k]; } for (k=0; k<ddN.T; k++) tot += vec[k] = uvec[k]; free(uvec); } else if ( ddP.alphapr ) { /* * this is rather poor, and should be rewritten */ for (k=0; k<ddN.T; k++) tot += vec[k] = ddP.alphapr[k]; } if ( tot <=0 ) return vec; for (k=0; k<ddN.T; k++) vec[k] /= tot; return vec; }
SPF::SPF(model_settings* model_set, Data* dataset) { settings = model_set; data = dataset; // user influence printf("\tinitializing user influence (tau)\n"); tau = sp_fmat(data->user_count(), data->user_count()); logtau = sp_fmat(data->user_count(), data->user_count()); a_tau = sp_fmat(data->user_count(), data->user_count()); b_tau = sp_fmat(data->user_count(), data->user_count()); // user preferences printf("\tinitializing user preferences (theta)\n"); theta = fmat(settings->k, data->user_count()); logtheta = fmat(settings->k, data->user_count()); a_theta = fmat(settings->k, data->user_count()); b_theta = fmat(settings->k, data->user_count()); // item attributes printf("\tinitializing item attributes (beta)\n"); printf("\t%d users and %d items\n", data->user_count(), data->item_count()); beta = fmat(settings->k, data->item_count()); logbeta = fmat(settings->k, data->item_count()); a_beta = fmat(settings->k, data->item_count()); a_beta_user = fmat(settings->k, data->item_count()); b_beta = fmat(settings->k, data->item_count()); delta = fvec(data->item_count()); a_delta = fvec(data->item_count()); b_delta = settings->b_delta + data->user_count(); a_delta_user = fvec(data->item_count()); // keep track of old a_beta and a_delta for SVI a_beta_old = fmat(settings->k, data->item_count()); a_beta_old.fill(settings->a_beta); a_delta_old = fvec(data->item_count()); a_delta_old.fill(settings->a_delta); printf("\tsetting random seed\n"); rand_gen = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(rand_gen, (long) settings->seed); // init the seed initialize_parameters(); scale = settings->svi ? data->user_count() / settings->sample_size : 1; }
//rotate an euclidean vector counter-clockwise fvec rotate(fvec a, float alpha) { fvec tmp = fvec(2, 0.0); tmp[0] = cos(alpha) * a[0] - sin(alpha) * a[1]; tmp[1] = sin(alpha) * a[0] + cos(alpha) * a[1]; return tmp; }
/**------------------------------------------------- * Make a quadrature given a Polynomial. * @param P :: A polynomial to use to make the quadrature. */ void MakeQuadrature::makeQuadrature(const Polynomial& P) { auto& r = P.getRoots(); auto& w = P.getWeights(); const size_t n = r.size(); auto quad = new Quadrature; quad->setRowCount( int(n) ); quad->addDoubleColumn("r", API::NumericColumn::X); auto& rc = quad->getDoubleData("r"); rc = r; quad->addDoubleColumn("w", API::NumericColumn::Y); auto& wc = quad->getDoubleData("w"); wc = w; FunctionDomain1DView domain( r ); FunctionValues values( domain ); std::vector<double> wgt; std::vector<double> wgtDeriv; P.weightFunction()->function( domain, values ); values.copyToStdVector( wgt ); P.weightDerivative()->function( domain, values ); values.copyToStdVector( wgtDeriv ); quad->addDoubleColumn("weight", API::NumericColumn::Y); auto& wgtc = quad->getDoubleData("weight"); wgtc = wgt; quad->addDoubleColumn("deriv", API::NumericColumn::Y); auto& derc = quad->getDoubleData("deriv"); derc = wgtDeriv; Quadrature::FuncVector fvec( n ); Quadrature::FuncVector dvec( n ); for(size_t i = 0; i < n; ++i) { std::string colInd = boost::lexical_cast<std::string>( i ); quad->addDoubleColumn("f"+colInd, API::NumericColumn::Y); fvec[i] = &quad->getDoubleData("f"+colInd); quad->addDoubleColumn("d"+colInd, API::NumericColumn::Y); dvec[i] = &quad->getDoubleData("d"+colInd); } P.calcPolyValues( fvec, dvec ); quad->init(); setClassProperty( "Quadrature", API::TableWorkspace_ptr( quad ) ); { const double startX = get("StartX"); const double endX = get("EndX"); ChebfunWorkspace_sptr cheb( new ChebfunWorkspace(chebfun( 100, startX, endX )) ); cheb->fun().fit( P ); setClassProperty("ChebWorkspace", cheb); } }
/************************************************* * build document proportions vec for topic k */ static float *docprop(int k) { float *vec = fvec(ddN.DT); int i; if ( !vec) return NULL; if ( ddP.theta ) { for (i=0; i<ddN.DT; i++) vec[i] = ddP.theta[i][k]; } else { for (i=0; i<ddN.DT; i++) vec[i] = ddS.Ndt[i][k] / (float)ddS.NdT[i]; } return vec; }
int FIRCoef (double *cf, int Len, double fl, double fh, double amp) { int i; double *Coef; double Sum, TmpFloat; int CoefNum, HalfLen, Cnt; fvec (Coef, 8192); CoefNum = Len; if (Len % 2 == 0) { CoefNum++; } HalfLen = (CoefNum - 1) / 2; Coef[HalfLen] = fh - fl; for (Cnt = 1; Cnt <= HalfLen; Cnt++) { TmpFloat = M_PI * Cnt; Coef[HalfLen + Cnt] = 2.0 * sin ((fh - fl) / 2.0 * TmpFloat) * cos ((fh + fl) / 2.0 * TmpFloat) / TmpFloat; Coef[HalfLen - Cnt] = Coef[HalfLen + Cnt]; } TmpFloat = 2.0 * M_PI / (CoefNum - 1.0); Sum = 0.0; for (Cnt = 0; Cnt < CoefNum; Cnt++) { Coef[Cnt] *= (0.54 - 0.46 * cos (TmpFloat * Cnt)); Sum += Coef[Cnt]; } for (Cnt = 0; Cnt < CoefNum; Cnt++) cf[Cnt] = cf[Cnt] + Coef[Cnt] * amp; free (Coef); return 0; }
fvec Hypergraph::getRepulsiveForce(fvec &pt1, fvec &pt2, float edgeLength) { int dim = pt1.n_elem; fvec d = pt2 - pt1; fvec disp; float normDSqr = dot(d,d); if (normDSqr<1.0e-6) { disp = fvec(dim); for (int iDim=0; iDim<dim; ++iDim) { disp(iDim) = rand()%100/100.0f; } disp *= edgeLength*edgeLength; } else { disp = d*edgeLength*edgeLength/normDSqr; } return disp; }
/************************************************* * build topic proportions vec for doc d */ static float *topprop(int d) { float *vec = fvec(ddN.T); double tot = 0; int k; if ( !vec) return NULL; if ( ddP.theta ) { for (k=0; k<ddN.T; k++) { assert( ddP.theta[d][k]>=0 ); tot += vec[k] = ddP.theta[d][k]; } } else { for (k=0; k<ddN.T; k++) { assert(ddS.Ndt[d][k]>=0); tot += vec[k] = ddS.Ndt[d][k]; } } if ( tot <=0 ) return vec; for (k=0; k<ddN.T; k++) vec[k] /= tot; return vec; }
void BFilterUKF::predict(){ //L=numel(x); //numer of states //m=numel(z); //numer of measurements unsigned int numStates = particles.samples.n_cols; float alpha=1.0f; //default 1e-3, tunable float kappa=0.0f; //default, tunable float beta=2.0f; //default, tunable //lambda=alpha^2*(L+kappa)-L; //scaling factor float lambda=alpha*alpha*(numStates+kappa)-numStates; //scaling factor float c=numStates+lambda; //scaling factor gamma //Wm=[lambda/c 0.5/c+zeros(1,2*L)]; //weights for means Wm=zeros<fmat>(1, 2*numStates+1) + (0.5f/c); //weights for means Wm(0)=lambda/c; Wc=Wm; Wc(0)=Wc(0)+(1-alpha*alpha+beta); //weights for covariance c=sqrt(c); fmat X=sigmas(fvec(particles.samples),P,c); //sigma points around x utProcess(X,Wm,Wc,numStates,process->Q); }
EndCriteria::Type LevenbergMarquardt::minimize(Problem& P, const EndCriteria& endCriteria) { EndCriteria::Type ecType = EndCriteria::None; P.reset(); Array x_ = P.currentValue(); currentProblem_ = &P; initCostValues_ = P.costFunction().values(x_); int m = initCostValues_.size(); int n = x_.size(); boost::scoped_array<double> xx(new double[n]); std::copy(x_.begin(), x_.end(), xx.get()); boost::scoped_array<double> fvec(new double[m]); boost::scoped_array<double> diag(new double[n]); int mode = 1; double factor = 1; int nprint = 0; int info = 0; int nfev =0; boost::scoped_array<double> fjac(new double[m*n]); int ldfjac = m; boost::scoped_array<int> ipvt(new int[n]); boost::scoped_array<double> qtf(new double[n]); boost::scoped_array<double> wa1(new double[n]); boost::scoped_array<double> wa2(new double[n]); boost::scoped_array<double> wa3(new double[n]); boost::scoped_array<double> wa4(new double[m]); // requirements; check here to get more detailed error messages. QL_REQUIRE(n > 0, "no variables given"); QL_REQUIRE(m >= n, "less functions (" << m << ") than available variables (" << n << ")"); QL_REQUIRE(endCriteria.functionEpsilon() >= 0.0, "negative f tolerance"); QL_REQUIRE(xtol_ >= 0.0, "negative x tolerance"); QL_REQUIRE(gtol_ >= 0.0, "negative g tolerance"); QL_REQUIRE(endCriteria.maxIterations() > 0, "null number of evaluations"); // call lmdif to minimize the sum of the squares of m functions // in n variables by the Levenberg-Marquardt algorithm. MINPACK::LmdifCostFunction lmdifCostFunction = boost::bind(&LevenbergMarquardt::fcn, this, _1, _2, _3, _4, _5); MINPACK::lmdif(m, n, xx.get(), fvec.get(), static_cast<double>(endCriteria.functionEpsilon()), static_cast<double>(xtol_), static_cast<double>(gtol_), static_cast<int>(endCriteria.maxIterations()), static_cast<double>(epsfcn_), diag.get(), mode, factor, nprint, &info, &nfev, fjac.get(), ldfjac, ipvt.get(), qtf.get(), wa1.get(), wa2.get(), wa3.get(), wa4.get(), lmdifCostFunction); info_ = info; // check requirements & endCriteria evaluation QL_REQUIRE(info != 0, "MINPACK: improper input parameters"); //QL_REQUIRE(info != 6, "MINPACK: ftol is too small. no further " // "reduction in the sum of squares " // "is possible."); if (info != 6) ecType = QuantLib::EndCriteria::StationaryFunctionValue; //QL_REQUIRE(info != 5, "MINPACK: number of calls to fcn has " // "reached or exceeded maxfev."); endCriteria.checkMaxIterations(nfev, ecType); QL_REQUIRE(info != 7, "MINPACK: xtol is too small. no further " "improvement in the approximate " "solution x is possible."); QL_REQUIRE(info != 8, "MINPACK: gtol is too small. fvec is " "orthogonal to the columns of the " "jacobian to machine precision."); // set problem std::copy(xx.get(), xx.get()+n, x_.begin()); P.setCurrentValue(x_); P.setFunctionValue(P.costFunction().value(x_)); return ecType; }
void Triangles::setC2d(const f2ten &c) { float temp = 0.0; float alpha = 0.0; float ab = 0.0; float ac = 0.0; //float bc = 0.0; fvec AB = fvec(3, 0); fvec AC = fvec(3, 0); //fvec BC = fvec(3, 0); c2d.resize(2); (c2d[0]).resize(4, 0.0); (c2d[1]).resize(4, 0.0); AB[0] = coord[0][1] - coord[0][0]; AB[1] = coord[1][1] - coord[1][0]; AB[2] = coord[2][1] - coord[2][0]; AC[0] = coord[0][2] - coord[0][0]; AC[1] = coord[1][2] - coord[1][0]; AC[2] = coord[2][2] - coord[2][0]; //BC[0] = coord[0][2] - coord[0][1]; //BC[1] = coord[1][2] - coord[1][1]; //BC[2] = coord[2][2] - coord[2][1]; ab = abs(AB); ac = abs(AC); //bc = abs(BC); temp = scalar_product(AB, AC); temp /= ab; temp /= ac; //now temp == cos(aplha) alpha = acos(temp); c2d[0][1] = ab; //c2d[1][1] = 0; c2d[0][2] = ac * temp; //temp = cos(alpha) c2d[1][2] = ac * sin(alpha); if (c2d[1][2] < 0.0) { c2d[1][2] *= (-1); } else ; /* { cout << "\nnew triangle:\n" << flush; cout << "-------------\n" << flush; for(int j = 0; j < 4; j++) { for(int i = 0; i < 2; i++) { cout << c2d[i][j] << flush << " " << flush; } cout << '\n'; } cout << "\n____________________\n" << flush; } */ }
void carbonDioxide(fvec &ePotential, f2ten &eField, float ucharge, float size, const f2ten &coord) { const int numPoints = (coord[0]).size(); const float rmin = fmax((size * 0.002), 0.00001); fvec c1 = fvec(3); c1[0] = size / 2; c1[1] = size / 2; c1[2] = 0; fvec o1 = fvec(3); o1[0] = c1[0] - size / 8; o1[1] = c1[1]; o1[2] = 0; fvec o2 = fvec(3); o2[0] = c1[0] + size / 8; o2[1] = c1[1]; o2[2] = 0; fvec elpot = fvec(numPoints); f2ten elfi = f2ten(3); { for (int j = 0; j < 3; j++) { elfi[j].resize(numPoints); } } { float rC1 = 0.0; float rO1 = 0.0; float rO2 = 0.0; float r3C1 = 0.0; float r3O1 = 0.0; float r3O2 = 0.0; fvec tmpC1 = fvec(3); fvec tmpO1 = fvec(3); fvec tmpO2 = fvec(3); for (int i = 0; i < numPoints; i++) { for (int j = 0; j < 3; j++) { tmpC1[j] = coord[j][i] - c1[j]; tmpO1[j] = coord[j][i] - o1[j]; tmpO2[j] = coord[j][i] - o2[j]; } rC1 = fmax(rmin, abs(tmpC1)); rO1 = fmax(rmin, abs(tmpO1)); rO2 = fmax(rmin, abs(tmpO2)); elpot[i] = ((-2.0) * ucharge / rC1) + (1.0 * ucharge / rO1) + (1.0 * ucharge / rO2); //electric potential r3C1 = pow(rC1, 3); r3O1 = pow(rO1, 3); r3O2 = pow(rO2, 3); for (int j = 0; j < 3; j++) { elfi[j][i] = ((2.0 * ucharge / r3C1) * (tmpC1[j])) + (((-1.0) * ucharge / r3O1) * (tmpO1[j])) + (((-2.0) * ucharge / r3O2) * (tmpO2[j])); } } } ePotential = elpot; eField = elfi; }
void oscbank( struct FFTSound *fftsound, struct RSynthData *rsd, double C[], int N,int R,int I, double O[], int ch,int Nw, double coef[], int Np, double a0 ) { // static int L = 8192, static int first = 1; static double *table; int amp, freq, n, chan; double Iinv; /* first pass: allocate memory for and compute cosine table */ if ( first ) { first = 0; fvec(table,L); for ( n = 0; n < L; n++ ) table[n] = N*cos( TwoPi*(double)n/L); } Iinv=1./I; /* for each channel, compute I samples using linear interpolation on the amplitude and frequency control values */ for ( chan = 0; chan < fftsound->NP; chan++ ) { double a, ainc, f, finc, address; freq = ( amp = ( chan << 1 ) ) + 1; C[freq] *= fftsound->Pinc; finc = ( C[freq] - ( f = rsd->lastfreq[ch][chan] ) )*Iinv; if (C[amp]<fftsound->synt) C[amp] = 0.; else if (Np) C[amp]*=lpamp(chan*fftsound->P*Pi/fftsound->N, a0, coef, Np)/ lpamp(chan*Pi/N, a0, coef, Np); ainc = ( C[amp] - ( a = rsd->lastamp[ch][chan] ) )*Iinv; address = rsd->indx[ch][chan]; /* accumulate the I samples from each oscillator into output array O (initially assumed to be zero); f is frequency in Hz scaled by oscillator increment factor and pitch (Pinc); a is amplitude; */ if (ainc!=0. || a !=0.) for ( n = 0; n < I; n++ ) { // O[n] += a*table[ (int) address ]; O[n] += a * (N*cos( TwoPi*address/L)); address += f; while ( address >= L ) address -= L; while ( address < 0 ) address += L; a += ainc; f += finc; } /* save current values for next iteration */ rsd->lastfreq[ch][chan] = C[freq]; rsd->lastamp[ch][chan] = C[amp]; rsd->indx[ch][chan] = address; } }
#include "scene.h" fvec scene::BACKGROUND = fvec( "0 0 0 1" ); mat rotation_matrix( const vec &a, double angle ) { // init cross-product mat cp( 3, 3 ); // zero out the response cp.zeros( 3, 3 ); vec na(a); // create a new rotation matrix mat rm( 3, 3 ); // zero out the response rm.zeros( 3, 3 ); // calculate cp cp( 0, 1 ) = -a( 2 ); cp( 1, 2 ) = -a( 0 ); cp( 2, 0 ) = -a( 1 ); cp( 0, 2 ) = a( 1 ); cp( 1, 0 ) = a( 2 ); cp( 2, 1 ) = a( 0 ); // calculate rotation matrix rm = ( cos( angle ) * eye( 3, 3 ) + 1 - cos( angle )) * a * a.t() + sin( angle ) * cp; return rm; } scene::scene( const vec &camera ) :
WORD FFTFtrAlo (SPDBLK FAR *lpSpdBlk, FFTBLK FAR *lpFFTBlk, EFFPOLPRC lpPolPrc, DWORD ulPolDat) { float flResRat; float FAR *lpWinBuf; LPCPXF lpXfrBuf; /********************************************************************/ /********************************************************************/ _fmemset (lpFFTBlk, 0, sizeof (*lpFFTBlk)); /********************************************************************/ /* Initialize FFT block */ /********************************************************************/ flResRat = lpSpdBlk->ulDstFrq / (float) lpSpdBlk->ulSrcFrq; ulDstFrq = lpSpdBlk->ulDstFrq; ulSrcFrq = lpSpdBlk->ulSrcFrq; flResRat = (float) 1; if (EffFFTAlo (lpSpdBlk->usFFTOrd, flResRat, lpFFTBlk, lpPolPrc, ulPolDat)) { SPDERRMSG ("Error setting FFT filter parameters.\n"); return ((WORD) -1); } /********************************************************************/ /* Initialize / allocate vocoder function block */ /********************************************************************/ if (EffVocAlo (lpSpdBlk->bfFrcOBS ? MSTVocOBS : NULL, &vbVocBlk, NULL, lpSpdBlk->usFFTOrd, lpSpdBlk->usWinOrd, lpSpdBlk->flSpdMul, lpSpdBlk->flPchMul, lpSpdBlk->flSynThr, lpSpdBlk->ulSrcFrq)) { if (TBxGlo.usDebFlg & ERR___DEB) MsgDspUsr ("Error allocating vocoder memory.\n"); EffFFTRel (lpFFTBlk); return (0); } /********************************************************************/ /* Lock data window memory, initialize */ /* Note: Data window is twice the FFT point size - overlap saved */ /********************************************************************/ if (NULL != (lpWinBuf = (float FAR *) GloMemLck (lpFFTBlk->mhWinHdl))) { EffWinGen (EFFWINTAP, lpWinBuf, 2 * lpFFTBlk->ulFFTPts); GloMemUnL (lpFFTBlk->mhWinHdl); } /********************************************************************/ /* Convert infinite length transfer functions into valid frequency */ /* domain filter. Lock FFT filter transfer buffer & window. */ /********************************************************************/ if (NULL != (lpXfrBuf = GloMemLck (lpFFTBlk->mhXfrHdl))) { EffWinRsp (EFFWINHAM, lpXfrBuf, lpFFTBlk->ulFFTPts); GloMemUnL (lpFFTBlk->mhXfrHdl); } fvec( Hwin, (INT) lpFFTBlk->ulFFTPts ) ; /* plain Hamming window */ fvec( Wanal,(INT) vbVocBlk.ulWinPts ) ; /* analysis window */ fvec( Wsyn, (INT) vbVocBlk.ulWinPts ) ; /* synthesis window */ makewindows (Hwin, Wanal, Wsyn, (INT) vbVocBlk.ulWinPts, (INT) lpFFTBlk->ulFFTPts, (INT) ulSrcFrq, 0); /********************************************************************/ /********************************************************************/ return (0); }
// read input examples vector<Example> read_input_examples(string input_filename, Sparm &sparm) { vector<Example> sample; std::string line; ifstream inputStream(input_filename.c_str()); size_t maxFeatureNum = 0; if (inputStream.fail()) { //cout << "Cannot read from input file " << input_filename << "!" << endl; cerr << "Cannot read from input file " << input_filename << "!" << endl; exit(1); } const vector<double>& qt_time = sparm.GetQuantTime(); while (!getline(inputStream, line, '\n').eof()) { // process line std::string::size_type lastPos = line.find_first_of(" \n",0); double survival_time = 0; survival_time = atof((line.substr(0, lastPos).c_str())); // censoring status std::string::size_type censoredPos = line.find_first_of(" \n", lastPos+1); int censoring_status = atoi(line.substr(lastPos+1,censoredPos-lastPos).c_str()); bool c; if (censoring_status==1) { c = true; } else { c= false; } lastPos = censoredPos; vector<pair<size_t,double> > feature_vec; std::string::size_type pos = line.find_first_of(':', lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { size_t i = (size_t) atoi((line.substr(lastPos, pos - lastPos).c_str())); lastPos = line.find_first_of(" \n", pos); double v = atof((line.substr(pos+1, lastPos - pos).c_str())); pos = line.find_first_of(':', lastPos); if (i>maxFeatureNum) maxFeatureNum = i; feature_vec.push_back(make_pair(i,v)); } SparseVector fvec(feature_vec); int n = 0; while ((n<sparm.GetMaxMonth())&&(survival_time>qt_time[n])) { n++; } sample.push_back(Example(fvec, n, c, survival_time)); } sparm.SetSizePsi(maxFeatureNum+1); inputStream.close(); return(sample); }
void Hypergraph::layoutPartitioned(int boundary [], bool bUpdate) { int dim = 2; int nIteration = bUpdate?50:500; float temperature = 10; typedef fvec2 LayoutPoint; srand(time(NULL)); int area = 1; for (int i=0; i<dim; ++i) { area *= boundary[2*i+1]-boundary[2*i]; } float k = 1.0*sqrt(area*1.0f/_nVertices); /*initialize vertex layout*/ int nEdges = _edges.size(); int nTotal = _nVertices+nEdges; _layout.resize(nTotal); vector<LayoutPoint> dispBuf (nTotal); if (!bUpdate) { for (int i=0; i<nTotal; ++i) { _layout[i] = fvec(dim); for (int j=0; j<dim; ++j) { _layout[i](j) = boundary[2*j]+rand()%(boundary[2*j+1]-boundary[2*j]); } dispBuf[i] = fvec(dim); } _pinWeights.resize(nTotal); _pinWeights.assign(nTotal, 1); } int nClusters = *max_element(_clusters.begin(), _clusters.end())+1; int nPartitions; vector<int> partitionSizes; getPartitionsByEdge(nPartitions, partitionSizes, _partitions); //getPartitionsByCluster(nPartitions, partitionSizes, _partitions); //getPartitionsByKDTree(nPartitions, partitionSizes, _partitions); vector<LayoutPoint> partCenters (nPartitions); vector<vector<int> > edgeBuf (_nVertices); for (int i=0; i<_edges.size(); ++i) { for (int j=0; j<_edges[i].size(); ++j) { edgeBuf[_edges[i][j]].push_back(i+_nVertices); } } int i,j; DWORD t0 = GetTickCount(); DWORD perItTime = 0; DWORD tReplInt = 0; DWORD tReplExt = 0; DWORD tAttr = 0; QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1); prog.setCancelButton(NULL); for (int it=0; it<nIteration; ++it) { DWORD t1 = GetTickCount(); bool bChanged = false; for (int i=0; i<nTotal; ++i) { dispBuf[i].fill(0); } for (int i=0; i<nPartitions; ++i) { partCenters[i].fill(0); for (int j=0; j<nTotal; ++j) { if (i!=_partitions[j]) { continue; } partCenters[i] += _layout[j]; } partCenters[i] /= partitionSizes[i]; } for (int i=0; i<nTotal; ++i) { if (_pinWeights[i]<1.0e-3) { continue; } float edgeLength = (i<_nVertices&&_clusters[i]==-1)?1.5*k:k; /*interior repulsive forces*/ DWORD t2 = GetTickCount(); for (int j=0; j<i; ++j) { if (_partitions[i]!=_partitions[j]) { continue; } int vertexIdx = j; fvec disp = getRepulsiveForce(_layout[i], _layout[j], k); dispBuf[i] -= disp; dispBuf[j] += disp; } tReplInt += GetTickCount() - t2; /*exterior repulsive forces*/ t2 = GetTickCount(); for (int j=0; j<nPartitions; ++j) { if (j==_partitions[i]) { continue; } if (partitionSizes[j]!=0) { fvec disp = partitionSizes[j]*getRepulsiveForce(_layout[i], partCenters[j], k); dispBuf[i] -= disp; } } tReplExt += GetTickCount() - t2; /*attractive forces*/ t2 = GetTickCount(); if (i<_nVertices) { for (int j=0; j<edgeBuf[i].size(); ++j) { int edgeIdx = edgeBuf[i][j]; fvec disp = getAttractiveForce(_layout[i], _layout[edgeIdx], edgeLength); dispBuf[i] += 3.0*disp; dispBuf[edgeIdx] -= 3.0*disp; } } tAttr += GetTickCount() - t2; } /*cooling*/ for (int i=0; i<nTotal; ++i) { /*adjust forces*/ for (int j=0; j<dim; ++j) { float c1=1.0e5; float x = _layout[i](j); float d = c1*(1.0/(x-boundary[j*2]+1.0e-3)-1.0/(boundary[j*2+1]-x+1.0e-3)); dispBuf[i](j) += d; } float n = norm(dispBuf[i],2); fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature*_pinWeights[i])/n; for (int j=0; j<dim; ++j) { int minBoundary = boundary[2*j]; int maxBoundary = boundary[2*j+1]; newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j)); } _layout[i] = newLayout; } perItTime += GetTickCount() - t1; prog.setValue(it); } DWORD totalTime = GetTickCount()-t0; tReplInt /= nIteration; tReplExt /= nIteration; tAttr /= nIteration; perItTime /= nIteration; return; }
void Hypergraph::layoutClustered(int boundary [], int nIteration, int dim/* =2 */, float c/* =1.0 */) { _layoutDim = dim; float temperature = 10; int nEdges = _edges.size(); int nTotal = _nVertices+nEdges; srand(time(NULL)); int area = 1; for (int i=0; i<dim; ++i) { area *= boundary[2*i+1]-boundary[2*i]; } float k = c*sqrt(area*1.0f/nTotal); /*initialize vertex layout*/ _layout.resize(nTotal); vector<fvec> dispBuf (nTotal); for (int i=0; i<nTotal; ++i) { _layout[i] = fvec(dim); for (int j=0; j<dim; ++j) { _layout[i](j) = boundary[2*j]+rand()%(boundary[2*j+1]-boundary[2*j]); } dispBuf[i] = fvec(dim); } int i,j; QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1); prog.setCancelButton(NULL); for (int it=0; it<nIteration; ++it) { DWORD t1 = GetTickCount(); bool bChanged = false; for (i=0; i<nTotal; ++i) { dispBuf[i].fill(0); } DWORD t2 = GetTickCount(); /*calculate repulsive force*/ for (i=0; i<nTotal; ++i) { int clusterI = i<_nVertices?_clusters[i]:i-_nVertices; for (j=0; j<i; ++j) { int clusterJ = j<_nVertices?_clusters[j]:j-_nVertices; float edgeLengthSqr = 1; if (i<_nVertices) { edgeLengthSqr = clusterI==clusterJ?1.5:4; } else { if (j<_nVertices) { edgeLengthSqr = clusterI==clusterJ?1:4; } else { edgeLengthSqr = 9; } } edgeLengthSqr*=k*k; fvec d = _layout[j]-_layout[i]; fvec disp; float normD = norm(d,2); if (normD<1.0e-5) { disp = fvec(dim); for (int iDim=0; iDim<dim; ++iDim) { disp(iDim) = rand()%100/100.0f; } disp *= temperature; } else { //disp = d*k*k/pow(normD,2); disp = edgeLengthSqr/pow(normD, 2)*d; } dispBuf[j] += disp; dispBuf[i] -= disp; } } DWORD tRepForce = GetTickCount()-t2; /*calculate attractive force*/ for (i=0; i<_edges.size(); ++i) { int edgeIdx = i+_nVertices; for (j=0; j<_edges[i].size(); ++j) { float c2 = 10; float edgeLengthSqr = _clusters[_edges[i][j]]==i?1:9.0; edgeLengthSqr *= k; fvec d = _layout[edgeIdx] - _layout[_edges[i][j]]; fvec disp = c2*d*norm(d,2)/edgeLengthSqr; dispBuf[edgeIdx] -= disp; dispBuf[_edges[i][j]] += disp; /*for (int m=0; m<j; ++m) { if (m==j) { continue; } float edgeLengthSqr = _clusters[_edges[i][j]]==_clusters[_edges[i][m]]?1:16.0; edgeLengthSqr *= k; fvec d = _layout[_edges[i][m]] - _layout[_edges[i][j]]; fvec disp = c2*d*norm(d,2)/edgeLengthSqr; dispBuf[_edges[i][m]] -= disp; dispBuf[_edges[i][j]] += disp; }*/ } } DWORD tRepAttrForces = GetTickCount()-t2; /*restrict the points from being pushed towards the boundary*/ for (i=0; i<nTotal; ++i) { for (j=0; j<dim; ++j) { float c1=1.0e6; float x = _layout[i](j); if (x==boundary[j*2] || x==boundary[j*2+1]) { int stop = 1; } float d = c1*(1/(x-boundary[j*2]+1.0e-3)-1/(boundary[j*2+1]-x+1.0e-3)); dispBuf[i](j) += d; } } /*limit the maximum displacement, boundary check*/ for (i=0; i<nTotal; ++i) { float n = norm(dispBuf[i],2); fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature)/n; for (j=0; j<dim; ++j) { int minBoundary = boundary[2*j]; int maxBoundary = boundary[2*j+1]; newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j)); } if (norm(newLayout-_layout[i], 2)>1.0e-3) { _layout[i] = newLayout; bChanged = true; } } if (!bChanged) { break; } DWORD perItTime = GetTickCount() - t1; t1 = GetTickCount(); prog.setValue(it); } }
/*********************************************************************** Vocoder: tratto da Ceres di ([email protected]) ***********************************************************************/ ULONG WavVocoder (PCSZ name, LONG argc, const RXSTRING * argv, PCSZ queuename, PRXSTRING retstr) { PSHORT pCh, pCh2, ptemp; APIRET rc; int i, frame, FDec, nCamp; int campioni, puntifft, Kn2, Koverlap; double soglia; if (argc != 4) { SendMsg (FUNC_VOCODER, ERR_NUMERO_PARAMETRI); return INVALID_ROUTINE; } if (!sscanf (argv[0].strptr, "%d", &pCh)) { SendMsg (FUNC_VOCODER, ERR_PUNTATORE_ERRATO); return INVALID_ROUTINE; } if (!sscanf (argv[1].strptr, "%d", &pCh2)) { SendMsg (FUNC_VOCODER, ERR_PUNTATORE_ERRATO); return INVALID_ROUTINE; } nCamp = atol (argv[2].strptr); if (nCamp < 1) { SendMsg (FUNC_VOCODER, ERR_VALORE_INVALIDO); return INVALID_ROUTINE; } pCh = (PSHORT) AllineaCh (pCh, (ULONG) nCamp, FUNC_VOCODER); if (!pCh) return INVALID_ROUTINE; pCh2 = (PSHORT) AllineaCh (pCh2, (ULONG) nCamp, FUNC_VOCODER); if (!pCh2) return INVALID_ROUTINE; soglia = atof (argv[3].strptr) / 1000000; if ((soglia < 0) | (soglia > 1)) { SendMsg (FUNC_VOCODER, ERR_VALORE_INVALIDO); return INVALID_ROUTINE; } fvec (inout, K_PUNTI); fvec (buffer, K_PUNTI); fvec (dativoc, K_PUNTI); fvec (WAnalisi, K_PUNTI); fvec (WSintesi, K_PUNTI); campioni = K_PUNTI; puntifft = K_PUNTI / 2; Kn2 = K_PUNTI / 2; Koverlap = 2; FDec = campioni / Koverlap; makewindows (WAnalisi, WSintesi, campioni, campioni, FDec); for (frame = 0; frame < (10 * nCamp / K_PUNTI); frame++) { for (i = 0; i < campioni; i++) inout[i] = (double) *pCh++ / (double) MAX_CAMPIONE; fold (inout, WAnalisi, campioni, buffer, campioni, frame * campioni); for (i = 0; i < campioni; i++) inout[i] = (double) 0; /* */ rfft (buffer, puntifft, FORWARD); convert (buffer, dativoc, Kn2, FDec, FreqCamp, 1); /* if(frame==100) for (i=0; i<Kn2; i++) { printf("freq %f, amp %f\n", dativoc[i+i+1], dativoc[i+i] * 1000); } */ for (i = 0; i < Kn2; i++) { if (dativoc[i + i] < soglia) dativoc[i + i] = 0; } unconvert (dativoc, buffer, Kn2, FDec, FreqCamp, 1); rfft (buffer, puntifft, INVERSE); overlapadd (buffer, campioni, WSintesi, inout, campioni, frame * campioni); for (i = 0; i < campioni; i++) *pCh2++ = *pCh2 + (SHORT) (inout[i] * MAX_CAMPIONE); pCh = pCh - (SHORT) (K_PUNTI * 0.9); pCh2 = pCh2 - (SHORT) (K_PUNTI * 0.9); } free (inout); free (buffer); free (dativoc); free (WAnalisi); free (WSintesi); sprintf (retstr->strptr, "%f", ERR_OK); retstr->strlength = strlen (retstr->strptr); return VALID_ROUTINE; }
void Triangles::normaliseC2d() { ///////////////////////////////////////////////////////////////////// float temp = 0.0; float alpha = 0.0; float minus_alpha = 0.0; //for clockwise rotations float ab = 0.0; float ac = 0.0; float bc = 0.0; fvec AB = fvec(2, 0); fvec AC = fvec(2, 0); fvec BC = fvec(2, 0); f2ten cnew = f2ten(2); (cnew[0]).resize(4, 0); (cnew[1]).resize(4, 0); fvec old = fvec(2, 0); ivec edge_order(3, 0); ///////////////////////////////////////////////////////////////////// AB[0] = c2d[0][1] - c2d[0][0]; AB[1] = c2d[1][1] - c2d[1][0]; AC[0] = c2d[0][2] - c2d[0][0]; AC[1] = c2d[1][2] - c2d[1][0]; BC[0] = c2d[0][2] - c2d[0][1]; BC[1] = c2d[1][2] - c2d[1][1]; ab = abs(AB); ac = abs(AC); bc = abs(BC); edge_order = edgeOrder(edge_order, ab, ac, bc); cnew = c2d; ///////////////////////////////////////////////////////////////////// //AB is the longest edge, e.g. edge_order[0]=1 ! if (edge_order[0] == 1) { //cout << "\nlongest edge: 1, " << flush; //AC shortest ? if ((edge_order[1] == 2) && (edge_order[2] == 3)) { //cout << "the second is 2\n" << flush; //ABC c2d[0][3] = 1.0; c2d[1][3] = 1.0; } else if ((edge_order[1] == 3) && (edge_order[2] == 2)) { //cout << "the second is 3\n" << flush; //BAC c2d = triXflect(c2d, 1, 1); c2d[0][3] = 2.0; c2d[1][3] = -1.0; } else { cout << "\n... unexpected situation occured in" << flush; cout << "\nsetting edge order of triangles ...\n" << flush; } } //BC ist the longest edge else if (edge_order[0] == 2) { //cout << "\nlongest edge: 2, " << flush; old[0] = 1.0; old[1] = 0.0; temp = scalar_product(old, BC); temp /= bc; alpha = acos(temp); minus_alpha = (-1) * alpha; c2d = triXshift(c2d, c2d[0][1]); old[0] = c2d[0][0]; old[1] = c2d[1][0]; old = rotate(old, minus_alpha); c2d[0][0] = old[0]; c2d[1][0] = old[0]; c2d[0][1] = 0.0; c2d[1][1] = 0.0; c2d[0][2] = bc; c2d[1][2] = 0.0; //AB shortest ? if ((edge_order[1] == 3) && (edge_order[2] == 1)) { //cout << "the second is 3\n" << flush;//BAC //BCA c2d[0][3] = 2.0; c2d[1][3] = 1.0; } else if ((edge_order[1] == 1) && (edge_order[2] == 3)) { //cout << "the second is 1\n" << flush;//BAC //CBA c2d = triXflect(c2d, 2, 1); c2d[0][3] = 3.0; c2d[1][3] = -1.0; } else { cout << "\n... unexpected situation occured in" << flush; cout << "\nsetting edge order of triangles ...\n" << flush; } } //AC or CA ist the longest edge else if (edge_order[0] == 3) { //cout << "\nlongest edge: 3, " << flush; old[0] = 1.0; old[1] = 0.0; fvec tmp = fvec(2, 0.0); tmp[0] = (-1) * AC[0]; tmp[1] = (-1) * AC[1]; //tmp = CA wanted!! temp = scalar_product(tmp, old); temp /= ac; alpha = acos(temp); c2d = triShift(c2d, AC); c2d[0][2] = 0.0; c2d[1][2] = 0.0; c2d[0][0] = ac; c2d[1][0] = 0.0; old[0] = c2d[0][1]; old[1] = c2d[1][1]; old = rotate(old, alpha); c2d[0][1] = old[0]; c2d[1][1] = old[1]; //BC shortest ? if ((edge_order[1] == 1) && (edge_order[2] == 2)) { //cout << "the second is 1\n" << flush; //CAB c2d[0][3] = 3.0; c2d[1][3] = 1.0; } else if ((edge_order[1] == 2) && (edge_order[2] == 1)) { //cout << "the second is 2\n" << flush; //ACB c2d = triXflect(c2d, 3, 1); c2d[0][3] = 1.0; c2d[1][3] = -1.0; } else { cout << "\n... unexpected situation occured in" << flush; cout << "\nsetting edge order of triangles ...\n" << flush; } } else { cout << "\n... unexpected situation occured in" << flush; cout << "\nsetting edge order of triangles ...\n" << flush; } }
/* * print out the topic topk=10 words. report the PMI score. */ double report_pmi(char *topfile, /* name of topics file */ char *pmifile, /* name of PMI file */ int T, /* total topics */ int W, /* total words */ int E, /* number of epochs */ int topk, double *tp) { int lineno = 0; int i,k, thee; /* * mapping from local index to actual word index */ uint32_t *wind = u32vec(topk*T*E); int n_wind = 0; /* * boolean vector ... is word used */ uint32_t *wuse = u32vec(W/32+1); /* * PMI's by local index */ uint32_t *topic = u32vec(topk); float *coherency = fvec(E); double **pmi; float ave = 0; char *line; size_t n_line; FILE *fr; if ( !wind || !wuse ) yap_quit("Out of memory in report_pmi()\n"); /* * read in file of top word indices in topic */ fr = fopen(topfile,"r"); if ( !fr ) yap_sysquit("Topic file '%s' not read\n", topfile); line = NULL; n_line = 0; lineno = 0; while ( getline(&line, &n_line, fr)>0 ) { char *buf = line; unsigned j; int e = 0; lineno ++; buf += strspn(buf," \t\n"); // skip space if ( (E==1 && sscanf(buf, "%d: ", &k)<1) || (E>1 && sscanf(buf, "%d,%d: ", &e, &k)<2) ) yap_quit("Cannot read topic in topic line %d from file '%s'\n", lineno, topfile); if ( k<0 || k>=T ) continue; if ( e<0 || e>=E ) continue; for (i = 0; i<topk && *buf; i++) { buf = strpbrk(buf," \t\n"); // skip to next space if ( sscanf(buf, " %u", &j) <1 ) { if ( verbose>2 ) yap_message("Cannot read word %d in topic line %d from file '%s'\n", i+1, lineno, topfile); break; } if ( j>=W) { yap_quit("Bad word %d in topic line %d from file '%s'\n", i+1, lineno, topfile); } buf += strspn(buf," \t\n"); // skip space /* * check if word exists, and set up its index */ if ( wuse[j/32U] & (1U<<(j%32U)) ) { // yes, so search for it int ii; for (ii=0; ii<n_wind; ii++) if ( wind[ii]==j ) break; if ( ii>=n_wind ) yap_quit("Lookup of word %d failed at line %d in report_pmi()\n", (int)j, lineno); } else { // no, so add it wuse[j/32U] |= (1U<<(j%32U)); wind[n_wind] = j; n_wind++; } } free(line); line = NULL; n_line = 0; } fclose(fr); pmi = dmat(n_wind,n_wind); /* * build hash table now since we know size */ hashsize = n_wind*2; hashtab = malloc(sizeof(*hashtab)*hashsize); if ( !pmi || !hashtab ) yap_quit("Out of memory in report_pmi()\n"); for (i=0; i<hashsize; i++) hashtab[i] = 0; for (i=0; i<n_wind; i++) addw(wind[i],i); /* * load up PMI file, only keeping words mentioned in hash table */ { unsigned t1, t2; double value; int zcat = 0; fr = fopen(pmifile,"r"); if ( !fr ) { /* * try to zcat it */ char *cmd = malloc(strlen(pmifile)+20); sprintf(cmd,"%s.gz", pmifile); fr = fopen(cmd,"r"); if ( !fr ) yap_sysquit("Cannot open pmifile '%s' in report_pmi()\n", pmifile); fclose(fr); sprintf(cmd,"gunzip -c %s", pmifile); fr = popen(cmd,"r"); if ( !fr ) yap_sysquit("Cannot open or zcat pmifile '%s' in report_pmi()\n", pmifile); zcat = 1; free(cmd); } while (fscanf(fr, "%u %u %lg", &t1, &t2, &value)==3 ) { if ( t1>=W || t2>= W ) yap_quit("Illegal word index in report_pmi()\n"); if ( t1!= t2 && ( wuse[t1/32U] & (1U<<(t1%32U)) ) && ( wuse[t2/32U] & (1U<<(t2%32U))) ) { int i1, i2; i1 = findw(t1,wind); i2 = findw(t2,wind); if ( i1==UINT32_MAX || i2==UINT32_MAX ) yap_quit("Could not locate word index in report_pmi()\n"); pmi[i1][i2]=value; pmi[i2][i1]=value; } } if ( zcat ) pclose(fr); else fclose(fr); } /* * compute PMI score for each topic */ fr = fopen(topfile,"r"); if ( !fr ) yap_sysquit("Topic file '%s' not read\n", topfile); line = NULL; n_line = 0; thee = 0; lineno = 0; if ( E>1 ) yap_message("PMI %d:: ", 0); else yap_message("PMI :: "); while ( getline(&line, &n_line, fr)>0 ) { /* * repeat logic above to read topic file again */ char *buf = line; unsigned j; int cnt = 0; int e = 0; double coh = 0; buf += strspn(buf," \t\n"); // skip space if ( (E==1 && sscanf(buf, "%d: ", &k)<1) || (E>1 && sscanf(buf, "%d,%d: ", &e, &k)<2) ) yap_quit("Cannot read topic in topic line %d from file '%s'\n", lineno, topfile); if ( k<0 || k>=T ) continue; if ( e<0 || e>=E ) continue; if ( e!=thee ) { thee = e; yap_message("\nPMI %d:: ", e); } for (i = 0; i<topk && *buf; i++) { buf = strpbrk(buf," \t\n"); // skip to next space if ( sscanf(buf, " %u", &j) <1 ) { yap_message("Cannot read word %d in topic line %d from file '%s'\n", i+1, lineno, topfile); break; } if ( j>=W) { yap_quit("Bad word %d in topic line %d from file '%s'\n", i+1, lineno, topfile); } buf += strspn(buf," \t\n"); // skip space topic[i] = findw(j,wind); } if ( i<topk ) topic[i] = W; /* * topics now read */ for (i=0; i<topk && topic[i]<W; i++) { for (j=i+1; j<topk && topic[j]<W; j++) { coh += pmi[topic[i]][topic[j]]; cnt ++; } } if ( cnt>0 ) coh /= cnt; coherency[e] += coh * tp[k]; yap_message(" %d:%.3lf", k, coh); } fclose(fr); yap_message("\nPMI ="); if ( E==1 ) { yap_message(" %.3lf\n", coherency[0]); ave = coherency[0]; } else { int e; for (e=0; e<E; e++) { ave += coherency[e]; yap_message(" %.3lf", coherency[e]); } ave /= E; yap_message(" -> %.3lf\n", ave); } free(wind); free(coherency); free(wuse); free(topic); free(pmi[0]); free(pmi); free(hashtab); hashtab = NULL; hashsize = 0; return ave; }
void Hypergraph::layoutFast(int boundary [], int dim, float c, int Vmax, int Smax, int nIteration) { _layoutDim = dim; float temperature = 10; srand(time(NULL)); int area = 1; for (int i=0; i<dim; ++i) { area *= boundary[2*i+1]-boundary[2*i]; } float k = c*sqrt(area*1.0f/_nVertices); /*initialize vertex layout*/ int nEdges = _edges.size(); int nTotal = _nVertices+nEdges; _layout.resize(nTotal); vector<fvec> dispBuf (nTotal); for (int i=0; i<nTotal; ++i) { _layout[i] = fvec(dim); for (int j=0; j<dim; ++j) { _layout[i](j) = boundary[2*j]+rand()%(boundary[2*j+1]-boundary[2*j]); } dispBuf[i] = fvec(dim); } int i,j; vector<list<int> > sampleBufs (nTotal); vector<int> Vsizes (nTotal); vector<float> maxDists (nTotal); maxDists.assign(nTotal, 40); /*initialize distance matrix*/ vector<float> distMat (nTotal*(nTotal-1)/2); distMat.assign(nTotal*(nTotal-1)/2, 50); for (int i=0; i<nEdges; ++i) { int edgeIdx = i+_nVertices; for (int j=0; j<_edges[i].size(); ++j) { int n1 = _edges[i][j]; for (int k=0; k<j; ++k) { int n2 = _edges[i][k]; distMat[n1*(n1-1)/2+n2] = 20; } distMat[edgeIdx*(edgeIdx-1)/2+n1] = 10; } } QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1); prog.setCancelButton(NULL); for (int it=0; it<nIteration; ++it) { DWORD t1 = GetTickCount(); bool bChanged = false; for (i=0; i<nTotal; ++i) { dispBuf[i].fill(0); } DWORD t2 = GetTickCount(); DWORD tFindSample = 0; for (i=0; i<nTotal; ++i) { DWORD t3 = GetTickCount(); findSampleSets(i, maxDists[i], distMat, sampleBufs[i], Vsizes[i], Vmax, Smax); list<int> &sampleBuf = sampleBufs[i]; tFindSample += GetTickCount()-t3; //for (j=0; j<sampleBuf.size(); ++j) for (list<int>::iterator sampleIt = sampleBuf.begin(); sampleIt!=sampleBuf.end(); ++sampleIt) { int sampleIdx = *sampleIt; ++sampleIt; float dist = *sampleIt; if (sampleIdx==i) { continue; } fvec d = _layout[sampleIdx]-_layout[i]; float normD = norm(d,2); /*calculate repulsive force*/ fvec dispRepulsive; if (normD<1.0e-5) { dispRepulsive = fvec(dim); for (int iDim=0; iDim<dim; ++iDim) { dispRepulsive(iDim) = rand()%100/100.0f; } dispRepulsive *= temperature; } else { dispRepulsive = d*k*k/pow(normD,2); } dispBuf[i] -= dispRepulsive; dispBuf[sampleIdx] += dispRepulsive; /*calculate attractive force*/ //float dist = i>sampleIdx?distMat[i*(i-1)/2+sampleIdx]:distMat[sampleIdx*(sampleIdx-1)/2+i]; /*if (dist<50) { float c3 = dist<15?3.0:1.0; fvec dispAttractive = c3*d*normD/k; dispBuf[i] += dispAttractive; dispBuf[sampleIdx] -= dispAttractive; }*/ } } DWORD tRepAttrForces = GetTickCount()-t2; /*restrict the points from being pushed towards the boundary*/ t2 = GetTickCount(); for (i=0; i<nTotal; ++i) { for (j=0; j<dim; ++j) { float c1=1.0e6; float x = _layout[i](j); if (x==boundary[j*2] || x==boundary[j*2+1]) { int stop = 1; } float d = c1*(1/(x-boundary[j*2]+1.0e-3)-1/(boundary[j*2+1]-x+1.0e-3)); dispBuf[i](j) += d; } } DWORD tBoundaries = GetTickCount()-t2; /*limit the maximum displacement, boundary check*/ t2 = GetTickCount(); for (i=0; i<nTotal; ++i) { float n = norm(dispBuf[i],2); fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature)/n; for (j=0; j<dim; ++j) { int minBoundary = boundary[2*j]; int maxBoundary = boundary[2*j+1]; newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j)); } } DWORD tLimits = GetTickCount()-t2; DWORD perItTime = GetTickCount() - t1; t1 = GetTickCount(); prog.setValue(it); } }
/* This version is nearly 3 times faster. (38s / 105s) */ void oscbank( struct FFTSound *fftsound, struct RSynthData *rsd, double C[], int N,int R,int I, double O[], int ch,int Nw, double coef[], int Np, double a0 ) { // static int L = 8192, static int first = 1; static double *table; int amp, freq, n, chan; double Iinv; int address1=0; int address2=0; /* first pass: allocate memory for and compute cosine table */ if ( first ) { first = 0; fvec(table,L); for ( n = 0; n < L; n++ ){ table[n] = (double)(N*cos( TwoPi*(double)n/L)); } } Iinv=1./I; /* for each channel, compute I samples using linear interpolation on the amplitude and frequency control values */ for ( chan = 0; chan < fftsound->NP; chan++ ) { double a, ainc, f, finc, address; freq = ( amp = ( chan << 1 ) ) + 1; C[freq] *= fftsound->Pinc; finc = ( C[freq] - ( f = rsd->lastfreq[ch][chan] ) )*Iinv; if (C[amp]<fftsound->synt){ C[amp] = 0.; }else{ if (Np){ C[amp]*=lpamp(chan*fftsound->P*Pi/N, a0, coef, Np)/ lpamp(chan*Pi/N, a0, coef, Np); } } ainc = ( C[amp] - ( a = rsd->lastamp[ch][chan] ) )*Iinv; address = rsd->indx[ch][chan]; /* accumulate the I samples from each oscillator into output array O (initially assumed to be zero); f is frequency in Hz scaled by oscillator increment factor and pitch (Pinc); a is amplitude; */ address1=(int)address; address2=(int)((address-(float)address1)*MAXL); if (ainc!=0. || a !=0.){ int f1=(int)f; int f2=(int)(((f-(float)f1)*MAXL)); int finc1=(int)finc; int finc2=(int)((finc-(float)finc1)*MAXL); for ( n = 0; n < I; n++ ) { O[n] += a*table[address1]; // O[n] += a*table[ (int) address ]; address1+=f1; address2+=f2; if(address2>=MAXL){ address1++; address2-=MAXL; }else{ if(address2<0){ address1--; address2+=MAXL; } } // address += f; while ( address1 >= L ) address1 -= L; while ( address1 < 0 ) address1 += L; a += ainc; f1+=finc1; f2+=finc2; if(f2>=MAXL){ f1++; f2-=MAXL; }else{ if(f2<0){ f1--; f2+=MAXL; } } // a += ainc; // f += finc; } } /* save current values for next iteration */ rsd->lastfreq[ch][chan] = C[freq]; rsd->lastamp[ch][chan] = C[amp]; rsd->indx[ch][chan] = (float)address1+(address2/(float)MAXL); // indx[chan] = (float)address1+(address2/(float)MAXL); } //end for ( chan = 0; chan < fftsound->NP; chan++ ) { }
void Hypergraph::layoutGraph( int boundary [], int dim/*=2*/, float c/*=1.0*/ ) { _layoutDim = dim; int nIteration = 500; float temperature = 10; srand(time(NULL)); int area = 1; for (int i=0; i<dim; ++i) { area *= boundary[2*i+1]-boundary[2*i]; } float k = c*sqrt(area*1.0f/_nVertices); /*initialize vertex layout*/ int nEdges = _edges.size(); int nTotal = _nVertices+nEdges; _layout.resize(nTotal); vector<fvec> dispBuf (nTotal); for (int i=0; i<nTotal; ++i) { _layout[i] = fvec(dim); for (int j=0; j<dim; ++j) { _layout[i](j) = boundary[2*j]+rand()%(boundary[2*j+1]-boundary[2*j]); } dispBuf[i] = fvec(dim); } int i,j; QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1); prog.setCancelButton(NULL); for (int it=0; it<nIteration; ++it) { DWORD t1 = GetTickCount(); bool bChanged = false; for (i=0; i<nTotal; ++i) { dispBuf[i].fill(0); } DWORD t2 = GetTickCount(); /*calculate repulsive force*/ for (i=0; i<nTotal; ++i) { for (j=0; j<i; ++j) { if (j==i) { continue; } fvec disp = getRepulsiveForce(_layout[i], _layout[j], k); dispBuf[j] += disp; dispBuf[i] -= disp; } } DWORD tRepForce = GetTickCount()-t2; /*calculate attractive force*/ for (i=0; i<_edges.size(); ++i) { int edgeIdx = i+_nVertices; for (j=0; j<_edges[i].size(); ++j) { float c2 = 300.0; fvec disp1 = c2*getAttractiveForce(_layout[_edges[i][j]], _layout[edgeIdx], k); dispBuf[edgeIdx] -= disp1; dispBuf[_edges[i][j]] += disp1; } } DWORD tRepAttrForces = GetTickCount()-t2; /*restrict the points from being pushed towards the boundary*/ for (i=0; i<nTotal; ++i) { for (j=0; j<dim; ++j) { float c1=1.0e6; float x = _layout[i](j); if (x==boundary[j*2] || x==boundary[j*2+1]) { int stop = 1; } float d = c1*(1/(x-boundary[j*2]+1.0e-3)-1/(boundary[j*2+1]-x+1.0e-3)); dispBuf[i](j) += d; } } /*limit the maximum displacement, boundary check*/ for (i=0; i<nTotal; ++i) { float n = norm(dispBuf[i],2); fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature)/n; for (j=0; j<dim; ++j) { int minBoundary = boundary[2*j]; int maxBoundary = boundary[2*j+1]; newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j)); } if (norm(newLayout-_layout[i], 2)>1.0e-3) { _layout[i] = newLayout; bChanged = true; } } if (!bChanged) { break; } DWORD perItTime = GetTickCount() - t1; t1 = GetTickCount(); prog.setValue(it); } }
void Hypergraph::updateLayout(const vector<int> &changedSet, int boundary [], int dim, float c) { _layoutDim = dim; int nIteration = 500; float temperature = 10; srand(time(NULL)); int area = 1; for (int i=0; i<dim; ++i) { area *= boundary[2*i+1]-boundary[2*i]; } float k = c*sqrt(area*1.0f/_nVertices); int nEdges = _edges.size(); int nTotal = _nVertices+nEdges; vector<fvec> dispBuf (nTotal); for (int i=0; i<nTotal; ++i) { dispBuf[i] = fvec(dim); } int i,j; vector<bool> bMovable (nTotal); for (i=0; i<changedSet.size(); ++i) { bMovable[changedSet[i]] = true; } QProgressDialog prog ("Performing graph layout ...", "", 0, nIteration-1); prog.setCancelButton(NULL); for (int it=0; it<nIteration; ++it) { DWORD t1 = GetTickCount(); bool bChanged = false; for (i=0; i<nTotal; ++i) { dispBuf[i].fill(0); } DWORD t2 = GetTickCount(); /*calculate repulsive force*/ for (i=0; i<changedSet.size(); ++i) { int idx = changedSet[i]; for (j=0; j<nTotal; ++j) { if (j==idx) { continue; } fvec d = _layout[j]-_layout[idx]; fvec disp; float normD = norm(d,2); if (normD<1.0e-5) { disp = fvec(dim); for (int iDim=0; iDim<dim; ++iDim) { disp(iDim) = rand()%100/100.0f; } disp *= temperature; } else { disp = d*k*k/pow(normD,2); } dispBuf[idx] -= disp; } } DWORD tRepForce = GetTickCount()-t2; /*calculate attractive force*/ for (i=0; i<_edges.size(); ++i) { int edgeIdx = i+_nVertices; for (j=0; j<_edges[i].size(); ++j) { if (!bMovable[_edges[i][j]]) { continue; } float c2 = 3.0; fvec d1 = _layout[edgeIdx] - _layout[_edges[i][j]]; fvec disp1 = c2*d1*norm(d1,2)/k; dispBuf[edgeIdx] -= disp1; dispBuf[_edges[i][j]] += disp1; for (int m=0; m<_edges[i].size(); ++m) { if (m==j) { continue; } fvec d = _layout[_edges[i][m]] - _layout[_edges[i][j]]; fvec disp = d*norm(d,2)/k; dispBuf[_edges[i][j]] += disp; } } } DWORD tRepAttrForces = GetTickCount()-t2; /*restrict the points from being pushed towards the boundary*/ for (i=0; i<nTotal; ++i) { if (!bMovable[i]) { continue; } for (j=0; j<dim; ++j) { float c1=1.0e6; float x = _layout[i](j); if (x==boundary[j*2] || x==boundary[j*2+1]) { int stop = 1; } float d = c1*(1/(x-boundary[j*2]+1.0e-3)-1/(boundary[j*2+1]-x+1.0e-3)); dispBuf[i](j) += d; } } /*limit the maximum displacement, boundary check*/ for (i=0; i<nTotal; ++i) { if (!bMovable[i]) { continue; } float n = norm(dispBuf[i],2); fvec newLayout = _layout[i]+dispBuf[i]*min(n, temperature)/n; for (j=0; j<dim; ++j) { int minBoundary = boundary[2*j]; int maxBoundary = boundary[2*j+1]; newLayout(j) = newLayout(j) < minBoundary?minBoundary:(newLayout(j)>maxBoundary?maxBoundary:newLayout(j)); } if (norm(newLayout-_layout[i], 2)>1.0e-3) { _layout[i] = newLayout; bChanged = true; } } if (!bChanged) { break; } DWORD perItTime = GetTickCount() - t1; t1 = GetTickCount(); prog.setValue(it); } }
/*********************************************************************** FIR: filtro a risposta finita all'impulso Vuole il puntatore ad una traccia gia' allocate, la durata in campioni, uno stem con i valori di ampiezza per ciascuna banda ***********************************************************************/ ULONG WavGraphEQ (PCSZ name, LONG argc, const RXSTRING * argv, PCSZ queuename, PRXSTRING retstr) { PSHORT pCh = NULL; ULONG nCamp, nbandeF; float tmp; double ampBanda[MAX], *coef; RXSTEMDATA bandeFreq; double sum, fh, fl; INT i, j, nCoeff; APIRET rc; if (argc != 3) { SendMsg (FUNC_GRAPHEQ, ERR_NUMERO_PARAMETRI); return INVALID_ROUTINE; } if (!sscanf (argv[0].strptr, "%d", &pCh)) { SendMsg (FUNC_GRAPHEQ, ERR_PUNTATORE_ERRATO); return INVALID_ROUTINE; } nCamp = atol (argv[1].strptr); if (!nCamp) { SendMsg (FUNC_GRAPHEQ, ERR_NUMERO_CAMPIONI); return INVALID_ROUTINE; } bandeFreq.count = 0; strcpy (bandeFreq.varname, argv[2].strptr); bandeFreq.stemlen = argv[2].strlength; strupr (bandeFreq.varname); if (bandeFreq.varname[bandeFreq.stemlen - 1] != '.') bandeFreq.varname[bandeFreq.stemlen++] = '.'; if (FetchStem (bandeFreq, &tmp)) { SendMsg (FUNC_GRAPHEQ, ERR_LETTURA_STEM); printf (" RexxVariablePool rc:%i\n", bandeFreq.shvb.shvret); return INVALID_ROUTINE; } else bandeFreq.count = tmp; if (bandeFreq.count > MAX) { SendMsg (FUNC_GRAPHEQ, ERR_STEM_MASSIMO); return INVALID_ROUTINE; } nbandeF = bandeFreq.count; bandeFreq.count = 0; pCh = (PSHORT) AllineaCh (pCh, nCamp, FUNC_GRAPHEQ); if (!pCh) return INVALID_ROUTINE; for (i = 0; i < nbandeF; i++) { bandeFreq.count++; if (FetchStem (bandeFreq, &tmp)) { SendMsg (FUNC_GRAPHEQ, ERR_LETTURA_STEM); printf (" RexxVariablePool rc:%i\n", bandeFreq.shvb.shvret); return INVALID_ROUTINE; } ampBanda[i + 1] = (double) tmp; } nCoeff = 32 + nbandeF * 32; fvec (coef, nCoeff); fl = (double) (20480 / ((double) FreqCamp / 2)); fh = 1; for (i = 0; i < nCoeff; i++) coef[i] = 0; for (j = nbandeF; j != 0; j--) { fl = fl / pow ((double) 2048, (double) (1 / (double) nbandeF)); FIRCoef (coef, (int) nCoeff, fl, fh, ampBanda[j]); fh = fl; } pCh = pCh + nCamp; for (i = nCamp - nCoeff; i != 0; i--) { sum = 0.0; for (j = nCoeff; j != 0; j--) { sum += coef[j] * *pCh--; } pCh = pCh + nCoeff; *pCh-- = (SHORT) sum; } for (i = nCoeff; i != 0; i--) { sum = 0.0; for (j = nCoeff; j != 0; j--) { sum += coef[j] * *pCh--; } pCh = pCh + nCoeff--; *pCh-- = (SHORT) sum; } retstr->strlength = strlen (retstr->strptr); return VALID_ROUTINE; }