Esempio n. 1
0
/*
 *  accepts #elif
 */
static lex_t *delif(const lmap_t *pos)
{
    if (!cond_list)
        err_dpos(pos, ERR_PP_NOMATCHIF, "#elif");
    else {
        if (!cond_list->prev)
            mg_state = MG_SINIT;
        if (cond_list->epos)
            (void)(err_dpos(pos, ERR_PP_ELIFAFTRELSE) &&
                   err_dpos(cond_list->epos, ERR_PP_ELSEHERE));
        else if (cond_list->f.once)
            cond_list->f.ignore = 1;
        else if (cond_list->f.ignore != 2) {
            expr_t *c;
            lex_t *t;

            NEXTSP(t);    /* consumes elif */
            if (t->id == LEX_NEWLINE)
                err_dpos(lmap_after(pos), ERR_PP_NOIFEXPR, "#elif");
            else {
                c = expr_start(&t, "#elif");
                if (cond_list->f.once)
                    cond_list->f.ignore = 1;
                else
                    cond_list->f.once = !(cond_list->f.ignore = xe(c->u.u, xO));
            }

            return t;
        }
    }

    return lst_nexti();    /* consumes elif */
}
// Name/Value pair item:
// <name>value</name>
void xmlBuffer::name_value_item( const char *name, const char *format, ... ) {
  xmlElement xe(this,name, xmlElement::delayed_LF);
  va_list ap;
  va_start(ap, format);
vprint(format,ap);
  va_end(ap);
}
Esempio n. 3
0
// static
bool SchemaRecordCoder::fieldsEqual(const FieldsMap& x, const FieldsMap& y) {
	if (x.end_i() != y.end_i()) {
		return false;
	}
	for (size_t i = 0; i < x.end_i(); ++i) {
		fstring xname = x.key(i);
		size_t j = y.find_i(xname);
		if (j == y.end_i()) {
			return false;
		}
		fstring yname = y.key(j);
		BSONElement xe(xname.data()-1, xname.size()+1, BSONElement::FieldNameSizeTag());
		BSONElement ye(yname.data()-1, yname.size()+1, BSONElement::FieldNameSizeTag());
		if (xe.type() == NumberDouble || ye.type() == NumberDouble) {
			double xd = xe.numberDouble();
			double yd = ye.numberDouble();
			if (fabs((xd - yd) / xd) > 0.1)
				return false;
			else
				continue;
		}
		else if (xe != ye)
			return false;
	}
	return true;
}
/*******************************************************************************
  14.9.2 fn:parse-xml-fragment
********************************************************************************/
bool FnParseXmlFragmentIterator::nextImpl(
    store::Item_t& result,
    PlanState& planState) const
{
  zstring docString;

  FnParseXmlFragmentIteratorState* state;
  DEFAULT_STACK_INIT(FnParseXmlFragmentIteratorState, state, planState);

  if (consumeNext(result, theChildren[0].getp(), planState))
  {
    if (result->isStreamable())
    {
      state->theFragmentStream.theStream = &result->getStream();
    }
    else
    {
      result->getStringValue2(docString);
      state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
      state->theFragmentStream.theStream = state->theFragmentStream.theIss;
    }

    state->theProperties.setBaseUri(theSctx->get_base_uri());
    state->theProperties.setParseExternalParsedEntity(true);
    state->theProperties.setStoreDocument(false);

    state->baseUri = state->theProperties.getBaseUri();    

    // create only one document node holding all fragment nodes
    state->theFragmentStream.only_one_doc_node = 1;
       
    try
    {
      result = GENV.getStore().loadDocument(state->baseUri,
                                            state->docUri,
                                            state->theFragmentStream,
                                            state->theProperties);
    }
    catch ( ZorbaException const &e )
    {
      if ( !state->theProperties.getNoError() )
      {
        XQueryException xe(
          XQUERY_EXCEPTION(err::FODC0006,
          ERROR_PARAMS( "fn:parse-xml-fragment()", e.what() ),
          ERROR_LOC( loc )));

        set_data( xe, e );
        throw xe;
      }
      result = nullptr;
    }

    if (result != NULL)
      STACK_PUSH(true, state);
  } // if 

  STACK_END(state);
}
Esempio n. 5
0
/* Exception handling ------------------------------------------------------ */
void _Xmipp_error(const ErrorType nerr, const String &what,
                  const String &file, const long line)
{
    XmippError xe(nerr, what, file, line);
    std::cerr << xe << std::endl;
    //std::cout << nerr << ": " << what << std::endl
    //<< "File: " << file << " line: " << line << std::endl;
    exit(nerr);
}
Eigen::MatrixXd kalmanFilter::kalmanFunc(Eigen::MatrixXd phi, Eigen::MatrixXd upsilon, Eigen::MatrixXd basis, Eigen::MatrixXd initial, Eigen::MatrixXd initial_cov, int measurements, Eigen::MatrixXd noise){
		Eigen::MatrixXd x(measurements,2), xe(measurements,2), ym(measurements,1), covariance(measurements,2);
		Eigen::MatrixXd gain;
		x.setZero(measurements,2);
		x.row(0) = initial;
		
		
		xe.setZero(measurements,2);
		
		ym.setZero(measurements,1);
		ym.row(0) = (basis*x.row(0).transpose()).transpose()+(noise.cwiseSqrt().row(0))*Eigen::MatrixXd::Random(1,1);

		covariance.setZero(measurements,2);
		covariance.row(0) = initial_cov.diagonal().transpose();
		
		
		
		// Main loop
		
		for(int i=0; i<(measurements-1); i++){
			
			// Truth and Measurements
			x.row(i+1) = (phi*x.row(i).transpose()+upsilon*(noise.cwiseSqrt().row(1))*Eigen::MatrixXd::Random(1,1)).transpose();
			ym.row(i+1) = (basis*x.row(i+1).transpose()).transpose()+(noise.cwiseSqrt().row(0))*Eigen::MatrixXd::Random(1,1);
			

			
			// Update Equations
			
			gain = initial_cov*basis.transpose()*((basis*initial_cov*basis.transpose())+noise.row(0)).cwiseInverse();
			initial_cov = (Eigen::MatrixXd::Identity(2,2)-gain*basis)*initial_cov;
			xe.row(i) = xe.row(i)+(gain*(ym.row(i)-basis*xe.row(i).transpose())).transpose();


			
			// Propagation Equations
			
			xe.row(i+1) = (phi*xe.row(i).transpose()).transpose();
			initial_cov = phi*initial_cov*phi.transpose()+upsilon*noise.row(1)*upsilon.transpose();
			covariance.row(i+1) = initial_cov.diagonal().transpose();
			
		}

		
		Eigen::MatrixXd result(measurements,6);
		result << xe, x, (covariance.cwiseSqrt())*3;
		
		return result;







}
Esempio n. 7
0
/*
 *  accepts #if, #ifdef or #ifndef (a start of conditionals);
 *  ASSUMPTION: no signed zero on the host
 */
