Cn Analitza::operate(Container* c) { Q_ASSERT(c); Operator *op=0; Cn ret(0.); QList<Cn> numbers; if(c->containerType() > 100) qDebug() << "wow"; if(c->m_params.isEmpty()) { m_err << i18n("Empty container: %1").arg(c->containerType()); return Cn(0.); } if(c->m_params[0]->type() == Object::oper) op = (Operator*) c->m_params[0]; if(op!= 0 && op->operatorType()==Object::sum) ret = sum(*c); else if(op!= 0 && op->operatorType()==Object::product) ret = product(*c); else switch(c->containerType()) { case Object::apply: case Object::math: case Object::bvar: case Object::uplimit: case Object::downlimit: { if(c->m_params[0]->type() == Object::variable) { Ci* var= (Ci*) c->m_params[0]; if(var->isFunction()) ret = func(c); else ret = calc(c->m_params[0]); } else { QList<Object*>::iterator it = c->m_params.begin(); for(; it!=c->m_params.end(); it++) { if((*it)==0) { m_err << i18n("Null Object found"); ret.setCorrect(false); return ret; } else if((*it)->type() != Object::oper) { numbers.append(calc(*it)); } } if(op==0) { ret = numbers.first(); } else if(op->nparams()>-1 && numbers.count()!=op->nparams() && op->operatorType()!=Object::minus) { m_err << i18n("Too much operators for <em>%1</em>").arg(op->operatorType()); ret = Cn(0.); } else if(numbers.count()>=1 && op->type()==Object::oper) { if(numbers.count()>=2) { QList<Cn>::iterator it = numbers.begin(); ret = *it; ++it; for(; it != numbers.end(); ++it) reduce(op->operatorType(), &ret, *it, false); } else { ret=numbers.first(); reduce(op->operatorType(), &ret, 0., true); } } else { ret = numbers.first(); } } } break; case Object::declare: { if(c->m_params.count()<=1) { m_err << i18n("Need a var name and a value"); return Cn(0.); } Ci *var = (Ci*) c->m_params[0]; switch(c->m_params[1]->type()) { case Object::variable: m_vars->modify(var->name(), new Ci(c->m_params[1])); break; case Object::value: m_vars->modify(var->name(), new Cn(c->m_params[1])); break; case Object::oper: m_vars->modify(var->name(), new Operator(c->m_params[1])); break; case Object::container: m_vars->modify(var->name(), new Container(c->m_params[1])); break; case Object::none: m_err << i18n("Unvalid var type"); break; } } break; case Object::lambda: ret = calc(c->m_params[c->m_params.count()-1]); break; case Object::cnone: break; } return ret; }
} delete hij; delete vij; max=-10000; max_index=0; for (ii=0;ii<wid;ii++) { int imm; newh[ii]=kk[imm]; } HdeltaMax = max(Hdelta,[],3); hs = sum(HdeltaMax(:)); VdeltaMax = max(Vdelta,[],3); vs = sum(VdeltaMax(:)); hij = reshape(Hdelta,size(Hdelta,1)*size(Hdelta,2),size(Hdelta,3)); %shij = sum(hij,1); vij = reshape(Vdelta,size(Vdelta,1)*size(Vdelta,2),size(Vdelta,3)); %svij = sum(vij,1); newh = zeros(size(hij,1),1); for ii = 1:size(hij,1), tmp1 = hij(ii,:); tmp2 = vij(ii,:); mtmp1 = max(tmp1); mtmp2 = max(tmp2); mtmp1 = mtmp1(1); mtmp2 = mtmp2(1); mm = max(mtmp1,mtmp2); im1 = find(tmp1==mtmp1); im2 = find(tmp2==mtmp2); if mm == mtmp1, imm = im1(1); else, imm = im2(1); end newh(ii) = kk(imm); end total_coarseness = mean(newh);
static void basic_tests(void) { char string[] = "I am a string"; WCHAR wstring[] = {'I',' ','a','m',' ','a',' ','w','s','t','r','i','n','g', 0}; int f[5] = {1, 3, 0, -2, -4}; vector_t a = {1, 3, 7}; vector_t vec1 = {4, -2, 1}, vec2 = {-5, 2, 3}, *pvec2 = &vec2; pvectors_t pvecs = {&vec1, &pvec2}; sp_inner_t spi = {42}; sp_t sp = {-13, &spi}; aligns_t aligns; pints_t pints; ptypes_t ptypes; padded_t padded; padded_t padded2[2]; bogus_t bogus; int i1, i2, i3, *pi2, *pi3, **ppi3; double u, v; float s, t; long q, r; short h; char c; int x; str_struct_t ss = {string}; wstr_struct_t ws = {wstring}; str_t str; se_t se; ok(int_return() == INT_CODE, "RPC int_return\n"); ok(square(7) == 49, "RPC square\n"); ok(sum(23, -4) == 19, "RPC sum\n"); x = 0; square_out(11, &x); ok(x == 121, "RPC square_out\n"); x = 5; square_ref(&x); ok(x == 25, "RPC square_ref\n"); ok(str_length(string) == strlen(string), "RPC str_length\n"); ok(str_t_length(string) == strlen(string), "RPC str_length\n"); ok(dot_self(&a) == 59, "RPC dot_self\n"); ok(str_struct_len(&ss) == lstrlenA(string), "RPC str_struct_len\n"); ok(wstr_struct_len(&ws) == lstrlenW(wstring), "RPC str_struct_len\n"); v = 0.0; u = square_half(3.0, &v); ok(u == 9.0, "RPC square_half\n"); ok(v == 1.5, "RPC square_half\n"); t = 0.0f; s = square_half_float(3.0f, &t); ok(s == 9.0f, "RPC square_half_float\n"); ok(t == 1.5f, "RPC square_half_float\n"); r = 0; q = square_half_long(3, &r); ok(q == 9, "RPC square_half_long\n"); ok(r == 1, "RPC square_half_long\n"); i1 = 19; i2 = -3; i3 = -29; pi2 = &i2; pi3 = &i3; ppi3 = &pi3; pints.pi = &i1; pints.ppi = &pi2; pints.pppi = &ppi3; ok(pints_sum(&pints) == -13, "RPC pints_sum\n"); c = 10; h = 3; q = 14; s = -5.0f; u = 11.0; ptypes.pc = &c; ptypes.ps = &h; ptypes.pl = &q; ptypes.pf = &s; ptypes.pd = &u; ok(ptypes_sum(&ptypes) == 33.0, "RPC ptypes_sum\n"); ok(dot_pvectors(&pvecs) == -21, "RPC dot_pvectors\n"); ok(dot_copy_vectors(vec1, vec2) == -21, "RPC dot_copy_vectors\n"); ok(sum_fixed_array(f) == -2, "RPC sum_fixed_array\n"); ok(sum_sp(&sp) == 29, "RPC sum_sp\n"); ok(enum_ord(E1) == 1, "RPC enum_ord\n"); ok(enum_ord(E2) == 2, "RPC enum_ord\n"); ok(enum_ord(E3) == 3, "RPC enum_ord\n"); ok(enum_ord(E4) == 4, "RPC enum_ord\n"); se.f = E2; check_se2(&se); memset(&aligns, 0, sizeof(aligns)); aligns.c = 3; aligns.i = 4; aligns.s = 5; aligns.d = 6.0; ok(sum_aligns(&aligns) == 18.0, "RPC sum_aligns\n"); padded.i = -3; padded.c = 8; ok(sum_padded(&padded) == 5, "RPC sum_padded\n"); padded2[0].i = -5; padded2[0].c = 1; padded2[1].i = 3; padded2[1].c = 7; ok(sum_padded2(padded2) == 6, "RPC sum_padded2\n"); padded2[0].i = -5; padded2[0].c = 1; padded2[1].i = 3; padded2[1].c = 7; ok(sum_padded_conf(padded2, 2) == 6, "RPC sum_padded_conf\n"); i1 = 14; i2 = -7; i3 = -4; bogus.h.p1 = &i1; bogus.p2 = &i2; bogus.p3 = &i3; bogus.c = 9; ok(sum_bogus(&bogus) == 12, "RPC sum_bogus\n"); check_null(NULL); str = get_filename(); ok(!strcmp(str, __FILE__), "get_filename() returned %s instead of %s\n", str, __FILE__); midl_user_free(str); }
main(){ char sal='0',opt,optarre; printf("Bernardo Orozco Garza 1719152\n"); printf("Lo llenaras tu o random? 1) TU 0) RANDOM "); fflush(stdin); scanf("%c",&optarre); while(optarre!='1'&&optarre!='0'){ printf("ERROR de captura "); fflush(stdin); scanf("%c",&optarre); } printf("Dame el tamano del arreglo (1-10)\t"); scanf("%d",&n); while(n<1||n>10){ printf("ERROR de captura "); scanf("%d",&n); } switch(optarre){ case '1': printf("Introduce los valores del arreglo\n"); for(i=0;i<n;i++){ for(j=0;j<n;j++){ printf("%d,%d = ",i+1,j+1); scanf("%f",&list[i][j]); } } break; case '0': for(i=0;i<n;i++){ for(j=0;j<n;j++){ list[i][j]=rand() % 10 + 1; } } break; } do{ printf("Que quieres hacer? \n 1) SUMA\n 2) RESTA\n 3) DIVICION\n 4) MULTIPLICACION\n 5) ORDENAR ARREGLO\n 6) BUSQUEDA\n 7) SUMA TRIANGULO SUPERIOR E INFERIOR\n 8) SALIR\n"); fflush(stdin); opt=getch(); while(opt!='1'&&opt!='2'&&opt!='3'&&opt!='4'&&opt!='5'&&opt!='6'&&opt!='7'&&opt!='8'){ printf("ERROR de captura 1-8 "); fflush(stdin); opt=getch(); } switch(opt){ case '1': sum(); break; case '2': res(); break; case '3': div(); break; case '4': mul(); break; case '5': ordenacion(); break; case '6': busqueda(); break; case '7': triangulo(); break; } if(opt!='8'){ printf("\n\ndeseas salir? 1) SI 0) NO "); fflush(stdin); scanf("%c",&sal); } while(sal!='1'&&sal!='0'){ printf("ERROR de captura 1 o 0 "); fflush(stdin); sal=getch(); } system("cls"); }while(sal=='0'&&opt!='8'); getch(); }
main() { int n;float s=1;float sum(int,float); scanf("%d",&n); sum(n,s); }
int main(int argc, char const *argv[]) { int *c = (int *)malloc(3 * sizeof(int)); // Изначально вводит тип предполагаемой операции: // + - сложение // c - умножение на число // m - скалярное произведение // v - векторное произведение // g - скалярной произведение с кв.формой int j; char s; scanf("%s\n", &s); for (j = 0; j < 3; j++) scanf("%d", a + j); for (j = 0; j < 3; j++) scanf("%d", b + j); if (s == '+') { c = sum(a, b); printf("Result:\n"); int j; for (j = 0; j < 3; j++) printf("%d ", c[j]); } if (s == 'c') { c = cmul(a, b); printf("Result:\n"); int j; for (j = 0; j < 3; j++) printf("%d ", c[j]); } if (s == 'v') { c = vmul(a, b); printf("Result:\n"); int j; for (j = 0; j < 1; j++) printf("%d ", c[j]); } if (s == 'm') { c = scmul(a, b); printf("Result:\n"); printf("%d ", c[0]); } if (s == 'g') { for (j = 0; j < 3; j++) scanf("%d", g + j); c = scmul_g(a, b, g); printf("Result:\n"); printf("%d ", c[0]); } free(c); return 0; }
const Real GreensFunction2DAbs::p_int_theta_second(const Real r, const Real theta, const Real t) const { const Real r_0(this->getr0()); const Real a(this->geta()); const Real minusDt(-1e0 * this->getD() * t); const Integer num_in_term_use(100); const Integer num_out_term_use(100); const Real threshold(CUTOFF); Real sum(0e0); Real term(0e0); Integer n(1); for(; n < num_out_term_use; ++n) { Real in_sum(0e0); Real in_term(0e0); Real in_term1(0e0); Real in_term2(0e0); Real in_term3(0e0); Real a_alpha_mn(0e0); Real alpha_mn(0e0); Real Jn_r_alpha_mn(0e0); Real Jn_r0_alpha_mn(0e0); Real Jn_d_1_a_alpha_mn(0e0);// J_n-1(a alpha_mn) Real Jn_p_1_a_alpha_mn(0e0);// J_n+1(a alpha_mn) Real n_real(static_cast<double>(n)); int n_int(static_cast<int>(n)); Integer m(1); for(; m < num_in_term_use; ++m) { a_alpha_mn = gsl_sf_bessel_zero_Jnu(n_real, m); alpha_mn = a_alpha_mn / a; Jn_r_alpha_mn = gsl_sf_bessel_Jn(n_int, r * alpha_mn); Jn_r0_alpha_mn = gsl_sf_bessel_Jn(n_int, r_0 * alpha_mn); Jn_d_1_a_alpha_mn = gsl_sf_bessel_Jn(n_int - 1, a_alpha_mn); Jn_p_1_a_alpha_mn = gsl_sf_bessel_Jn(n_int + 1, a_alpha_mn); in_term1 = std::exp(alpha_mn * alpha_mn * minusDt); in_term2 = Jn_r_alpha_mn * Jn_r0_alpha_mn; in_term3 = Jn_d_1_a_alpha_mn - Jn_p_1_a_alpha_mn; in_term = in_term1 * in_term2 / (in_term3 * in_term3); in_sum += in_term; // std::cout << "inner sum " << in_sum << ", term" << in_term << std::endl; if(fabs(in_term/in_sum) < threshold) { // std::cout << "normal exit. m = " << m << " second term" << std::endl; break; } } if(m == num_in_term_use) std::cout << "warning: use term over num_in_term_use" << std::endl; // term = in_sum * std::cos(n_real * theta); term = in_sum * std::sin(n_real * theta) / n_real; sum += term; // std::cout << "outer sum " << sum << ", term" << term << std::endl; if(fabs(in_sum / (n_real * sum)) < threshold) { /* if n * theta is a multiple of \pi, the term may be zero and * * term/sum become also zero. this is a problem. sin is in a * * regeon [-1, 1], so the order of term does not depend on * * value of sin, so this considers only (in_sum / n_real). */ // std::cout << "normal exit. n = " << n << " second term" << std::endl; break; } } if(n == num_out_term_use) std::cout << "warning: use term over num_out_term_use" << std::endl; return (8e0 * sum / (M_PI * a * a)); }
/// /// \brief Vespucci::Math::DimensionReduction::VCA /// Vertex Component Analysis /// \param R The dataset /// \param endmembers Number of endmembers to compute /// \param indices Row indices of pure components. /// \param endmember_spectra Spectra of pure components (note that these are in /// columns, not rows as in spectra_) /// \param projected_data Projected data /// \param fractional_abundances Purity of a given spectrum relative to endmember /// \return Convergeance (no actual test implemented...) /// bool Vespucci::Math::DimensionReduction::VCA(const arma::mat &R, arma::uword p, arma::uvec &indices, arma::mat &endmember_spectra, arma::mat &projected_data, arma::mat &fractional_abundances) { //Initializations arma::uword L = R.n_rows; arma::uword N = R.n_cols; if (L == 0 || N == 0){ std::cerr << "No data!" << std::endl; return false; } if (p > L){ std::cerr << "wrong number of endmembers (" << p << ")!"<< std::endl; std::cerr << "set to 5 or one less than number of spectra" << std::endl; p = (L < 5? 5: L-1); } //mat of SNR arma::mat r_m = mean(R, 1); arma::mat R_m = arma::repmat(r_m, 1, N); //the mean of each spectral band arma::mat R_o = R - R_m; //mean-center the data arma::mat Ud; arma::vec Sd; arma::mat Vd; //arma::svds(Ud, Sd, Vd, arma::sp_mat(R_o * R_o.t()/N), p); Vespucci::Math::DimensionReduction::svds(R_o*R_o.t()/N, p, Ud, Sd, Vd); arma::mat x_p; try{ x_p = Ud.t() * R_o; }catch(std::exception e){ std::cout << "Ud.t() * R_o" << std::endl; } double SNR = Vespucci::Math::DimensionReduction::estimate_snr(R, r_m, x_p); double SNR_th = 15 + 10*log10(p); //Choose projective projection or projection to p-1 subspace arma::mat y; if (SNR < SNR_th){ arma::uword d = p - 1; Ud = Ud.cols(0, d-1); projected_data = Ud * x_p.rows(0, d-1) + R_m; //in dimension L arma::mat x = x_p.rows(0, d-1);//x_p = trans(Ud)*R_o, p-dimensional subspace //following three lines are one in arma::matlab... arma::mat sum_squares = sum(pow(x, 2)); double c = sum_squares.max(); c = std::sqrt(c); y = arma::join_vert(x, c*arma::ones(1, N)); } else{ arma::uword d = p; Vespucci::Math::DimensionReduction::svds(R*R.t()/N, p, Ud, Sd, Vd); arma::svds(Ud, Sd, Vd, arma::sp_mat(R*R.t()/N), d);//R_o is a mean centered version... x_p = Ud.t() * R; projected_data = Ud * x_p.rows(0, d-1); arma::mat x = Ud.t() * R; arma::mat u = arma::mean(x, 1); y = x / arma::repmat(sum(x % arma::repmat(u, 1, N)), d, 1); } // The VCA algorithm arma::vec w; w.set_size(p); arma::vec f; arma::rowvec v; indices.set_size(p); //there are no fill functions for arma::uvecs for (arma::uword i = 0; i < p; ++i) indices(i) = 0; arma::mat A = arma::zeros(p, p); double v_max; double sum_squares; arma::uvec q1; A(p-1, 0) = 1; for (arma::uword i = 0; i < p; ++i){ w.randu(); f = w - A*arma::pinv(A)*w; sum_squares = std::sqrt(arma::sum(arma::square(f))); f /= sum_squares; v = f.t() * y; v_max = arma::max(arma::abs(v)); q1 = arma::find(arma::abs(v) == v_max, 1); indices(i) = q1(0); A.col(i) = y.col(indices(i)); //same as x.col(indices(i)); } endmember_spectra = projected_data.cols(indices); fractional_abundances = arma::trans(pinv(endmember_spectra) * projected_data); return true; }
Type Foam::fieldValues::cellSource::processValues ( const Field<Type>& values, const scalarField& V, const scalarField& weightField ) const { Type result = pTraits<Type>::zero; switch (operation_) { case opSum: { result = sum(values); break; } case opSumMag: { result = sum(cmptMag(values)); break; } case opAverage: { result = sum(values)/values.size(); break; } case opWeightedAverage: { result = sum(values)/sum(weightField); break; } case opVolAverage: { result = sum(values*V)/sum(V); break; } case opVolIntegrate: { result = sum(values*V); break; } case opMin: { result = min(values); break; } case opMax: { result = max(values); break; } case opCoV: { Type meanValue = sum(values*V)/sum(V); const label nComp = pTraits<Type>::nComponents; for (direction d=0; d<nComp; ++d) { scalarField vals(values.component(d)); scalar mean = component(meanValue, d); scalar& res = setComponent(result, d); res = sqrt(sum(V*sqr(vals - mean))/sum(V))/mean; } break; } default: { // Do nothing } } return result; }
//Class constructor TimeSegmentation(Tobj &G, Col <T1> map_in, Col <T1> timeVec_in, uword a, uword b, uword c, uword interptype = 1, uword shots = 1) { cout << "Entering Class constructor" << endl; n1 = a; //Data size n2 = b;//Image size L = c; //number of time segments type = interptype; // type of time segmentation performed Nshots = shots; // number of shots obj = &G; fieldMap = map_in; cout << "N1 = " << n1 << endl; cout << "N2 = " << n2 << endl; cout << "L = " << L << endl; AA.set_size(n1, L); //time segments weights timeVec = timeVec_in; T_min =timeVec.min(); T1 rangt = timeVec.max()-T_min; tau = (rangt + datum::eps) / (L - 1); // it was L-1 before timeVec = timeVec-T_min; uword NOneShot = n1/Nshots; if (L==1) { tau = 0; AA.ones(); } else { Mat <CxT1> tempAA(NOneShot, L); if (type==1) {// Hanning interpolator cout << "Hanning interpolation" << endl; for (unsigned int ii = 0; ii<L; ii++) { for (unsigned int jj = 0; jj<NOneShot; jj++) { if ((std::abs(timeVec(jj)-((ii)*tau)))<=tau) { tempAA(jj, ii) = 0.5+0.5*std::cos((datum::pi)*(timeVec(jj)-((ii)*tau))/tau); } else { tempAA(jj, ii) = 0.0; } } } AA = repmat(tempAA, Nshots, 1); } else if (type==2) { // Min-max interpolator: Exact LS interpolator cout << "Min Max time segmentation" << endl; Mat <CxT1> Ltp; Ltp.ones(1, L); Col <CxT1> ggtp; ggtp.ones(n2, 1); Mat <CxT1> gg; gg = exp(i*fieldMap*tau)*Ltp; Mat <CxT1> iGTGGT; iGTGGT.set_size(L+1, n2); Mat <CxT1> gl; gl.zeros(n2, L); for (unsigned int ii = 0; ii<L; ii++) { for (unsigned int jj = 0; jj<n2; jj++) { gl(jj, ii) = pow(gg(jj, ii), (T1) (ii+1)); } } Mat <CxT1> G; G.set_size(n2, L); for (unsigned int jj = 0; jj<L; jj++) { if (jj==0) { G.col(jj) = ggtp; } else { G.col(jj) = gl.col(jj-1); } } Col <CxT1> glsum; Mat <CxT1> GTG; GTG.zeros(L, L); GTG.diag(0) += n2; glsum = sum(gl.t(), 1); Mat <CxT1> GTGtp(L, L); for (unsigned int ii = 0; ii < (L - 1); ii++) { GTGtp.zeros(); GTGtp.diag(-(T1) (ii+1)) += glsum(ii); GTGtp.diag((T1) (ii+1)) += std::conj(glsum(ii)); GTG = GTG+GTGtp; } T1 rcn = 1/cond(GTG); if (rcn>10*2e-16) { //condition number of GTG iGTGGT = inv(GTG)*G.t(); } else { iGTGGT = pinv(GTG)*G.t(); // pseudo inverse } Mat <CxT1> iGTGGTtp; Mat <CxT1> ftp; Col <CxT1> res, temp; for (unsigned int ii = 0; ii<NOneShot; ii++) { ftp = exp(i*fieldMap*timeVec(ii)); res = iGTGGT*ftp; tempAA.row(ii) = res.t(); } AA = repmat(tempAA, Nshots, 1); } } savemat("aamat.mat", "AA", vectorise(AA)); cout << "Exiting class constructor." << endl; }
List objectivex(const arma::mat& transition, NumericVector emissionArray, const arma::vec& init, IntegerVector obsArray, const arma::imat& ANZ, IntegerVector emissNZ, const arma::ivec& INZ, const arma::ivec& nSymbols, const arma::mat& coef, const arma::mat& X, arma::ivec& numberOfStates, int threads) { IntegerVector eDims = emissionArray.attr("dim"); //m,p,r IntegerVector oDims = obsArray.attr("dim"); //k,n,r arma::cube emission(emissionArray.begin(), eDims[0], eDims[1], eDims[2], false, true); arma::icube obs(obsArray.begin(), oDims[0], oDims[1], oDims[2], false, true); arma::icube BNZ(emissNZ.begin(), emission.n_rows, emission.n_cols - 1, emission.n_slices, false, true); unsigned int q = coef.n_rows; arma::vec grad( arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q, arma::fill::zeros); arma::mat weights = exp(X * coef).t(); if (!weights.is_finite()) { grad.fill(-arma::math::inf()); return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad)); } weights.each_row() /= sum(weights, 0); arma::mat initk(emission.n_rows, obs.n_slices); for (unsigned int k = 0; k < obs.n_slices; k++) { initk.col(k) = init % reparma(weights.col(k), numberOfStates); } arma::cube alpha(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k arma::cube beta(emission.n_rows, obs.n_cols, obs.n_slices); //m,n,k arma::mat scales(obs.n_cols, obs.n_slices); //m,n,k arma::sp_mat sp_trans(transition); internalForwardx(sp_trans.t(), emission, initk, obs, alpha, scales, threads); if (!scales.is_finite()) { grad.fill(-arma::math::inf()); return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad)); } internalBackwardx(sp_trans, emission, obs, beta, scales, threads); if (!beta.is_finite()) { grad.fill(-arma::math::inf()); return List::create(Named("objective") = arma::math::inf(), Named("gradient") = wrap(grad)); } arma::ivec cumsumstate = arma::cumsum(numberOfStates); arma::mat gradmat( arma::accu(ANZ) + arma::accu(BNZ) + arma::accu(INZ) + (numberOfStates.n_elem- 1) * q, obs.n_slices, arma::fill::zeros); #pragma omp parallel for if(obs.n_slices >= threads) schedule(static) num_threads(threads) \ default(none) shared(q, alpha, beta, scales, gradmat, nSymbols, ANZ, BNZ, INZ, \ numberOfStates, cumsumstate, obs, init, initk, X, weights, transition, emission) for (int k = 0; k < obs.n_slices; k++) { int countgrad = 0; // transitionMatrix if (arma::accu(ANZ) > 0) { for (int jj = 0; jj < numberOfStates.n_elem; jj++) { arma::vec gradArow(numberOfStates(jj)); arma::mat gradA(numberOfStates(jj), numberOfStates(jj)); int ind_jj = cumsumstate(jj) - numberOfStates(jj); for (int i = 0; i < numberOfStates(jj); i++) { arma::uvec ind = arma::find(ANZ.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1)); if (ind.n_elem > 0) { gradArow.zeros(); gradA.eye(); gradA.each_row() -= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1); gradA.each_col() %= transition.row(ind_jj + i).subvec(ind_jj, cumsumstate(jj) - 1).t(); for (int j = 0; j < numberOfStates(jj); j++) { for (unsigned int t = 0; t < (obs.n_cols - 1); t++) { double tmp = alpha(ind_jj + i, t, k); for (unsigned int r = 0; r < obs.n_rows; r++) { tmp *= emission(ind_jj + j, obs(r, t + 1, k), r); } gradArow(j) += tmp * beta(ind_jj + j, t + 1, k) / scales(t + 1, k); } } gradArow = gradA * gradArow; gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradArow.rows(ind); countgrad += ind.n_elem; } } } } if (arma::accu(BNZ) > 0) { // emissionMatrix for (unsigned int r = 0; r < obs.n_rows; r++) { arma::vec gradBrow(nSymbols(r)); arma::mat gradB(nSymbols(r), nSymbols(r)); for (unsigned int i = 0; i < emission.n_rows; i++) { arma::uvec ind = arma::find(BNZ.slice(r).row(i)); if (ind.n_elem > 0) { gradBrow.zeros(); gradB.eye(); gradB.each_row() -= emission.slice(r).row(i).subvec(0, nSymbols(r) - 1); gradB.each_col() %= emission.slice(r).row(i).subvec(0, nSymbols(r) - 1).t(); for (int j = 0; j < nSymbols(r); j++) { if (obs(r, 0, k) == j) { double tmp = initk(i, k); for (unsigned int r2 = 0; r2 < obs.n_rows; r2++) { if (r2 != r) { tmp *= emission(i, obs(r2, 0, k), r2); } } gradBrow(j) += tmp * beta(i, 0, k) / scales(0, k); } for (unsigned int t = 0; t < (obs.n_cols - 1); t++) { if (obs(r, t + 1, k) == j) { double tmp = beta(i, t + 1, k) / scales(t + 1, k); for (unsigned int r2 = 0; r2 < obs.n_rows; r2++) { if (r2 != r) { tmp *= emission(i, obs(r2, t + 1, k), r2); } } gradBrow(j) += arma::dot(alpha.slice(k).col(t), transition.col(i)) * tmp; } } } gradBrow = gradB * gradBrow; gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradBrow.rows(ind); countgrad += ind.n_elem; } } } } if (arma::accu(INZ) > 0) { for (int i = 0; i < numberOfStates.n_elem; i++) { int ind_i = cumsumstate(i) - numberOfStates(i); arma::uvec ind = arma::find( INZ.subvec(ind_i, cumsumstate(i) - 1)); if (ind.n_elem > 0) { arma::vec gradIrow(numberOfStates(i), arma::fill::zeros); for (int j = 0; j < numberOfStates(i); j++) { double tmp = weights(i, k); for (unsigned int r = 0; r < obs.n_rows; r++) { tmp *= emission(ind_i + j, obs(r, 0, k), r); } gradIrow(j) += tmp * beta(ind_i + j, 0, k) / scales(0, k); } arma::mat gradI(numberOfStates(i), numberOfStates(i), arma::fill::zeros); gradI.eye(); gradI.each_row() -= init.subvec(ind_i, cumsumstate(i) - 1).t(); gradI.each_col() %= init.subvec(ind_i, cumsumstate(i) - 1); gradIrow = gradI * gradIrow; gradmat.col(k).subvec(countgrad, countgrad + ind.n_elem - 1) = gradIrow.rows(ind); countgrad += ind.n_elem; } } } for (int jj = 1; jj < numberOfStates.n_elem; jj++) { int ind_jj = (cumsumstate(jj) - numberOfStates(jj)); for (int j = 0; j < emission.n_rows; j++) { double tmp = 1.0; for (unsigned int r = 0; r < obs.n_rows; r++) { tmp *= emission(j, obs(r, 0, k), r); } if ((j >= ind_jj) & (j < cumsumstate(jj))) { gradmat.col(k).subvec(countgrad + q * (jj - 1), countgrad + q * jj - 1) += tmp * beta(j, 0, k) / scales(0, k) * initk(j, k) * X.row(k).t() * (1.0 - weights(jj, k)); } else { gradmat.col(k).subvec(countgrad + q * (jj - 1), countgrad + q * jj - 1) -= tmp * beta(j, 0, k) / scales(0, k) * initk(j, k) * X.row(k).t() * weights(jj, k); } } } } return List::create(Named("objective") = -arma::accu(log(scales)), Named("gradient") = wrap(-sum(gradmat, 1))); }
//[[Rcpp::export]] List rhierMnlRwMixture_rcpp_loop(List const& lgtdata, mat const& Z, vec const& deltabar, mat const& Ad, mat const& mubar, mat const& Amu, double nu, mat const& V, double s, int R, int keep, int nprint, bool drawdelta, mat olddelta, vec const& a, vec oldprob, mat oldbetas, vec ind, vec const& SignRes){ // Wayne Taylor 10/01/2014 int nlgt = lgtdata.size(); int nvar = V.n_cols; int nz = Z.n_cols; mat rootpi, betabar, ucholinv, incroot; int mkeep; mnlMetropOnceOut metropout_struct; List lgtdatai, nmix; // convert List to std::vector of struct std::vector<moments> lgtdata_vector; moments lgtdatai_struct; for (int lgt = 0; lgt<nlgt; lgt++){ lgtdatai = lgtdata[lgt]; lgtdatai_struct.y = as<vec>(lgtdatai["y"]); lgtdatai_struct.X = as<mat>(lgtdatai["X"]); lgtdatai_struct.hess = as<mat>(lgtdatai["hess"]); lgtdata_vector.push_back(lgtdatai_struct); } // allocate space for draws vec oldll = zeros<vec>(nlgt); cube betadraw(nlgt, nvar, R/keep); mat probdraw(R/keep, oldprob.size()); vec loglike(R/keep); mat Deltadraw(1,1); if(drawdelta) Deltadraw.zeros(R/keep, nz*nvar);//enlarge Deltadraw only if the space is required List compdraw(R/keep); if (nprint>0) startMcmcTimer(); for (int rep = 0; rep<R; rep++){ //first draw comps,ind,p | {beta_i}, delta // ind,p need initialization comps is drawn first in sub-Gibbs List mgout; if(drawdelta) { olddelta.reshape(nvar,nz); mgout = rmixGibbs (oldbetas-Z*trans(olddelta),mubar,Amu,nu,V,a,oldprob,ind); } else { mgout = rmixGibbs(oldbetas,mubar,Amu,nu,V,a,oldprob,ind); } List oldcomp = mgout["comps"]; oldprob = as<vec>(mgout["p"]); //conversion from Rcpp to Armadillo requires explict declaration of variable type using as<> ind = as<vec>(mgout["z"]); //now draw delta | {beta_i}, ind, comps if(drawdelta) olddelta = drawDelta(Z,oldbetas,ind,oldcomp,deltabar,Ad); //loop over all LGT equations drawing beta_i | ind[i],z[i,],mu[ind[i]],rooti[ind[i]] for(int lgt = 0; lgt<nlgt; lgt++){ List oldcomplgt = oldcomp[ind[lgt]-1]; rootpi = as<mat>(oldcomplgt[1]); //note: beta_i = Delta*z_i + u_i Delta is nvar x nz if(drawdelta){ olddelta.reshape(nvar,nz); betabar = as<vec>(oldcomplgt[0])+olddelta*vectorise(Z(lgt,span::all)); } else { betabar = as<vec>(oldcomplgt[0]); } if (rep == 0) oldll[lgt] = llmnl_con(vectorise(oldbetas(lgt,span::all)),lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,SignRes); //compute inc.root ucholinv = solve(trimatu(chol(lgtdata_vector[lgt].hess+rootpi*trans(rootpi))), eye(nvar,nvar)); //trimatu interprets the matrix as upper triangular and makes solve more efficient incroot = chol(ucholinv*trans(ucholinv)); metropout_struct = mnlMetropOnce_con(lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,vectorise(oldbetas(lgt,span::all)), oldll[lgt],s,incroot,betabar,rootpi,SignRes); oldbetas(lgt,span::all) = trans(metropout_struct.betadraw); oldll[lgt] = metropout_struct.oldll; } //print time to completion and draw # every nprint'th draw if (nprint>0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R); if((rep+1)%keep==0){ mkeep = (rep+1)/keep; betadraw.slice(mkeep-1) = oldbetas; probdraw(mkeep-1, span::all) = trans(oldprob); loglike[mkeep-1] = sum(oldll); if(drawdelta) Deltadraw(mkeep-1, span::all) = trans(vectorise(olddelta)); compdraw[mkeep-1] = oldcomp; } } if (nprint>0) endMcmcTimer(); nmix = List::create(Named("probdraw") = probdraw, Named("zdraw") = R_NilValue, //sets the value to NULL in R Named("compdraw") = compdraw); //ADDED FOR CONSTRAINTS //If there are sign constraints, return f(betadraws) as "betadraws" //conStatus will be set to true if SignRes has any non-zero elements bool conStatus = any(SignRes); if(conStatus){ int SignResSize = SignRes.size(); //loop through each sign constraint for(int i = 0;i < SignResSize; i++){ //if there is a constraint loop through each slice of betadraw if(SignRes[i] != 0){ for(int s = 0;s < R/keep; s++){ betadraw(span(),span(i),span(s)) = SignRes[i] * exp(betadraw(span(),span(i),span(s))); } } }//end loop through SignRes } if(drawdelta){ return(List::create( Named("Deltadraw") = Deltadraw, Named("betadraw") = betadraw, Named("nmix") = nmix, Named("loglike") = loglike, Named("SignRes") = SignRes)); } else { return(List::create( Named("betadraw") = betadraw, Named("nmix") = nmix, Named("loglike") = loglike, Named("SignRes") = SignRes)); } }
int main(int argc, char *argv[]) { // Initialize POOMA and output stream, using Tester class Pooma::initialize(argc, argv); Pooma::Tester tester(argc, argv); tester.out() << argv[0]; tester.out() << ": DynamicArray dynamic ops w/views." << std::endl; tester.out() << "-------------------------------------------" << std::endl; // Create an Interval object to create and index into an Array with tester.out() << "Creating an Interval<1> object ..." << std::endl; Interval<1> D1(3); tester.out() << "D1 = " << D1 << std::endl; // Create simple dynamic array. tester.out() << "Creating DynamicArray using domain ..." << std::endl; DynamicArray<int,Dynamic> a(D1); tester.check(a.domain().size() == D1.size()); // Initialize dynamic array with scalar. a = 3; tester.out() << "Initialized DynamicArray to 3:" << std::endl; tester.out() << "a = " << a << std::endl; tester.check(sum(a) == (a.domain().size() * 3)); // Create elements in the array. tester.out() << "Creating 2 elements at end of a ..." << std::endl; a.create(2); a.sync(); tester.out() << "a = " << a << std::endl; tester.check(a.domain().size() == (D1.size() + 2)); #if 0 // This test is bogous, as the comment in Engine/DynamicEngine.cpp::create() // tells (the check for shared data is commented out): // "It would be nice to assert that no-one else is looking at the engine // when we perform dynamic operations, but all the particle swap operations // take place inside iterates which means the engine is a copy of another // engine, so the data is shared." // Call a function which takes a view and the original DynamicArray std::cout << "The program should abort in the next operation when it\n"; std::cout << "tries to create elements in an array with an existing view."; std::cout << std::endl; tester.out() << "Calling testview with a and a(1,3) ..." << std::endl; tester.check(testview(tester, a, a(Interval<1>(1,3)))); #endif // Return resulting error code and exit; Tester will shut down POOMA. tester.out() << "-------------------------------------------" << std::endl; int retval = tester.results("DynamicArray dynamic ops w/views"); Pooma::finalize(); return retval; }
void main(){ int a = sum(); printf("The sum is %d\n", a); }
int main(int argc, char *argv[]) { #include "postProcess.H" #include "setRootCase.H" #include "createTime.H" #include "createMesh.H" #include "createControl.H" #include "createFields.H" #include "createFvOptions.H" #include "initContinuityErrs.H" #include "createTimeControls.H" #include "compressibleCourantNo.H" #include "setInitialDeltaT.H" turbulence->validate(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Info<< "\nStarting time loop\n" << endl; while (runTime.run()) { #include "readTimeControls.H" #include "compressibleCourantNo.H" #include "setDeltaT.H" runTime++; Info<< "Time = " << runTime.timeName() << nl << endl; #include "rhoEqn.H" // --- Pressure-velocity PIMPLE corrector loop while (pimple.loop()) { #include "UEqn.H" #include "EEqn.H" // --- Pressure corrector loop while (pimple.correct()) { #include "pEqn.H" } if (pimple.turbCorr()) { turbulence->correct(); } } rho = thermo.rho(); runTime.write(); Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s" << " ClockTime = " << runTime.elapsedClockTime() << " s" << endl; Info<< "Inflow : " << -1.0* sum(phi.boundaryField()[inlet]) <<" [kg/s]" << endl; Info<< "Outflow : " << sum(phi.boundaryField()[outlet]) <<" [kg/s]" << endl; Info<< "EnergyInflow : " << -1.0* sum( phi.boundaryField()[inlet] * ( thermo.he().boundaryField()[inlet] + 0.5*magSqr(U.boundaryField()[inlet]) ) ) <<" [W]" << endl; Info<< "EnergyOutflow : " << sum( phi.boundaryField()[outlet] * ( thermo.he().boundaryField()[outlet] + 0.5*magSqr(U.boundaryField()[outlet]) ) ) <<" [W]" << endl; Info<< "EnergyBalance : " << sum( phi.boundaryField()[outlet] * ( thermo.he().boundaryField()[outlet] + 0.5*magSqr(U.boundaryField()[outlet]) ) ) +1.0* sum( phi.boundaryField()[inlet] * ( thermo.he().boundaryField()[inlet] + 0.5*magSqr(U.boundaryField()[inlet]) ) ) <<" [W]" << endl; Info<< "rho max/avg/min : " << gMax(thermo.rho()) << " " << gAverage(thermo.rho()) << " " << gMin(thermo.rho()) << endl; Info<< "T max/avg/min : " << gMax(thermo.T()) << " " << gAverage(thermo.T()) << " " << gMin(thermo.T()) << endl; Info<< "P max/avg/min : " << gMax(thermo.p()) << " " << gAverage(thermo.p()) << " " << gMin(thermo.p()) << endl; Info<< "Prg max/avg/min : " << gMax(p_rgh) << " " << gAverage(p_rgh) << " " << gMin(p_rgh) << endl; Info<< "U max/avg/min : " << max(U.component(2)).value() << " " << average(U.component(2)).value() << " " << min(U.component(2)).value() << endl; Info<< "Prg max-min : " << gMax(p_rgh) - gMin(p_rgh) << endl; Info<< " " << endl; Info<< "sngrad(rho) :" << gMax(snGradRho.boundaryField()[outlet]) << " " << gAverage(snGradRho.boundaryField()[outlet]) << " " << gMin(snGradRho.boundaryField()[outlet]) << endl; Info<< " " << endl; } Info<< "End\n" << endl; return 0; }
Int_t main(Int_t argc, Char_t *argv[]) { ROOT::Mpi::TEnvironment env(argc, argv); ROOT::Mpi::TIntraCommunicator world; TVectorT<Double_t> mResult; Double_t fScalarResult; TVectorT<Double_t> v1(elements); TVectorT<Double_t> v2(elements); for (Int_t i = 0; i < elements; i++) { v1[i] = i + (i + world.Size()); v2[i] = i * (i + world.Size()); } /////////////////////////////////////////////// //Testing methdos with results in single Rank// /////////////////////////////////////////////// ROOT::Mpi::Math::TVectorTWrapper<Double_t> add(v1); add.Addition(v2, root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> sub(v1); sub.Subtraction(v2, root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> dot(v1); dot.Dot(v2, root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2Sqr(v1); norm2Sqr.Norm2Sqr(root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm1(v1); norm1.Norm1(root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> min(v1); min.Min(root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> max(v1); max.Max(root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> normalize(v1); normalize.Normalize(root); ROOT::Mpi::Math::TVectorTWrapper<Double_t> sum(v1); sum.Sum(root); if (world.Rank() == root) { add.GetResult(mResult); MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition Single"); sub.GetResult(mResult); MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction Single"); dot.GetResult(fScalarResult); MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product Single"); norm2Sqr.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v1.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr Single"); norm1.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v1.Norm1() , world.Rank(), "Vector Norm1 Single"); min.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v1.Min() , world.Rank(), "Vector Min Single"); max.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v1.Max() , world.Rank(), "Vector Max Single"); normalize.GetResult(mResult); MpiCompareTest(mResult.Norm2Sqr(), ((1 / TMath::Sqrt(v1.Norm2Sqr()))*v1).Norm2Sqr() , world.Rank(), "Vector Normalize Single"); sum.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v1.Sum(), world.Rank(), "Vector Sum Single"); } /////////////////////////////////////////////// //Testing methdos with results in all ranks // /////////////////////////////////////////////// ROOT::Mpi::Math::TVectorTWrapper<Double_t> addAll(v1); add.Addition(v2); ROOT::Mpi::Math::TVectorTWrapper<Double_t> subAll(v1); sub.Subtraction(v2); add.GetResult(mResult); MpiCompareTVectorTest(mResult, v1 + v2, world.Rank(), "Vector Addition All"); sub.GetResult(mResult); MpiCompareTVectorTest(mResult, v1 - v2, world.Rank(), "Vector Subtraction All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> dotAll(v1); dotAll.Dot(v2); dotAll.GetResult(fScalarResult); MpiCompareTest(fScalarResult, Dot(v1, v2) , world.Rank(), "Vector Dot Product All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm2SqrAll(v2); norm2SqrAll.Norm2Sqr(); norm2SqrAll.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v2.Norm2Sqr() , world.Rank(), "Vector Norm2Sqr All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> norm1All(v2); norm1All.Norm1(); norm1All.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v2.Norm1() , world.Rank(), "Vector Norm1 All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> minAll(v2); minAll.Min(); minAll.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v2.Min() , world.Rank(), "Vector Min All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> maxAll(v2); maxAll.Max(); maxAll.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v2.Max() , world.Rank(), "Vector Max All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> normalizeAll(v2); normalizeAll.Normalize(); normalizeAll.GetResult(mResult); //show if the vector is normalize, then Norm2Sqr of result is near to 1 MpiCompareTest(mResult.Norm2Sqr(), ((1 / TMath::Sqrt(v2.Norm2Sqr()))*v2).Norm2Sqr() , world.Rank(), "Vector Normalize All"); ROOT::Mpi::Math::TVectorTWrapper<Double_t> sumAll(v2); sumAll.Sum(); sumAll.GetResult(fScalarResult); MpiCompareTest(fScalarResult, v2.Sum() , world.Rank(), "Vector Sum All"); return 0; }
void pxsnsr(vector<vector<Point>> &contours, Mat &Seg_img_red, Mat &Seg_img_blue) { Rect *r = new Rect[contours.size()]; // 定义外接矩形数组 Mat obj_rec_thr = Mat::zeros(Seg_img_red.size(), CV_8UC3); for (unsigned int i = 0; i < contours.size(); i++) { r[i] = boundingRect(Mat(contours[i]));// boundingRect获取这个外接矩形 } /// 绘出轮廓及其凸包 Mat Seg_img_blue_hull(Seg_img_blue.size(), CV_8U, Scalar(0)); vector<vector<Point> >hull(contours.size()); for (unsigned int i = 0; i< contours.size(); i++) { convexHull(Mat(contours[i]), hull[i], false); fillConvexPoly(Seg_img_blue_hull, &hull[i][0], hull[i].size(), Scalar(1)); } erode(Seg_img_blue_hull, Seg_img_blue_hull, Mat(), Point(-1, -1), dilate_size); // 对图像进行之前的膨胀恢复 Seg_img_blue_hull.convertTo(Seg_img_blue_hull, CV_32F); imshow("Seg_img_blue _hull", Seg_img_blue_hull); double Evaluation = 0; // 对潜在目标的打分值初始化 double Evaluation_max = 0; // 对潜在目标的打分最大值初始化 int index_best = -1; // 最优轮廓标记 <注意此处初始值应为-1> int index = 0; // 轮廓标记 cout << contours.size() << endl; vector<vector<Point>>::const_iterator itContours = contours.begin(); //for (; itContours != contours.end(); ++itContours) while (itContours != contours.end()) { Mat imageROI_red = Seg_img_red(cv::Rect(r[index].x, r[index].y, r[index].width, r[index].height)); Mat imageROI_blue = Seg_img_blue_hull(cv::Rect(r[index].x, r[index].y, r[index].width, r[index].height)); Mat imageROI_red_blue = imageROI_red + imageROI_blue; threshold(imageROI_red_blue, imageROI_red_blue, 1, 1, THRESH_BINARY); // 进行阈值分割(大于阈值1等于2时候取 1) Scalar s1 = sum(imageROI_red_blue); Scalar s2 = sum(imageROI_blue); double sum_red = s1.val[0]; // 获取图像块包含在蓝色中的红色像素数量 double sum_blue = s2.val[0]; // 获取图像块中蓝色像素数量 double pixel_sum_rate = rate(sum_red, sum_blue); // 计算图像块中红蓝像素的比例 cout << "sum_red:" << sum_red << "\t" << "," << "sum_blue:" << sum_blue << "\t"; cout << "pixel_sum_rate:" << pixel_sum_rate << endl; // 将红蓝像素比太低的连通域轮廓删除 if ((pixel_sum_rate < threshold_value_pixel_rate) || (sum_red < 12)) // 如当前轮廓不含一定的红色像素 { itContours = contours.erase(itContours); // 删除当前轮廓 <特别注意:删除当前轮廓后迭代器自动指向后一个> index++; continue; } else // 如当前轮廓含一定的红色像素 { int aaa = contours.size(); // 用于设置条件断点 Evaluation = sum_red; // 目标轮廓简单评价值定义 if (Evaluation > Evaluation_max) { Evaluation_max = Evaluation; index_best++; cout << "index_best - " << index_best << endl; } index++; itContours++; // 继续检索下一个轮廓 <此处必须要代码指定迭代器转向后一个轮廓> } } int ttt = contours.size(); // 用于设置条件断点 // 如果仍然有大于一个潜在目标则选取最优的一个 if (ttt > 1) { int index = 0; vector<vector<Point>>::const_iterator itContours_2 = contours.begin(); while(itContours_2 != contours.end()) { if (index != index_best) itContours_2 = contours.erase(itContours_2); else ++itContours_2; index++; } } delete[] r; }
inline bool op_princomp::direct_princomp ( Mat< std::complex<typename T1::pod_type> >& coeff_out, Mat< std::complex<typename T1::pod_type> >& score_out, Col< typename T1::pod_type >& latent_out, Col< std::complex<typename T1::pod_type> >& tsquared_out, const Base< std::complex<typename T1::pod_type>, T1 >& X, const typename arma_cx_only<typename T1::elem_type>::result* junk ) { arma_extra_debug_sigprint(); arma_ignore(junk); typedef typename T1::pod_type T; typedef std::complex<T> eT; const unwrap_check<T1> Y( X.get_ref(), score_out ); const Mat<eT>& in = Y.M; const uword n_rows = in.n_rows; const uword n_cols = in.n_cols; if(n_rows > 1) // more than one sample { // subtract the mean - use score_out as temporary matrix score_out = in; score_out.each_row() -= mean(in); // singular value decomposition Mat<eT> U; Col< T> s; const bool svd_ok = svd(U, s, coeff_out, score_out); if(svd_ok == false) { return false; } // normalize the eigenvalues s /= std::sqrt( double(n_rows - 1) ); // project the samples to the principals score_out *= coeff_out; if(n_rows <= n_cols) // number of samples is less than their dimensionality { score_out.cols(n_rows-1,n_cols-1).zeros(); Col<T> s_tmp = zeros< Col<T> >(n_cols); s_tmp.rows(0,n_rows-2) = s.rows(0,n_rows-2); s = s_tmp; // compute the Hotelling's T-squared s_tmp.rows(0,n_rows-2) = 1.0 / s_tmp.rows(0,n_rows-2); const Mat<eT> S = score_out * diagmat(Col<T>(s_tmp)); tsquared_out = sum(S%S,1); } else { // compute the Hotelling's T-squared const Mat<eT> S = score_out * diagmat(Col<T>(T(1) / s)); tsquared_out = sum(S%S,1); } // compute the eigenvalues of the principal vectors latent_out = s%s; } else // 0 or 1 samples { coeff_out.eye(n_cols, n_cols); score_out.copy_size(in); score_out.zeros(); latent_out.set_size(n_cols); latent_out.zeros(); tsquared_out.set_size(n_rows); tsquared_out.zeros(); } return true; }
// Coordinate descent for logistic models RcppExport SEXP cdfit_binomial_hsr(SEXP X_, SEXP y_, SEXP row_idx_, SEXP lambda_, SEXP nlambda_, SEXP lam_scale_, SEXP lambda_min_, SEXP alpha_, SEXP user_, SEXP eps_, SEXP max_iter_, SEXP multiplier_, SEXP dfmax_, SEXP ncore_, SEXP warn_, SEXP verbose_) { XPtr<BigMatrix> xMat(X_); double *y = REAL(y_); int *row_idx = INTEGER(row_idx_); double lambda_min = REAL(lambda_min_)[0]; double alpha = REAL(alpha_)[0]; int n = Rf_length(row_idx_); // number of observations used for fitting model int p = xMat->ncol(); int L = INTEGER(nlambda_)[0]; int lam_scale = INTEGER(lam_scale_)[0]; double eps = REAL(eps_)[0]; int max_iter = INTEGER(max_iter_)[0]; double *m = REAL(multiplier_); int dfmax = INTEGER(dfmax_)[0]; int warn = INTEGER(warn_)[0]; int user = INTEGER(user_)[0]; int verbose = INTEGER(verbose_)[0]; NumericVector lambda(L); NumericVector Dev(L); IntegerVector iter(L); IntegerVector n_reject(L); NumericVector beta0(L); NumericVector center(p); NumericVector scale(p); int p_keep = 0; // keep columns whose scale > 1e-6 int *p_keep_ptr = &p_keep; vector<int> col_idx; vector<double> z; double lambda_max = 0.0; double *lambda_max_ptr = &lambda_max; int xmax_idx = 0; int *xmax_ptr = &xmax_idx; // set up omp int useCores = INTEGER(ncore_)[0]; #ifdef BIGLASSO_OMP_H_ int haveCores = omp_get_num_procs(); if(useCores < 1) { useCores = haveCores; } omp_set_dynamic(0); omp_set_num_threads(useCores); #endif if (verbose) { char buff1[100]; time_t now1 = time (0); strftime (buff1, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now1)); Rprintf("\nPreprocessing start: %s\n", buff1); } // standardize: get center, scale; get p_keep_ptr, col_idx; get z, lambda_max, xmax_idx; standardize_and_get_residual(center, scale, p_keep_ptr, col_idx, z, lambda_max_ptr, xmax_ptr, xMat, y, row_idx, lambda_min, alpha, n, p); p = p_keep; // set p = p_keep, only loop over columns whose scale > 1e-6 if (verbose) { char buff1[100]; time_t now1 = time (0); strftime (buff1, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now1)); Rprintf("Preprocessing end: %s\n", buff1); Rprintf("\n-----------------------------------------------\n"); } arma::sp_mat beta = arma::sp_mat(p, L); //beta double *a = Calloc(p, double); //Beta from previous iteration double a0 = 0.0; //beta0 from previousiteration double *w = Calloc(n, double); double *s = Calloc(n, double); //y_i - pi_i double *eta = Calloc(n, double); int *e1 = Calloc(p, int); //ever-active set int *e2 = Calloc(p, int); //strong set double xwr, xwx, pi, u, v, cutoff, l1, l2, shift, si; double max_update, update, thresh; // for convergence check int i, j, jj, l, violations, lstart; double ybar = sum(y, n) / n; a0 = beta0[0] = log(ybar / (1-ybar)); double nullDev = 0; double *r = Calloc(n, double); for (i = 0; i < n; i++) { r[i] = y[i]; nullDev = nullDev - y[i]*log(ybar) - (1-y[i])*log(1-ybar); s[i] = y[i] - ybar; eta[i] = a0; } thresh = eps * nullDev / n; double sumS = sum(s, n); // temp result sum of s double sumWResid = 0.0; // temp result: sum of w * r // set up lambda if (user == 0) { if (lam_scale) { // set up lambda, equally spaced on log scale double log_lambda_max = log(lambda_max); double log_lambda_min = log(lambda_min*lambda_max); double delta = (log_lambda_max - log_lambda_min) / (L-1); for (l = 0; l < L; l++) { lambda[l] = exp(log_lambda_max - l * delta); } } else { // equally spaced on linear scale double delta = (lambda_max - lambda_min*lambda_max) / (L-1); for (l = 0; l < L; l++) { lambda[l] = lambda_max - l * delta; } } Dev[0] = nullDev; lstart = 1; n_reject[0] = p; } else { lstart = 0; lambda = Rcpp::as<NumericVector>(lambda_); } for (l = lstart; l < L; l++) { if(verbose) { // output time char buff[100]; time_t now = time (0); strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now)); Rprintf("Lambda %d. Now time: %s\n", l, buff); } if (l != 0) { // Check dfmax int nv = 0; for (j = 0; j < p; j++) { if (a[j] != 0) { nv++; } } if (nv > dfmax) { for (int ll=l; ll<L; ll++) iter[ll] = NA_INTEGER; Free_memo_bin_hsr(s, w, a, r, e1, e2, eta); return List::create(beta0, beta, center, scale, lambda, Dev, iter, n_reject, Rcpp::wrap(col_idx)); } // strong set cutoff = 2*lambda[l] - lambda[l-1]; for (j = 0; j < p; j++) { if (fabs(z[j]) > (cutoff * alpha * m[col_idx[j]])) { e2[j] = 1; } else { e2[j] = 0; } } } else { // strong set cutoff = 2*lambda[l] - lambda_max; for (j = 0; j < p; j++) { if (fabs(z[j]) > (cutoff * alpha * m[col_idx[j]])) { e2[j] = 1; } else { e2[j] = 0; } } } n_reject[l] = p - sum(e2, p); while (iter[l] < max_iter) { while (iter[l] < max_iter) { while (iter[l] < max_iter) { iter[l]++; Dev[l] = 0.0; for (i = 0; i < n; i++) { if (eta[i] > 10) { pi = 1; w[i] = .0001; } else if (eta[i] < -10) { pi = 0; w[i] = .0001; } else { pi = exp(eta[i]) / (1 + exp(eta[i])); w[i] = pi * (1 - pi); } s[i] = y[i] - pi; r[i] = s[i] / w[i]; if (y[i] == 1) { Dev[l] = Dev[l] - log(pi); } else { Dev[l] = Dev[l] - log(1-pi); } } if (Dev[l] / nullDev < .01) { if (warn) warning("Model saturated; exiting..."); for (int ll=l; ll<L; ll++) iter[ll] = NA_INTEGER; Free_memo_bin_hsr(s, w, a, r, e1, e2, eta); return List::create(beta0, beta, center, scale, lambda, Dev, iter, n_reject, Rcpp::wrap(col_idx)); } // Intercept xwr = crossprod(w, r, n, 0); xwx = sum(w, n); beta0[l] = xwr / xwx + a0; si = beta0[l] - a0; if (si != 0) { a0 = beta0[l]; for (i = 0; i < n; i++) { r[i] -= si; //update r eta[i] += si; //update eta } } sumWResid = wsum(r, w, n); // update temp result: sum of w * r, used for computing xwr; max_update = 0.0; for (j = 0; j < p; j++) { if (e1[j]) { jj = col_idx[j]; xwr = wcrossprod_resid(xMat, r, sumWResid, row_idx, center[jj], scale[jj], w, n, jj); v = wsqsum_bm(xMat, w, row_idx, center[jj], scale[jj], n, jj) / n; u = xwr/n + v * a[j]; l1 = lambda[l] * m[jj] * alpha; l2 = lambda[l] * m[jj] * (1-alpha); beta(j, l) = lasso(u, l1, l2, v); shift = beta(j, l) - a[j]; if (shift !=0) { // update change of objective function // update = - u * shift + (0.5 * v + 0.5 * l2) * (pow(beta(j, l), 2) - pow(a[j], 2)) + l1 * (fabs(beta(j, l)) - fabs(a[j])); update = pow(beta(j, l) - a[j], 2) * v; if (update > max_update) max_update = update; update_resid_eta(r, eta, xMat, shift, row_idx, center[jj], scale[jj], n, jj); // update r sumWResid = wsum(r, w, n); // update temp result w * r, used for computing xwr; a[j] = beta(j, l); // update a } } } // Check for convergence if (max_update < thresh) break; } // Scan for violations in strong set sumS = sum(s, n); violations = check_strong_set_bin(e1, e2, z, xMat, row_idx, col_idx, center, scale, a, lambda[l], sumS, alpha, s, m, n, p); if (violations==0) break; } // Scan for violations in rest violations = check_rest_set_bin(e1, e2, z, xMat, row_idx, col_idx, center, scale, a, lambda[l], sumS, alpha, s, m, n, p); if (violations==0) break; } } Free_memo_bin_hsr(s, w, a, r, e1, e2, eta); return List::create(beta0, beta, center, scale, lambda, Dev, iter, n_reject, Rcpp::wrap(col_idx)); }
int sum(int idx) { return idx >= 1 ? tree[idx] + sum(idx - lowbit(idx)) : 0; }
float sum(float a[], int n) { if (n == 0) return a[0]; else return a[n] + sum(a, n-1); }
/*Funktionsdefinitionen*/ int sum(int n) { if(n>0) return n + sum(n-1); return 0; }
match *find_best_match(const adapter_array *aa, const char *read, float *p_quals, float prior, float p_match, int min_l) { /* Take an adapter array, and check the read against all adapters. Brute force string matching is used. This is to avoid approximate matching algorithms which required an a priori specified number mismatches. */ match *best_match=NULL; int i, shift, max_shift, found_contam=0; int *best_arr=NULL, best_adapter=0, best_length=0, best_shift=0, best_score=INT_MIN; int curr_score, *curr_arr=NULL; size_t al, rl = strlen(read); posterior_set *ps=NULL; float *best_p_quals=NULL; max_shift = rl - min_l; for (shift = 0; shift < max_shift; shift++) { for (i = 0; i < aa->n; i++) { if (min_l >= aa->adapters[i].length) { fprintf(stderr, "Minimum match length (option -n) greater than or " \ "equal to length of adapter.\n"); exit(EXIT_FAILURE); } al = min(aa->adapters[i].length, rl - shift); curr_arr = score_sequence(&(read)[shift], (aa->adapters[i]).seq, al); curr_score = sum(curr_arr, al); if (curr_score > best_score) { best_score = curr_score; best_length = al; best_shift = shift; best_p_quals = &(p_quals)[shift]; best_arr = curr_arr; best_adapter = i; ps = posterior(best_arr, best_p_quals, prior, 0.25, best_length); found_contam = ps->is_contam; if (found_contam) { break; } else { free(ps); ps=NULL; free(best_arr); } } else free(curr_arr); } if (found_contam) break; } if (!found_contam) /* no match found */ return NULL; /* save this match */ best_match = xmalloc(sizeof(match)); best_match->match = best_arr; best_match->shift = best_shift; best_match->length = best_length; best_match->ps = ps; best_match->score = best_score; best_match->adapter_index = best_adapter; best_match->p_quals = best_p_quals; best_match->match_pos = calloc(best_length, sizeof(int)); for (i = 0; i < best_length; i++) best_match->match_pos[i] = best_match->match[i] == MATCH_SCORE; return best_match; }
unsigned sum(unsigned n) { if (n) return n + sum(n - 1); else return 0; }
void lower_bound(vrp_problem *vrp, lb_params *lb_par, heurs *lh, int ub, int jobs, int *tids, int *sent) { int s_bufid, dummy; int y, i, alpha, interval; int *sorted_demand, trials; int m1, numroutes = vrp->numroutes, capacity = vrp->capacity; if (!lb_par->lower_bound) return; if (vrp->par.verbosity > 1) printf("\nNow beginning lower bounding ....\n\n"); /*Calculate m1 = maximum # of single vehicle routes*/ sorted_demand = (int *) calloc (vrp->vertnum, sizeof(int)); memcpy (sorted_demand, vrp->demand, vrp->vertnum*sizeof(int)); qsort (sorted_demand+1, vrp->vertnum-1, sizeof(int), intcompar); for (m1 = 0;; m1++) if (!(capacity*(numroutes-m1-1) >= sum(sorted_demand, m1+2, vrp->vertnum-1))) break; trials = (lb_par->lower_bound)*(numroutes-m1); lh->tids = tids; lh->jobs = jobs; if (!jobs) { fprintf(stderr, "\nNo jobs started .... \n\n"); return; } else if (vrp->par.verbosity >2) printf("\n%i jobs started ...\n\n", jobs); /*-----------------------------------------------------------------------*\ | Broadcast data to the lower bounding procedure | \*-----------------------------------------------------------------------*/ for(i=0; i<trials; i++) { s_bufid = init_send(DataInPlace); send_int_array(&dummy, 1); send_msg(tids[i%jobs], MST); sent[i%jobs]++; broadcast(vrp, tids+(i%jobs), 1); s_bufid = init_send(DataInPlace); send_int_array(&numroutes, 1); send_int_array(&ub, 1); send_int_array(&lb_par->lb_max_iter, 1); send_int_array(&m1, 1); send_msg(tids[i%jobs], VRP_LB_DATA); } interval = lb_par->lb_penalty_mult/lb_par->lower_bound; for (i=trials-1, y = m1, alpha = lb_par->lb_penalty_mult; i>=0; i--, y++) { s_bufid = init_send(DataInPlace); send_int_array(&y, 1); send_int_array(&alpha, 1); send_msg(tids[i%jobs], VRP_LB_DATA2); if (y == numroutes) { y = m1-1; alpha -= interval; } } freebuf(s_bufid); FREE(sorted_demand); }
int main() { return sum(10); }
int test_boost_point_arithmetic(point_type const& left, point_type const& right) { int error_count = 0; point_type a(left); point_type b = right; point_type sum(a); boost::geometry::add_point(sum, b); std::cout << "Point addition: a + b = " << to_string(sum) << "\n"; error_count += test_expected_value<0>(sum, left.template get<0>() + right.template get<0>()); error_count += test_expected_value<1>(sum, left.template get<1>() + right.template get<1>()); point_type difference(a); boost::geometry::subtract_point(difference, b); std::cout << "Point subtraction: a - b = " << to_string(difference) << "\n"; error_count += test_expected_value<0>(difference, left.template get<0>() - right.template get<0>()); error_count += test_expected_value<1>(difference, left.template get<1>() - right.template get<1>()); point_type pointwise_product(a); boost::geometry::multiply_point(pointwise_product, b); std::cout << "Pointwise product: " << to_string(pointwise_product) << "\n"; error_count += test_expected_value<0>(pointwise_product, left.template get<0>() * right.template get<0>()); error_count += test_expected_value<1>(pointwise_product, left.template get<1>() * right.template get<1>()); point_type pointwise_quotient(a); boost::geometry::divide_point(pointwise_quotient, b); std::cout << "Pointwise quotient: " << to_string(pointwise_quotient) << "\n"; error_count += test_expected_value<0>(pointwise_quotient, left.template get<0>() / right.template get<0>()); error_count += test_expected_value<1>(pointwise_quotient, left.template get<1>() / right.template get<1>()); point_type scalar_product(a); boost::geometry::multiply_value(scalar_product, 2); std::cout << "Scalar product: " << to_string(scalar_product) << "\n"; error_count += test_expected_value<0>(scalar_product, left.template get<0>() * 2); error_count += test_expected_value<1>(scalar_product, left.template get<1>() * 2); point_type scalar_quotient(a); boost::geometry::divide_value(scalar_quotient, 2); std::cout << "Scalar quotient: " << to_string(scalar_quotient) << "\n"; error_count += test_expected_value<0>(scalar_quotient, left.template get<0>() / 2); error_count += test_expected_value<1>(scalar_quotient, left.template get<1>() / 2); double distance = boost::geometry::distance(left, right); // double other_distance = left.distance_to(right); std::cout << "Geographic distance between points: " << distance << "\n"; return error_count; }
int depthSum(vector<NestedInteger>& nestedList) { return sum(nestedList,1); }
T mean(const libNumerics::vector<T>& v) { return (T) ( sum(v) / v.nrow() ); }
result_type result(Args const &args) const { extractor<SumFeature> sum; return numeric::fdiv(sum(args), count(args)); }