Exemple #1
0
/**
 * Check if X509Cert is signed by trusted issuer
 * @return 0 or openssl error_code. Get human readable cause with X509_verify_cert_error_string(code)
 * @throw IOException if error
 */
int digidoc::X509Cert::verify() const throw(IOException)
{
    X509_STORE_CTX *csc = X509_STORE_CTX_new(); X509_STORE_CTX_scope csct(&csc);
    if (!csc)
        THROW_IOEXCEPTION("Failed to create X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));

    X509_STORE *store = digidoc::X509CertStore::getInstance()->getCertStore();
    X509* x = getX509(); X509_scope xt(&x);
    if(!X509_STORE_CTX_init(csc, store, x, NULL))
        THROW_IOEXCEPTION("Failed to init X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));

    int ok = X509_verify_cert(csc);

    if(!ok)
    {
        int err = X509_STORE_CTX_get_error(csc);
        X509Cert cause(X509_STORE_CTX_get_current_cert (csc));
        std::ostringstream s;
        s << "Unable to verify " << cause.getSubject();
        s << ". Cause: " << X509_verify_cert_error_string(err);
        switch(err)
        {
        case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
        {
            IOException e(__FILE__, __LINE__, s.str());
            e.setCode( Exception::CertificateIssuerMissing );
            throw e;
            break;
        }
        default: THROW_IOEXCEPTION(s.str().c_str()); break;
        }
    }

    return ok;
}
double ML_multi_Powell::f1dim(const double x)
{
    int j;
    v_ratep_type xt(ncom);
    for (j = 0; j < ncom; ++j) {
        xt[j] = pcom[j] + x*xicom[j];
    }
    return ((this->*nrfunc)(xt));
}
Exemple #3
0
bool bdoc::X509Cert::verify(X509_STORE* aStore, struct tm* tm) const
{
	if (aStore == NULL) {
		THROW_STACK_EXCEPTION("Invalid argument to verify");
	}

	X509_STORE* store = aStore;
	X509_STORE** ppStore = NULL;
	X509_STORE_scope xst(ppStore);

	X509_STORE_CTX *csc = X509_STORE_CTX_new();
	X509_STORE_CTX_scope csct(&csc);
	if (csc == NULL) {
		THROW_STACK_EXCEPTION("Failed to create X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));
	}

	X509* x = getX509();
	X509_scope xt(&x);
	if (!X509_STORE_CTX_init(csc, store, x, NULL)) {
		THROW_STACK_EXCEPTION("Failed to init X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));
	}

	if (tm != NULL) {
		time_t t = timegm(tm);
		if (t == -1) {
			THROW_STACK_EXCEPTION("Given time cannot be represented as calendar time");
		}

		X509_VERIFY_PARAM *param = X509_STORE_CTX_get0_param(csc);
		if (param == NULL) {
			THROW_STACK_EXCEPTION("Failed to retrieve X509_STORE_CTX verification parameters %s",
				ERR_reason_error_string(ERR_get_error()));
		}
		X509_VERIFY_PARAM_set_time(param, t);
	}

	int ok = X509_verify_cert(csc);

	if (ok != 1) {
		int err = X509_STORE_CTX_get_error(csc);
		X509Cert cause(X509_STORE_CTX_get_current_cert (csc));
		std::ostringstream s;
		s << "Unable to verify " << cause.getSubject();
		s << ". Cause: " << X509_verify_cert_error_string(err);
		switch (err) {
			case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
				{
					THROW_STACK_EXCEPTION("Certificate issuer missing: %s", s.str().c_str());
				}
			default: THROW_STACK_EXCEPTION(s.str().c_str()); break;
		}
	}

	return (ok == 1);
}
 void LevenbergMarquardt::fcn(int, int n, double* x, double* fvec, int*) {
     Array xt(n);
     std::copy(x, x+n, xt.begin());
     // constraint handling needs some improvement in the future:
     // starting point should not be close to a constraint violation
     if (currentProblem_->constraint().test(xt)) {
         const Array& tmp = currentProblem_->values(xt);
         std::copy(tmp.begin(), tmp.end(), fvec);
     } else {
         std::copy(initCostValues_.begin(), initCostValues_.end(), fvec);
     }
 }
Exemple #5
0
//------------------------------------------------------------------------------
void Triangulation::stereo_triangulation(const double xL[2], const double xR[2],
										 const cv::Mat& R, const cv::Mat& T, const double fc_left[2], const double cc_left[2],
										 const double kc_left[5], const double fc_right[2], const double cc_right[2],
										 const double kc_right[5], double XW[3], const bool undistortPoint)
{
	// Normalize the image projection according to the intrinsic parameters of the left
	// and right cameras.
	double xt_[2], xtt_[2];
	normalize_pixel(xL, fc_left, cc_left, kc_left, xt_, undistortPoint);
	normalize_pixel(xR, fc_right, cc_right, kc_right, xtt_, undistortPoint);
	
	// Extend the normalized projections in homogeneous coordinates
	cv::Mat xt(3, 1, CV_64FC1);
	cv::Mat xtt(3, 1, CV_64FC1);
	xt.at<double>(0,0) = xt_[0];  xt.at<double>(1,0) = xt_[1];  xt.at<double>(2,0) = 1.0;
	xtt.at<double>(0,0) = xtt_[0];  xtt.at<double>(1,0) = xtt_[1];  xtt.at<double>(2,0) = 1.0;
	
	// Triangulation of the rays in 3D space:
	cv::Mat u = R * xt;
	double n_xt2 = xt.dot(xt);
	double n_xtt2 = xtt.dot(xtt);
	
	double dot_uxtt = u.dot(xtt);
	double DD = n_xt2 * n_xtt2 - dot_uxtt*dot_uxtt;
	
	double dot_uT = u.dot(T);
	double dot_xttT = xtt.dot(T);
	double dot_xttu = u.dot(xtt);
	
	double NN1 = dot_xttu*dot_xttT - n_xtt2 * dot_uT;
	double NN2 = n_xt2*dot_xttT - dot_uT*dot_xttu;
	
	double Zt = NN1/DD;
	double Ztt = NN2/DD;
	
	cv::Mat X1 = xt * Zt;
	
	// Tranpose of rotation matrix
	cv::Mat Rt(3, 3, CV_64FC1);
	cv::transpose(R, Rt);
	
	cv::Mat X2 = Rt * (xtt*Ztt - T);
	
	cv::Mat Xworld = 0.5 * (X1 + X2);
	XW[0] = Xworld.at<double>(0,0);
	XW[1] = Xworld.at<double>(1,0);
	XW[2] = Xworld.at<double>(2,0);
}
Exemple #6
0
    // Have FFTW develop "wisdom" on doing this kind of transform
    void KTable::fftwMeasure() const 
    {
        // Copy data into new array to avoid NaN's, etc., but not bothering
        // with scaling, etc.
        FFTW_Array<std::complex<double> > t_array = _array;

        XTable xt( _N, 2*M_PI/(_N*_dk) );

        // Note: The fftw_execute function is the only thread-safe FFTW routine.
        // So if we decide to go with some kind of multi-threading (rather than multi-process
        // parallelism) all of the plan creation and destruction calls in this file 
        // will need to be placed in critical blocks or the equivalent (mutex locks, etc.).
        fftw_plan plan = fftw_plan_dft_c2r_2d(
            _N, _N, t_array.get_fftw(), xt._array.get_fftw(), FFTW_MEASURE);
#ifdef FFT_DEBUG
        if (plan==NULL) throw FFTInvalid();
#endif
        fftw_destroy_plan(plan);
    }
unsigned int BlumGoldwasserPrivateKey::Decrypt(const byte *input, unsigned int cipherTextLength, byte *output)
{
	if (cipherTextLength <= modulusLen)
		return 0;

	Integer xt(input, modulusLen);
	PublicBlumBlumShub bbs(n, Integer::Zero());
	unsigned int plainTextLength = cipherTextLength - modulusLen;
	unsigned int t = ((plainTextLength)*8 + bbs.maxBits-1) / bbs.maxBits;
	Integer dp = a_exp_b_mod_c((p+1)/4, t, p-1);
	Integer dq = a_exp_b_mod_c((q+1)/4, t, q-1);
	Integer xp = a_exp_b_mod_c(xt%p, dp, p);
	Integer xq = a_exp_b_mod_c(xt%q, dq, q);
	bbs.current = CRT(xp, p, xq, q, u);
	bbs.bitsLeft = bbs.maxBits;

	bbs.ProcessString(output, input+modulusLen, plainTextLength);
	return plainTextLength;
}
Exemple #8
0
int main()
{
    size_t n = 1000;
    std::vector<double> x, y;

    const double w = 0.05;
    const double a = n/2;

    for (size_t i=0; i<n; i++) {
        x.push_back(i);
        y.push_back(a*sin(w*i));
    }

    std::vector<double> xt(2), yt(2);

    plt::title("Tangent of a sine curve");
    plt::xlim(x.front(), x.back());
    plt::ylim(-a, a);
    plt::axis("equal");

    // Plot sin once and for all.
    plt::named_plot("sin", x, y);

    // Prepare plotting the tangent.
    plt::Plot plot("tangent");

    plt::legend();

    for (size_t i=0; i<n; i++) {
        if (i % 10 == 0) {
            update_window(x[i], y[i], a*w*cos(w*x[i]), xt, yt);

            // Just update data for this plot.
            plot.update(xt, yt);

            // Small pause so the viewer has a chance to enjoy the animation.
            plt::pause(0.1);
        }
   }
}
Exemple #9
0
void graph(FILE * fp)
{
   static char buf[BUFLNG], arg[BUFLNG / 2], xtype[16], ytype[16];
   static double xa, ya, xap, yap, xmin, xmax, ymin, ymax;
   static double xs = -NSCALE, ys = -NSCALE;
   int n, c;
   char *s, *p;
   double x, y, lpt, th, dt, lscale, rad;
   int is_grid, old_lbl = 0;
   char xory;

   h *= fct;
   w *= fct;

   for (n = 0; (s = fgets(buf, BUFLNG, fp));) {
      s = getarg(s, arg);
      if (s == NULL || *arg == '#');    /* comment line */
      else if ((!is_t && strcmp(arg, "x") == 0)
               || (is_t && strcmp(arg, "y") == 0)) {
         s = gettyp(s, xtype);
         if (sscanf(s, "%lf %lf %lf", &xmin, &xmax, &xa) != 3)
            xa = xmin;
         if (strncmp(xtype, "log", 3) == 0) {
            xmin = log10(xmin);
            xmax = log10(xmax);
            xa = log10(xa);
            is_xlog = (xtype[3] == '*') ? -1 : 1;
         }
         xfct = xl / (xmax - xmin);
         xap = (xa - xmin) * xfct;
         x00 = -xmin * xfct;
      } else if ((!is_t && strcmp(arg, "y") == 0)
                 || (is_t && strcmp(arg, "x") == 0)) {
         s = gettyp(s, ytype);
         if (sscanf(s, "%lf %lf %lf", &ymin, &ymax, &ya) != 3)
            ya = ymin;
         if (strncmp(ytype, "log", 3) == 0) {
            ymin = log10(ymin);
            ymax = log10(ymax);
            ya = log10(ya);
            is_ylog = (ytype[3] == '*') ? -1 : 1;
         }
         yfct = (yl) ? yl / (ymax - ymin) : 0;
         yap = (ya - ymin) * yfct;
         y00 = -ymin * yfct;
      } else if ((!is_t && strncmp(arg, "xscale", 6) == 0)
                 || (is_t && strncmp(arg, "yscale", 6) == 0)) {
         is_grid = *(arg + 6);
         if (type < 0 || (ya != ymin && ya != ymax)) {
            plot(0.0, yap, 3);
            plot(xl, yap, 2);
         }
         ys = yap - h - MSCALE;
         while ((s = getarg(s, p = arg)) != NULL) {
            if (*p != '"') {
               x = atof((is_number(*p)) ? p : p + 1);
               if (strncmp(xtype, "mel", 3) == 0)
                  x = argapf(x / nz(xmax, xmin),
                             atof(xtype + 3)) * nz(xmax, xmin);
               else if (is_xlog)
                  x = log10(x);
               x = (x - xmin) * xfct;
               lscale = (*p == 's') ? LSCALE / 2 : LSCALE;
               if (*p != '\\' && *p != '@') {
                  plot(x, yap, 3);
                  plot(x, yap + lscale, 2);
                  if (type > 0 && !is_grid && yap == 0) {
                     plot(x, yl, 3);
                     plot(x, yl - lscale, 2);
                  }
               } else if (*p == '\\')
                  ++p;
            }
            if (is_number(*p) || *p++ == '"')
               _symbol(x - sleng(p, h, w) / 2, ys - ysadj(), p, h, w, 0.0);
         }
      } else if ((!is_t && strncmp(arg, "yscale", 6) == 0)
                 || (is_t && strncmp(arg, "xscale", 6) == 0)) {
         is_grid = *(arg + 6);
         if (type < 0 || (xa != xmin && xa != xmax)) {
            plot(xap, 0.0, 3);
            plot(xap, yl, 2);
         }
         while ((s = getarg(s, p = arg)) != NULL) {
            if (*p != '"') {
               y = atof((is_number(*p)) ? p : p + 1);
               if (strncmp(ytype, "mel", 3) == 0)
                  y = argapf(y / nz(ymax, ymin),
                             atof(ytype + 3)) * nz(ymax, ymin);
               else if (is_ylog)
                  y = log10(y);
               y = (y - ymin) * yfct;
               lscale = (*p == 's') ? LSCALE / 2 : LSCALE;
               if (*p != '\\' && *p != '@') {
                  plot(xap, y, 3);
                  plot(xap + lscale, y, 2);
                  if (type > 0 && !is_grid && xap == 0) {
                     plot(xl, y, 3);
                     plot(xl - lscale, y, 2);
                  }
               } else if (*p == '\\')
                  ++p;
            }
            if (is_number(*p) || *p++ == '"') {
               x = xap - sleng(p, h, w) - MSCALE;
               if (x < xs)
                  xs = x;
               _symbol(x, y - h * 0.5, p, h, w, 0.0);
            }
         }
      } else if (strcmp(arg + 1, "grid") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         if ((!is_t && (*arg == 'x')) || (is_t && (*arg == 'y'))) {
            ybuf[0] = 0;
            ybuf[1] = yl;
            while ((s = getarg(s, arg)) != NULL) {
               x = atof(arg);
               if (is_xlog)
                  x = log10(x);
               xbuf[0] = xbuf[1]
                   = (x - xmin) * xfct;
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
            }
         } else {
            xbuf[0] = 0;
            xbuf[1] = xl;
            while ((s = getarg(s, arg)) != NULL) {
               y = atof(arg);
               if (is_ylog)
                  y = log10(y);
               ybuf[0] = ybuf[1]
                   = (y - ymin) * yfct;
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
            }
         }
         n = 0;
      } else if (strcmp(arg + 1, "circle") == 0) {
         xory = *arg;
         s = getarg(s, arg);
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         x = xfct * x + x00;
         y = yfct * y + y00;
         while ((s = getarg(s, arg)) != NULL) {
            if ((!is_t && xory == 'x') || (is_t && xory == 'y'))
               rad = xt(atof(arg)) * xfct;
            else
               rad = yt(atof(arg)) * yfct;
            pntstyl(ptyp);
            circle(x, y, rad, rad, 0., 360.);
         }
      } else if (strcmp(arg, "circle") == 0) {
         s = getarg(s, arg);
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         x = xfct * x + x00;
         y = yfct * y + y00;
         while ((s = getarg(s, arg)) != NULL) {
            rad = atof(arg);
            pntstyl(ptyp);
            circle(x, y, rad, rad, 0., 360.);
         }
      } else if (strcmp(arg + 1, "name") == 0) {
         s = getname(s, p = arg + 1);
         if ((!is_t && *arg == 'x') || (is_t && *arg == 'y'))
            _symbol((xl - sleng(s, h, w)) / 2,
                    (*p) ? -atof(p) - h : ys - h - NSCALE, s, h, w, 0.0);
         else
            _symbol((*p) ? -atof(p) : xs - MSCALE,
                    (yl - sleng(s, h, w)) / 2, s, h, w, 90.0);
      } else if (strncmp(arg, "title", 5) == 0 || strncmp(arg, "print", 5) == 0) {
         sscanf(s, "%lf %lf", &x, &y);
         swap(&x, &y);
         if (*arg == 'p') {
            x = xfct * xt(x) + x00;
            y = yfct * yt(y) + y00;
         }
         s = gettxt_fig(s);
         th = getarg(s + strlen(s) + 1, arg) ? atof(arg) : 0;
         if (*(arg + 5)) {
            x -= rx(LADJ * h / 2, h / 2, th);
            y -= ry(LADJ * h / 2, h / 2, th);
         }
         _symbol(x, y, s, h, w, th);
      } else if (strcmp(arg, "eod") == 0 || strcmp(arg, "EOD") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         n = 0;
      } else if (strcmp(arg, "pen") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         pen(atoi(s));
      } else if (strcmp(arg, "join") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         join(atoi(s));
      } else if (strcmp(arg, "csize") == 0) {
         if (sscanf(s, "%lf %lf", &h, &w) != 2)
            w = h;
      } else if (strcmp(arg, "hight") == 0) {
         if (sscanf(s, "%lf %lf", &mh, &mw) != 2)
            mw = mh;
      } else if (strcmp(arg, "line") == 0) {
         n = flush(xbuf, ybuf, n, wf, hf, fct);
         if (sscanf(s, "%d %lf", &ltype, &lpt) != 2) {
            if (ltype > 0)
               lpt = lpit[ltype - 1];
         }
         if (--ltype >= 0)
            mode(lmod[ltype], lpt);
      } else if (strcmp(arg, "italic") == 0)
         italic(atof(s));
      else if (strcmp(arg, "mark") == 0) {
         while (*s == ' ' || *s == '\t')
            ++s;
         if (*s == '\\' && *(s + 1) == '0')
            *label = '\0';
         else
            strcpy(label, s);
      } else if (strcmp(arg, "paint") == 0) {
         sscanf(s, "%d %lf %lf", &ptyp, &dhat, &that);
      } else if (strcmp(arg, "clip") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         for (n = 0; (s = getarg(s, arg)) != NULL; ++n) {
            x = xt(atof(arg));
            if ((s = getarg(s, arg)) == NULL)
               break;
            y = yt(atof(arg));
            swap(&x, &y);
            xbuf[n] = xfct * x + x00;
            ybuf[n] = yfct * y + y00;
         }
         if (n == 0) {
            xclip0 = yclip0 = 0;
            xclip1 = xl;
            yclip1 = yl;
            swap(&xclip1, &yclip1);
         } else if (n == 2) {
            xclip0 = xbuf[0];
            yclip0 = ybuf[0];
            xclip1 = xbuf[1];
            yclip1 = ybuf[1];
         }
         n = 0;
      } else if (strcmp(arg, "box") == 0) {
         draw_fig0(xbuf, ybuf, n, wf, hf, fct);
         for (n = 0; (s = getarg(s, arg)) != NULL; ++n) {
            x = xt(atof(arg));
            if ((s = getarg(s, arg)) == NULL)
               break;
            y = yt(atof(arg));
            swap(&x, &y);
            xbuf[n] = xfct * x + x00;
            ybuf[n] = yfct * y + y00;
         }
         if (n == 2) {
            xbuf[2] = xbuf[1];
            ybuf[3] = ybuf[2] = ybuf[1];
            ybuf[1] = ybuf[0];
            xbuf[3] = xbuf[0];
            n = 4;
         }
         polyg(xbuf, ybuf, n, wf, hf, fct);
         n = 0;
      } else {
         x = xt(atof(arg));
         s = getarg(s, arg);
         y = yt(atof(arg));
         swap(&x, &y);
         xbuf[n] = x = xfct * x + x00;
         ybuf[n] = y = yfct * y + y00;
         if (is_in(x, y) && ((s = getarg(s, arg))
                             || *label || old_lbl > 0)) {
            c = 0;
            if (s || *label) {
               if (s == NULL)
                  s = getarg(label, arg);
               if (*arg == '\\' && (abs(c = atoi(arg + 1))) < 16)
                  mark(abs(c), &x, &y, 1, mh, 1);
               else if (abs(c) == 16) {
                  pntstyl(ptyp);
                  circle(x, y, mh / 2, mh / 2, 0., 360.);
               } else {
                  if (c) {
                     *arg = c;
                     *(arg + 1) = '\0';
                  }
                  _symbol(x - LADJ * h / 2, y - w / 2, arg, h, w, atof(s));
               }
            }
            if (c > 0)
               n = flush(xbuf, ybuf, n, wf, hf, fct);
            if ((c > 0 || old_lbl > 0) && n) {
               dt = atan2(y - ybuf[0], x - xbuf[0]);
               if (old_lbl > 0) {
                  xbuf[0] += MADJ * mh * cos(dt);
                  ybuf[0] += MADJ * mh * sin(dt);
               }
               if (c > 0) {
                  xbuf[1] -= MADJ * mh * cos(dt);
                  ybuf[1] -= MADJ * mh * sin(dt);
               }
               draw_fig0(xbuf, ybuf, 2, wf, hf, fct);
               xbuf[0] = x;
               ybuf[0] = y;
               n = 0;
            }
            old_lbl = c;
         }
         if (++n >= BUFLNG)
            n = flush(xbuf, ybuf, n, wf, hf, fct);
      }
   }
   draw_fig0(xbuf, ybuf, n, wf, hf, fct);
}
Exemple #10
0
void
LIBeam3dNL :: computeStiffnessMatrix(FloatMatrix &answer, MatResponseMode rMode, TimeStep *tStep)
{
    int i, j, k;
    double s1, s2;
    FloatMatrix d, x, xt(12, 6), dxt, sn, sm, sxd, y;
    FloatArray n(3), m(3), xd(3), TotalStressVector;
    IntegrationRule *iRule = integrationRulesArray [ giveDefaultIntegrationRule() ];
    GaussPoint *gp = iRule->getIntegrationPoint(0);

    answer.resize( this->computeNumberOfDofs(EID_MomentumBalance), this->computeNumberOfDofs(EID_MomentumBalance) );
    answer.zero();

    // linear part

    this->updateTempTriad(tStep); // update temp triad
    this->computeXMtrx(x, tStep);
    xt.zero();
    for ( i = 1; i <= 12; i++ ) {
        for ( j = 1; j <= 3; j++ ) {
            for ( k = 1; k <= 3; k++ ) {
                // compute x*Tbar, taking into account sparsity of Tbar
                xt.at(i, j)   += x.at(i, k) * tempTc.at(k, j);
                xt.at(i, j + 3) += x.at(i, k + 3) * tempTc.at(k, j);
            }
        }
    }

    this->computeConstitutiveMatrixAt(d, rMode, gp, tStep);
    dxt.beProductTOf(d, xt);
    answer.beProductOf(xt, dxt);
    answer.times(1. / this->l0);

    // geometric stiffness ks = ks1+ks2
    // ks1
    this->computeStressVector(TotalStressVector, gp, tStep);

    for ( i = 1; i <= 3; i++ ) {
        s1 = s2 = 0.0;
        for ( j = 1; j <= 3; j++ ) {
            s1 += tempTc.at(i, j) * TotalStressVector.at(j);
            s2 += tempTc.at(i, j) * TotalStressVector.at(j + 3);
        }

        n.at(i)   = s1;
        m.at(i)   = s2;
    }

    this->computeSMtrx(sn, n);
    this->computeSMtrx(sm, m);

    for ( i = 1; i <= 3; i++ ) {
        for ( j = 1; j <= 3; j++ ) {
            answer.at(i, j + 3)   += sn.at(i, j);
            answer.at(i, j + 9)   += sn.at(i, j);
            answer.at(i + 3, j + 3) += sm.at(i, j);
            answer.at(i + 3, j + 9) += sm.at(i, j);

            answer.at(i + 6, j + 3) -= sn.at(i, j);
            answer.at(i + 6, j + 9) -= sn.at(i, j);
            answer.at(i + 9, j + 3) -= sm.at(i, j);
            answer.at(i + 9, j + 9) -= sm.at(i, j);
        }
    }

    // ks2
    this->computeXdVector(xd, tStep);
    this->computeSMtrx(sxd, xd);

    y.beProductOf(sxd, sn);
    y.times(0.5);

    for ( i = 1; i <= 3; i++ ) {
        for ( j = 1; j <= 3; j++ ) {
            answer.at(i + 3, j)     -= sn.at(i, j);
            answer.at(i + 3, j + 3)   += y.at(i, j);
            answer.at(i + 3, j + 6)   += sn.at(i, j);
            answer.at(i + 3, j + 9)   += y.at(i, j);

            answer.at(i + 9, j)     -= sn.at(i, j);
            answer.at(i + 9, j + 3)   += y.at(i, j);
            answer.at(i + 9, j + 6)   += sn.at(i, j);
            answer.at(i + 9, j + 9)   += y.at(i, j);
        }
    }
}
Exemple #11
0
void OrganizedData::process(RawData* raw, int nBlock, double pTest, int nSupport)
{
    int nData = raw->nData, nDim = raw->nDim - 1;

    this->nSupport = nSupport;
    this->nBlock   = nBlock;
    this->nDim     = nDim;

    train   = field<mat>(nBlock,2);
    test    = field<mat>(nBlock,2);
    support = field<mat>(1,2);

    mat xm(nSupport,nDim),
        ym(nSupport,1);

    vec mark(nData); mark.fill(0);

    printf("Randomly selecting %d supporting point ...\n", nSupport);

    for (int i = 0; i < nSupport; i++)
	{
		int pos = IRAND(0, nData - 1);
		while (mark[pos] > 0)
			pos = IRAND(0, nData - 1);
		mark[pos] = 1;
		for (int j = 0; j < nDim; j++)
			xm(i, j) = raw->X(pos,j);
		ym(i,0) = raw->X(pos,nDim);
	}

	support(0,0) = xm; xm.clear();
	support(0,1) = ym; ym.clear();

    cout << "Partitioning the remaining data into " << nBlock << " cluster using K-Mean ..." << endl;

    vvd _remain;

    for (int i = 0; i < nData; i++) if (!mark(i))
    {
        rowvec R = raw->X.row(i);
        _remain.push_back(r2v(R));
    }

    mat remaining = v2m(_remain);

    mark.clear();

    RawData* remain = new RawData(remaining);

    KMean* partitioner = new KMean(remain);

    Partition* clusters = partitioner->cluster(nBlock);

    cout << "Packaging training/testing data points into their respective cluster" << endl;

    for (int i = 0; i < nBlock; i++)
    {
        cout << "Processing block " << i + 1 << endl;

        int bSize   = (int) clusters->member[i].size(),
            tSize   = (int) floor(bSize * pTest),
            pos     = 0,
            counter = 0;

        mark = vec(bSize); mark.fill(0);

        if (bSize > tSize)  // if we can afford to draw tSize test points from this block without depleting it ...
        {
            mat xt(tSize,nDim),
                yt(tSize,1);

            for (int j = 0; j < tSize; j++)
            {
                pos = IRAND(0, bSize - 1);
				while (mark[pos] > 0)
					pos = IRAND(0, bSize - 1);
				mark[pos] = 1; pos = clusters->member[i][pos];

				for (int t = 0; t < nDim; t++)
					xt(j, t) = remain->X(pos,t);
				yt(j,0) = remain->X(pos,nDim);
            }

            bSize  -= tSize;
            nTest  += tSize;

            test(i,0) = xt; xt.clear();
            test(i,1) = yt; yt.clear();
        }

        nTrain += bSize;

        mat xb(bSize,nDim),
            yb(bSize,1);

        //cout << remain->X.n_rows << endl;

        for (int j = 0; j < (int)mark.n_elem; j++) if (mark[j] < 1)
        {
            for (int t = 0; t < nDim; t++) {
                xb(counter,t) = remain->X(clusters->member[i][j],t);
            }
            yb(counter++,0) = remain->X(clusters->member[i][j],nDim);
        }

        train(i,0) = xb; xb.clear();
        train(i,1) = yb; yb.clear();

        mark.clear();

        printf("Done ! nData[%d] = %d, nTrain[%d] = %d, nTest[%d] = %d .\n", i, (int) clusters->member[i].size(), i, train(i,0).n_rows, i, (int) test(i,0).n_rows);
    }
}
Exemple #12
0
/*
 *  recognizes character constants;
 *  ASSUMPTION: signed/unsigned integers are compatible on the host
 */
ux_t (clx_ccon)(lex_t *t, int *w)
{
    int cbyte;
    sz_t len = 0;
    const char *ss, *s, *e;
    ux_t lim, c;
#ifdef HAVE_ICONV
    iconv_t *cd;
#endif    /* HAVE_ICONV */

    assert(t);
    assert(w);
    assert(BUFUNIT > 2);
    assert(ty_wuchartype);    /* ensures types initialized */
    assert(xgeu(xmxu, TG_UCHAR_MAX));
    assert(xgeu(xmxu, TG_WUCHAR_MAX));
    assert(ir_cur);

    ss = s = LEX_SPELL(t);
    if (*s == 'L')
        *w = 1, s++;
    e = ++s;    /* skips ' */

    if (*w) {
        cbyte = ty_wchartype->size;
        assert(cbyte <= BUFUNIT);
        lim = TG_WUCHAR_MAX;
#ifdef HAVE_ICONV
        cd = main_ntow;
#endif    /* HAVE_ICONV */
    } else {
        cbyte = 1;
        lim = TG_UCHAR_MAX;
#ifdef HAVE_ICONV
        cd = main_ntoe;
#endif    /* HAVE_ICONV */
    }

    switch(*e) {
        case '\'':    /* empty; diagnosed elsewhere */
        case '\0':    /* unclosed; diagnosed elsewhere */
            return xO;
        case '\\':    /* escape sequences */
            assert(sizeof(c) >= cbyte);
            c = lex_bs(t, ss, &e, lim, "character constant");
#if HAVE_ICONV
            if (cd && !(s[1] == 'x' || (s[1] >= '0' && s[1] <= '7'))) {
                char x = xnu(c);
                ICONV_DECL(&x, 1);
                assert(xe(xiu(x), c));
                obuf = strg_sbuf, obufv = strg_sbuf;
                olen = strg_slen, olenv = strg_slen;
                ICONV_DO(cd, 1, {});
                strg_sbuf = obuf, strg_slen = olen;    /* for later reuse */
                len = strg_slen - len - olenv;
            } else {
#else    /* !HAVE_ICONV */
            {
#endif    /* HAVE_ICONV */
                if (*w)
                    memcpy(strg_sbuf, (char *)&c + ((LITTLE)? 0: sizeof(c)-cbyte), cbyte);
                else
                    strg_sbuf[0] = xnu(c);
                len = cbyte;
            }
            break;
        default:    /* ordinary chars */
#ifdef HAVE_ICONV
            if (cd) {
                do {
                    e++;
                } while(!FIRSTUTF8(*e));
                {
                    ICONV_DECL((char *)s, e - s);
                    obuf = strg_sbuf, obufv = strg_sbuf;
                    olen = strg_slen, olenv = strg_slen;
                    ICONV_DO(cd, 1, {});
                    strg_sbuf = obuf, strg_slen = olen;    /* for later reuse */
                    len = strg_slen - len - olenv;
                }
            } else {
#else    /* !HAVE_ICONV */
            {
#endif    /* HAVE_ICONV */
                assert(TG_CHAR_BIT == CHAR_BIT);
                if (*w) {
                    strg_sbuf[(LITTLE)? 0: cbyte-1] = *e;
                    memset(strg_sbuf + ((LITTLE)? 1: 0), 0, cbyte-1);
                } else
                    strg_sbuf[0] = *e;
                e++;
                len = cbyte;
            }
            break;
    }

    if (*e != '\'' && *e != '\0') {
        for (s = e; *e != '\0' && *e != '\''; e++)
            continue;
        err_dpos((FIRSTUTF8(*s))? lmap_spell(t, ss, s, e): t->pos, ERR_CONST_LARGECHAR);
    } else if (len != cbyte) {
        err_dpos(t->pos, (*w)? ERR_CONST_WIDENOTFIT: ERR_CONST_MBNOTFIT);
        return xO;
    }

    c = xO;
    memcpy(&c, strg_sbuf + ((LITTLE)? 0: sizeof(c)-cbyte), cbyte);
    if (*w) {
        switch(main_opt()->wchart) {
            case 0:    /* long */
                c = SYM_CROPSL(c);
                break;
            case 1:    /* ushort */
                c = SYM_CROPUS(c);
                break;
            case 2:    /* int */
                c = SYM_CROPSI(c);
                break;
        }
    } else    /* int from char */
        c = (main_opt()->uchar)? SYM_CROPUC(c): SYM_CROPSC(c);

    return c;
}


/*
 *  recognizes string literals
 */
static sz_t scon(lex_t *t, int *w)
{
    int cbyte;
    lex_t *n;
    sz_t clen = 0, len = 0;
    const char *ss, *s, *e;
    ux_t lim;
#ifdef HAVE_ICONV
    iconv_t *cd;
#endif

    assert(t);
    assert(w);
    assert(BUFUNIT > 2);
    assert(ty_wuchartype);    /* ensures types initialized */
    assert(xgeu(xmxu, TG_UCHAR_MAX));
    assert(xgeu(xmxu, TG_WUCHAR_MAX));
    assert(ir_cur);

    ss = s = LEX_SPELL(t);
    if (*s == 'L')
        *w = 1, s++;
    e = ++s;    /* skips " */
    while ((n = lst_peekns())->id == LEX_SCON) {
        if (*n->spell == 'L') {
            if (!*w) {    /* mb + wide = wide */
                err_dmpos(n->pos, ERR_CONST_MBWIDE, t->pos, NULL);
                err_dmpos(n->pos, ERR_CONST_MBWIDESTD, t->pos, NULL);
                *w = 2;    /* silences warnings */
            }
        } else if (*w == 1) {    /* wide + mb = wide */
            err_dmpos(n->pos, ERR_CONST_MBWIDE, t->pos, NULL);
            err_dmpos(n->pos, ERR_CONST_MBWIDESTD, t->pos, NULL);
            *w = 2;    /* silences warnings */
        }
        while ((t = lst_append(t, lst_next()))->id != LEX_SCON)
            continue;
    }
    clx_cpos = lmap_range(t->next->pos, t->pos);

    if (*w) {
        cbyte = ty_wchartype->size;
        assert(cbyte <= BUFUNIT);
        lim = TG_WUCHAR_MAX;
#ifdef HAVE_ICONV
        cd = main_ntow;
#endif    /* HAVE_ICONV */
    } else {
        cbyte = 1;
        lim = TG_UCHAR_MAX;
#ifdef HAVE_ICONV
        cd = main_ntoe;
#endif    /* HAVE_ICONV */
    }

    n = t->next;
    while (1) {
        while (1) {
            while (*e != '\\' && *e != '"' && *e != '\0')
                e++;
            if (e > s) {    /* ordinary chars */
#ifdef HAVE_ICONV
                if (cd) {
                    ICONV_DECL((char *)s, e - s);
                    obuf = strg_sbuf, obufv = strg_sbuf + len;
                    olen = strg_slen, olenv = strg_slen - len;
                    ICONV_INIT(cd);
                    ICONV_DO(cd, 0, {});
                    strg_sbuf = obuf, strg_slen = olen;    /* for later reuse */
                    len += (strg_slen - len - olenv);
                } else {
#else    /* !HAVE_ICONV */
                {
#endif    /* HAVE_ICONV */
                    sz_t d = e - s;
                    assert(TG_CHAR_BIT == CHAR_BIT);
                    while (len + (d*cbyte) > strg_slen)    /* rarely iterates */
                        MEM_RESIZE(strg_sbuf, strg_slen += BUFUNIT);
                    if (*w) {
                        while (s < e) {
                            strg_sbuf[len + ((ir_cur->f.little_endian)? 0: cbyte-1)] = *s++;
                            memset(strg_sbuf + len + ((ir_cur->f.little_endian)? 1: 0), 0,
                                   cbyte-1);
                            len += cbyte;
                        }
                    } else {
                        memcpy(&strg_sbuf[len], s, d);
                        len += d;
                    }
                }
                for (; s < e; s++)
                    if (FIRSTUTF8(*s))
                        clen++;
            }
            if (*e == '\\') {    /* escape sequences */
                ux_t c;
                assert(sizeof(c) >= cbyte);
                c = lex_bs(n, ss, &e, lim, "string literal");
#if HAVE_ICONV
                if (cd) {    /* inserts initial seq before every esc seq */
                    ICONV_DECL(NULL, 0);
                    UNUSED(ilenv);
                    UNUSED(ibufv);
                    obuf = strg_sbuf, obufv = strg_sbuf + len;
                    olen = strg_slen, olenv = strg_slen - len;
                    ICONV_INIT(cd);
                    strg_sbuf = obuf, strg_slen = olen;    /* for later reuse */
                    len += (strg_slen - len - olenv);
                }
                if (cd && !(s[1] == 'x' || (s[1] >= '0' && s[1] <= '7'))) {
                    char x = xnu(c);
                    ICONV_DECL(&x, 1);
                    assert(xe(xiu(x), c));
                    obuf = strg_sbuf, obufv = strg_sbuf + len;
                    olen = strg_slen, olenv = strg_slen - len;
                    ICONV_DO(cd, 0, {});
                    strg_sbuf = obuf, strg_slen = olen;    /* for later reuse */
                    len += (strg_slen - len - olenv);
                } else {
#else    /* !HAVE_ICONV */
                {
#endif    /* HAVE_ICONV */
                    if (len + cbyte > strg_slen)
                        MEM_RESIZE(strg_sbuf, strg_slen += BUFUNIT);
                    if (*w) {
                        if (LITTLE != ir_cur->f.little_endian)
                            CHGENDIAN(c, sizeof(c));
                        memcpy(strg_sbuf+len,
                               &c + ((ir_cur->f.little_endian)? 0: sizeof(c)-cbyte), cbyte);
                        len += cbyte;
                    } else
                        strg_sbuf[len++] = xnu(c);
                }
                clen++;
                s = e;
                continue;
            }
            break;    /* " or NUL */
        }
        if (n == t) {
            if (len + cbyte > strg_slen)
                MEM_RESIZE(strg_sbuf, strg_slen += BUFUNIT);
            memset(strg_sbuf+len, 0, cbyte);
            len += cbyte;
            clen++;
            break;
        }
        while ((n = n->next)->id != LEX_SCON)
            if (n->id < 0)
                strg_free((arena_t *)n->spell);
        ss = s = LEX_SPELL(n);
        if (*s == 'L')
            s++;
        e = ++s;    /* skips " */
    }

    if (len % cbyte != 0)
        err_dpos(clx_cpos, ERR_CONST_WIDENOTFIT);
    if (*w)
        clen = (len /= cbyte);

    if (clen - 1 > TL_STR_STD) {    /* -1 for NUL; note TL_STR_STD may warp around */
        err_dpos(clx_cpos, ERR_CONST_LONGSTR);
        err_dpos(clx_cpos, ERR_CONST_LONGSTRSTD, (unsigned long)TL_STR_STD);
    }

    return len;
}


#define N 0    /* no suffix */
#define U 1    /* suffix: U */
#define L 2    /* suffix: L */
#define X 3    /* suffix: UL */
#ifdef SUPPORT_LL
#define M 4    /* suffix: LL */
#define Z 5    /* suffix: ULL */
#endif    /* SUPPORT_LL */
#define D 0    /* base: decimal */
#define H 1    /* base: octal or hexadecimal */

/*
 *  determines the type of an integer constant
 */
static const char *icon(const char *cs, ux_t n, int ovf, int base, const lmap_t *pos)
{
    static struct tab {
        ux_t limit;
        ty_t *type;
#ifdef SUPPORT_LL
    } tab[Z+1][H+1][7];
#else    /* !SUPPORT_LL */
    } tab[X+1][H+1][5];
#endif    /* SUPPORT_LL */

    int suffix;
    struct tab *p;

    assert(cs);
    assert(pos);
    assert(ty_inttype);
#ifdef SUPPORT_LL
    assert(xgeu(xmxu, TG_ULLONG_MAX));
#else    /* !SUPPORT_LL */
    assert(xgeu(xmxu, TG_ULONG_MAX));
#endif    /* SUPPORT_LL */

    if (xe(tab[N][D][0].limit, xO)) {
        /* no suffix, decimal; different in C90 */
        tab[N][D][0].limit = TG_INT_MAX;
        tab[N][D][0].type  = ty_inttype;
        tab[N][D][1].limit = TG_LONG_MAX;
        tab[N][D][1].type  = ty_longtype;
#ifdef SUPPORT_LL
        tab[N][D][2].limit = TG_LLONG_MAX;
        tab[N][D][2].type  = ty_llongtype;
        tab[N][D][3].limit = TG_ULLONG_MAX;
        tab[N][D][3].type  = ty_ullongtype;
        tab[N][D][4].limit = xmxu;
        tab[N][D][4].type  = ty_inttype;
#else    /* SUPPORT_LL */
        tab[N][D][2].limit = TG_ULONG_MAX;
        tab[N][D][2].type  = ty_ulongtype;
        tab[N][D][3].limit = xmxu;
        tab[N][D][3].type  = ty_inttype;
#endif    /* SUPPORT_LL */

        /* no suffix, octal or hex */
        tab[N][H][0].limit = TG_INT_MAX;
        tab[N][H][0].type  = ty_inttype;
        tab[N][H][1].limit = TG_UINT_MAX;
        tab[N][H][1].type  = ty_unsignedtype;
        tab[N][H][2].limit = TG_LONG_MAX;
        tab[N][H][2].type  = ty_longtype;
        tab[N][H][3].limit = TG_ULONG_MAX;
        tab[N][H][3].type  = ty_ulongtype;
#ifdef SUPPORT_LL
        tab[N][H][4].limit = TG_LLONG_MAX;
        tab[N][H][4].type  = ty_llongtype;
        tab[N][H][5].limit = TG_ULLONG_MAX;
        tab[N][H][5].type  = ty_ullongtype;
        tab[N][H][6].limit = xmxu;
        tab[N][H][6].type  = ty_inttype;
#else    /* !SUPPORT_LL */
        tab[N][H][4].limit = xmxu;
        tab[N][H][4].type  = ty_inttype;
#endif    /* SUPPORT_LL */

        /* U, decimal, octal or hex */
        tab[U][H][0].limit = tab[U][D][0].limit = TG_UINT_MAX;
        tab[U][H][0].type  = tab[U][D][0].type  = ty_unsignedtype;
        tab[U][H][1].limit = tab[U][D][1].limit = TG_ULONG_MAX;
        tab[U][H][1].type  = tab[U][D][1].type  = ty_ulongtype;
#ifdef SUPPORT_LL
        tab[U][H][2].limit = tab[U][D][2].limit = TG_ULLONG_MAX;
        tab[U][H][2].type  = tab[U][D][2].type  = ty_ullongtype;
        tab[U][H][3].limit = tab[U][D][3].limit = xmxu;
        tab[U][H][3].type  = tab[U][D][3].type  = ty_inttype;
#else    /* !SUPPORT_LL */
        tab[U][H][2].limit = tab[U][D][2].limit = xmxu;
        tab[U][H][2].type  = tab[U][D][2].type  = ty_inttype;
#endif    /* SUPPORT_LL */

        /* L, decimal; different in C90 */
        tab[L][D][0].limit = TG_LONG_MAX;
        tab[L][D][0].type  = ty_longtype;
#ifdef SUPPORT_LL
        tab[L][D][1].limit = TG_LLONG_MAX;
        tab[L][D][1].type  = ty_llongtype;
        tab[L][D][2].limit = TG_ULLONG_MAX;
        tab[L][D][2].type  = ty_ullongtype;
        tab[L][D][3].limit = xmxu;
        tab[L][D][3].type  = ty_inttype;
#else    /* !SUPPORT_LL */
        tab[L][D][1].limit = TG_ULONG_MAX;
        tab[L][D][1].type  = ty_ulongtype;
        tab[L][D][2].limit = xmxu;
        tab[L][D][2].type  = ty_inttype;
#endif    /* SUPPORT_LL */

        /* L, octal or hex */
        tab[L][H][0].limit = TG_LONG_MAX;
        tab[L][H][0].type  = ty_longtype;
        tab[L][H][1].limit = TG_ULONG_MAX;
        tab[L][H][1].type  = ty_ulongtype;
#ifdef SUPPORT_LL
        tab[L][H][2].limit = TG_LLONG_MAX;
        tab[L][H][2].type  = ty_llongtype;
        tab[L][H][3].limit = TG_ULLONG_MAX;
        tab[L][H][3].type  = ty_ullongtype;
        tab[L][H][4].limit = xmxu;
        tab[L][H][4].type  = ty_inttype;
#else    /* !SUPPORT_LL */
        tab[L][H][2].limit = xmxu;
        tab[L][H][2].type  = ty_inttype;
#endif    /* SUPPORT_LL */

        /* UL, decimal, octal or hex */
        tab[X][H][0].limit = tab[X][D][0].limit = TG_ULONG_MAX;
        tab[X][H][0].type  = tab[X][D][0].type  = ty_ulongtype;
#ifdef SUPPORT_LL
        tab[X][H][1].limit = tab[X][D][1].limit = TG_ULLONG_MAX;
        tab[X][H][1].type  = tab[X][D][1].type  = ty_ullongtype;
        tab[X][H][2].limit = tab[X][D][2].limit = xmxu;
        tab[X][H][2].type  = tab[X][D][2].type  = ty_inttype;
#else    /* !SUPPORT_LL */
        tab[X][H][1].limit = tab[X][D][1].limit = xmxu;
        tab[X][H][1].type  = tab[X][D][1].type  = ty_inttype;
#endif    /* SUPPORT_LL */

#ifdef SUPPORT_LL
        /* LL, decimal, octal or hex */
        tab[M][H][0].limit = tab[M][D][0].limit = TG_LLONG_MAX;
        tab[M][H][0].type  = tab[M][D][0].type  = ty_llongtype;
        tab[M][H][1].limit = tab[M][D][1].limit = TG_ULLONG_MAX;
        tab[M][H][1].type  = tab[M][D][1].type  = ty_ullongtype;
        tab[M][H][2].limit = tab[M][D][2].limit = xmxu;
        tab[M][H][2].type  = tab[M][D][2].type  = ty_inttype;

        /* ULL, decimal, octal or hex */
        tab[Z][H][0].limit = tab[Z][D][0].limit = TG_ULLONG_MAX;
        tab[Z][H][0].type  = tab[Z][D][0].type  = ty_ullongtype;
        tab[Z][H][1].limit = tab[Z][D][1].limit = xmxu;
        tab[Z][H][1].type  = tab[Z][D][1].type  = ty_inttype;
#endif    /* SUPPORT_LL */
    }

    base = (base == 10)? D: H;
    suffix = N;

    if (tolower((unsigned char)cs[0]) == 'l') {
#ifdef SUPPORT_LL
        if (cs[1] == cs[0])
            cs += 2, suffix = M;
        else
#endif    /* SUPPORT_LL */
            cs++, suffix = L;
    }
    if (tolower((unsigned char)cs[0]) == 'u')
        cs++, suffix++;
    if (suffix <= U && tolower((unsigned char)cs[0]) == 'l') {
#ifdef SUPPORT_LL
        if (cs[1] == cs[0])
            cs += 2, suffix += M;
        else
#endif    /* SUPPORT_LL */
            cs++, suffix += L;
    }

    for (p = tab[suffix][base]; xgu(n, p->limit); p++)
        continue;
    if (ovf || (xe(p->limit, xmxu) && p->type == ty_inttype)) {
        err_dpos(pos, ERR_CONST_LARGEINT);
#ifdef SUPPORT_LL
        n = TG_ULLONG_MAX;
        tval.type = ty_ullongtype;
#else    /* !SUPPORT_LL */
        n = TG_ULONG_MAX;
        tval.type = ty_ulongtype;
#endif    /* SUPPORT_LL */
    } else
        tval.type = p->type;

#ifdef SUPPORT_LL
    if (suffix % 2 == 0 && base == D && TY_ISUNSIGN(p->type))
        err_dpos(pos, ERR_CONST_LARGEUNSIGN);
    else if (tval.type == ty_llongtype && (suffix == N || suffix == L) && xleu(n, TG_ULONG_MAX)) {
        err_dpos(pos, ERR_CONST_UNSIGNINC90);
        if (main_opt()->std == 1)
            tval.type = ty_ulongtype;
    }
    if ((TY_ISLLONG(tval.type) || TY_ISULLONG(tval.type)))
        err_dpos(pos, ERR_CONST_LLONGINC90, tval.type);
#endif    /* SUPPORT_LL */

#ifdef SUPPORT_LL
    if (tval.type->op == TY_INT || tval.type->op == TY_LONG || tval.type->op == TY_LLONG)
#else    /* !SUPPORT_LL */
    if (tval.type->op == TY_INT || tval.type->op == TY_LONG)
#endif    /* SUPPORT_LL */
        tval.u.c.v.s = n;
    else
        tval.u.c.v.u = n;

    return cs;
}

#undef H
#undef D
#undef Z
#undef M
#undef X
#undef L
#undef U
#undef N


/*
 *  determines the type of a floating constant;
 *  ASSUMPTION: fp types of the host are same as those of the target
 */
static const char *fcon(const char *cs, long double ld, const lmap_t *pos)
{
    assert(cs);
    assert(pos);
    assert(ty_floattype);    /* ensures types initiailized */

    switch(*cs) {
        case 'f':
        case 'F':
            cs++;    /* skips f or F */
            if ((OVF(ld) && errno == ERANGE) || ld > TG_FLT_MAX) {
                err_dpos(pos, ERR_CONST_LARGEFP);
                ld = TG_FLT_MAX;
            } else if ((ld == 0.0 && errno == ERANGE) || (ld > 0.0 && ld < TG_FLT_MIN)) {
                err_dpos(pos, ERR_CONST_TRUNCFP);
                ld = 0.0f;
            }
            tval.type = ty_floattype;
            tval.u.c.v.f = (float)ld;
            break;
        case 'l':
        case 'L':
            cs++;    /* skips l or L */
            if ((OVF(ld) && errno == ERANGE) || ld > TG_LDBL_MAX) {
                err_dpos(pos, ERR_CONST_LARGEFP);
                ld = TG_LDBL_MAX;
            } else if ((ld == 0.0 && errno == ERANGE) || (ld > 0.0 && ld < TG_LDBL_MIN))
                err_dpos(pos, ERR_CONST_TRUNCFP);
            tval.type = ty_ldoubletype;
            tval.u.c.v.ld = (long double)ld;
            break;
        default:
            if ((OVF(ld) && errno == ERANGE) || ld > TG_DBL_MAX) {
                err_dpos(pos, ERR_CONST_LARGEFP);
                ld = (double)TG_DBL_MAX;
            } else if ((ld == 0.0 && errno == ERANGE) || (ld > 0.0 && ld < TG_DBL_MIN)) {
                err_dpos(pos, ERR_CONST_TRUNCFP);
                ld = 0.0;
            }
            tval.type = ty_doubletype;
            tval.u.c.v.d = (double)ld;
            break;
    }

    return cs;
}


/*
 *  recognizes integer or floating constants;
 *  ASSUMPTION: strtold() supported on the host
 */
static int ifcon(lex_t *t)
{
    ux_t n;
    int b, d;
    long double ld;
    int err = 0, ovf = 0;
    const char *ss, *s;
    char *p = "0123456789abcdef";    /* no const for reuse with strtold() */

    assert(t);

    ss = s = LEX_SPELL(t);

    if (*s == '.')
        goto fcon;
    n = xO;
    if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X') &&
        isxdigit(((unsigned char *)s)[2])) {    /* 0x[0-9] */
        b = 16;
        s++;    /* skips 0 */
        while (isxdigit(*(unsigned char *)++s)) {
            d = strchr(p, tolower(*(unsigned char *)s)) - p;
            if (xt(xba(n, xbc(xsrl(xmxu, 4)))))
                ovf = 1;
            n = xau(xsl(n, 4), xiu(d));
        }
        s = icon(s, n, ovf, b, t->pos);
        b = LEX_ICON;
    } else {    /* 0 or other digits */
        b = (*s == '0')? 8: 10;
        if (b == 8)
            while (isdigit(*(unsigned char *)s)) {
                d = *s++ - '0';
                if (*s == '8' || *s == '9')
                    p = (char *)s, err = 1;
                if (xt(xba(n, xbc(xsrl(xmxu, 3)))))
                    ovf = 1;
                n = xau(xsl(n, 3), xiu(d));
            }
        else    /* b == 10 */
            while (isdigit(*(unsigned char *)s)) {
                d = *s++ - '0';
                if (xgu(n, xdu(xsu(xmxu, xiu(d)), xiu(10))))
                    ovf = 1;
                n = xau(xmu(xiu(10), n), xiu(d));
            }

        fcon:
            if (b != 16 && (*s == '.' || *s == 'e' || *s == 'E')) {
                if (*s == '.')
                    do {
                        s++;    /* skips . and digits */
                    } while(isdigit(*s));
                if (*s == 'e' || *s == 'E') {
                    if (*++s == '-' || *s == '+')    /* skips e or E */
                        s++;    /* skips - or + */
                    if (!isdigit(*s)) {
                        err_dpos(lmap_spell(t, ss, s, s+1), ERR_CONST_NOEXPDIG);
                        err = 1;
                    }
                }
                if (!err) {
                    errno = 0;
                    ld = strtold(ss, &p);
                    s = fcon((s = p), ld, t->pos);
                }
                b = LEX_FCON;
            } else {
                if (err)
                    err_dpos(lmap_spell(t, ss, p, p+1), ERR_CONST_ILLOCTESC);
                else
                    s = icon(s, n, ovf, b, t->pos);
                b = LEX_ICON;
            }
    }

    if (*s && !err) {
        for (p = (char *)s; *p; p++)
            continue;
        err_dpos(lmap_spell(t, ss, s, p), ERR_CONST_PPNUMSFX, s, b);
        err = 1;
    }

    clx_sym = (err)? NULL: &tval;
    return b;
}
Exemple #13
0
Transformation Boonas:: parseParams(int start, int argc, char** argv, Transformation matrix) 
{
	QString currIn;
	
	for(int i = start; i < (argc - 1); i += 2) // iterate through parameters skiping every other
	{
		if(strcmp(argv[i], "XT") == 0)
		{
			currIn = argv[i + 1];
			matrix = xt(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "YT") == 0)
		{
			currIn = argv[i + 1];
			matrix = yt(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "ZT") == 0)
		{
			currIn = argv[i + 1];
			matrix = zt(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "XS") == 0)
		{
			currIn = argv[i + 1];
			matrix = xs(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "YS") == 0)
		{
			currIn = argv[i + 1];
			matrix = ys(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "ZS") == 0)
		{
			currIn = argv[i + 1];
			matrix = zs(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "US") == 0)
		{
			currIn = argv[i + 1];
			matrix = us(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "XD") == 0)
		{
			currIn = argv[i + 1];
			matrix = xd(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "YD") == 0)
		{
			currIn = argv[i + 1];
			matrix = yd(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "ZD") == 0)
		{
			currIn = argv[i + 1];
			matrix = zd(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "XR") == 0)
		{
			currIn = argv[i + 1];
			matrix = xr(currIn.toFloat(), matrix);
		}
		else if(strcmp(argv[i], "YR") == 0)
		{
			currIn = argv[i + 1];
			matrix = yr(currIn.toFloat(), matrix);
		}
		else // MUST BE ZR
		{
			currIn = argv[i + 1];
			matrix = zr(currIn.toFloat(), matrix);
		}
	}
	
	return matrix;
}
void
arrangement::compute_ACScellBeginEnd()
{
    int ncr_begin = -1;
    int ncr_end = -1;

    Walk_pl walk_pl(nonCriticalRegions);

    // get NCR start
    Rational xt(target_centre.x());
    Rational yt(target_centre.y());
    Conic_point_2 pt(xt,yt);
    Arrangement_2::Vertex_handle v = insert_point(nonCriticalRegions, pt, walk_pl);
    try
    {
        ncr_begin = v->face()->data();
        nonCriticalRegions.remove_isolated_vertex(v);
    }
    catch (const std::exception exn)
    {
        target_centre = QPoint(target_centre.x()+1, target_centre.y()+1);
        compute_ACScellBeginEnd();
        return;
    }

    // get NCR end
    Rational xe(target_centre_end.x());
    Rational ye(target_centre_end.y());
    Conic_point_2 pe(xe,ye);
    Arrangement_2::Vertex_handle w = insert_point(nonCriticalRegions, pe, walk_pl);
    try
    {
        ncr_end = w->face()->data();
        nonCriticalRegions.remove_isolated_vertex(w);
    }
    catch (const std::exception exn)
    {
        target_centre_end = QPoint(target_centre_end.x()+1, target_centre_end.y()+1);
        compute_ACScellBeginEnd();
        return;
    }

    // retrieve ACScell
    for (int i = 0; i < (int) ACScells.size(); i++)
    if (ACScells[i].NCR == ncr_begin)
    {
        Rational x(manipulator_centre.x());
        Rational y(manipulator_centre.y());
        Conic_point_2 p(x,y);
        Walk_pl walk(ACScells[i].arr);
        Arrangement_2::Vertex_handle u = insert_point(ACScells[i].arr, p, walk);
        try
        {
            if (!u->face()->is_unbounded())
            {
                ACScells[i].arr.remove_isolated_vertex(u);
                AcscellBegin = i;
                break;
            }
        }
        catch (const std::exception exn)
        {
            manipulator_centre = QPoint(manipulator_centre.x()+1, manipulator_centre.y()+1);
            compute_ACScellBeginEnd();
            return;
        }
    }

    for (int i = 0; i < (int) ACScells.size(); i++)
    if (ACScells[i].NCR == ncr_end)
    {
        Rational x(manipulator_centre_end.x());
        Rational y(manipulator_centre_end.y());
        Conic_point_2 p(x,y);
        Walk_pl walk(ACScells[i].arr);
        Arrangement_2::Vertex_handle u = insert_point(ACScells[i].arr, p, walk);
        try
        {
            if (!u->face()->is_unbounded())
            {
                ACScells[i].arr.remove_isolated_vertex(u);
                AcscellEnd = i;
                break;
            }
        }
        catch (const std::exception exn)
        {
            manipulator_centre_end = QPoint(manipulator_centre_end.x()+1, manipulator_centre_end.y()+1);
            compute_ACScellBeginEnd();
            return;
        }
    }
}
Exemple #15
0
  // Run one valid triangle. Solve for x in
  //     P' T Q' x = R \ b,
  // where P = diag(p) and similarly for Q and R, and T is a triangle.
  static int test (const TestOptions& to, const bool print_options=false,
                   const bool exception_expected=false) {
    int nerr = 0;

    const Int max_nrhs = 3;
    const Real tol = std::numeric_limits<Real>::epsilon()*1e6;

    // Generate matrix data.
    Data d;
    Size nnz;
    {
      ut::gen_tri_matrix(to, d);     // triangle
      nnz = d.ir.back();
      ut::gen_rand_perm(d.m, d.p);   // row permutation vector
      ut::gen_rand_perm(d.m, d.q);   // col permutation vector
      ut::gen_rand_vector(d.m, d.r); // row scaling
    }

    const Int ldb = d.m + 3, ldx = d.m + 4;
    std::vector<Sclr> b(ldb*max_nrhs), xt(d.m*max_nrhs), x(ldx*max_nrhs);
    {
      // True x.
      ut::gen_rand_vector(xt.size(), xt);
      // Generate the rhs b.
      for (Int irhs = 0; irhs < max_nrhs; ++irhs) {
        const Sclr* const xtp = xt.data() + irhs*d.m;
        Sclr* const bp = b.data() + irhs*ldb;
        std::vector<Sclr> y(d.m);
        for (Int i = 0; i < d.m; ++i)
          x[i] = xtp[d.q[i]];
        ut::mvp(d, to.transpose, to.conjugate, x.data(), y.data());
        for (Int i = 0; i < d.m; ++i)
          bp[d.p[i]] = y[i];
        for (Int i = 0; i < d.m; ++i)
          bp[i] *= d.r[i];
      }
    }
    std::vector<Sclr> bo(b);

    typename ihts::CrsMatrix* T;
    typename ihts::Options opts;
    {
      T = ihts::make_CrsMatrix(d.m, d.ir.data(), d.jc.data(), d.v.data(),
                               to.transpose, to.conjugate);
      if ( ! to.reprocess && to.nthreads > 1)
        ihts::register_Deallocator(T, &d);
      if (to.solve_type == TestOptions::ls_only)
        ihts::set_level_schedule_only(opts);
      else if (to.solve_type == TestOptions::rb_only)
        opts.min_lset_size = d.m + 1;
      // To really test things well, choose very small block sizes. (This is bad
      // for performance.) These parameters are not meant to be set by the user
      // ordinarily, but they are exposed in case an expert is tuning performance
      // or, as here, for testing.
      opts.min_block_size = 6;
      opts.min_parallel_rows = 2;
      opts.pp_min_block_size = 12;
      if (to.matrix_type == TestOptions::block_sparse)
        opts.levelset_block_size = to.block_size;
    }

    {
      typename ihts::Impl* impl;
      try {
        impl = ihts::preprocess(T, max_nrhs - 1 /* For testing; see below. */,
                                to.nthreads, to.reprocess, d.p.data(), d.q.data(),
                                d.r.data(), &opts);
      } catch (...) {
        if ( ! exception_expected) {
          std::cerr << "Unexpected exception on ";
          to.print(std::cerr);
          std::cerr << "\n";
          ut::write_matrixmarket(d, "unexpected_exception.mm");
        }
        ihts::delete_CrsMatrix(T);
        throw;
      }
      if (print_options)
        ihts::print_options(impl, std::cout);
      if (to.reprocess) {
        // This isn't necessary since we aren't changing the numbers, but
        // pretend we are to test the numerical phase. Do it 3 times to test
        // idempotency.
        for (int rep = 0; rep < 3; ++rep)
          ihts::reprocess_numeric(impl, T, d.r.data());
      }
      // Exercise reset_max_nrhs.
      ihts::reset_max_nrhs(impl, max_nrhs);
      if (ihts::is_lower_tri(impl) &&
          ((to.upper && ! to.transpose) || ( ! to.upper && to.transpose)) &&
          d.m > 1 && nnz > static_cast<Size>(d.m) /* not diag */)
        ++nerr;
      for (int slv = 0; slv < 2; ++slv) {
        // Check each solve interface.
        switch (slv) {
        case 0:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), ldb, ldx);
          break;
        case 1:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 0.0,  1.0,
                          ldb, ldx);
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 2.0, -1.0,
                          ldb, ldx);
          break;
        case 2:
          ihts::solve_omp(impl, b.data(), to.nrhs, ldb);
          break;
        }
        double rd = 0;
        for (Int i = 0; i < to.nrhs; ++i)
          rd = std::max(
            rd, ut::reldif(xt.data() + i*d.m,
                           (slv == 2 ? b.data() + i*ldb : x.data() + i*ldx),
                           d.m));
        if (slv == 2) b = bo;
        if (rd >= tol) {
          ++nerr;
          if (to.verbose) std::cout << "rd " << slv << ": " << rd << "\n";
        }
      }
      ihts::delete_Impl(impl);
    }

    if (to.nthreads == 1) {
      std::vector<Sclr> xb(d.m*to.nrhs), w(d.m);
      for (Int irhs = 0; irhs < to.nrhs; ++irhs) {
        const Sclr* const bp = b.data() + irhs*ldb;
        Sclr* const xbp = xb.data() + irhs*d.m;
        for (Int i = 0; i < d.m; ++i)
          xbp[i] = bp[i];
      }
      ihts::solve_serial(T, ! to.upper, xb.data(), to.nrhs, d.p.data(),
                         d.q.data(), d.r.data(), w.data());
      const double rd = ut::reldif(xt.data(), xb.data(), d.m*to.nrhs);
      if (rd >= tol) {
        ++nerr;
        if (to.verbose) std::cout << "serial rd: " << rd << "\n";
      }
    }

    ihts::delete_CrsMatrix(T);

    if (to.verbose) {
      const bool print = to.verbose == 2 || (to.verbose == 1 && nerr);
      if (print) {
        std::cout << (nerr ? "fail" : "pass") << "ed: ";
        to.print(std::cout);
        std::cout << "\n";
      }
    }

    return nerr;
  }
Exemple #16
0
 // Same thing, but return a new XTable
 boost::shared_ptr<XTable> KTable::transform() const 
 {
     boost::shared_ptr<XTable> xt(new XTable( _N, 2*M_PI/(_N*_dk) ));
     transform(*xt);
     return xt;
 }
Exemple #17
0
void Boonas::doRotate(QString outfile, QString vectx, QString vecty, QString vectz, QString px, QString py, QString pz, QString divisions, QString degrees) 
{
	Point centerP(px.toFloat(), py.toFloat(), pz.toFloat());
	Vector centerV(vectx.toFloat(), vecty.toFloat(), vectz.toFloat());
	Transformation matrix;
	float theta;
	float phi;
	float angleOfRot = degrees.toFloat() / divisions.toFloat();
	
	// translate to x
	matrix = xt(-px.toFloat(), matrix);
	matrix = yt(-py.toFloat(), matrix);
	matrix = zt(-pz.toFloat(), matrix);
	
	
	if(vectz.toFloat() == 0)
	{
		if((vectx.toFloat() == 1) && (vectz.toFloat() == 0))
		{
			theta = 1.57079633;
		}
		else
		{
			theta = 0.0;
		}
	}
	else
	{
		theta = atan(vectx.toFloat() / vectz.toFloat());
	}
	
	matrix = yr(-theta, matrix);
	phi = atan(vecty.toFloat() / (sqrt((vectx.toFloat() * vectx.toFloat()) + (vectz.toFloat() * vectz.toFloat()))));
	matrix = xr(phi, matrix);
	
	// apply matrix
	doMult(matrix);
	
	// do rotates and divisions along Z
	doZrm(outfile, angleOfRot, divisions.toFloat());
	
	// have to re-read from a temp file after this
	delete orig;
	orig = new LNHHolder();
	readTfile(outfile);
	
	//unrotate
	matrix = Transformation();
	matrix = xr(-phi, matrix);
	matrix = yr(theta, matrix);
	
	// untranslate
	matrix = xt(px.toFloat(), matrix);
	matrix = yt(py.toFloat(), matrix);
	matrix = zt(pz.toFloat(), matrix);
	
	// apply matrix
	doMult(matrix);
	
	return;
}