static lex_t *dif(const lmap_t *pos, int kind, int ign)
{
    lex_t *t;
    expr_t *c;
    const char *s;

    assert(pos);

    cond_push(kind, pos);
    t = lst_nexti();    /* skips if/ifdef/ifndef */
    if (ign) {
        cond_list->f.ignore = 2;    /* inside ignoring section */
        SKIPNL(t);
        return t;
    }
    SKIPSP(t);
    switch(kind) {
        case COND_KIF:
            if (t->id == LEX_NEWLINE)
                err_dpos(lmap_after(pos), ERR_PP_NOIFEXPR, "#if");
            else {
                c = expr_start(&t, "#if");
                cond_list->f.once = !(cond_list->f.ignore = xe(c->u.u, xO));
            }
            break;
        case COND_KIFNDEF:
            if (mg_state == MG_SINIT && state == SIDIREC)
                mg_state = MG_SIFNDEF;
        case COND_KIFDEF:
            if (t->id != LEX_ID) {
                err_dmpos(lmap_after(pos), ERR_PP_NOIFID, pos, NULL, kind);
                SKIPNL(t);
                return t;
            }
            if (mg_state == MG_SIFNDEF) {
                mg_name = hash_string(LEX_SPELL(t));
                mg_state = MG_SMACRO;
            }
            cond_list->f.once = !(cond_list->f.ignore =
                                      mcr_redef(s = LEX_SPELL(t)) ^ (kind == COND_KIFDEF));
            MCR_IDVAARGS(s, t);
            t = lst_nexti();
            break;
        default:
            assert(!"invalid conditional kind -- should never reach here");
            break;
    }

    return t;
}
void ArtaObjects::oop_print_xml_on(oop o, xmlBuffer *xb, bool ref) {
  if (ref) {
    // objref printing
assert(o->is_oop_or_null(),"o is invalid");
    if (o == NULL) {
      xmlElement xe(xb, "object_ref");
      null_print_xml_on(xb);
      return;
    }
  } else {
    // object printing
assert(o!=NULL,"o is NULL");
assert(o->is_oop(),"o an invalid oop");
  }
  o->print_xml_on(xb, ref);
}
void serials_releaser::set_serials_list() {
	xml_editor xe("serials.xml");

	QVector<serial_info> serials = xe.load_data();

	QVBoxLayout * lay = new QVBoxLayout();
	serial_items.clear();
	foreach(serial_info serial, serials) {
		serial_item * it = new serial_item();
		it->ui.label_serial_title->setText(serial.title);
		it->ui.spinBox_season->setValue(serial.season);
		it->ui.spinBox_episode->setValue(serial.episode);
		
		serial_items.push_back(it);
		it->change_enabled_form();
		lay->addWidget(it);
	}
Esempio n. 10
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;
}
bool FnZorbaParseXmlFragmentIterator::nextImpl(
    store::Item_t& result,
    PlanState& planState) const
{
  store::Store& lStore = GENV.getStore();
  zstring docString;
  store::Item_t tempItem;
  bool validated = true;

  FnZorbaParseXmlFragmentIteratorState* state;
  DEFAULT_STACK_INIT(FnZorbaParseXmlFragmentIteratorState, state, planState);

  if (consumeNext(result, theChildren[0].getp(), planState))
  {
    if (result->isStreamable())
    {
      state->theFragmentStream.theStream = &result->getStream();
      state->theFragmentStream.setStreamReleaser(result->getStreamReleaser());
      result->setStreamReleaser(nullptr);
    }
    else
    {
      result->getStringValue2(docString);
      state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
      state->theFragmentStream.theStream = state->theFragmentStream.theIss;
    }

    // read options
    consumeNext(tempItem, theChildren[1].getp(), planState);
    state->theProperties.setBaseUri(theSctx->get_base_uri());
    state->theProperties.setStoreDocument(false);
    state->theProperties.setUseCachedDocument(false);
    processOptions(tempItem, state->theProperties, theSctx, loc);
    state->theProperties.setCreateDocParentLink(false);

    // baseURI serves both as the base URI used by the XML parser
    // to resolve relative entity references within the document,
    // and as the base URI of the document node that is returned.
    state->baseUri = state->theProperties.getBaseUri();
    state->docUri = state->theProperties.getBaseUri();


    ////////////////////////////////////////////////////////////////////////
    // External parsed entity processing
    ////////////////////////////////////////////////////////////////////////
    if (state->theProperties.getParseExternalParsedEntity())
    {
      state->theFragmentStream.root_elements_to_skip =
      state->theProperties.getSkipRootNodes();

      while ( ! state->theFragmentStream.stream_is_consumed())
      {
        try
        {
          result = lStore.loadDocument(state->baseUri,
                                       state->docUri,
                                       state->theFragmentStream,
                                       state->theProperties);
        }
        catch ( ZorbaException const &e )
        {
          if ( !state->theProperties.getNoError() )
          {
            XQueryException xe(
              XQUERY_EXCEPTION(
                err::FODC0006,
                ERROR_PARAMS( "parse-xml:parse()", e.what() ),
                ERROR_LOC( loc )
              )
            );
            set_data( xe, e );
            throw xe;
          }
          result = nullptr;
        }

        if (result == NULL)
          continue;

        // Return the children of document node
        state->theFragmentStream.children = result->getChildren();
        while (state->theFragmentStream.children->next(result) && result != NULL)
        {
          if (state->theProperties.getSkipTopLevelTextNodes() && result->getNodeKind() == store::StoreConsts::textNode)
            continue;

          STACK_PUSH(true, state);
        }
      }
    }
    ////////////////////////////////////////////////////////////////////////
    // XML document processing
    ////////////////////////////////////////////////////////////////////////
    else  // if (!state->theProperties.getEnableExtParsedEntity())
    {
      try 
      {
        result = lStore.loadDocument(state->baseUri, state->docUri, *state->theFragmentStream.theStream, state->theProperties);
      }
      catch ( ZorbaException const &e )
      {
        if ( !state->theProperties.getNoError() )
        {
          XQueryException xe(
            XQUERY_EXCEPTION(
              err::FODC0006,
              ERROR_PARAMS( "parse-xml:parse()", e.what() ),
              ERROR_LOC( loc )
            )
          );
          set_data( xe, e );
          throw xe;
        }
        result = nullptr;
      }

      if (result != NULL)
      {
#ifndef ZORBA_NO_XMLSCHEMA
        if (state->theProperties.getSchemaLaxValidate() ||
            state->theProperties.getSchemaStrictValidate())
        {
          try
          {
            tempItem = NULL; // used as the effectiveValidationValue()'s typeName
            validated = Validator::effectiveValidationValue(
                          result,
                          result,
                          tempItem,
                          theSctx->get_typemanager(),
                          state->theProperties.getSchemaLaxValidate() ? ParseConstants::val_lax : ParseConstants::val_strict,
                          theSctx,
                          this->loc);
          }
          catch (ZorbaException& /*e*/)
          {
            if ( ! state->theProperties.getNoError())
              throw;
            else
            {
              result = NULL;
              validated = false;
            }
          }
        }
#endif
        // Ignore the schema validation options if Zorba is built without schema support

        STACK_PUSH(validated, state);
      } // if (result != NULL)
    } // if (state->theProperties.getEnableExtParsedEntity())
  } // if (consumeNext(result, theChildren[0].getp(), planState))

  STACK_END(state);
}
/*************************************************************************
Main unittest subroutine
*************************************************************************/
bool testsst(bool silent)
{
    bool result;
    int maxmn;
    int passcount;
    double threshold;
    ap::real_2d_array aeffective;
    ap::real_2d_array aparam;
    ap::real_1d_array xe;
    ap::real_1d_array b;
    int n;
    int pass;
    int i;
    int j;
    int cnts;
    int cntu;
    int cntt;
    int cntm;
    bool waserrors;
    bool isupper;
    bool istrans;
    bool isunit;
    double v;
    double s;

    waserrors = false;
    maxmn = 15;
    passcount = 15;
    threshold = 1000*ap::machineepsilon;
    
    //
    // Different problems
    //
    for(n = 1; n <= maxmn; n++)
    {
        aeffective.setbounds(0, n-1, 0, n-1);
        aparam.setbounds(0, n-1, 0, n-1);
        xe.setbounds(0, n-1);
        b.setbounds(0, n-1);
        for(pass = 1; pass <= passcount; pass++)
        {
            for(cnts = 0; cnts <= 1; cnts++)
            {
                for(cntu = 0; cntu <= 1; cntu++)
                {
                    for(cntt = 0; cntt <= 1; cntt++)
                    {
                        for(cntm = 0; cntm <= 2; cntm++)
                        {
                            isupper = cnts==0;
                            isunit = cntu==0;
                            istrans = cntt==0;
                            
                            //
                            // Skip meaningless combinations of parameters:
                            // (matrix is singular) AND (matrix is unit diagonal)
                            //
                            if( cntm==2&&isunit )
                            {
                                continue;
                            }
                            
                            //
                            // Clear matrices
                            //
                            for(i = 0; i <= n-1; i++)
                            {
                                for(j = 0; j <= n-1; j++)
                                {
                                    aeffective(i,j) = 0;
                                    aparam(i,j) = 0;
                                }
                            }
                            
                            //
                            // Prepare matrices
                            //
                            if( isupper )
                            {
                                for(i = 0; i <= n-1; i++)
                                {
                                    for(j = i; j <= n-1; j++)
                                    {
                                        aeffective(i,j) = 0.9*(2*ap::randomreal()-1);
                                        aparam(i,j) = aeffective(i,j);
                                    }
                                    aeffective(i,i) = (2*ap::randominteger(2)-1)*(0.8+ap::randomreal());
                                    aparam(i,i) = aeffective(i,i);
                                }
                            }
                            else
                            {
                                for(i = 0; i <= n-1; i++)
                                {
                                    for(j = 0; j <= i; j++)
                                    {
                                        aeffective(i,j) = 0.9*(2*ap::randomreal()-1);
                                        aparam(i,j) = aeffective(i,j);
                                    }
                                    aeffective(i,i) = (2*ap::randominteger(2)-1)*(0.8+ap::randomreal());
                                    aparam(i,i) = aeffective(i,i);
                                }
                            }
                            if( isunit )
                            {
                                for(i = 0; i <= n-1; i++)
                                {
                                    aeffective(i,i) = 1;
                                    aparam(i,i) = 0;
                                }
                            }
                            if( istrans )
                            {
                                if( isupper )
                                {
                                    for(i = 0; i <= n-1; i++)
                                    {
                                        for(j = i+1; j <= n-1; j++)
                                        {
                                            aeffective(j,i) = aeffective(i,j);
                                            aeffective(i,j) = 0;
                                        }
                                    }
                                }
                                else
                                {
                                    for(i = 0; i <= n-1; i++)
                                    {
                                        for(j = i+1; j <= n-1; j++)
                                        {
                                            aeffective(i,j) = aeffective(j,i);
                                            aeffective(j,i) = 0;
                                        }
                                    }
                                }
                            }
                            
                            //
                            // Prepare task, solve, compare
                            //
                            for(i = 0; i <= n-1; i++)
                            {
                                xe(i) = 2*ap::randomreal()-1;
                            }
                            for(i = 0; i <= n-1; i++)
                            {
                                v = ap::vdotproduct(&aeffective(i, 0), &xe(0), ap::vlen(0,n-1));
                                b(i) = v;
                            }
                            rmatrixtrsafesolve(aparam, n, b, s, isupper, istrans, isunit);
                            ap::vmul(&xe(0), ap::vlen(0,n-1), s);
                            ap::vsub(&xe(0), &b(0), ap::vlen(0,n-1));
                            v = ap::vdotproduct(&xe(0), &xe(0), ap::vlen(0,n-1));
                            v = sqrt(v);
                            waserrors = waserrors||v>threshold;
                        }
                    }
                }
            }
        }
    }
    
    //
    // report
    //
    if( !silent )
    {
        printf("TESTING RMatrixTRSafeSolve\n");
        if( waserrors )
        {
            printf("TEST FAILED\n");
        }
        else
        {
            printf("TEST PASSED\n");
        }
        printf("\n\n");
    }
    result = !waserrors;
    return result;
}
Esempio n. 13
0
vector<double> CNelderMead::NelderMeadFunction(double (*f)(vector<double>, RMSEinputs rmsein), NMsettings nmset, vector<vector<double> > x)
{
	int NumIters = 0;
	int i,j;

	double MaxIters   = nmset.MaxIters;
	double tolerance  = nmset.tolerance;
	int N = nmset.N;
	RMSEinputs rmsein = nmset.RMSEinp;
	double S = rmsein.S;
	double T = rmsein.T;
	double r = rmsein.r;

	// Value of the function at the vertices
	vector<vector<double> > F(N+1, vector<double>(2));

	// Step 0.  Ordering and Best and Worst points
	// Order according to the functional values, compute the best and worst points
	step0:
	NumIters += 1;
	for (j=0; j<=N; j++){
		vector<double> z(N, 0.0);								// Create vector to contain
		for (i=0; i<=N-1; i++)
			z[i] = x[i][j];
		F[j][0] = f(z,rmsein);		       						// Function values
		F[j][1] = j;											// Original index positions
	}
	sort(F.begin(), F.end());

	// New vertices order first N best initial vectors and
	// last (N+1)st vertice is the worst vector
	// y is the matrix of vertices, ordered so that the worst vertice is last
	vector<vector<double> > y(N, vector<double>(N+1));
	for (j=0; j<=N; j++)
		for (i=0; i<=N-1; i++)
			y[i][j] = x[i][F[j][1]];

	//  First best vector y(1) and function value f1
	vector<double> x1(N, 0.0); for (i=0; i<=N-1; i++) x1[i] = y[i][0];
	double f1 = f(x1,rmsein);

	// Last best vector y(N) and function value fn
	vector<double> xn(N, 0.0); for (i=0; i<=N-1; i++) xn[i] = y[i][N-1];
	double fn = f(xn,rmsein);

	// Worst vector y(N+1) and function value fn1
	vector<double> xn1(N, 0.0); for (i=0; i<=N-1; i++) xn1[i] = y[i][N];
	double fn1 = f(xn1,rmsein);

	// z is the first N vectors from y, excludes the worst y(N+1)
	vector<vector<double> > z(N, vector<double>(N));
	for (j=0; j<=N-1; j++)
		for (i=0; i<=N-1; i++)
			z[i][j] = y[i][j];

	// Mean of best N values and function value fm
	vector<double> xm(N, 0.0); xm = CNelderMead::VMean(z,N);
	double fm = f(xm,rmsein);

	// Reflection point xr and function fr
	vector<double> xr(N, 0.0); xr = CNelderMead::VSub(VAdd(xm, xm), xn1);
	double fr = f(xr,rmsein);

	// Expansion point xe and function fe
	vector<double> xe(N, 0.0); xe = CNelderMead::VSub(VAdd(xr, xr), xm);
	double fe = f(xe,rmsein);

	// Outside contraction point and function foc
	vector<double> xoc(N, 0.0);	xoc = CNelderMead::VAdd(CNelderMead::VMult(xr, 0.5), VMult(xm, 0.5));
	double foc = f(xoc,rmsein);

	// Inside contraction point and function foc
	vector<double> xic(N, 0.0);	xic = CNelderMead::VAdd(CNelderMead::VMult(xm, 0.5), CNelderMead::VMult(xn1, 0.5));
	double fic = f(xic,rmsein);

	while ((NumIters <= MaxIters) && (abs(f1-fn1) >= tolerance))
	{
		// Step 1. Reflection Rule
		if ((f1<=fr) && (fr<fn)) {
			for (j=0; j<=N-1; j++)
				for (i=0; i<=N-1; i++)
					x[i][j] = y[i][j];
			for (i=0; i<=N-1; i++)
				x[i][N] = xr[i];
			goto step0;
		}

		// Step 2.  Expansion Rule
		if (fr<f1) {
			for (j=0; j<=N-1; j++) {
				for (i=0; i<=N-1; i++)  x[i][j] = y[i][j]; }
			if (fe<fr)
				for (i=0; i<=N-1; i++)	x[i][N] = xe[i];
			else
				for (i=0; i<=N-1; i++)	x[i][N] = xr[i];
			goto step0;
		}

		// Step 3.  Outside contraction Rule
		if ((fn<=fr) && (fr<fn1) && (foc<=fr)) {
			for (j=0; j<=N-1; j++) {
				for (i=0; i<=N-1; i++)  x[i][j] = y[i][j]; }
			for (i=0; i<=N-1; i++)	x[i][N] = xoc[i];
			goto step0;
		}

		// Step 4.  Inside contraction Rule
		if ((fr>=fn1) && (fic<fn1)) {
			for (j=0; j<=N-1; j++) {
				for (i=0; i<=N-1; i++)  x[i][j] = y[i][j]; }
			for (i=0; i<=N-1; i++)	x[i][N] = xic[i];
			goto step0;
		}

		// Step 5. Shrink Step
		for (i=0; i<=N-1; i++)
			x[i][0] = y[i][0];
		for (i=0; i<=N-1; i++) {
			for (j=1; j<=N; j++)
				x[i][j] = 0.5*(y[i][j] + x[i][0]);
		}
		goto step0;
	}

	// Output component
	// Return N parameter values, value of objective function, and number of iterations
	vector<double> out(N+2);
	for (i=0; i<=N-1; i++)
		out[i] = x1[i];
	out[N] = f1;
	out[N+1] = NumIters;
	return out;
}
	bool TuneForBest(int maxIteration,
			double tol = 1E8 * std::numeric_limits<float>::epsilon(),
			std::vector<std::vector<float> > x = std::vector<
					std::vector<float> >())
	{
		std::vector<float> init;
		for(size_t pi=0;pi<paramsCount;pi++)
		{
			init.push_back(parameters[pi].data);
		}
		int N = paramsCount;                         //space dimension
		const double a = 1.0, b = 1.0, g = 0.5, h = 0.5;   //coefficients
														   //a: reflection  -> xr
														   //b: expansion   -> xe
														   //g: contraction -> xc
														   //h: full contraction to x1
		std::vector<float> xcentroid_old(N, 0);   //simplex center * (N+1)
		std::vector<float> xcentroid_new(N, 0);   //simplex center * (N+1)
		std::vector<float> vf(N + 1, 0);    //f evaluated at simplex vertexes
		int x1 = 0, xn = 0, xnp1 = 0; //x1:   f(x1) = min { f(x1), f(x2)...f(x_{n+1} }
									  //xnp1: f(xnp1) = max { f(x1), f(x2)...f(x_{n+1} }
									  //xn:   f(xn)<f(xnp1) && f(xn)> all other f(x_i)
		int cnt = 0; //iteration step number

		if (x.size() == 0) //if no initial simplex is specified
		{ //construct the trial simplex
			//based upon the initial guess parameters
			std::vector<float> del(init);
			std::transform(del.begin(), del.end(), del.begin(),
					std::bind2nd(std::divides<float>(), 20));	//'20' is picked
															//assuming initial trail close to true

			for (int i = 0; i < N; ++i)
			{
				std::vector<float> tmp(init);
				tmp[i] += del[i];
				x.push_back(tmp);
			}
			x.push_back(init);		               //x.size()=N+1, x[i].size()=N

			//xcentriod
			std::transform(init.begin(), init.end(), xcentroid_old.begin(),
					std::bind2nd(std::multiplies<float>(), N + 1));
		}		                             //constructing the simplex finished

		//optimization begins
		for (cnt = 0; cnt < maxIteration; ++cnt)
		{

			for (int i = 0; i < N + 1; ++i)
			{
				vf[i] = (obj.*pFunc)(x[i]);
			}

			x1 = 0;
			xn = 0;
			xnp1 = 0;		         //find index of max, second max, min of vf.

			for (size_t i = 0; i < vf.size(); ++i)
			{
				if (vf[i] < vf[x1])
				{
					x1 = i;
				}
				if (vf[i] > vf[xnp1])
				{
					xnp1 = i;
				}
			}

			xn = x1;

			for (size_t i = 0; i < vf.size(); ++i)
			{
				if (vf[i] < vf[xnp1] && vf[i] > vf[xn])
					xn = i;
			}
			//x1, xn, xnp1 are found

			std::vector<float> xg(N, 0);	//xg: centroid of the N best vertexes
			for (size_t i = 0; i < x.size(); ++i)
			{
				if (i != (size_t)xnp1)
					std::transform(xg.begin(), xg.end(), x[i].begin(),
							xg.begin(), std::plus<float>());
			}
			std::transform(xg.begin(), xg.end(), x[xnp1].begin(),
					xcentroid_new.begin(), std::plus<float>());
			std::transform(xg.begin(), xg.end(), xg.begin(),
					std::bind2nd(std::divides<float>(), N));
			//xg found, xcentroid_new updated

			//termination condition
			float diff = 0;        //calculate the difference of the simplex centers
							   //see if the difference is less than the termination criteria
			for (int i = 0; i < N; ++i)
				diff += fabs(xcentroid_old[i] - xcentroid_new[i]);

			if (diff / N < tol)
				break;              //terminate the optimizer
			else
				xcentroid_old.swap(xcentroid_new); //update simplex center

			//reflection:
			std::vector<float> xr(N, 0);
			for (int i = 0; i < N; ++i)
				xr[i] = xg[i] + a * (xg[i] - x[xnp1][i]);
			//reflection, xr found

			float fxr = (obj.*pFunc)(xr); //record function at xr

			if (vf[x1] <= fxr && fxr <= vf[xn])
				std::copy(xr.begin(), xr.end(), x[xnp1].begin());

			//expansion:
			else if (fxr < vf[x1])
			{
				std::vector<float> xe(N, 0);
				for (int i = 0; i < N; ++i)
					xe[i] = xr[i] + b * (xr[i] - xg[i]);
				if ((obj.*pFunc)(xe) < fxr)
					std::copy(xe.begin(), xe.end(), x[xnp1].begin());
				else
					std::copy(xr.begin(), xr.end(), x[xnp1].begin());
			} //expansion finished,  xe is not used outside the scope

			//contraction:
			else if (fxr > vf[xn])
			{
				std::vector<float> xc(N, 0);
				for (int i = 0; i < N; ++i)
					xc[i] = xg[i] + g * (x[xnp1][i] - xg[i]);
				if ((obj.*pFunc)(xc) < vf[xnp1])
					std::copy(xc.begin(), xc.end(), x[xnp1].begin());
				else
				{
					for (size_t i = 0; i < x.size(); ++i)
					{
						if (i != (size_t)x1)
						{
							for (int j = 0; j < N; ++j)
								x[i][j] = x[x1][j] + h * (x[i][j] - x[x1][j]);
						}
					}
				}
			} //contraction finished, xc is not used outside the scope

		} //optimization is finished

		for(size_t pi=0;pi<x[x1].size();pi++)
		{
			parameters[pi].data = x[x1][pi];
		}
		cout << " Tune counter = " << cnt << endl;
		if (cnt == maxIteration)
		{
			return false;
		}
		return true;
	}
