void OpenNaturalCubicSpline::computeCoefficients() { int nPoints = m_vControlPoints.size(); QVector< float > gamma( nPoints ); QVector< float > delta( nPoints ); QVector< float > D( nPoints ); gamma[0] = 0.5f; for( int i = 1; i < nPoints - 1; ++i ) { gamma[i] = 1.0f / ( 4.0f - gamma[ i - 1 ] ); } gamma[ nPoints - 1 ] = 1.0f / ( 2.0f - gamma[ nPoints - 2 ] ); delta[0] = 3.0f * ( m_vControlPoints[1] - m_vControlPoints[0] ) * gamma[0]; for( int i = 1; i < nPoints - 1; ++i ) { delta[i] = ( 3.0f * ( m_vControlPoints[i+1] - m_vControlPoints[i-1] ) - delta[i-1] ) * gamma[i]; } delta[ nPoints - 1 ] = ( 3.0f * ( m_vControlPoints[ nPoints - 1 ] - m_vControlPoints[ nPoints - 2 ] ) - delta[ nPoints - 2 ] ) * gamma[ nPoints - 1 ]; D[ nPoints - 1 ] = delta[ nPoints - 1 ]; for( int i = nPoints - 2; i >= 0; --i ) { D[i] = delta[i] - gamma[i] * D[ i+1 ]; } m_vCoefficients.resize( nPoints - 1 ); for( int i = 0; i < nPoints - 1; ++i ) { m_vCoefficients[i][0] = m_vControlPoints[i]; m_vCoefficients[i][1] = D[i]; m_vCoefficients[i][2] = 3.0f * ( m_vControlPoints[ i + 1 ] - m_vControlPoints[i] ) - 2.0f * D[i] - D[ i + 1 ]; m_vCoefficients[i][3] = 2.0f * ( m_vControlPoints[i] - m_vControlPoints[ i + 1 ] ) + D[i] + D[ i + 1 ]; } }
NAMESPACE_END SEAL::SEAL(const byte *key, word32 counter, unsigned int L) : L(L), R(4*L/8192), S(256), T(512), startCount(counter), counter(counter), position(0), buffer(L/8) { assert(L%8192 == 0); Gamma gamma(key); unsigned int i; for (i=0; i<512; i++) T[i] = gamma.Apply(i); for (i=0; i<256; i++) S[i] = gamma.Apply(0x1000+i); for (i=0; i<4*(L/8192); i++) R[i] = gamma.Apply(0x2000+i); Generate(counter, buffer); }
int poiss2(double lambda){ // Gamma method by Ahrens-Dieter // Resulting distribution corresponds to one given by p_poiss int k = 0; int n; double c = 2.2160358671665; double w = lambda; double p,b,u,x; id1: if(w>=c){ n = floor(7.0*w/8.0); x = gamma(n); if(x>w){ p = w/x; do{ u = uniform(0.0,1.0); if(u<=p){ k++; } // maybe u not n? <- that's right: must be u, not n! n = n-1; }while(n>1); //k--; // do not need this decrement return k; } else{ k = k + n; w = w - x; goto id1; } } else{ p = 1.0; b = exp(-w); do{ u = uniform(0.0,1.0); p = p*u; k++; }while(p>=b); k--; return k; } }
Interaction Triangle::Sample(const Point2f &u) const { Point2f b = UniformSampleTriangle(u); // Get triangle vertices in _p0_, _p1_, and _p2_ const Point3f &p0 = mesh->p[v[0]]; const Point3f &p1 = mesh->p[v[1]]; const Point3f &p2 = mesh->p[v[2]]; Interaction it; it.p = b[0] * p0 + b[1] * p1 + (1 - b[0] - b[1]) * p2; // Compute surface normal for sampled point on triangle if (mesh->n) it.n = Normalize(b[0] * mesh->n[v[0]] + b[1] * mesh->n[v[1]] + (1 - b[0] - b[1]) * mesh->n[v[2]]); else it.n = Normalize(Normal3f(Cross(p1 - p0, p2 - p0))); if (reverseOrientation) it.n *= -1; // Compute error bounds for sampled point on triangle Point3f pAbsSum = Abs(b[0] * p0) + Abs(b[1] * p1) + Abs((1 - b[0] - b[1]) * p2); it.pError = gamma(6) * Vector3f(pAbsSum.x, pAbsSum.y, pAbsSum.z); return it; }
/* * Noekeon Key Schedule */ void Noekeon::key_schedule(const byte key[], size_t) { u32bit A0 = load_be<u32bit>(key, 0); u32bit A1 = load_be<u32bit>(key, 1); u32bit A2 = load_be<u32bit>(key, 2); u32bit A3 = load_be<u32bit>(key, 3); for(size_t i = 0; i != 16; ++i) { A0 ^= RC[i]; theta(A0, A1, A2, A3); A1 = rotate_left(A1, 1); A2 = rotate_left(A2, 5); A3 = rotate_left(A3, 2); gamma(A0, A1, A2, A3); A1 = rotate_right(A1, 1); A2 = rotate_right(A2, 5); A3 = rotate_right(A3, 2); } A0 ^= RC[16]; DK.resize(4); DK[0] = A0; DK[1] = A1; DK[2] = A2; DK[3] = A3; theta(A0, A1, A2, A3); EK.resize(4); EK[0] = A0; EK[1] = A1; EK[2] = A2; EK[3] = A3; }
/* Synopsis: attempts to set a real form and dual real form interactively. In case of failure, throws an InputError and returns. */ void repr_mode_entry() throw(EntryError) { try { RealReductiveGroup& GR = currentRealGroup(); Weight lambda_rho; RatWeight gamma(0); KGBElt x; sub = new SubSystemWithGroup (interactive::get_parameter(GR,x,lambda_rho,gamma)); Permutation pi; std::cout << "Subsystem on dual side is "; if (sub->rank()==0) std::cout << "empty.\n"; else { std::cout << "of type " << dynkin::Lie_type(sub->cartanMatrix(),true,false,pi) << ", with roots "; for (weyl::Generator s=0; s<sub->rank(); ++s) std::cout << sub->parent_nr_simple(pi[s]) << (s<sub->rank()-1 ? "," : ".\n"); } sr = new StandardRepr(currentRepContext().sr(x,lambda_rho,gamma)); } catch(error::InputError& e) { repr_mode_exit(); // clean up e("no parameter was set"); throw EntryError(); } }
double gamma ( double x ) { double ret; if ( x<=0.0 ) { ret = 0.0; } #if 0 else if ( x<0.5 ) { ret = gamma_kernel(x+1.0)/x; /* Puts x in [0.5,1.5) */ } else if ( x<1.5 ) { ret = gamma_kernel(x); /* Puts x in [0.5,1.5) */ } else { ret = (x-1.0) * gamma(x-1.0); /* Recurse till x in [0.5,1.5) */ } #else else if ( x<1.0 )
Panel::Panel() { // declare a panel _accessMode=new LcdAccessMode; _gl=new LcdPanel(*_accessMode); // apply the gamma curve. Note that gammas are panel specific. This curve is appropriate // to a replacement (non-original) panel obtained from ebay. uint8_t levels[13]={ 0xe,0,1,1,0,0,0,0,0,0,3,4,0 }; R61523Gamma gamma(levels); _gl->applyGamma(gamma); // create the default backlight and leave it switched off for now _backlight=new LcdBacklight(*_accessMode); // clear to black while the lights are out _gl->setBackground(ColourNames::BLACK); _gl->clearScreen(); }
double calculateMaxTrackSpeedAngle(double T, double theta, double error, double max_vel_x, double max_vel_th, double v_max_ang) { if (fabs(theta) <= EPSILON) return max_vel_x; if (fabs(theta / T) <= max_vel_th) { double vstar_error = calcVstarError(T, theta, error); if (vstar_error <= v_max_ang) { //return 0; return std::min(vstar_error * (2.0 * (1.0 - cos(theta))) / (theta * sin(theta)), max_vel_x); } else { double a, b, g; a = T * T; b = beta(T, theta, v_max_ang); g = gamma(T, theta, error, v_max_ang); //return 1; return std::min((-b + sqrt(collvoid::sqr(b) - 4 * collvoid::sqr(a) * g)) / (2.0 * g), max_vel_x); } } else // return 2; return std::min(sign(theta) * error * max_vel_th / theta, max_vel_x); }
double RNG::gamma(double shape, double scale) { if (shape < 1.) return gamma(shape + 1., scale) * pow(rand_open01(), 1.0 / shape); const double d = shape - 1. / 3.; const double c = 1. / sqrt(9. * d); double x, v; for (;;) { do { x = RNOR(); v = 1.0 + c * x; } while (v <= 0.0); v = v * v * v; const double u = rand_open01(); const double x2 = x * x; if (u < 1.0 - 0.0331 * x2 * x2) return (d * v / scale); if (log(u) < 0.5 * x2 + d * (1.0 - v + log(v))) return (d * v / scale); } } // RNG::gamma
void AddWeightedTest::testAllocate0() { m_operator->setParameter(AddWeighted::DATA_FLOW, runtime::Enum(AddWeighted::ALLOCATE)); m_operator->initialize(); m_operator->activate(); runtime::DataContainer src1(new cvsupport::Image("lenna.jpg", cvsupport::Image::DEPTH_16)); runtime::Float64 alpha(-1.0); runtime::DataContainer src2(new cvsupport::Image("barbara.jpg", cvsupport::Image::DEPTH_16)); runtime::Float64 beta(10.0); runtime::Float64 gamma(2.0); m_operator->setInputData(AddWeighted::SRC_1, src1); m_operator->setParameter(AddWeighted::ALPHA, alpha); m_operator->setInputData(AddWeighted::SRC_2, src2); m_operator->setParameter(AddWeighted::BETA, beta); m_operator->setParameter(AddWeighted::GAMMA, gamma); runtime::DataContainer dstResult = m_operator->getOutputData(AddWeighted::DST); runtime::ReadAccess dstAccess(dstResult); cvsupport::Image::save("AddWeightedTest_testAllocate0_dst.png", dstAccess.get<runtime::Image>()); }
void MSSM(double mA, double tanb, double *ldu, double *lvu, double *kuu){ double mZ = 91.0; double mh = 125.09; double su_d = TMath::Sqrt(1+ ( ((mA*mA)+(mZ*mZ))*((mA*mA)+(mZ*mZ))*tanb*tanb ) / (( (mZ*mZ) + (mA*mA*tanb*tanb) - (mh*mh)*(1+tanb*tanb) )*( (mZ*mZ) + (mA*mA*tanb*tanb) - (mh*mh)*(1+tanb*tanb) )) ); double su = 1./su_d; double sd = su*( ((mA*mA)+(mZ*mZ))*tanb ) / ((mZ*mZ) + (mA*mA*tanb*tanb) - mh*mh*(1+tanb*tanb)); // MSSM Stylee double tanb2s = TMath::Sqrt(1+(tanb*tanb)); double kV = (sd+(tanb*su))/tanb2s; double ku = su*tanb2s/tanb; double kd = sd*tanb2s; //double G = gamma(kV,ku,kd); // std::cout << mA << ", " << tanb << std::endl; // std::cout << kV << ", " << ku << ", " << kd << ", " << std::endl; // std::cout << gamma(kV,ku,kd) << std::endl; *ldu = kd/ku; *lvu = kV/ku; *kuu = ku*ku/gamma(kV,ku,kd); }
void type1(double cosbma, double tanbeta, double *ldu, double *lvu, double *kuu){ double sinbma = TMath::Sqrt(1-cosbma*cosbma); double tana = (tanbeta*cosbma-sinbma)/(cosbma+tanbeta*sinbma); double cosa = 1./(TMath::Sqrt(1+tana*tana)); double sinb = tanbeta/(TMath::Sqrt(1+tanbeta*tanbeta)); // get the sign of cos(a) .... sigh! double bma = TMath::ACos(cosbma); double beta = TMath::ATan(tanbeta); double alpha = beta-bma; double scos = TMath::Cos(alpha); cosa *= scos/TMath::Abs(scos); // Type-1 double kV = sinbma; double kf = cosa/sinb; // now the returns! *ldu = 1.; *lvu = kV/kf; *kuu = kf*kf/gamma(kV,kf,kf); }
// [[Rcpp::interfaces(cpp)]] double pr(int choice,int m,int chg,double add0,double add1,double* mGam,double* mOm1,double* mOm2,int* mRnew,int* mR,int mg){ arma::icolvec R(mR,mg,false); arma::icolvec Rnew(mRnew,mg,false); arma::colvec gamma(mGam,m,false); arma::colvec omega1(mOm1,m,false); arma::colvec omega2(mOm2,m,false); double out=0; double add=((R[chg+choice]==0)?add0:add1); double addnew=((Rnew[chg+choice]==0)?add0:add1); if(choice==0){ out=out+pRedge(gamma[choice],omega2[choice],Rnew[chg+choice],Rnew[chg+choice+1],addnew); out=out-pRedge(gamma[choice],omega2[choice],R[chg+choice],R[chg+choice+1],add); } if(choice==(m-1)){ out=out+pRedge(gamma[choice],omega1[choice],Rnew[chg+choice],Rnew[chg+choice-1],addnew); out=out-pRedge(gamma[choice],omega1[choice],R[chg+choice],R[chg+choice-1],add); } if(choice>0 && choice<(m-1)){ out=out+pRmiddle(gamma[choice],omega1[choice],omega2[choice],Rnew[chg+choice],Rnew[chg+choice-1],Rnew[chg+choice+1],addnew); out=out-pRmiddle(gamma[choice],omega1[choice],omega2[choice],R[chg+choice],R[chg+choice-1],R[chg+choice+1],add); } return out; }
double dermin ( int maxits , // Iteration limit double critlim , // Quit if crit drops this low double tol , // Convergence tolerance double (*criter) (double * , int , double * , double * ) , // Criterion func int n , // Number of variables double *x , // In/out of independent variable double ystart , // Input of starting function value double *base , // Work vector n long double *direc , // Work vector n long double *g , // Work vector n long double *h , // Work vector n long double *deriv2 , // Work vector n long int progress // Print progress? ) { int i, iter, user_quit, convergence_counter, poor_cj_counter ; double fval, fbest, high, scale, t1, t2, t3, y1, y2, y3, dlen, dot1, dot2 ; double prev_best, toler, gam, improvement ; char msg[400] ; /* Initialize for the local univariate criterion which may be called by 'glob_min' and 'brentmin' to minimize along the search direction. */ local_x = x ; local_base = base ; local_direc = direc ; local_n = n ; local_criter = criter ; /* Initialize that the user has not pressed ESCape. Evaluate the function and, more importantly, its derivatives, at the starting point. This call to criter puts the gradient into direc, but we flip its sign to get the downhill search direction. Also initialize the CJ algorithm by putting that vector in g and h. */ user_quit = 0 ; fbest = criter ( x , 1 , direc , deriv2 ) ; prev_best = 1.e30 ; for (i=0 ; i<n ; i++) direc[i] = -direc[i] ; memcpy ( g , direc , n * sizeof(double) ) ; memcpy ( h , direc , n * sizeof(double) ) ; #if DEBUG printf ( "\nDERMIN starting error = %lf", fbest ) ; #endif if (fbest < 0.0) { // If user pressed ESCape during criter call fbest = ystart ; user_quit = 1 ; goto FINISH ; } /* Main loop. For safety we impose a limit on iterations. There are two counters that have somewhat similar purposes. The first, convergence_counter, counts how many times an iteration failed to reduce the function value to the user's tolerance level. We require failure several times in a row before termination. The second, poor_cj_counter, has a (generally) higher threshold. It keeps track of poor improvement, and imposes successively small limits on gamma, thus forcing the algorithm back to steepest descent if CJ is doing poorly. */ convergence_counter = 0 ; poor_cj_counter = 0 ; iter = 0 ; for (;;) { if ((maxits > 0) && (iter++ >= maxits)) break ; if (fbest < critlim) // Do we satisfy user yet? break ; /* Convergence check */ if (prev_best <= 1.0) // If the function is small toler = tol ; // Work on absolutes else // But if it is large toler = tol * prev_best ; // Keep things relative if ((prev_best - fbest) <= toler) { // If little improvement if (++convergence_counter >= 3) // Then count how many break ; // And quit if too many } else // But a good iteration convergence_counter = 0 ; // Resets this counter /* Does the user want to quit? */ if ((user_quit = user_pressed_escape ()) != 0) break ; /* Here we do a few quick things for housekeeping. We save the base for the linear search in 'base', which lets us parameterize from t=0. We find the greatest second derivative. This makes an excellent scaling factor for the search direction so that the initial global search for a trio containing the minimum is fast. Because this is so stable, we use it to bound the generally better but unstable Newton scale. We also compute the length of the search vector and its dot product with the gradient vector, as well as the directional second derivative. That lets us use a sort of Newton's method to help us scale the initial global search to be as fast as possible. In the ideal case, the 't' parameter will be exactly equal to 'scale', the center point of the call to glob_min. */ dot1 = dot2 = dlen = 0.0 ; // For finding directional derivs high = 1.e-4 ; // For scaling glob_min for (i=0 ; i<n ; i++) { base[i] = x[i] ; // We step out from here if (deriv2[i] > high) // Keep track of second derivatives high = deriv2[i] ; // For linear search via glob_min dot1 += direc[i] * g[i] ; // Directional first derivative (neg) dot2 += direc[i] * direc[i] * deriv2[i] ; // and second dlen += direc[i] * direc[i] ; // Length of search vector } dlen = sqrt ( dlen ) ; // Actual length #if DEBUG printf ( "\n(x d1 d2) d1=%lf d2=%lf len=%lf rat=%lf h=%lf:", dot1, dot2, dlen, dot1 / dot2, 1.5 / high ) ; #endif #if DEBUG > 1 for (i=0 ; i<n ; i++) printf ( "( %lf %lf %lf)", x[i], direc[i], deriv2[i] ) ; #endif /* The search direction is in 'direc' and the maximum second derivative is in 'high'. That stable value makes a good approximate scaling factor. The ideal Newton scaling factor is numerically unstable. So compute the Newton ideal, then bound it to be near the less ideal but far more stable maximum second derivative. Pass the first function value, corresponding to t=0, to the routine in *y2 and flag this by using a negative npts. */ scale = dot1 / dot2 ; // Newton's ideal but unstable scale high = 1.5 / high ; // Less ideal but more stable heuristic if (high < 1.e-4) // Subjectively keep it realistic high = 1.e-4 ; if (scale < 0.0) // This is truly pathological scale = high ; // So stick with old reliable else if (scale < 0.1 * high) // Bound the Newton scale scale = 0.1 * high ; // To be close to the stable scale else if (scale > 10.0 * high) // Bound it both above and below scale = 10.0 * high ; y2 = prev_best = fbest ; #if DEBUG printf ( "\nStarting GLOBAL " ) ; #endif user_quit = glob_min ( 0.0 , 2.0 * scale , -3 , 0 , critlim , univar_crit , &t1 , &y1 , &t2 , &y2 , &t3 , &y3 , progress) ; #if DEBUG printf ( "\nGLOBAL t=%lf f=%lf", t2 / scale , y2 ) ; #endif if (user_quit || (y2 < critlim)) { // ESCape or good enough already? if (y2 < fbest) { // If global caused improvement for (i=0 ; i<n ; i++) // Implement that improvement x[i] = base[i] + t2 * direc[i] ; fbest = y2 ; } else { // Else revert to starting point for (i=0 ; i<n ; i++) x[i] = base[i] ; } break ; } /* We just used a crude global strategy to find three points that bracket the minimum. Refine using Brent's method. If we are possibly near the end, as indicated by the convergence_counter being nonzero, then try extra hard. */ if (convergence_counter) fbest = brentmin ( 20 , critlim , tol , 1.e-7 , univar_crit , &t1 , &t2 , &t3 , y2 , progress ) ; else fbest = brentmin ( 10 , critlim , 10.0 * tol , 1.e-5 , univar_crit , &t1 , &t2 , &t3 , y2 , progress ) ; #if DEBUG printf ( "\nBRENT t=%lf f=%lf", t2 / scale , fbest ) ; #endif /* We just completed the global and refined search. Update the current point to reflect the minimum obtained. Then evaluate the error and its derivatives there. (The linear optimizers only evaluated the error, not its derivatives.) If the user pressed ESCape during dermin, fbest will be returned negative. */ for (i=0 ; i<n ; i++) x[i] = base[i] + t2 * direc[i] ; if (fbest < 0.0) { // If user pressed ESCape fbest = -fbest ; user_quit = 1 ; break ; } improvement = (prev_best - fbest) / prev_best ; #if DEBUG printf ( "\nDIREC improvement = %lf %%", 100. * improvement ) ; #endif #if DEBUG > 1 printf ( "\a..." ) ; getch () ; #endif if (fbest < critlim) // Do we satisfy user yet? break ; fval = criter ( x , 1 , direc , deriv2 ) ; // Need derivs now for (i=0 ; i<n ; i++) // Flip sign to get direc[i] = -direc[i] ; // negative gradient if (fval < 0.0) { // If user pressed ESCape user_quit = 1 ; break ; } sprintf ( msg , "scale=%lf f=%le dlen=%le improvement=%lf%%", t2 / scale , fval, dlen, 100.0 * improvement ) ; if (progress) write_progress ( msg ) ; else write_non_progress ( msg ) ; #if DEBUG printf ( "\nf=%lf at (", fval ) ; #endif #if DEBUG > 1 for (i=0 ; i<n ; i++) printf ( " %lf", x[i] ) ; printf ( ")...\a" ) ; getch () ; #endif gam = gamma ( n , g , direc ) ; #if DEBUG dlen = 0.0 ; for (i=0 ; i<n ; i++) dlen += direc[i] * direc[i] ; printf ( "\nGamma = %lf with grad len = %lf", gam, sqrt(dlen) ) ; #endif if (gam < 0.0) gam = 0.0 ; if (gam > 10.0) // limit gamma gam = 10.0 ; if (improvement < 0.001) // Count how many times we ++poor_cj_counter ; // got poor improvement else // in a row poor_cj_counter = 0 ; if (poor_cj_counter >= 2) { // If several times if (gam > 1.0) // limit gamma gam = 1.0 ; } if (poor_cj_counter >= 6) { // If too many times poor_cj_counter = 0 ; // set gamma to 0 gam = 0.0 ; // to use steepest descent (gradient) #if DEBUG printf ( "\nSetting Gamma=0" ) ; #endif } find_new_dir ( n , gam , g , h , direc ) ; // Compute search direction } // Main loop FINISH: if (user_quit) return -fbest ; else return fbest ; }
inline double tgamma(double x) { return gamma(x); }
void MethodAdamsMoulton<ODESystemKernel>::MemoryAllocationMethod() { // Ode System Memory Allocation this->MemoryAllocation(); // Safety coefficient for choosing the optimal new order deltaAlfa1_ = DELTA_ALFA1; deltaAlfa3_ = DELTA_ALFA3; alfa2_ = new double[MAX_ORDER + 1]; for (unsigned int i = 0; i <= MAX_ORDER; i++) alfa2_[i] = ALFA2; // Auxiliary function Eigen::VectorXd gamma(MAX_ORDER + 2); gamma(0) = 1.; for (unsigned int i = 1; i <= MAX_ORDER; i++) { double sum = 0.; for (unsigned j = 1; j <= i; j++) sum -= gamma(j - 1) / double(i - j + 2); gamma(i) = sum; } // Allocating memory for vectors z and v z_ = new Eigen::VectorXd[MAX_ORDER + 3]; v_ = new Eigen::VectorXd[MAX_ORDER + 3]; for (unsigned int i = 0; i <= MAX_ORDER + 2; i++) { z_[i].resize(this->ne_); v_[i].resize(this->ne_); } // Allocating memory for vector r r_ = new Eigen::VectorXd[MAX_ORDER + 1]; for (unsigned int i = 0; i <= MAX_ORDER; i++) { r_[i].resize(MAX_ORDER); r_[i].setZero(); } // Filling vector r with constant values specific of the Adams Moulton algorithms // See Buzzi-Ferraris, pag 682 (equations 29.191-29.197) // Order 1: 1 1 // Order 2: 1/2 1 1/2 // Order 3: 5/12 1 3/4 1/6 // Order 4: 3/8 1 11/12 1/3 1/24 // Order 5: 251/720 1 25/24 35/72 5/40 1/120 // ... r_[0](0) = 1.; r_[1](0) = 1.; r_[1](1) = 1.; r_[2](1) = 1.; for (unsigned int j = 3; j <= MAX_ORDER; j++) { r_[1](j - 1) = Factorial(j - 1); for (unsigned int i = 3; i <= j; i++) r_[i - 1](j - 1) = double(j - 1)*r_[i - 1](j - 1 - 1) + r_[i - 2](j - 1 - 1); r_[j](j - 1) = 1.; } for (unsigned int j = 2; j <= MAX_ORDER; j++) { r_[0](j - 1) = r_[0](j - 1 - 1) + gamma(j - 1); r_[1](j - 1) = 1.; for (unsigned int i = 3; i <= j + 1; i++) r_[i - 1](j - 1) = r_[i - 1](j - 1) / (double(i - 1)*Factorial(j - 1)); } // Initialize vector of error coefficients Ep (Buzzi-Ferraris) Ep_ = new double[MAX_ORDER + 1]; Ep_[0] = 1.; Ep_[1] = 1.; Ep_[2] = .5; Ep_[3] = 1.; for (unsigned int j = 3; j < MAX_ORDER; j++) Ep_[j + 1] = -double(Factorial(j + 2))*gamma(j + 1); // Memory allocation b_.resize(this->ne_); y_.resize(this->ne_); va_.resize(this->ne_); deltab_.resize(this->ne_); f_.resize(this->ne_); vb_.resize(this->ne_); }
List EM(const arma::mat& transition_, const arma::cube& emission_, const arma::vec& init_, const arma::ucube& obs, const arma::uvec& nSymbols, int itermax, double tol, int trace, unsigned int threads) { // Make sure we don't alter the original vec/mat/cube // needed for cube, in future maybe in other cases as well arma::cube emission(emission_); arma::mat transition(transition_); arma::vec init(init_); // EM-algorithm begins double change = tol + 1.0; int iter = -1; //for backward compatibility double sumlogLik_new = 0; double sumlogLik = -1e150; //sum(ll); while ((change > tol) & (iter < itermax)) { iter++; arma::mat ksii(emission.n_rows, emission.n_rows, arma::fill::zeros); arma::cube gamma(emission.n_rows, emission.n_cols, emission.n_slices, arma::fill::zeros); arma::vec delta(emission.n_rows, arma::fill::zeros); sumlogLik_new = 0; double max_sf = 1; unsigned int error_code = 0; #pragma omp parallel for if(obs.n_slices>=threads) schedule(static) reduction(+:sumlogLik_new) num_threads(threads) \ default(none) shared(init, transition, obs, emission, delta, ksii, gamma, nSymbols, error_code, max_sf) for (unsigned int k = 0; k < obs.n_slices; k++) { arma::mat alpha(emission.n_rows, obs.n_cols); //m,n,k arma::vec scales(obs.n_cols); arma::sp_mat sp_trans(transition); uvForward(sp_trans.t(), emission, init, obs.slice(k), alpha, scales); arma::mat beta(emission.n_rows, obs.n_cols); //m,n,k uvBackward(sp_trans, emission, obs.slice(k), beta, scales); sumlogLik_new -= arma::sum(log(scales)); arma::mat ksii_k(emission.n_rows, emission.n_rows, arma::fill::zeros); arma::cube gamma_k(emission.n_rows, emission.n_cols, emission.n_slices, arma::fill::zeros); arma::vec delta_k(emission.n_rows); delta_k = alpha.col(0) % beta.col(0); if (obs.n_cols > 1) { for (unsigned int j = 0; j < emission.n_rows; j++) { for (unsigned int i = 0; i < emission.n_rows; i++) { if (transition(i, j) > 0.0) { for (unsigned int t = 0; t < (obs.n_cols - 1); t++) { double tmp = alpha(i, t) * transition(i, j) * beta(j, t + 1) * scales(t + 1); for (unsigned int r = 0; r < obs.n_rows; r++) { tmp *= emission(j, obs(r, t + 1, k), r); } ksii_k(i, j) += tmp; } } } } } for (unsigned int r = 0; r < emission.n_slices; r++) { for (unsigned int l = 0; l < nSymbols(r); l++) { for (unsigned int i = 0; i < emission.n_rows; i++) { if (emission(i, l, r) > 0.0) { for (unsigned int t = 0; t < obs.n_cols; t++) { if (l == (obs(r, t, k))) { gamma_k(i, l, r) += alpha(i, t) * beta(i, t); } } } } } } #pragma omp critical { if(!scales.is_finite()) { error_code = 1; } if(!beta.is_finite()) { error_code = 2; } max_sf = std::min(max_sf, scales.max()); delta += delta_k; ksii += ksii_k; gamma += gamma_k; } } if(error_code == 1) { return List::create(Named("error") = 1); } if(error_code == 2) { return List::create(Named("error") = 2); } if (max_sf > 1e150) { Rcpp::warning("Largest scaling factor was %e, results can be numerically unstable.", max_sf); } change = (sumlogLik_new - sumlogLik) / (std::abs(sumlogLik) + 0.1); sumlogLik = sumlogLik_new; if (trace > 0) { if(iter == 1) { Rcout << "Log-likelihood of initial model: " << sumlogLik << std::endl; } else { if (trace > 1) { Rcout << "iter: " << iter; Rcout << " logLik: " << sumlogLik; Rcout << " relative change: " << change << std::endl; } } } if (change > tol) { if (obs.n_cols > 1) { ksii.each_col() /= sum(ksii, 1); transition = ksii; } for (unsigned int r = 0; r < emission.n_slices; r++) { gamma.slice(r).cols(0, nSymbols(r) - 1).each_col() /= sum( gamma.slice(r).cols(0, nSymbols(r) - 1), 1); emission.slice(r).cols(0, nSymbols(r) - 1) = gamma.slice(r).cols(0, nSymbols(r) - 1); } delta /= arma::as_scalar(arma::accu(delta)); init = delta; } // internalForward(transition, emission, init, obs, alpha, scales, threads); // if(!scales.is_finite()) { // return List::create(Named("error") = 1); // } // internalBackward(transition, emission, obs, beta, scales, threads); // if(!beta.is_finite()) { // return List::create(Named("error") = 2); // } // double min_sf = scales.min(); // if (min_sf < 1e-150) { // Rcpp::warning("Smallest scaling factor was %e, results can be numerically unstable.", min_sf); // } // // ll = sum(log(scales)); //double tmp = sum(ll); } if (trace > 0) { if (iter == itermax) { Rcpp::Rcout << "EM algorithm stopped after reaching the maximum number of " << iter << " iterations." << std::endl; } else { Rcpp::Rcout << "EM algorithm stopped after reaching the relative change of " << change; Rcpp::Rcout << " after " << iter << " iterations." << std::endl; } Rcpp::Rcout << "Final log-likelihood: " << sumlogLik << std::endl; } return List::create(Named("initialProbs") = wrap(init), Named("transitionMatrix") = wrap(transition), Named("emissionArray") = wrap(emission), Named("logLik") = sumlogLik, Named("iterations") = iter, Named("change") = change, Named("error") = 0); }
void *threadFunction(void *tNum){ Vec3 camera_pos; set( camera_pos, 0., 0., -4. ); Vec3 camera_dir; set( camera_dir, 0., 0., 1. ); const double camera_fov = 75.0 * (PI/180.0); Vec3 bg_color; set( bg_color, 0.8, 0.8, 1 ); const double pixel_dx = tan( 0.5*camera_fov ) / ((double)width*0.5); const double pixel_dy = tan( 0.5*camera_fov ) / ((double)height*0.5); const double subsample_dx = halfSamples ? pixel_dx / ((double)halfSamples*2.0) : pixel_dx; const double subsample_dy = halfSamples ? pixel_dy / ((double)halfSamples*2.0) : pixel_dy; for( int px=*(int *)tNum; px<width; px += nthreads ) { const double x = pixel_dx * ((double)( px-(width/2) )); for( int py=0; py<height; ++py ) { const double y = pixel_dy * ((double)( py-(height/2) )); Vec3 pixel_color; set( pixel_color, 0, 0, 0 ); for( int xs=-halfSamples; xs<=halfSamples; ++xs ) { for( int ys=-halfSamples; ys<=halfSamples; ++ys ) { double subx = x + ((double)xs)*subsample_dx; double suby = y + ((double)ys)*subsample_dy; /* construct the ray coming out of the camera, through * the screen at (subx,suby) */ ray_t pixel_ray; copy( pixel_ray.org, camera_pos ); Vec3 pixel_target; set( pixel_target, subx, suby, z ); sub( pixel_ray.dir, pixel_target, camera_pos ); norm( pixel_ray.dir, pixel_ray.dir ); Vec3 sample_color; copy( sample_color, bg_color ); /* trace the ray from the camera that * passes through this pixel */ trace( &scene, sample_color, &pixel_ray, 0 ); /* sum color for subpixel AA */ add( pixel_color, pixel_color, sample_color ); } } /* at this point, have accumulated (2*halfSamples)^2 samples, * so need to average out the final pixel color */ if( halfSamples ) { mul( pixel_color, pixel_color, (1.0/( 4.0 * halfSamples * halfSamples ) ) ); } /* done, final floating point color values are in pixel_color. * Scaled color values are stored in a 3-d array to be printed later, * in order to avoid race conditions between threads */ scaled_color[px][py][0] = gamma( pixel_color[0] ) * max_color; scaled_color[px][py][1] = gamma( pixel_color[1] ) * max_color; scaled_color[px][py][2] = gamma( pixel_color[2] ) * max_color; /* enforce caps, replace with real gamma */ for( int i=0; i<3; i++) scaled_color[px][py][i] = max( min(scaled_color[px][py][i], 255), 0); } } return NULL; }
void main() //main code { printf("\nRUNGE-KUTTA METHOD\n\nR M Rho\n"); //printing titles for values displayed double c = 10.0; //the parameter rho(c) int n; //the integer steps, n //declare arrays float x[N]; float y[N]; float z[N]; //r,m,p as the radius, mass and density double r,m,p; //declare initial conditons for arrays x[0] = h; //first array is for r=h y[0] = (h*h*h/3)*c; //initial conditon for scaled mass (m) z[0] = c*(1-((h*h*c)/(6*gamma(c)))); //initial conditon for rho //for loop for n=0,1,...,200 for(n=0;n<N;n++) { //declared how x(n+1) relates to x(n), y(n+1) relates to y(n), z(n+1) relates to z(n) x[n+1] = x[n]+h; y[n+1] = y[n]+(h/6)*(M(x[n],y[n],z[n])+2*M2(x[n],y[n],z[n])+2*M3(x[n],y[n],z[n])+M4(x[n],y[n],z[n])); z[n+1] = z[n]+(h/6)*(rho(x[n],y[n],z[n])+2*rho2(x[n],y[n],z[n])+2*rho3(x[n],y[n],z[n])+rho4(x[n],y[n],z[n])); if(isnan(z[n+1])) { break; } //r,m,p will be declared in pg-plot r = x[n+1]; m = y[n+1]; p = z[n+1]; printf("%.2e %.2e %.2e\n",x[n+1],y[n+1],z[n+1]); //printed values for x and y respectively } //Use pg-plot to plot mass and density // cpgbeg starts a plotting page, in this case with 2x1 panels cpgbeg(0,"?",2,1); // sets colour: 1-black, 2-red, 3-green, 4-blue cpgsci(1); // sets line style: 1-solid, 2-dashed, 3-dot-dashed, 4-dotted cpgsls(1); // sets charachter height, larger number = bigger cpgsch(1.); // cpgpage() moves to the next panel cpgpage(); // sets the axes limits in the panel cpgswin(0,r,0,m); // draw the axes cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0); // label the bottom axis cpgmtxt("B",2.,.5,.5,"radius"); // label the left axis cpgmtxt("L",2.5,.5,.5,"saclaed mass"); // connect N points in ax and ay with a line cpgline(n,x,y); // cpgpage() moves to the next panel cpgpage(); // sets the axes limits in the panel cpgswin(0,r,0,c); // draw the axes cpgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0); // label the bottom axis cpgmtxt("B",2.,.5,.5,"radius"); // label the left axis cpgmtxt("L",2.5,.5,.5,"density"); // connect N points in ax and ay with a line cpgline(n,x,z); // close all pgplot applications cpgend(); // end program return; }
float SolidNoise::knot(int i, int j, int k, Vector3& v) const { return omega(v.x()) * omega(v.y()) * omega(v.z()) * dot(gamma(i, j, k), v); }
void doc_manager::populate(void) { add_class_descriptor(ml::k_base); add_class_descriptors(ml::k_base, { ml::k_classification, ml::k_regression }); add_class_descriptors(ml::k_regression, { ml::k_ann, ml::k_linreg, ml::k_logreg }); add_class_descriptors(ml::k_classification, { ml::k_svm, ml::k_adaboost, ml::k_anbc, ml::k_dtw, ml::k_hmmc, ml::k_softmax, ml::k_randforest, ml::k_mindist, ml::k_knn, ml::k_gmm, ml::k_dtree }); add_class_descriptors(ml::k_feature_extraction, { ml::k_peak, ml::k_minmax, ml::k_zerox }); descriptors[ml::k_ann].desc("Artificial Neural Network").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MLP"); descriptors[ml::k_linreg].desc("Linear Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LinearRegression"); descriptors[ml::k_logreg].desc("Logistic Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LogisticRegression"); descriptors[ml::k_peak].desc("Peak Detection").url("").num_outlets(1); descriptors[ml::k_minmax].desc("Minimum / Maximum Detection").url("").num_outlets(1); descriptors[ml::k_zerox].desc("Zero Crossings Detection").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ZeroCrossingCounter"); descriptors[ml::k_svm].desc("Support Vector Machine").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/SVM"); descriptors[ml::k_adaboost].desc("Adaptive Boosting").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/AdaBoost"); descriptors[ml::k_anbc].desc("Adaptive Naive Bayes Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ANBC"); descriptors[ml::k_dtw].desc("Dynamic Time Warping").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DTW"); descriptors[ml::k_hmmc].desc("Continuous Hidden Markov Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/HMM"); descriptors[ml::k_softmax].desc("Softmax Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/Softmax"); descriptors[ml::k_randforest].desc("Random Forests").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/RandomForests"); descriptors[ml::k_mindist].desc("Minimum Distance").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MinDist"); descriptors[ml::k_knn].desc("K Nearest Neighbour").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/KNN"); descriptors[ml::k_gmm].desc("Gaussian Mixture Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/GMMClassifier"); descriptors[ml::k_dtree].desc("Decision Trees").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DecisionTree"); for (auto& desc : {&descriptors[ml::k_hmmc], &descriptors[ml::k_dtw]}) { desc->notes( "add and map messages for time series should be delimited with record messages, e.g. record 1, add 1 40 50, add 1 41 50, record 0" ); } // base descriptor message_descriptor add( "add", "list comprising a class id followed by n features, <class> <feature 1> <feature 2> etc", "1 0.2 0.7 0.3 0.1" ); message_descriptor train( "train", "train the model based on vectors added with 'add'" ); message_descriptor map( "map", "generate the output value(s) for the input feature vector", "0.2 0.7 0.3 0.1" ); message_descriptor write( "write", "write training data and / or model, first argument gives path to write file", "/path/to/my_ml-lib_data" ); message_descriptor read( "read", "read training data and / or model, first argument gives path to the read file", "/path/to/my_ml-lib_data" ); message_descriptor clear( "clear", "clear the stored training data and model" ); message_descriptor help( "help", "post usage statement to the console" ); valued_message_descriptor<int> scaling( "scaling", "sets whether values are automatically scaled", {0, 1}, 1 ); valued_message_descriptor<int> record( "record", "start or stop time series recording for a single example of a given class", {0, 1}, 0 ); ranged_message_descriptor<float> training_rate( "training_rate", "set the learning rate, used to update the weights at each step of learning algorithms such as stochastic gradient descent.", 0.01, 1.0, 0.1 ); ranged_message_descriptor<float> min_change( "min_change", "set the minimum change that must be achieved between two training epochs for the training to continue", 0.0, 1.0, 1.0e-5 ); ranged_message_descriptor<int> max_iterations( "max_iterations", "set the maximum number of training iterations", 0, 1000, 100 ); record.insert_before = "add"; descriptors[ml::k_base].add_message_descriptor(add, write, read, train, clear, map, help, scaling, training_rate, min_change, max_iterations); // generic classification descriptor valued_message_descriptor<bool> null_rejection( "null_rejection", "toggle NULL rejection off or on, when 'on' classification results below the NULL-rejection threshold will be discarded", {false, true}, true ); ranged_message_descriptor<float> null_rejection_coeff( "null_rejection_coeff", "set a multiplier for the NULL-rejection threshold ", 0.1, 1.0, 0.9 ); valued_message_descriptor<int> probs( "probs", "determines whether probabilities are sent from the right outlet", {0, 1}, 0 ); descriptors[ml::k_classification].add_message_descriptor(null_rejection_coeff, probs, null_rejection); // generic feature extraction descriptor // descriptors[ml::k_feature_extraction].add_message_descriptor(null_rejection_coeff, null_rejection); // generic regression descriptor // descriptors[ml::k_regression].add_message_descriptor(training_rate, min_change, max_iterations); // Object-specific descriptors //-- Regressifiers //---- ann valued_message_descriptor<ml::data_type> mode("mode", "set the mode of the ANN, " + std::to_string(ml::LABELLED_CLASSIFICATION) + " for classification, " + std::to_string(ml::LABELLED_REGRESSION) + " for regression", {ml::LABELLED_CLASSIFICATION, ml::LABELLED_REGRESSION, ml::LABELLED_TIME_SERIES_CLASSIFICATION}, ml::defaults::data_type ); message_descriptor add_ann( "add", "class id followed by n features, <class> <feature 1> <feature 2> etc when in classification mode or N output values followed by M input values when in regression mode (N = num_outputs)", "1 0.2 0.7 0.3 0.1" ); ranged_message_descriptor<int> num_outputs( "num_outputs", "set the number of neurons in the output layer", 1, 1000, ml::defaults::num_output_dimensions ); ranged_message_descriptor<int> num_hidden( "num_hidden", "set the number of neurons in the hidden layer", 1, 1000, ml::defaults::num_hidden_neurons ); ranged_message_descriptor<int> min_epochs( "min_epochs", "setting the minimum number of training iterations", 1, 1000, 10 ); // TODO: check if the "epochs" are still needed or if we can use "iterations" as inherited from ml_regression ranged_message_descriptor<int> max_epochs( "max_epochs", "setting the maximum number of training iterations", 1, 10000, 100 ); ranged_message_descriptor<float> momentum( "momentum", "set the momentum", 0.0, 1.0, 0.5 ); ranged_message_descriptor<float> gamma( "gamma", "set the gamma", 0.0, 10.0, 2.0 ); // TODO: have optional value_labels for value labels valued_message_descriptor<int> input_activation_function( "input_activation_function", "set the activation function for the input layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID", {0, 1, 2}, 0 ); valued_message_descriptor<int> hidden_activation_function( "hidden_activation_function", "set the activation function for the hidden layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID", {0, 1, 2}, 0 ); valued_message_descriptor<int> output_activation_function( "output_activation_function", "set the activation function for the output layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID", {0, 1, 2}, 0 ); ranged_message_descriptor<int> rand_training_iterations( "rand_training_iterations", "set the number of random training iterations", 0, 1000, 10 ); valued_message_descriptor<bool> use_validation_set( "use_validation_set", "set whether to use a validation training set", {false, true}, true ); ranged_message_descriptor<int> validation_set_size( "validation_set_size", "set the size of the validation set", 1, 100, 20 ); valued_message_descriptor<bool> randomize_training_order( "randomize_training_order", "sets whether to randomize the training order", {false, true}, false ); descriptors[ml::k_ann].add_message_descriptor(add_ann, probs, mode, null_rejection, null_rejection_coeff, num_outputs, num_hidden, min_epochs, max_epochs, momentum, gamma, input_activation_function, hidden_activation_function, output_activation_function, rand_training_iterations, use_validation_set, validation_set_size, randomize_training_order); //-- Classifiers //---- ml.svm ranged_message_descriptor<int> type( "type", "set SVM type," " 0:C-SVC (multi-class)," " 1:nu-SVC (multi-class)," " 2:one-class SVM," // " 3:epsilon-SVR (regression)," // " 4:nu-SVR (regression)" , 0, 2, 0 // " 0 -- C-SVC (multi-class classification)\n" // " 1 -- nu-SVC (multi-class classification)\n" // " 2 -- one-class SVM\n" // " 3 -- epsilon-SVR (regression)\n" // " 4 -- nu-SVR (regression)\n" ); ranged_message_descriptor<int> kernel( "kernel", "set type of kernel function, " "0:linear, " // (u'*v)," "1:polynomial, " // (gamma*u'*v + coef0)^degree," "2:radial basis function, " //: exp(-gamma*|u-v|^2)," "3:sigmoid, " // tanh(gamma*u'*v + coef0)," "4:precomputed kernel (kernel values in training_set_file)", 0, 4, 0 // " 0 -- linear: u'*v\n" // " 1 -- polynomial: (gamma*u'*v + coef0)^degree\n" // " 2 -- radial basis function: exp(-gamma*|u-v|^2)\n" // " 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n" // " 4 -- precomputed kernel (kernel values in training_set_file)\n" ); ranged_message_descriptor<float> degree( "degree", "set degree in kernel function", 0, 20, 3 ); ranged_message_descriptor<float> svm_gamma( "gamma", "set gamma in kernel function", 0.0, 1.0, 0.5 ); ranged_message_descriptor<float> coef0( "coef0", "coef0 in kernel function", INFINITY * -1.f, INFINITY, 0.0 ); ranged_message_descriptor<float> cost( "cost", "set the parameter C of C-SVC, epsilon-SVR, and nu-SVR", INFINITY * -1.f, INFINITY, 1.0 ); ranged_message_descriptor<float> nu( "nu", "set the parameter nu of nu-SVC, one-class SVM, and nu-SVR", INFINITY * -1.f, INFINITY, 0.5 ); message_descriptor cross_validation( "cross_validation", "perform cross validation" ); ranged_message_descriptor<int> num_folds( "num_folds", "set the number of folds used for cross validation", 1, 100, 10 ); descriptors[ml::k_svm].add_message_descriptor(cross_validation, num_folds, type, kernel, degree, svm_gamma, coef0, cost, nu); //---- ml.adaboost ranged_message_descriptor<int> num_boosting_iterations( "num_boosting_iterations", "set the number of boosting iterations that should be used when training the model", 0, 200, 20 ); valued_message_descriptor<int> prediction_method( "prediction_method", "set the Adaboost prediction method, 0:MAX_VALUE, 1:MAX_POSITIVE_VALUE", {GRT::AdaBoost::MAX_VALUE, GRT::AdaBoost::MAX_POSITIVE_VALUE}, GRT::AdaBoost::MAX_VALUE ); valued_message_descriptor<int> set_weak_classifier( "set_weak_classifier", "sets the weak classifier to be used by Adaboost, 0:DECISION_STUMP, 1:RADIAL_BASIS_FUNCTION", {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION}, ml::weak_classifiers::DECISION_STUMP ); valued_message_descriptor<int> add_weak_classifier( "add_weak_classifier", "add a weak classifier to the list of classifiers used by Adaboost", {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION}, ml::weak_classifiers::DECISION_STUMP ); descriptors[ml::k_adaboost].add_message_descriptor(num_boosting_iterations, prediction_method, set_weak_classifier, add_weak_classifier); //---- ml.anbc message_descriptor weights("weights", "vector of 1 integer and N floating point values where the integer is a class label and the floats are the weights for that class. Sending weights with a vector size of zero clears all weights" ); descriptors[ml::k_anbc].add_message_descriptor(weights); //---- ml.dtw valued_message_descriptor<int> rejection_mode( "rejection_mode", "sets the method used for null rejection, 0:TEMPLATE_THRESHOLDS, 1:CLASS_LIKELIHOODS, 2:THRESHOLDS_AND_LIKELIHOODS", {GRT::DTW::TEMPLATE_THRESHOLDS, GRT::DTW::CLASS_LIKELIHOODS, GRT::DTW::THRESHOLDS_AND_LIKELIHOODS}, GRT::DTW::TEMPLATE_THRESHOLDS ); ranged_message_descriptor<float> warping_radius( "warping_radius", "sets the radius of the warping path, which is used if the constrain_warping_path is set to 1", 0.0, 1.0, 0.2 ); valued_message_descriptor<bool> offset_time_series( "offset_time_series", "set if each timeseries should be offset by the first sample in the time series", {false, true}, false ); valued_message_descriptor<bool> constrain_warping_path( "constrain_warping_path", "sets the warping path should be constrained to within a specific radius from the main diagonal of the cost matrix", {false, true}, true ); valued_message_descriptor<bool> enable_z_normalization( "enable_z_normalization", "turn z-normalization on or off for training and prediction", {false, true}, false ); valued_message_descriptor<bool> enable_trim_training_data( "enable_trim_training_data", "enabling data trimming prior to training", {false, true}, false ); descriptors[ml::k_dtw].insert_message_descriptor(record); descriptors[ml::k_dtw].add_message_descriptor(rejection_mode, warping_radius, offset_time_series, constrain_warping_path, enable_z_normalization, enable_trim_training_data); //---- ml.hmmc valued_message_descriptor<int> model_type( "model_type", "set the model type used, 0:ERGODIC, 1:LEFTRIGHT", {HMM_ERGODIC, HMM_LEFTRIGHT}, HMM_LEFTRIGHT ); ranged_message_descriptor<int> delta( "delta", "control how many states a model can transition to if the LEFTRIGHT model type is used", 1, 100, 11 ); ranged_message_descriptor<int> max_num_iterations( "max_num_iterations", "set the maximum number of training iterations", 1, 1000, 100 ); ranged_message_descriptor<int> committee_size( "committee_size", "set the committee size for the number of votes combined to make a prediction", 1, 1000, 5 ); ranged_message_descriptor<int> downsample_factor( "downsample_factor", "set the downsample factor for the resampling of each training time series. A factor of 5 will result in each time series being resized (smaller) by a factor of 5", 1, 1000, 5 ); descriptors[ml::k_hmmc].insert_message_descriptor(record); descriptors[ml::k_hmmc].add_message_descriptor(model_type, delta, max_num_iterations, committee_size, downsample_factor); //---- ml.softmax //---- ml.randforest ranged_message_descriptor<int> num_random_splits( "num_random_splits", "set the number of steps that will be used to search for the best spliting value for each node", 1, 1000, 100 ); ranged_message_descriptor<int> min_samples_per_node2( "min_samples_per_node", "set the minimum number of samples that are allowed per node", 1, 100, 5 ); ranged_message_descriptor<int> max_depth( "max_depth", "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node", 1, 100, 10 ); descriptors[ml::k_randforest].add_message_descriptor(num_random_splits, min_samples_per_node2, max_depth); //----ml.mindist ranged_message_descriptor<int> num_clusters( "num_clusters", "set how many clusters each model will try to find during the training phase", 1, 100, 10 ); descriptors[ml::k_mindist].add_message_descriptor(num_clusters); //---- ml.knn // "best_k_value_search:\tbool (0 or 1) set whether k value search is enabled or not (default 0)\n"; ranged_message_descriptor<int> k( "k", "sets the K nearest neighbours that will be searched for by the algorithm during prediction", 1, 500, 10 ); ranged_message_descriptor<int> min_k_search_value( "min_k_search_value", "set the minimum K value to use when searching for the best K value", 1, 500, 1 ); ranged_message_descriptor<int> max_k_search_value( "max_k_search_value", "set the maximum K value to use when searching for the best K value", 1, 500, 10 ); valued_message_descriptor<bool> best_k_value_search( "best_k_value_search", "set whether k value search is enabled or not", {false, true}, false ); descriptors[ml::k_knn].add_message_descriptor(k, min_k_search_value, max_k_search_value, best_k_value_search); //---- ml.gmm ranged_message_descriptor<int> num_mixture_models( "num_mixture_models", "sets the number of mixture models used for class", 1, 20, 2 ); descriptors[ml::k_gmm].add_message_descriptor(num_mixture_models); //---- ml.dtree valued_message_descriptor<bool> training_mode( "training_mode", "set the training mode", {GRT::Tree::BEST_ITERATIVE_SPILT, GRT::Tree::BEST_RANDOM_SPLIT}, GRT::Tree::BEST_ITERATIVE_SPILT ); ranged_message_descriptor<int> num_splitting_steps( "num_splitting_steps", "set the number of steps that will be used to search for the best spliting value for each node", 1, 500, 100 ); ranged_message_descriptor<int> min_samples_per_node( "min_samples_per_node", "sets the minimum number of samples that are allowed per node, if the number of samples at a node is below this value then the node will automatically become a leaf node", 1, 100, 5 ); ranged_message_descriptor<int> dtree_max_depth( "max_depth", "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node", 1, 100, 10 ); valued_message_descriptor<bool> remove_features_at_each_split( "remove_features_at_each_split", "set if a feature is removed at each spilt so it can not be used again", {false, true}, false ); descriptors[ml::k_dtree].add_message_descriptor(training_mode, num_splitting_steps, min_samples_per_node, dtree_max_depth, remove_features_at_each_split); //-- Feature extraction //---- ml.peak ranged_message_descriptor<int> search_window_size( "search_window_size", "set the search window size in values", 1, 500, 5 ); ranged_message_descriptor<float> peak( "float", "set the current value of the peak detector, a bang will be output when a peak is detected", INFINITY * -1.f, INFINITY, 1 ); message_descriptor reset( "reset", "reset the peak detector" ); message_descriptor peak_help( "help", "post usage statement to the console" ); descriptors[ml::k_peak].add_message_descriptor(peak, reset, search_window_size, peak_help); //---- ml.minmax message_descriptor input( "list", "list of float values in which to find minima and maxima", "0.1 0.5 -0.3 0.1 0.2 -0.1 0.7 0.1 0.3" ); ranged_message_descriptor<float> minmax_delta( "delta", "setting the minmax delta. Input values will be considered to be peaks if they are greater than the previous and next value by at least the delta value", 0, 1, 0.1 ); descriptors[ml::k_minmax].add_message_descriptor(input, minmax_delta); //---- ml.zerox valued_message_descriptor<float> zerox_map( "map", "a stream of input values in which to detect zero crossings", 0.5 ); ranged_message_descriptor<float> dead_zone_threshold( "dead_zone_threshold", "set the dead zone threshold", 0.f, 1.f, 0.01f ); ranged_message_descriptor<int> zerox_search_window_size( "search_window_size", "set the search window size in values", 1, 500, 20 ); descriptors[ml::k_zerox].add_message_descriptor(zerox_map, dead_zone_threshold, zerox_search_window_size); }
static double jvs(double n, double x) { double t, u, y, z, k; int ex; z = -x * x / 4.0; u = 1.0; y = u; k = 1.0; t = 1.0; while (t > MACHEP) { u *= z / (k * (n + k)); y += u; k += 1.0; if (y != 0) t = fabs(u / y); } #if CEPHES_DEBUG printf("power series=%.5e ", y); #endif t = frexp(0.5 * x, &ex); ex = ex * n; if ((ex > -1023) && (ex < 1023) && (n > 0.0) && (n < (MAXGAM - 1.0))) { t = pow(0.5 * x, n) / gamma(n + 1.0); #if CEPHES_DEBUG printf("pow(.5*x, %.4e)/gamma(n+1)=%.5e\n", n, t); #endif y *= t; } else { #if CEPHES_DEBUG z = n * log(0.5 * x); k = lgam(n + 1.0); t = z - k; printf("log pow=%.5e, lgam(%.4e)=%.5e\n", z, n + 1.0, k); #else t = n * log(0.5 * x) - lgam(n + 1.0); #endif if (y < 0) { sgngam = -sgngam; y = -y; } t += log(y); #if CEPHES_DEBUG printf("log y=%.5e\n", log(y)); #endif if (t < -MAXLOG) { return (0.0); } if (t > MAXLOG) { mtherr("Jv", OVERFLOW); return (NPY_INFINITY); } y = sgngam * exp(t); } return (y); }
int qmr(const Matrix& A, Vector& x, const Vector& b, LeftPreconditioner& L, const RightPreconditioner& R, Iteration& iter) { typedef typename mtl::Collection<Vector>::value_type Scalar; typedef typename mtl::Collection<Vector>::size_type Size; if (size(b) == 0) throw mtl::logic_error("empty rhs vector"); const Scalar zero= math::zero(b[0]), one= math::one(b[0]); Scalar rho_1, gamma(one), gamma_1, theta(zero), theta_1, eta(-one), delta, ep(one), beta; Size n(size(x)); Vector r(b - A * x), v_tld(r), y(solve(L, v_tld)), w_tld(r), z(adjoint_solve(R,w_tld)), v(n), w(n), y_tld(n), z_tld, p, q, p_tld, d, s; if (iter.finished(r)) return iter; Scalar rho = two_norm(y), xi = two_norm(z); while(! iter.finished(rho)) { if (rho == zero) return iter.fail(1, "qmr breakdown, rho=0 #1"); if (xi == zero) return iter.fail(2, "qmr breakdown, xi=0 #2"); v= v_tld / rho; y/= rho; w= w_tld / xi; z/= xi; delta = dot(z,y); if (delta == zero) return iter.fail(3, "qmr breakdown, delta=0 #3"); y_tld = solve(R,y); z_tld = adjoint_solve(L,z); if (iter.first()) { p = y_tld; q = z_tld; } else { p = y_tld - ((xi * delta) / ep) * p; q = z_tld - ((rho* delta) / ep) * q; } p_tld = A * p; ep = dot(q, p_tld); if (ep == zero) return iter.fail(4, "qmr breakdown ep=0 #4"); beta= ep / delta; if (beta == zero) return iter.fail(5, "qmr breakdown beta=0 #5"); v_tld = p_tld - beta * v; y = solve(L,v_tld); rho_1 = rho = two_norm(y); w_tld= trans(A)*q - beta*w; z = adjoint_solve(R, w_tld); xi = two_norm(z); gamma_1 = gamma; theta_1 = theta; theta = rho / (gamma_1 * beta); gamma = one / (sqrt(one + theta * theta)); if (gamma == zero) return iter.fail(6, "qmr breakdown gamma=0 #6"); eta= -eta * rho_1 * gamma * gamma / (beta * gamma_1 * gamma_1); if (iter.first()) { d= eta * p; s= eta * p_tld; } else { d= eta * p + (theta_1 * theta_1 * gamma * gamma) * d; s= eta * p_tld + (theta_1 * theta_1 * gamma * gamma) * s; } x += d; r -= s; ++iter; } return iter; }
bool Cylinder::Intersect(const Ray &r, Float *tHit, SurfaceInteraction *isect, bool testAlphaTexture) const { Float phi; Point3f pHit; // Transform _Ray_ to object space Vector3f oErr, dErr; Ray ray = (*WorldToObject)(r, &oErr, &dErr); // Compute quadratic cylinder coefficients // Initialize _EFloat_ ray coordinate values EFloat ox(ray.o.x, oErr.x), oy(ray.o.y, oErr.y), oz(ray.o.z, oErr.z); EFloat dx(ray.d.x, dErr.x), dy(ray.d.y, dErr.y), dz(ray.d.z, dErr.z); EFloat a = dx * dx + dy * dy; EFloat b = 2 * (dx * ox + dy * oy); EFloat c = ox * ox + oy * oy - EFloat(radius) * EFloat(radius); // Solve quadratic equation for _t_ values EFloat t0, t1; if (!Quadratic(a, b, c, &t0, &t1)) return false; // Check quadric shape _t0_ and _t1_ for nearest intersection if (t0.UpperBound() > ray.tMax || t1.LowerBound() <= 0) return false; EFloat tShapeHit = t0; if (tShapeHit.LowerBound() <= 0) { tShapeHit = t1; if (tShapeHit.UpperBound() > ray.tMax) return false; } // Compute cylinder hit point and $\phi$ pHit = ray((Float)tShapeHit); // Refine cylinder intersection point Float hitRad = std::sqrt(pHit.x * pHit.x + pHit.y * pHit.y); pHit.x *= radius / hitRad; pHit.y *= radius / hitRad; phi = std::atan2(pHit.y, pHit.x); if (phi < 0) phi += 2 * Pi; // Test cylinder intersection against clipping parameters if (pHit.z < zMin || pHit.z > zMax || phi > phiMax) { if (tShapeHit == t1) return false; tShapeHit = t1; if (t1.UpperBound() > ray.tMax) return false; // Compute cylinder hit point and $\phi$ pHit = ray((Float)tShapeHit); // Refine cylinder intersection point Float hitRad = std::sqrt(pHit.x * pHit.x + pHit.y * pHit.y); pHit.x *= radius / hitRad; pHit.y *= radius / hitRad; phi = std::atan2(pHit.y, pHit.x); if (phi < 0) phi += 2 * Pi; if (pHit.z < zMin || pHit.z > zMax || phi > phiMax) return false; } // Find parametric representation of cylinder hit Float u = phi / phiMax; Float v = (pHit.z - zMin) / (zMax - zMin); // Compute cylinder $\dpdu$ and $\dpdv$ Vector3f dpdu(-phiMax * pHit.y, phiMax * pHit.x, 0); Vector3f dpdv(0, 0, zMax - zMin); // Compute cylinder $\dndu$ and $\dndv$ Vector3f d2Pduu = -phiMax * phiMax * Vector3f(pHit.x, pHit.y, 0); Vector3f d2Pduv(0, 0, 0), d2Pdvv(0, 0, 0); // Compute coefficients for fundamental forms Float E = Dot(dpdu, dpdu); Float F = Dot(dpdu, dpdv); Float G = Dot(dpdv, dpdv); Vector3f N = Normalize(Cross(dpdu, dpdv)); Float e = Dot(N, d2Pduu); Float f = Dot(N, d2Pduv); Float g = Dot(N, d2Pdvv); // Compute $\dndu$ and $\dndv$ from fundamental form coefficients Float invEGF2 = 1 / (E * G - F * F); Normal3f dndu = Normal3f((f * F - e * G) * invEGF2 * dpdu + (e * F - f * E) * invEGF2 * dpdv); Normal3f dndv = Normal3f((g * F - f * G) * invEGF2 * dpdu + (f * F - g * E) * invEGF2 * dpdv); // Compute error bounds for cylinder intersection Vector3f pError = gamma(3) * Abs(Vector3f(pHit.x, pHit.y, 0)); // Initialize _SurfaceInteraction_ from parametric information *isect = (*ObjectToWorld)(SurfaceInteraction(pHit, pError, Point2f(u, v), -ray.d, dpdu, dpdv, dndu, dndv, ray.time, this)); // Update _tHit_ for quadric intersection *tHit = (Float)tShapeHit; return true; }
//declared the function for d(rho)/dr double rho(double r, double m, double p) { double t = -((m*p)/(gamma(p)*r*r)); //coupled equation for d(rho)/dr return t; //return d(rho)/dr }
virtual void on_draw() { pixfmt pixf(rbuf_window()); renderer_base rb(pixf); rb.clear(agg::rgba(1.0, 1.0, 1.0)); rb.copy_from(rbuf_img(0), 0, 110, 35); agg::rasterizer_scanline_aa<> ras; agg::scanline_u8 sl; agg::rendering_buffer img_rbuf(g_image, 4, 4, 4*4); double para[] = { 200, 40, 200+300, 40, 200+300, 40+300, 200, 40+300 }; agg::trans_affine img_mtx(para, 0,0,4,4); typedef agg::span_interpolator_linear<> interpolator_type; interpolator_type interpolator(img_mtx); agg::span_allocator<agg::rgba8> sa; pixfmt img_pixf(img_rbuf); typedef agg::image_accessor_clone<pixfmt> img_source_type; img_source_type source(img_pixf); ras.reset(); ras.move_to_d(para[0], para[1]); ras.line_to_d(para[2], para[3]); ras.line_to_d(para[4], para[5]); ras.line_to_d(para[6], para[7]); switch(m_filters.cur_item()) { case 0: { typedef agg::span_image_filter_rgba_nn<img_source_type, interpolator_type> span_gen_type; span_gen_type sg(source, interpolator); agg::render_scanlines_aa(ras, sl, rb, sa, sg); } break; case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: { agg::image_filter_lut filter; bool norm = m_normalize.status(); switch(m_filters.cur_item()) { case 1: filter.calculate(agg::image_filter_bilinear(), norm); break; case 2: filter.calculate(agg::image_filter_bicubic(), norm); break; case 3: filter.calculate(agg::image_filter_spline16(), norm); break; case 4: filter.calculate(agg::image_filter_spline36(), norm); break; case 5: filter.calculate(agg::image_filter_hanning(), norm); break; case 6: filter.calculate(agg::image_filter_hamming(), norm); break; case 7: filter.calculate(agg::image_filter_hermite(), norm); break; case 8: filter.calculate(agg::image_filter_kaiser(), norm); break; case 9: filter.calculate(agg::image_filter_quadric(), norm); break; case 10: filter.calculate(agg::image_filter_catrom(), norm); break; case 11: filter.calculate(agg::image_filter_gaussian(), norm); break; case 12: filter.calculate(agg::image_filter_bessel(), norm); break; case 13: filter.calculate(agg::image_filter_mitchell(), norm); break; case 14: filter.calculate(agg::image_filter_sinc(m_radius.value()), norm); break; case 15: filter.calculate(agg::image_filter_lanczos(m_radius.value()), norm); break; case 16: filter.calculate(agg::image_filter_blackman(m_radius.value()), norm); break; } typedef agg::span_image_filter_rgba<img_source_type, interpolator_type> span_gen_type; span_gen_type sg(source, interpolator, filter); agg::render_scanlines_aa(ras, sl, rb, sa, sg); agg::gamma_lut<agg::int8u, agg::int8u, 8, 8> gamma(m_gamma.value()); pixf.apply_gamma_inv(gamma); double x_start = 5.0; double x_end = 195.0; double y_start = 235.0; double y_end = initial_height() - 5.0; double x_center = (x_start + x_end) / 2; agg::path_storage p; agg::conv_stroke<agg::path_storage> stroke(p); stroke.width(0.8); unsigned i; for(i = 0; i <= 16; i++) { double x = x_start + (x_end - x_start) * i / 16.0; p.remove_all(); p.move_to(x+0.5, y_start); p.line_to(x+0.5, y_end); ras.add_path(stroke); agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(0, 0, 0, i == 8 ? 255 : 100)); } double ys = y_start + (y_end - y_start) / 6.0; p.remove_all(); p.move_to(x_start, ys); p.line_to(x_end, ys); ras.add_path(stroke); agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(0, 0, 0)); double radius = filter.radius(); unsigned n = unsigned(radius * 256 * 2); double dx = (x_end - x_start) * radius / 8.0; double dy = y_end - ys; const agg::int16* weights = filter.weight_array(); double xs = (x_end + x_start)/2.0 - (filter.diameter() * (x_end - x_start) / 32.0); unsigned nn = filter.diameter() * 256; p.remove_all(); p.move_to(xs+0.5, ys + dy * weights[0] / agg::image_filter_scale); for(i = 1; i < nn; i++) { p.line_to(xs + dx * i / n + 0.5, ys + dy * weights[i] / agg::image_filter_scale); } ras.add_path(stroke); agg::render_scanlines_aa_solid(ras, sl, rb, agg::rgba8(100, 0, 0)); } break; } agg::render_ctrl(ras, sl, rb, m_gamma); if(m_filters.cur_item() >= 14) { agg::render_ctrl(ras, sl, rb, m_radius); } agg::render_ctrl(ras, sl, rb, m_filters); agg::render_ctrl(ras, sl, rb, m_normalize); }
int main(int argc, char *argv[]) { # include "addTimeOptions.H" # include "setRootCase.H" # include "createTime.H" // Get times list instantList Times = runTime.times(); // set startTime and endTime depending on -time and -latestTime options # include "checkTimeOptions.H" runTime.setTime(Times[startTime], startTime); # include "createMesh.H" # include "readGravitationalAcceleration.H" const dictionary& piso = mesh.solutionDict().subDict("PISO"); label pRefCell = 0; scalar pRefValue = 0.0; int nNonOrthCorr = 0; if (piso.found("nNonOrthogonalCorrectors")) { nNonOrthCorr = readInt(piso.lookup("nNonOrthogonalCorrectors")); } for (label i = startTime; i < endTime; i++) { runTime.setTime(Times[i], i); Info<< "Time = " << runTime.timeName() << endl; IOobject pdHeader ( "pd", runTime.timeName(), mesh, IOobject::MUST_READ ); IOobject gammaHeader ( "gamma", runTime.timeName(), mesh, IOobject::MUST_READ ); IOobject Uheader ( "U", runTime.timeName(), mesh, IOobject::MUST_READ ); IOobject phiHeader ( "phi", runTime.timeName(), mesh, IOobject::MUST_READ ); // Check all fields exists if ( pdHeader.headerOk() && gammaHeader.headerOk() && Uheader.headerOk() && phiHeader.headerOk() ) { mesh.readUpdate(); Info<< " Reading pd" << endl; volScalarField pd(pdHeader, mesh); Info<< " Reading gamma" << endl; volScalarField gamma(gammaHeader, mesh); Info<< " Reading U" << endl; volVectorField U(Uheader, mesh); Info<< " Reading phi" << endl; surfaceScalarField phi(phiHeader, mesh); Info<< "Reading transportProperties\n" << endl; twoPhaseMixture twoPhaseProperties(U, phi, "gamma"); twoPhaseProperties.correct(); // Construct interface from gamma distribution interfaceProperties interface(gamma, U, twoPhaseProperties); // Create momentum matrix const dimensionedScalar& rho1 = twoPhaseProperties.rho1(); const dimensionedScalar& rho2 = twoPhaseProperties.rho2(); volScalarField rho ( IOobject ( "rho", runTime.timeName(), mesh, IOobject::READ_IF_PRESENT ), gamma*rho1 + (scalar(1) - gamma)*rho2, gamma.boundaryField().types() ); surfaceScalarField rhoPhi ( IOobject ( "rho*phi", runTime.timeName(), mesh, IOobject::NO_READ, IOobject::NO_WRITE ), fvc::interpolate(rho)*phi ); surfaceScalarField muf = twoPhaseProperties.muf(); fvVectorMatrix UEqn ( fvm::ddt(rho, U) + fvm::div(rhoPhi, U) - fvm::laplacian(muf, U) - (fvc::grad(U) & fvc::grad(muf)) == interface.sigmaK()*fvc::grad(gamma) + rho*g ); // Solve for static pressure volScalarField p ( IOobject ( "p", runTime.timeName(), mesh, IOobject::READ_IF_PRESENT, IOobject::NO_WRITE ), pd ); setRefCell(p, piso, pRefCell, pRefValue); volScalarField rUA = 1.0/UEqn.A(); surfaceScalarField rUAf = fvc::interpolate(rUA); U = rUA*UEqn.H(); phi = fvc::interpolate(U) & mesh.Sf(); for(int nonOrth = 0; nonOrth <= nNonOrthCorr; nonOrth++) { fvScalarMatrix pEqn ( fvm::laplacian(rUAf, p) == fvc::div(phi) ); pEqn.setReference(pRefCell, pRefValue); pEqn.solve(); } Info << "Writing p" << endl; p.write(); } else { Info << "Not all fields are present. " << endl; if (!pdHeader.headerOk()) { Info << "pd "; } if (!gammaHeader.headerOk()) { Info << "gamma "; } if (!Uheader.headerOk()) { Info << "U "; } if (!phiHeader.headerOk()) { Info << "phi "; } Info << "missing." << endl; } } Info<< "End\n" << endl; return(0); }
double jv(double n, double x) { double k, q, t, y, an; int i, sign, nint; nint = 0; /* Flag for integer n */ sign = 1; /* Flag for sign inversion */ an = fabs(n); y = floor(an); if (y == an) { nint = 1; i = an - 16384.0 * floor(an / 16384.0); if (n < 0.0) { if (i & 1) sign = -sign; n = an; } if (x < 0.0) { if (i & 1) sign = -sign; x = -x; } if (n == 0.0) return (j0(x)); if (n == 1.0) return (sign * j1(x)); } if ((x < 0.0) && (y != an)) { mtherr("Jv", DOMAIN); y = NPY_NAN; goto done; } if (x == 0 && n < 0 && !nint) { mtherr("Jv", OVERFLOW); return NPY_INFINITY / gamma(n + 1); } y = fabs(x); if (y * y < fabs(n + 1) * MACHEP) { return pow(0.5 * x, n) / gamma(n + 1); } k = 3.6 * sqrt(y); t = 3.6 * sqrt(an); if ((y < t) && (an > 21.0)) return (sign * jvs(n, x)); if ((an < k) && (y > 21.0)) return (sign * hankel(n, x)); if (an < 500.0) { /* Note: if x is too large, the continued fraction will fail; but then the * Hankel expansion can be used. */ if (nint != 0) { k = 0.0; q = recur(&n, x, &k, 1); if (k == 0.0) { y = j0(x) / q; goto done; } if (k == 1.0) { y = j1(x) / q; goto done; } } if (an > 2.0 * y) goto rlarger; if ((n >= 0.0) && (n < 20.0) && (y > 6.0) && (y < 20.0)) { /* Recur backwards from a larger value of n */ rlarger: k = n; y = y + an + 1.0; if (y < 30.0) y = 30.0; y = n + floor(y - n); q = recur(&y, x, &k, 0); y = jvs(y, x) * q; goto done; } if (k <= 30.0) { k = 2.0; } else if (k < 90.0) { k = (3 * k) / 4; } if (an > (k + 3.0)) { if (n < 0.0) k = -k; q = n - floor(n); k = floor(k) + q; if (n > 0.0) q = recur(&n, x, &k, 1); else { t = k; k = n; q = recur(&t, x, &k, 1); k = t; } if (q == 0.0) { underf: y = 0.0; goto done; } } else { k = n; q = 1.0; } /* boundary between convergence of * power series and Hankel expansion */ y = fabs(k); if (y < 26.0) t = (0.0083 * y + 0.09) * y + 12.9; else t = 0.9 * y; if (x > t) y = hankel(k, x); else y = jvs(k, x); #if CEPHES_DEBUG printf("y = %.16e, recur q = %.16e\n", y, q); #endif if (n > 0.0) y /= q; else y *= q; } else { /* For large n, use the uniform expansion or the transitional expansion. * But if x is of the order of n**2, these may blow up, whereas the * Hankel expansion will then work. */ if (n < 0.0) { mtherr("Jv", TLOSS); y = NPY_NAN; goto done; } t = x / n; t /= n; if (t > 0.3) y = hankel(n, x); else y = jnx(n, x); } done: return (sign * y); }
MainWindow::MainWindow() { openAction = new QAction(tr("&Open"), this); saveAction = new QAction(tr("&Save"), this); exitAction = new QAction(tr("E&xit"), this); equalAction = new QAction(tr("&Equalization"), this); otsuAction = new QAction(tr("&otsu"), this); isodataAction = new QAction(tr("&Isodata"), this); manualAction = new QAction(tr("&Manual"), this); gammaAction = new QAction(tr("&Gamma"), this); stretchingAction = new QAction(tr("&Stretching"), this); sigmaAction = new QAction(tr("&Sigma"), this); medianAction = new QAction(tr("&Median"), this); lineAction = new QAction(tr("&Lines"), this); pixelAction = new QAction(tr("&Pixels"), this); gaussianAction = new QAction(tr("&Gaussian"), this); sobelAction = new QAction(tr("&Sobel"), this); horizontalAction = new QAction(tr("&Line Intensity"), this); cannyAction = new QAction(tr("&Canny"),this); sumAction = new QAction(tr("&Add"),this); resAction = new QAction(tr("&Substract"),this); multAction = new QAction(tr("&Multiply"),this); divAction = new QAction(tr("&Divide"),this); avgAction = new QAction(tr("A&verage"),this); andAction = new QAction(tr("&And"),this); orAction = new QAction(tr("&Or"),this); xorAction = new QAction(tr("&Xor"),this); notAction = new QAction(tr("&Not"),this); minAction = new QAction(tr("M&in"),this); maxAction = new QAction(tr("M&ax"),this); kmeansAction = new QAction(tr("&Kmeans"),this); saveAction->setEnabled(false); connect(openAction, SIGNAL(triggered()), this, SLOT(open())); connect(saveAction, SIGNAL(triggered()), this, SLOT(save())); connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(equalAction, SIGNAL(triggered()), this, SLOT(equalization())); connect(otsuAction, SIGNAL(triggered()), this, SLOT(otsuThresh())); connect(isodataAction, SIGNAL(triggered()), this, SLOT(isodataSlot())); connect(manualAction, SIGNAL(triggered()), this, SLOT(manual())); connect(gammaAction,SIGNAL(triggered()),this,SLOT(gamma())); connect(stretchingAction,SIGNAL(triggered()),this,SLOT(stretching())); connect(sigmaAction, SIGNAL(triggered()), this, SLOT(sigma())); connect(medianAction, SIGNAL(triggered()), this, SLOT(median())); connect(lineAction, SIGNAL(triggered()), this, SLOT(line())); connect(pixelAction, SIGNAL(triggered()), this, SLOT(pixel())); connect(gaussianAction, SIGNAL(triggered()), this, SLOT(gaussian())); connect(sobelAction, SIGNAL(triggered()), this, SLOT(sobelEdges())); connect(horizontalAction,SIGNAL(triggered()),this,SLOT(horizontal())); connect(cannyAction,SIGNAL(triggered()),this,SLOT(cannySlot())); connect(sumAction,SIGNAL(triggered()),this,SLOT(sum())); connect(resAction,SIGNAL(triggered()),this,SLOT(res())); connect(multAction,SIGNAL(triggered()),this,SLOT(mult())); connect(divAction,SIGNAL(triggered()),this,SLOT(div())); connect(avgAction,SIGNAL(triggered()),this,SLOT(avg())); connect(andAction,SIGNAL(triggered()),this,SLOT(andSlot())); connect(orAction,SIGNAL(triggered()),this,SLOT(orSlot())); connect(xorAction,SIGNAL(triggered()),this,SLOT(xorSlot())); connect(notAction,SIGNAL(triggered()),this,SLOT(notSlot())); connect(minAction,SIGNAL(triggered()),this,SLOT(minSlot())); connect(maxAction,SIGNAL(triggered()),this,SLOT(maxSlot())); connect(kmeansAction,SIGNAL(triggered()),this,SLOT(kmeansSlot())); fileMenu = menuBar()->addMenu(tr("&File")); equalizationMenu = menuBar()->addMenu(tr("&Equalization")); thresholdMenu = menuBar()->addMenu(tr("&Thresholding")); contrastMenu = menuBar()->addMenu(tr("&Contrast")); noiseMenu = menuBar()->addMenu(tr("&Noise")); edgeMenu = menuBar()->addMenu(tr("E&dge")); operationMenu = menuBar()->addMenu(tr("&Operation")); boolMenu = operationMenu->addMenu(tr("&Boolean")); arithMenu = operationMenu->addMenu(tr("&Arithmetic")); relMenu = operationMenu->addMenu(tr("&Relational")); segmentationMenu = menuBar()->addMenu(tr("&Segmentation")); equalizationMenu->setEnabled(false); thresholdMenu->setEnabled(false); contrastMenu->setEnabled(false); noiseMenu->setEnabled(false); edgeMenu->setEnabled(false); operationMenu->setEnabled(false); segmentationMenu->setEnabled(false); fileMenu->addAction(openAction); fileMenu->addAction(saveAction); fileMenu->addSeparator(); fileMenu->addAction(exitAction); equalizationMenu->addAction(equalAction); thresholdMenu->addAction(otsuAction); thresholdMenu->addAction(isodataAction); thresholdMenu->addAction(manualAction); contrastMenu->addAction(gammaAction); contrastMenu->addAction(stretchingAction); noiseMenu->addAction(sigmaAction); noiseMenu->addAction(medianAction); noiseMenu->addAction(lineAction); noiseMenu->addAction(pixelAction); noiseMenu->addAction(gaussianAction); edgeMenu->addAction(sobelAction); edgeMenu->addAction(horizontalAction); edgeMenu->addAction(cannyAction); boolMenu->addAction(andAction); boolMenu->addAction(orAction); boolMenu->addAction(xorAction); boolMenu->addAction(notAction); arithMenu->addAction(sumAction); arithMenu->addAction(resAction); arithMenu->addAction(multAction); arithMenu->addAction(divAction); arithMenu->addAction(avgAction); relMenu->addAction(minAction); relMenu->addAction(maxAction); segmentationMenu->addAction(kmeansAction); //----- viewer = new ImageViewer(this); QScrollArea * scrollArea = new QScrollArea; scrollArea->setWidget(viewer); scrollArea->setFixedWidth(600); scrollArea->setWidgetResizable(true); boxW = new QSpinBox(); boxW->setEnabled(false); boxW->setMaximum(65535); boxC = new QSpinBox(); boxC->setEnabled(false); boxC->setMaximum(65535); histoViewer = new ImageViewer(this); QScrollArea * histoArea = new QScrollArea; histoArea->setWidget(histoViewer); histoArea->setFixedSize(268,278); histoArea->setWidgetResizable(false); QVBoxLayout * rightLayout = new QVBoxLayout; rightLayout->addWidget(new QLabel("Window:",this)); rightLayout->addWidget(boxW); rightLayout->addWidget(new QLabel("Level:",this)); rightLayout->addWidget(boxC); rightLayout->addWidget(histoArea); connect(boxW,SIGNAL(valueChanged(int)),this,SLOT(changeW(int))); connect(boxC,SIGNAL(valueChanged(int)),this,SLOT(changeC(int))); QWidget * rightSide = new QWidget; rightSide->setLayout(rightLayout); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(scrollArea); mainLayout->addWidget(rightSide); QWidget * centralWidget = new QWidget(); centralWidget->setLayout(mainLayout); setCentralWidget(centralWidget); setWindowTitle(tr("DICOM Image Processor")); setFixedSize(QSize(900,600)); }