rot_mx rot_mx::cancel() const { int g = den(); for(std::size_t i=0;i<9;i++) g = scitbx::math::gcd_int(g, num_[i]); if (g == 0) return *this; return rot_mx(num_ / g, den() / g); }
int main ( void ) { d = 0.0; do_fxam(); printf("0x%4x: %f\n", i, d ); d = -0.0; do_fxam(); printf("0x%4x: %f\n", i, d ); d = inf(); do_fxam(); printf("0x%4x: %f\n", i, d ); d = -inf(); do_fxam(); printf("0x%4x: %f\n", i, d ); d = nAn(); do_fxam(); printf("0x%4x: %f\n", i, d ); d = -nAn(); do_fxam(); printf("0x%4x: %f\n", i, d ); d = den(); do_fxam(); printf("0x%4x: %f\n", i, d ); d = -den(); do_fxam(); printf("0x%4x: %f\n", i, d ); return 0; }
int fx_mantissa(Rational lbd, Rational ubd, Rational small) /*;mantissa*/ { Rational exact_val; int *vnum, *vden, *int_1; int power; lbd = rat_abs(lbd); ubd = rat_abs(ubd); /* find the exact # of values to be represented (aside from 0) */ if (rat_gtr(lbd, ubd)) exact_val = rat_div(lbd, small); else exact_val = rat_div(ubd, small); vnum = num(exact_val); vden = den(exact_val); int_1 = int_fri(1); /* the mantissa is calculated assuming that the bound is 'small away * from a model number, so we subtract one before computing no. of bits */ vnum = int_sub(vnum, int_1); vnum = int_quo(vnum, vden); vden = int_fri(1); power = 1; while (int_gtr(vnum, vden)) { power++; vden = int_add(int_add(vden, vden), int_1); } return power; }
Nombre& Entier::soustraction(const Nombre& n) const { // Nombre -> Entier const Entier* ptEntier = dynamic_cast<const Entier*>(&n); if (ptEntier == 0) { // Nombre -> Reel const Reel* ptReel = dynamic_cast<const Reel*>(&n); if (ptReel == 0) { // Nombre -> Rationnel const Rationnel* ptRationnel = dynamic_cast<const Rationnel*>(&n); if (ptRationnel == 0) { throw CalculatriceException("Entier : soustraction : Impossible d'effectuer le dynamic cast!"); } else { // Entier - Rationnel Entier num(mX * ptRationnel->getDen().getX() - ptRationnel->getNum().getX()); Entier den(ptRationnel->getDen().getX()); Rationnel* res = new Rationnel(num.toEntier(), den.toEntier()); res->simplifier(); Nombre& ref = *res; return(ref); } } else { // Entier - Reel Reel* res = new Reel(mX - ptReel->getX()); Nombre& ref = *res; return(ref); } } else { // Entier - Entier Entier* res = new Entier(mX - ptEntier->getX()); Nombre& ref = *res; return(ref); } }
dgMatrix dgMatrix::Symetric3by3Inverse () const { dgMatrix copy(*this); dgMatrix inverse(dgGetIdentityMatrix()); for (dgInt32 i = 0; i < 3; i++) { dgVector den(dgFloat32(1.0f) / copy[i][i]); copy[i] = copy[i].CompProduct4(den); inverse[i] = inverse[i].CompProduct4(den); for (dgInt32 j = 0; j < 3; j++) { if (j != i) { dgVector pivot(copy[j][i]); copy[j] -= copy[i].CompProduct4(pivot); inverse[j] -= inverse[i].CompProduct4(pivot); } } } #ifdef _DEBUG dgMatrix test(*this * inverse); dgAssert(dgAbsf(test[0][0] - dgFloat32(1.0f)) < dgFloat32(0.01f)); dgAssert(dgAbsf(test[1][1] - dgFloat32(1.0f)) < dgFloat32(0.01f)); dgAssert(dgAbsf(test[2][2] - dgFloat32(1.0f)) < dgFloat32(0.01f)); #endif return inverse; }
std::vector<typename CGAL::Fraction_traits<Fraction>::Numerator_type > integralize( const std::vector<Fraction>& vec, typename CGAL::Fraction_traits<Fraction>::Denominator_type& d ) { typedef CGAL::Fraction_traits<Fraction> FT; typedef typename FT::Numerator_type Numerator_type; typedef typename FT::Denominator_type Denominator_type; typename FT::Decompose decompose; std::vector<Numerator_type> num(vec.size()); std::vector<Denominator_type> den(vec.size()); // decompose each coefficient into integral part and denominator for (unsigned int i = 0; i < vec.size(); i++) { decompose(vec[i], num[i], den[i]); } // compute 'least' common multiple of all denominator // We would like to use gcd, so let's think of Common_factor as gcd. typename FT::Common_factor gcd; d = 1; for (unsigned int i = 0; i < vec.size(); i++) { d *= CGAL::integral_division(den[i], gcd(d, den[i])); } // expand each (numerator, denominator) pair to common denominator for (unsigned int i = 0; i < vec.size(); i++) { // For simplicity ImplicitInteroperability is expected in this example num[i] *= CGAL::integral_division(d, den[i]); } return num; }
void MAST::TimeDomainFlutterSolution::init (const MAST::FlutterSolverBase& solver, const Real v_ref, const Real bref, const LAPACK_DGGEV& eig_sol) { // make sure that it hasn't already been initialized libmesh_assert(!_roots.size()); _ref_val = v_ref; // iterate over the roots and initialize the vector const RealMatrixX &B = eig_sol.B(); const ComplexMatrixX &VR = eig_sol.right_eigenvectors(), &VL = eig_sol.left_eigenvectors(); const ComplexVectorX &num = eig_sol.alphas(), &den = eig_sol.betas(); unsigned int nvals = (int)B.rows(); _roots.resize(nvals); for (unsigned int i=0; i<nvals; i++) { MAST::TimeDomainFlutterRoot* root = new MAST::TimeDomainFlutterRoot; _roots[i] = root; root->init(v_ref, bref, num(i), den(i), B, VR.col(i), VL.col(i)); } }
rot_mx rot_mx::new_denominator(int new_den) const { rot_mx result(new_den); if (utils::change_denominator(num_.begin(), den(), result.num_.begin(), new_den, num_.size()) != 0) { throw_unsuitable_rot_mx(__FILE__, __LINE__); } return result; }
// Get frequency response at freq float_type iir_coeff::freqz_mag(float_type freq) { int i; std::complex<float_type> z(1, 0); std::complex<float_type> z_inc = std::complex<float_type>(std::cos(freq), std::sin(freq)); std::complex<float_type> nom(0); std::complex<float_type> den(0); for (i = 0; i < order + 1; i++) { nom += z * b_tf[i]; den += z * a_tf[i]; z *= z_inc; } return std::sqrt(std::norm(nom / den)); }
void swgen(Swtch swp) { int *buckets, k, n; long *v = swp->values; buckets = newarray(swp->ncases + 1, sizeof *buckets, FUNC); for (n = k = 0; k < swp->ncases; k++, n++) { buckets[n] = k; while (n > 0 && den(n-1, k) >= density) n--; } buckets[n] = swp->ncases; swcode(swp, buckets, 0, n - 1); }
void MAST::PKFlutterSolution::init (const MAST::PKFlutterSolver& solver, const Real k_red, const Real v_ref, const Real bref, const RealMatrixX& kmat, const LAPACK_ZGGEV& eig_sol) { // make sure that it hasn't already been initialized libmesh_assert(!_roots.size()); _ref_val = v_ref; _k_red = k_red; _stiff_mat = kmat; // iterate over the roots and initialize the vector _Amat = eig_sol.A(); _Bmat = eig_sol.B(); const ComplexMatrixX &VR = eig_sol.right_eigenvectors(), &VL = eig_sol.left_eigenvectors(); const ComplexVectorX &num = eig_sol.alphas(), &den = eig_sol.betas(); unsigned int nvals = (unsigned int)_Bmat.rows(); _roots.resize(nvals); // iterate over the roots and initialize the vector for (unsigned int i=0; i<nvals; i++) { MAST::PKFlutterRoot* root = new MAST::PKFlutterRoot; root->init(k_red, v_ref, bref, num(i), den(i), kmat, VR.col(i), VL.col(i)); _roots[i] = root; } }
vec3d linePlaneIntersect(vec3d x1, vec3d x2, vec3d x3, vec3d x4, vec3d x5, double *tp) { mat44 num(1, 1, 1, 1, x1.v[0], x2.v[0], x3.v[0], x4.v[0], x1.v[1], x2.v[1], x3.v[1], x4.v[1], x1.v[2], x2.v[2], x3.v[2], x4.v[2]); mat44 den(1, 1, 1, 0, x1.v[0], x2.v[0], x3.v[0], x5.v[0] - x4.v[0], x1.v[1], x2.v[1], x3.v[1], x5.v[1] - x4.v[1], x1.v[2], x2.v[2], x3.v[2], x5.v[2] - x4.v[2]); // parametric value double t = -num.det() / den.det(); if (tp != NULL) *tp = t; return x4 + (x5 - x4) * t; }
std::string DecimalStr(const BigRat& q, const MachineInt& DecimalPlaces) { if (IsNegative(DecimalPlaces) || !IsSignedLong(DecimalPlaces) || IsZero(DecimalPlaces)) CoCoA_ERROR(ERR::BadArg, "FixedStr"); if (IsOneDen(q)) return DecimalStr(num(q), DecimalPlaces); const long DigitsAfterPoint = AsSignedLong(DecimalPlaces); const BigInt N = RoundDiv(abs(num(q))*power(10,DigitsAfterPoint),den(q)); string digits = ToString(N); if (len(digits) < 1+DigitsAfterPoint) { digits = string(DigitsAfterPoint+1-len(digits), '0') + digits; } string ans; if (q < 0) ans = '-'; const long IntegerPart = len(digits) - DigitsAfterPoint; ans.insert(ans.end(), &digits[0], &digits[IntegerPart]); ans += '.'; ans.insert(ans.end(), &digits[IntegerPart], &digits[IntegerPart+DigitsAfterPoint]); return ans; }
static void adjust_icalls_eprob(const blt_options& opt, dependent_prob_cache& dpc, icalls_t& ic, const snp_pos_info& pi, std::vector<float>& dependent_eprob) { const unsigned ic_size(ic.size()); #ifdef DEBUG_ADJUST for (unsigned i(0); i<ic_size; ++i) { base_call& bi(pi.calls[ic[i]]); std::cerr << "BEFORE: " << i << " " << bi.is_neighbor_mismatch << " " << dependent_eprob[ic[i]] << "\n"; } #endif static const bool is_use_vexp_frac(true); // produce weighted fraction of reads with a neighboring mismatch: blt_float_t vexp_frac(opt.bsnp_ssd_no_mismatch); if (is_use_vexp_frac) { static const blt_float_t lnran(std::log(0.75)); blt_float_t num(0); blt_float_t den(0); for (unsigned i(0); i<ic_size; ++i) { const base_call& bi(pi.calls[ic[i]]); // const blt_float_t eprob(dependent_eprob[ic[i]]); const blt_float_t weight(lnran-bi.ln_error_prob()); den += weight; if (bi.is_neighbor_mismatch) { num += weight; } } blt_float_t mismatch_frac(0); if (ic_size && (den>0.)) mismatch_frac=(num/den); vexp_frac=(1.-mismatch_frac)*opt.bsnp_ssd_no_mismatch+mismatch_frac*opt.bsnp_ssd_one_mismatch; } const bool is_limit_vexp_iterations(opt.max_vexp_iterations>0); const int max_vexp_iterations(opt.max_vexp_iterations); const bool is_limit_vexp(opt.is_min_vexp); const blt_float_t min_vexp(opt.min_vexp); // used cached dependent probs once we reach the min_vexp level: bool is_min_vexp(false); std::sort(ic.begin(),ic.end(),sort_icall_by_eprob(pi)); blt_float_t vexp(1.); for (unsigned i(0); i<ic_size; ++i) { const base_call& bi(pi.calls[ic[i]]); if (! is_min_vexp) { dependent_eprob[ic[i]] = static_cast<float>(get_dependent_eprob(bi.get_qscore(),vexp)); if (is_limit_vexp_iterations && (static_cast<int>(i)>=max_vexp_iterations)) continue; blt_float_t next_vexp(vexp); if (is_use_vexp_frac) { next_vexp *= (1.-vexp_frac); } else { if (bi.is_neighbor_mismatch) { next_vexp *= (1.-opt.bsnp_ssd_one_mismatch); } else { next_vexp *= (1.-opt.bsnp_ssd_no_mismatch); } } if (is_limit_vexp) { is_min_vexp=(next_vexp<=min_vexp); vexp = std::max(min_vexp,next_vexp); } else { vexp = next_vexp; } } else { // cached version: dependent_eprob[ic[i]] = static_cast<float>(dpc.get_dependent_val(bi.get_qscore(),vexp)); } } #ifdef DEBUG_ADJUST for (unsigned i(0); i<ic_size; ++i) { base_call& bi(pi.calls[ic[i]]); std::cerr << "AFTER: " << i << " " << bi.is_neighbor_mismatch << " " << dependent_eprob[ic[i]] << "\n"; } #endif }
std::vector<RingElem> BM_QQ(const SparsePolyRing& P, const ConstMatrixView& pts_in) { const long NumPts = NumRows(pts_in); const long dim = NumCols(pts_in); matrix pts = NewDenseMat(RingQQ(), NumPts, dim); for (long i=0; i < NumPts; ++i) for (long j=0; j < dim; ++j) { BigRat q; if (!IsRational(q, pts_in(i,j))) throw 999; SetEntry(pts,i,j, q); } // Ensure input pts have integer coords by using // scale factors for each indet. vector<BigInt> ScaleFactor(dim, BigInt(1)); for (long j=0; j < dim; ++j) for (long i=0; i < NumPts; ++i) ScaleFactor[j] = lcm(ScaleFactor[j], ConvertTo<BigInt>(den(pts(i,j)))); mpz_t **points = (mpz_t**)malloc(NumPts*sizeof(mpz_t*)); for (long i=0; i < NumPts; ++i) { points[i] = (mpz_t*)malloc(dim*sizeof(mpz_t)); for (long j=0; j < dim; ++j) mpz_init(points[i][j]); for (long j=0; j < dim; ++j) { mpz_set(points[i][j], mpzref(ConvertTo<BigInt>(ScaleFactor[j]*pts(i,j)))); } } BMGB char0; // these will be "filled in" by BM_affine below BM modp; // pp_cmp_PPM = &PPM(P); // not threadsafe! BM_affine(&char0, &modp, dim, NumPts, points, pp_cmp); // THIS CALL DOES THE REAL WORK!!! pp_cmp_PPM = NULL; for (long i=NumPts-1; i >=0 ; --i) { for (long j=0; j < dim; ++j) mpz_clear(points[i][j]); free(points[i]); } free(points); if (modp == NULL) { if (char0 != NULL) BMGB_dtor(char0); CoCoA_ERROR("Something went wrong", "BM_QQ"); } // Now extract the answer... const int GBsize = char0->GBsize; std::vector<RingElem> GB(GBsize); const long NumVars = dim; vector<long> expv(NumVars); // buffer for creating monomials for (int i=0; i < GBsize; ++i) { BigInt denom(1); // scale factor needed to make GB elem monic. for (int var = 0; var < NumVars; ++var) { expv[var] = modp->pp[modp->GB[i]][var]; denom *= power(ScaleFactor[var], expv[var]); } RingElem GBelem = monomial(P, 1, expv); for (int j=0; j < NumPts; ++j) { if (mpq_sgn(char0->GB[i][j])==0) continue; BigRat c(char0->GB[i][j]); for (int var = 0; var < NumVars; ++var) { expv[var] = modp->pp[modp->sep[j]][var]; c *= power(ScaleFactor[var], expv[var]); } GBelem += monomial(P, c/denom, expv); } GB[i] = GBelem; } BMGB_dtor(char0); BM_dtor(modp); return GB; // ignoring separators for the moment }
//--------------------------------------------------------------------------- //用于生成高斯点序列 int Gauss::Generate_gauss_array(vector<double> &gauss, vector<double> &weight)const { //开始计算 int n = precision; int iter = 10; //迭代次数 int m=int((n+1)/2); int e1=n*(n+1); int mm=4*m-1; vector<long double> t; for(int i=3; i<=mm; i=i+4) { t.push_back((PI/(4*n+2))*i); } int nn=(1-(1-1/n)/(8*n*n)); vector<long double> xo; for(int i=0; i<m; i++) { xo.push_back(nn*cos(t[i])); } vector<long double> pk; vector<long double> den(m); vector<long double> d1(m); vector<long double> dpn(m); vector<long double> d2pn(m); vector<long double> d3pn(m); vector<long double> d4pn(m); vector<long double> u(m); vector<long double> v(m); vector<long double> h(m); vector<long double> p(m); vector<long double> dp(m); for(int j=1; j<=iter; j++) { vector<long double> pkm1(m, 1.0); pk=xo; for(int k=2; k<=n; k++) { vector<long double> t1(m); vector<long double> pkp1(m); for(int i=0; i<m; i++) { t1[i]=xo[i]*pk[i]; pkp1[i]=t1[i]-pkm1[i]-(t1[i]-pkm1[i])/k+t1[i]; } pkm1=pk; pk=pkp1; } for(int i=0; i<m; i++) { den[i]=1.0-xo[i]*xo[i]; d1[i]=n*(pkm1[i]-xo[i]*pk[i]); dpn[i]=d1[i]/den[i]; d2pn[i]=(2.0*xo[i]*dpn[i]-e1*pk[i])/den[i]; d3pn[i]=(4*xo[i]*d2pn[i]+(2-e1)*dpn[i])/den[i]; d4pn[i]=(6*xo[i]*d3pn[i]+(6-e1)*d2pn[i])/den[i]; u[i]=pk[i]/dpn[i]; v[i]=d2pn[i]/dpn[i]; h[i]=-u[i]*(1+(0.5*u[i])*(v[i]+u[i]*(v[i]*v[i]-u[i]*d3pn[i]/(3*dpn[i])))); p[i]=pk[i]+h[i]*(dpn[i]+(0.5*h[i])*(d2pn[i]+(h[i]/3)*(d3pn[i]+0.25*h[i]*d4pn[i]))); dp[i]=dpn[i]+h[i]*(d2pn[i]+(0.5*h[i])*(d3pn[i]+h[i]*d4pn[i]/3)); h[i]=h[i]-p[i]/dp[i]; xo[i]=xo[i]+h[i]; } } vector<long double> bp(m); vector<long double> fx(m); vector<long double> wf(m); for(int i=0; i<m; i++) { bp[i]=-xo[i]-h[i]; fx[i]=d1[i]-h[i]*e1*(pk[i]+(h[i]/2)*(dpn[i]+(h[i]/3)*(d2pn[i]+(h[i]/4)*(d3pn[i]+(0.2*h[i])*d4pn[i])))); wf[i]=2*(1-bp[i]*bp[i])/(fx[i]*fx[i]); } if((m+m)>n) bp[m-1]=0; if((m+m) != n) m=m-1; for(int i=m-1; i>=0; i--) { bp.push_back(-bp[i]); wf.push_back(wf[i]); } for(int i=0; i<n; i++) { gauss.push_back(bp[i]); weight.push_back(wf[i]); } //cout << "bp=" << endl; //for(int i=0; i<n; i++) //{ // cout << setprecision(20) << bp[i] << endl; //} //cout << "wf=" << endl; //long double sum=0.0; //for(int i=0; i<n; i++) //{ // sum += wf[i]; // cout << setprecision(20) << wf[i] << endl; //} //cout << setprecision(20) << "sum=" << sum << endl; return 1; }
void run( const int N, const int M, const int L, const int hyper_threads, const int vector_lanes, const int nx, const int ny, const int nz, const int ichunk, const int nang, const int noct, const int ng, const int nmom, const int cmom, const vector<diag_c>& diag ) { typedef typename Kokkos::DefaultExecutionSpace device_t; typedef TeamPolicy<device_t> team_policy_t; typedef View<double*, device_t> view_1d_t; typedef View<double**, Kokkos::LayoutLeft, device_t> view_2d_t; typedef View<double***, Kokkos::LayoutLeft, device_t> view_3d_t; typedef View<double****, Kokkos::LayoutLeft, device_t> view_4d_t; typedef View<double*****, Kokkos::LayoutLeft, device_t> view_5d_t; typedef View<double******, Kokkos::LayoutLeft, device_t> view_6d_t; typedef View<double*******, Kokkos::LayoutLeft, device_t> view_7d_t; int id = 1; int ich = 1; int jlo = 0; int jhi = ny-1; int jst = 1; int jd = 2; int klo = 0; int khi = nz-1; int kst = 1; int kd = 2; double hi = c1; Kokkos::initialize(); Kokkos::DefaultExecutionSpace::print_configuration(cout); view_4d_t psii( "psii", nang, ny, nz, ng ); view_4d_t psij( "psij", nang, ichunk, nz, ng ); view_4d_t psik( "psik", nang, ichunk, ny, ng ); view_4d_t jb_in( "jb_in", nang, ichunk, ny, ng ); // jb_in(nang,ichunk,nz,ng) view_4d_t kb_in( "kb_in", nang, ichunk, ny, ng ); // kb_in(nang,ichunk,nz,ng) view_6d_t qim( "qim", nang, nx, ny, nz, noct, ng ); // qim(nang,nx,ny,nz,noct,ng) view_5d_t qtot( "qtot", cmom, nx, ny, nx, ng ); // qtot(cmom,nx,ny,nz,ng) view_2d_t ec( "ec", nang, cmom ); // ec(nang,cmom) view_1d_t mu( "mu", nang ); // mu(nang) view_1d_t w( "w", nang ); // w(nang) view_1d_t wmu( "wmu", nang ); // wmu(nang) view_1d_t weta( "weta", nang ); // weta(nang) view_1d_t wxi( "wxi", nang ); // wxi(nang) view_1d_t hj( "hj", nang ); // hj(nang) view_1d_t hk( "hk", nang ); // hk(nang) view_1d_t vdelt( "vdelt", ng ); // vdelt(ng) view_6d_t ptr_in( "ptr_in", nang, nx, ny, nz, noct, ng ); // ptr_in(nang,nx,ny,nz,noct,ng) view_6d_t ptr_out( "ptr_out", nang, nx, ny, nz, noct, ng ); // ptr_out(nang,nx,ny,nz,noct,ng) view_4d_t flux( "flux", nx, ny, nz, ng ); // flux(nx,ny,nz,ng) view_5d_t fluxm( "fluxm", cmom-1, nx, ny, nz, ng ); //fluxm(cmom-1,nx,ny,nz,ng) view_2d_t psi( "psi", nang, M ); view_2d_t pc( "pc", nang, M ); view_4d_t jb_out( "jb_out", nang, ichunk, nz, ng ); view_4d_t kb_out( "kb_out", nang, ichunk, ny, ng ); view_4d_t flkx( "flkx", nx+1, ny, nz, ng ); view_4d_t flky( "flky", nx, ny+1, nz, ng ); view_4d_t flkz( "flkz", nx, ny, nz+1, ng ); view_3d_t hv( "hv", nang, 4, M ); // hv(nang,4,M) view_3d_t fxhv( "fxhv", nang, 4, M ); // fxhv(nang,4,M) view_5d_t dinv( "dinv", nang, nx, ny, nz, ng ); // dinv(nang,nx,ny,nz,ng) view_2d_t den( "den", nang, M ); // den(nang,M) view_4d_t t_xs( "t_xs", nx, ny, nz, ng ); // t_xs(nx,ny,nz,ng) const team_policy_t policy( N, hyper_threads, vector_lanes ); for (int ii = 0; ii < n_test_iter; ii++) { Kokkos::Impl::Timer timer; for (int oct = 0; oct < noct; oct++) { parallel_for( policy, dim3_sweep2< team_policy_t, view_1d_t, view_2d_t, view_3d_t, view_4d_t, view_5d_t, view_6d_t, view_7d_t > ( M, L, ng, cmom, noct, nx, ny, nz, ichunk, diag, id, ich, oct, jlo, jhi, jst, jd, klo, khi, kst, kd, psii, psij, psik, jb_in, kb_in, qim, qtot, ec, mu, w, wmu, weta, wxi, hi, hj, hk, vdelt, ptr_in, ptr_out, flux, fluxm, psi, pc, jb_out, kb_out, flkx, flky, flkz, hv, fxhv, dinv, den, t_xs ) ); }// end noct std::cout << " ii " << ii << " elapsed time " << timer.seconds() << std::endl; } // end n_test_iter Kokkos::finalize(); }
mpz_class renf_elem_class::get_den() const { return den(); }
/// @brief Parses a list of parameters and sets reader state accordingly /// @param tags The list of parameters to parse void YUV4MPEGVideoProvider::ParseFileHeader(const std::vector<std::string>& tags) { if (tags.size() <= 1) throw VideoOpenError("ParseFileHeader: contentless header"); if (tags.front() == "YUV4MPEG2") throw VideoOpenError("ParseFileHeader: malformed header (bad magic)"); // temporary stuff int t_w = -1; int t_h = -1; int t_fps_num = -1; int t_fps_den = -1; Y4M_InterlacingMode t_imode = Y4M_ILACE_NOTSET; Y4M_PixelFormat t_pixfmt = Y4M_PIXFMT_NONE; for (unsigned i = 1; i < tags.size(); i++) { std::string tag; tag = tags[i]; if (tag.find("W") == 0) { tag.erase(0,1); t_w = agi::util::strtoi(tag); if (t_w == 0) throw VideoOpenError("ParseFileHeader: invalid width"); } else if (tag.find("H") == 0) { tag.erase(0,1); t_h = agi::util::strtoi(tag); if (t_h == 0) throw VideoOpenError("ParseFileHeader: invalid height"); } else if (tag.find("F") == 0) { tag.erase(0,1); int i = tag.find(":"); std::string num(tag.substr(0,i)); std::string den(tag.substr(i+1,den.size())); t_fps_num = agi::util::strtoi(num); t_fps_den = agi::util::strtoi(den); if ((t_fps_num == 0) || (t_fps_den == 0)) throw VideoOpenError("ParseFileHeader: invalid framerate"); } else if (tag.find("C") == 0) { tag.erase(0,1); // technically this should probably be case sensitive, // but being liberal in what you accept doesn't hurt agi::util::str_lower(tag); if (tag == "420") t_pixfmt = Y4M_PIXFMT_420JPEG; // is this really correct? else if (tag == "420jpeg") t_pixfmt = Y4M_PIXFMT_420JPEG; else if (tag == "420mpeg2") t_pixfmt = Y4M_PIXFMT_420MPEG2; else if (tag == "420paldv") t_pixfmt = Y4M_PIXFMT_420PALDV; else if (tag == "411") t_pixfmt = Y4M_PIXFMT_411; else if (tag == "422") t_pixfmt = Y4M_PIXFMT_422; else if (tag == "444") t_pixfmt = Y4M_PIXFMT_444; else if (tag == "444alpha") t_pixfmt = Y4M_PIXFMT_444ALPHA; else if (tag == "mono") t_pixfmt = Y4M_PIXFMT_MONO; else throw VideoOpenError("ParseFileHeader: invalid or unknown colorspace"); } else if (tag.find("I") == 0) { tag.erase(0,1); agi::util::str_lower(tag); if (tag == "p") t_imode = Y4M_ILACE_PROGRESSIVE; else if (tag == "t") t_imode = Y4M_ILACE_TFF; else if (tag == "b") t_imode = Y4M_ILACE_BFF; else if (tag == "m") t_imode = Y4M_ILACE_MIXED; else if (tag == "?") t_imode = Y4M_ILACE_UNKNOWN; else throw VideoOpenError("ParseFileHeader: invalid or unknown interlacing mode"); } else LOG_D("provider/video/yuv4mpeg") << "Unparsed tag: " << tags[i].c_str(); } // The point of all this is to allow multiple YUV4MPEG2 headers in a single file // (can happen if you concat several files) as long as they have identical // header flags. The spec doesn't explicitly say you have to allow this, // but the "reference implementation" (mjpegtools) does, so I'm doing it too. if (inited) { if (t_w > 0 && t_w != w) throw VideoOpenError("ParseFileHeader: illegal width change"); if (t_h > 0 && t_h != h) throw VideoOpenError("ParseFileHeader: illegal height change"); if ((t_fps_num > 0 && t_fps_den > 0) && (t_fps_num != fps_rat.num || t_fps_den != fps_rat.den)) throw VideoOpenError("ParseFileHeader: illegal framerate change"); if (t_pixfmt != Y4M_PIXFMT_NONE && t_pixfmt != pixfmt) throw VideoOpenError("ParseFileHeader: illegal colorspace change"); if (t_imode != Y4M_ILACE_NOTSET && t_imode != imode) throw VideoOpenError("ParseFileHeader: illegal interlacing mode change"); } else { w = t_w; h = t_h; fps_rat.num = t_fps_num; fps_rat.den = t_fps_den; pixfmt = t_pixfmt != Y4M_PIXFMT_NONE ? t_pixfmt : Y4M_PIXFMT_420JPEG; imode = t_imode != Y4M_ILACE_NOTSET ? t_imode : Y4M_ILACE_UNKNOWN; fps = double(fps_rat.num) / fps_rat.den; inited = true; } }
Rational to_rational(InputT& x) { // typedef Fraction_traits<Rational> FT; // typedef typename FT::Is_fraction Is_fraction; // typedef typename FT::Numerator_type Numerator_type; // typedef typename FT::Denominator_type Denominator_type; // typename FT::Compose compose; // BOOST_STATIC_ASSERT((::boost::is_same<Is_fraction,Tag_true>::value)); // BOOST_STATIC_ASSERT((::boost::is_same<Numerator_type,Denominator_type>::value)); typedef typename Rational::int_type Numerator_type; Numerator_type num(0),den(1); if (x != 0.0) { bool neg = (x < 0); if (neg) x = -x; const unsigned shift = 15; // a safe shift per step const int shift_pow = 32768; // = 2^shift const InputT width = 32768; // = 2^shift const int maxiter = 20; // ought not be necessary, but just // in case, max 300 bits of // precision int expt; InputT mantissa = std::frexp(x, &expt); long exponent = expt; InputT intpart; int k = 0; while (mantissa != 0.0 && k++ < maxiter) { mantissa *= width; // shift double mantissa mantissa = std::modf(mantissa, &intpart); num *= shift_pow; num += (int)intpart; exponent -= shift; } int expsign = (exponent>0 ? +1 : (exponent<0 ? -1 : 0)); exponent *= expsign; Numerator_type twopot(2); Numerator_type exppot(1); while (exponent!=0) { if (exponent & 1) exppot *= twopot; exponent >>= 1; twopot *= twopot; } if (expsign > 0) num *= exppot; else if (expsign < 0) den *= exppot; if (neg) num = -num; }