Esempio n. 15
0
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;
        }
    }
}
Esempio n. 16
0
grid_manager mpi_manager_2D::make_LocalGrid(grid_manager &GlobalGrid) {
	//! Take the global grid and generate a local one
	
	// First get all properties from global grid manager:
	NumArray<int> mx(DIM);
	NumArray<double> xb(DIM), Len(DIM);
	for(int dir=0; dir<DIM; ++dir) {
		mx[dir] = GlobalGrid.get_mx(dir);
		xb[dir] = GlobalGrid.get_xb(dir);
		Len[dir] = GlobalGrid.get_Len(dir);
	}

	// Now compute local extent of grid (cell-wise and space-wise)
	if (rank == 0) {
		for (int dir=0; dir<DIM; ++dir) {
			mx[dir] /= nproc[dir];
			Len[dir] /= nproc[dir];
		}
	}

	
	MPI_Barrier(comm2d);
	MPI_Bcast(mx, DIM, MPI_INT, 0, comm2d);
	MPI_Bcast(Len, DIM, MPI_DOUBLE, 0, comm2d);
	MPI_Bcast(xb, DIM, MPI_DOUBLE, 0, comm2d);
	MPI_Barrier(comm2d);

	// Now the local computations that need to be done by each rank:
	NumArray<double> xe(DIM);
	for (int dir=0; dir<DIM; ++dir) {
		xb[dir] += Len[dir]*coords[dir];
		xe[dir] = xb[dir] + Len[dir];
	}

	// if(rank == 2) {
	// 	std::cout << " mx: " << mx[0] << " " << mx[1] << " " << mx[2];
	// 	std::cout << std::endl;
	// 	std::cout << " Len: " << Len[0] << " " << Len[1] << " " << Len[2];
	// 	std::cout << std::endl;
	// 	std::cout << " xb: " << xb[0] << " " << xb[1] << " " << xb[2];
	// 	std::cout << std::endl;
	// 	std::cout << " xe: " << xe[0] << " " << xe[1] << " " << xe[2];
	// 	std::cout << std::endl;
	// }


	int rim = GlobalGrid.get_rim();


	// Now make the local grid manager:
	grid_manager LocalGrid(xb[0], xb[1], xe[0], xe[1],
	                       mx[0]+1, mx[1]+1, rim);

	// Now set corresponding boundary types (old type at
	// outer-boundaries / -1 at MPI boundaries)
	for(int bound=0; bound<2*DIM; ++bound) {
		if(is_OuterBoundary(bound)) {
			LocalGrid.set_bcType(bound, GlobalGrid.get_bcType(bound));
		} else {
			LocalGrid.set_bcType(bound, -1);
		}
	}

	return LocalGrid;

}
Esempio n. 17
0
void initPommes(int pommes[20][2]){
  int i;
  for (i=0; i<5; i++) placePomm:xe(pommes, i);
}
void ArtaObjects::null_print_xml_on(xmlBuffer *xb) {
  xmlElement xe(xb, "null");
}