예제 #1
0
파일: lsearch.cpp 프로젝트: andrejadd/ABC
LSearch::LSearch(int _dim, function_type _funct) : PSO(0.0, ///<The w parameter (influence of old vel - momentum)
  		0.0, ///<The minimum value for w -- decreased by time or level
  		0.0, ///<Influence of personal best
  		0.0, ///<Influence of global best
		0.0, ///<vmax = vmaxRatio*xmax, with vmaxRatio=0 no vmax is enforced 
		0.0, ///<Constriction factor, used by #Bird
  		0, ///<Swarmsize
  		_dim, ///<Dimension of the search space
		0, ///<Height of the pyramid, ignored for #seqSwarm
		0, ///<Branches per node of the pyramid, ignored for #seqSwarm
		0, ///<Swap allowed every swapDelay steps in #PyramidSwarm, ignored for #Swarm
  		_funct, ///<#function_type selection
		noNoise, ///<#noiseStyle_type selection, set in #optFunction
		0.0, ///<sigma parameter for gaussian distributed noise
  		seqSwarm) ///<#swarm_type selection
{

	TRACE_IN("LSearch::LSearch");
	DEBUG("New LSearch :");
	DEBUG1("dim = ",_dim);
	int a=0;

	for (int i=0; i<get_dim(); i++)
		currSolution.push_back(randDoubleRange(optFunction->get_min_x(), optFunction->get_max_x()));
	currentVal = evalFunction(currSolution);
	TRACE_OUT("LSearch::LSearch",0);
}
예제 #2
0
/** Create histogram workspace
 */
MatrixWorkspace_sptr CreateSampleWorkspace::createHistogramWorkspace(
    int numPixels, int numBins, double x0, double binDelta,
    int start_at_pixelID, Geometry::Instrument_sptr inst,
    const std::string &functionString, bool isRandom) {
  MantidVecPtr x, y, e;
  x.access().resize(numBins + 1);
  e.access().resize(numBins);
  for (int i = 0; i < numBins + 1; ++i) {
    x.access()[i] = x0 + i * binDelta;
  }

  std::vector<double> xValues(x.access().begin(), x.access().end() - 1);
  y.access() = evalFunction(functionString, xValues, isRandom ? 1 : 0);
  e.access().resize(numBins);

  // calculate e as sqrt(y)
  typedef double (*uf)(double);
  uf dblSqrt = std::sqrt;
  std::transform(y.access().begin(), y.access().end(), e.access().begin(),
                 dblSqrt);

  MatrixWorkspace_sptr retVal(new DataObjects::Workspace2D);
  retVal->initialize(numPixels, numBins + 1, numBins);
  retVal->setInstrument(inst);

  for (size_t wi = 0; wi < static_cast<size_t>(numPixels); wi++) {
    retVal->setX(wi, x);
    retVal->setData(wi, y, e);
    retVal->getSpectrum(wi)->setDetectorID(detid_t(start_at_pixelID + wi));
    retVal->getSpectrum(wi)->setSpectrumNo(specid_t(wi + 1));
  }

  return retVal;
}
예제 #3
0
SAWYER_EXPORT std::string
Grammar::evalArgument(TokenStream &tokens, ErrorLocation &eloc, bool requireRight) const {
    std::string retval, data;
    size_t depth = 0;
    while (!tokens.atEof()) {
        if (tokens.isa(TOK_LEFT)) {
            ++depth;
            retval += tokens.lexeme();
            tokens.consume();
        } else if (tokens.isa(TOK_RIGHT)) {
            if (0 == depth)
                break;
            --depth;
            retval += tokens.lexeme();
            tokens.consume();
        } else if (tokens.isa(TOK_FUNCTION)) {
            retval += evalFunction(tokens, eloc);
        } else {
            retval += tokens.lexeme();
            tokens.consume();
        }
    }
    if (requireRight) {
        if (!tokens.isa(TOK_RIGHT))
            throw SyntaxError("end-of-argument expected");
        tokens.consume();
    }
    if (depth > 0)
        throw SyntaxError("expected end-of-argument marker");
    return retval;
}
예제 #4
0
bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) {

    if (!evalFunction(_id)) { return false; }

    // parse evaluated result at stack top
    parseStyleResult(_key, _val);

    // pop result, empty stack
    duk_pop(m_ctx);

    return !_val.is<none_type>();
}
예제 #5
0
QQmlBinding::QQmlBinding(const QString &str, QObject *obj, QQmlContextData *ctxt)
: QQmlJavaScriptExpression(&QQmlBinding_jsvtable), QQmlAbstractBinding(Binding),
  m_lineNumber(0), m_columnNumber(0)
{
    setNotifyOnValueChanged(true);
    QQmlAbstractExpression::setContext(ctxt);
    setScopeObject(obj);

    QQmlRewrite::RewriteBinding rewriteBinding;
    QString code = rewriteBinding(str);

    m_expression = str.toUtf8();
    v8function = evalFunction(ctxt, obj, code, QString(), 0);
}
예제 #6
0
QT_BEGIN_NAMESPACE

QQmlBoundSignalExpression::QQmlBoundSignalExpression(QObject *target, int index,
                                                     QQmlContextData *ctxt, QObject *scope, const QString &expression,
                                                     const QString &fileName, quint16 line, quint16 column,
                                                     const QString &handlerName,
                                                     const QString &parameterString)
    : QQmlJavaScriptExpression(),
      m_index(index),
      m_target(target)
{
    init(ctxt, scope);

    QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine());
    QV4::ExecutionEngine *v4 = ep->v4engine();

    QString function;

    // Add some leading whitespace to account for the binding's column offset.
    // It's 2 off because a, we start counting at 1 and b, the '(' below is not counted.
    function.fill(QChar(QChar::Space), qMax(column, (quint16)2) - 2);
    function += QStringLiteral("(function ");
    function += handlerName;
    function += QLatin1Char('(');

    if (parameterString.isEmpty()) {
        QString error;
        //TODO: look at using the property cache here (as in the compiler)
        //      for further optimization
        QMetaMethod signal = QMetaObjectPrivate::signal(m_target->metaObject(), m_index);
        function += QQmlPropertyCache::signalParameterStringForJS(v4, signal.parameterNames(), &error);

        if (!error.isEmpty()) {
            qmlInfo(scopeObject()) << error;
            return;
        }
    } else
        function += parameterString;

    function += QStringLiteral(") { ");
    function += expression;
    function += QStringLiteral(" })");

    m_function.set(v4, evalFunction(context(), scopeObject(), function, fileName, line));

    if (m_function.isNullOrUndefined())
        return; // could not evaluate function.  Not valid.

}
예제 #7
0
bool StyleContext::evalFilter(FunctionID _id) {

    bool result = false;

    if (!evalFunction(_id)) { return false; };

    // check for evaluated value sitting at value stack top
    if (duk_is_boolean(m_ctx, -1)) {
        result = duk_get_boolean(m_ctx, -1);
    }

    // pop result
    duk_pop(m_ctx);

    return result;
}
예제 #8
0
QQmlBinding::QQmlBinding(const QQmlScriptString &script, QObject *obj, QQmlContext *ctxt)
: QQmlJavaScriptExpression(&QQmlBinding_jsvtable), QQmlAbstractBinding(Binding)
{
    if (ctxt && !ctxt->isValid())
        return;

    const QQmlScriptStringPrivate *scriptPrivate = script.d.data();
    if (!ctxt && (!scriptPrivate->context || !scriptPrivate->context->isValid()))
        return;

    bool needRewrite = true;
    QString code;

    int id = scriptPrivate->bindingId;
    if (id >= 0) {
        QQmlContextData *ctxtdata = QQmlContextData::get(scriptPrivate->context);
        QQmlEnginePrivate *engine = QQmlEnginePrivate::get(scriptPrivate->context->engine());
        if (engine && ctxtdata && !ctxtdata->url.isEmpty()) {
            QQmlTypeData *typeData = engine->typeLoader.getType(ctxtdata->url);
            Q_ASSERT(typeData);

            if (QQmlCompiledData *cdata = typeData->compiledData()) {
                needRewrite = false;
                code = cdata->primitives.at(id);
                m_url = cdata->name;
            }

            typeData->release();
        }
    }

    if (needRewrite) {
        QQmlRewrite::RewriteBinding rewriteBinding;
        code = rewriteBinding(scriptPrivate->script);
    }

    setNotifyOnValueChanged(true);
    QQmlAbstractExpression::setContext(QQmlContextData::get(ctxt ? ctxt : scriptPrivate->context));
    setScopeObject(obj ? obj : scriptPrivate->scope);

    m_expression = scriptPrivate->script.toUtf8();
    m_lineNumber = scriptPrivate->lineNumber;
    m_columnNumber = scriptPrivate->columnNumber;

    v8function = evalFunction(context(), scopeObject(), code, QString(), m_lineNumber);
}
예제 #9
0
void GradientDescent<DIM, POS, VAL>::optimize(PointSet<DIM, POS, VAL>& _pts)
{
	PointSet<DIM, POS, POS> data = _pts;
	
	int iSz = _pts.size();
	
	for(int d=0; d<DIM; d++)
	{
		Vector<DIM, POS> shift;
		shift[d] += m_shift;
			
		for(int i=0; i<iSz; i++)
		{
			data.push_back(Point<DIM, POS, POS>(_pts[i].pos() + shift, 0));
		}
	}
	
	evalFunction(data);

	m_max = 0.0;
	m_mean = 0.0;
	if(iSz != 0)
	{
		for(int i=0; i<iSz; i++)
		{
			Vector<DIM, POS> motion;
			
			for(int d=0; d<DIM; d++)
			{
				POS p = (data[i].val() - data[i+iSz*(d+1)].val()) / m_shift;
				_pts[i].pos()[d] -= p;
				motion[d] = p;
			}
			
			POS norm = motion.norm();
			m_mean += norm;
			if(m_max < norm) m_max = norm;
		}
		m_mean /= iSz;
	}
}
예제 #10
0
QQmlBinding::QQmlBinding(const QString &str, bool isRewritten, QObject *obj,
                         QQmlContextData *ctxt,
                         const QString &url, quint16 lineNumber, quint16 columnNumber)
: QQmlJavaScriptExpression(&QQmlBinding_jsvtable), QQmlAbstractBinding(Binding),
  m_url(url), m_lineNumber(lineNumber), m_columnNumber(columnNumber)
{
    setNotifyOnValueChanged(true);
    QQmlAbstractExpression::setContext(ctxt);
    setScopeObject(obj);

    QString code;
    if (isRewritten) {
        code = str;
    } else {
        QQmlRewrite::RewriteBinding rewriteBinding;
        code = rewriteBinding(str);
    }

    m_expression = str.toUtf8();

    v8function = evalFunction(ctxt, obj, code, url, m_lineNumber);
}
예제 #11
0
static int parseStmt(ej_t *ep, int state, int flags)
{
	ejfunc_t	func;
	ejfunc_t	*saveFunc;
	ejinput_t	condScript, endScript, bodyScript, incrScript;
	char_t		*value,	*identifier;
	int			done, expectSemi, thenFlags, elseFlags, tid, cond, forFlags;
	int			ejVarType;

	a_assert(ep);

/*
 *	Set these to NULL, else we try to free them if an error occurs.
 */
	endScript.putBackToken = NULL;
	bodyScript.putBackToken = NULL;
	incrScript.putBackToken = NULL;
	condScript.putBackToken = NULL;

	expectSemi = 0;
	saveFunc = NULL;

	for (done = 0; !done; ) {
		tid = ejLexGetToken(ep, state);

		switch (tid) {
		default:
			ejLexPutbackToken(ep, TOK_EXPR, ep->token);
			done++;
			break;

		case TOK_ERR:
			state = STATE_ERR;
			done++;
			break;

		case TOK_EOF:
			state = STATE_EOF;
			done++;
			break;

		case TOK_NEWLINE:
			break;

		case TOK_SEMI:
/*
 *			This case is when we discover no statement and just a lone ';'
 */
			if (state != STATE_STMT) {
				ejLexPutbackToken(ep, tid, ep->token);
			}
			done++;
			break;

		case TOK_ID:
/*
 *			This could either be a reference to a variable or an assignment
 */
			identifier = NULL;
			setString(B_L, &identifier, ep->token);
/*
 *			Peek ahead to see if this is an assignment
 */
			tid = ejLexGetToken(ep, state);
			if (tid == TOK_ASSIGNMENT) {
				if (parse(ep, STATE_RELEXP, flags) != STATE_RELEXP_DONE) {
					clearString(&identifier);
					goto error;
				}
				if (flags & FLAGS_EXE) {
					if ( state == STATE_DEC ) {
						ejSetLocalVar(ep->eid, identifier, ep->result);
					} else {
						ejVarType = ejGetVar(ep->eid, identifier, &value);
						if (ejVarType > 0) {
							ejSetLocalVar(ep->eid, identifier, ep->result);
						} else {
							ejSetGlobalVar(ep->eid, identifier, ep->result);
						}
					}
				}

			} else if (tid == TOK_INC_DEC ) {
				value = NULL;
				if (flags & FLAGS_EXE) {
					ejVarType = ejGetVar(ep->eid, identifier, &value);
					if (ejVarType < 0) {
						ejError(ep, T("Undefined variable %s\n"), identifier);
						goto error;
					}
					setString(B_L, &ep->result, value);
					if (evalExpr(ep, value, (int) *ep->token, T("1")) < 0) {
						state = STATE_ERR;
						break;
					}

					if (ejVarType > 0) {
						ejSetLocalVar(ep->eid, identifier, ep->result);
					} else {
						ejSetGlobalVar(ep->eid, identifier, ep->result);
					}
				}

			} else {
/*
 *				If we are processing a declaration, allow undefined vars
 */
				value = NULL;
				if (state == STATE_DEC) {
					if (ejGetVar(ep->eid, identifier, &value) > 0) {
						ejError(ep, T("Variable already declared"),
							identifier);
						clearString(&identifier);
						goto error;
					}
					ejSetLocalVar(ep->eid, identifier, NULL);
				} else {
					if ( flags & FLAGS_EXE ) {
						if (ejGetVar(ep->eid, identifier, &value) < 0) {
							ejError(ep, T("Undefined variable %s\n"),
								identifier);
							clearString(&identifier);
							goto error;
						}
					}
				}
				setString(B_L, &ep->result, value);
				ejLexPutbackToken(ep, tid, ep->token);
			}
			clearString(&identifier);

			if (state == STATE_STMT) {
				expectSemi++;
			}
			done++;
			break;

		case TOK_LITERAL:
/*
 *			Set the result to the literal (number or string constant)
 */
			setString(B_L, &ep->result, ep->token);
			if (state == STATE_STMT) {
				expectSemi++;
			}
			done++;
			break;

		case TOK_FUNCTION:
/*
 *			We must save any current ep->func value for the current stack frame
 */
			if (ep->func) {
				saveFunc = ep->func;
			}
			memset(&func, 0, sizeof(ejfunc_t));
			setString(B_L, &func.fname, ep->token);
			ep->func = &func;

			setString(B_L, &ep->result, T(""));
			if (ejLexGetToken(ep, state) != TOK_LPAREN) {
				freeFunc(&func);
				goto error;
			}

			if (parse(ep, STATE_ARG_LIST, flags) != STATE_ARG_LIST_DONE) {
				freeFunc(&func);
				ep->func = saveFunc;
				goto error;
			}
/*
 *			Evaluate the function if required
 */
			if (flags & FLAGS_EXE && evalFunction(ep) < 0) {
				freeFunc(&func);
				ep->func = saveFunc;
				goto error;
			}

			freeFunc(&func);
			ep->func = saveFunc;

			if (ejLexGetToken(ep, state) != TOK_RPAREN) {
				goto error;
			}
			if (state == STATE_STMT) {
				expectSemi++;
			}
			done++;
			break;

		case TOK_IF:
			if (state != STATE_STMT) {
				goto error;
			}
			if (ejLexGetToken(ep, state) != TOK_LPAREN) {
				goto error;
			}
/*
 *			Evaluate the entire condition list "(condition)"
 */
			if (parse(ep, STATE_COND, flags) != STATE_COND_DONE) {
				goto error;
			}
			if (ejLexGetToken(ep, state) != TOK_RPAREN) {
				goto error;
			}
/*
 *			This is the "then" case. We need to always parse both cases and
 *			execute only the relevant case.
 */
			if (*ep->result == '1') {
				thenFlags = flags;
				elseFlags = flags & ~FLAGS_EXE;
			} else {
				thenFlags = flags & ~FLAGS_EXE;
				elseFlags = flags;
			}
/*
 *			Process the "then" case.  Allow for RETURN statement
 */
			switch (parse(ep, STATE_STMT, thenFlags)) {
			case STATE_RET:
				return STATE_RET;
			case STATE_STMT_DONE:
				break;
			default:
				goto error;
			}
/*
 *			check to see if there is an "else" case
 */
			ejRemoveNewlines(ep, state);
			tid = ejLexGetToken(ep, state);
			if (tid != TOK_ELSE) {
				ejLexPutbackToken(ep, tid, ep->token);
				done++;
				break;
			}
/*
 *			Process the "else" case.  Allow for return.
 */
			switch (parse(ep, STATE_STMT, elseFlags)) {
			case STATE_RET:
				return STATE_RET;
			case STATE_STMT_DONE:
				break;
			default:
				goto error;
			}
			done++;
			break;

		case TOK_FOR:
/*
 *			Format for the expression is:
 *
 *				for (initial; condition; incr) {
 *					body;
 *				}
 */
			if (state != STATE_STMT) {
				goto error;
			}
			if (ejLexGetToken(ep, state) != TOK_LPAREN) {
				goto error;
			}

/*
 *			Evaluate the for loop initialization statement
 */
			if (parse(ep, STATE_EXPR, flags) != STATE_EXPR_DONE) {
				goto error;
			}
			if (ejLexGetToken(ep, state) != TOK_SEMI) {
				goto error;
			}

/*
 *			The first time through, we save the current input context just
 *			to each step: prior to the conditional, the loop increment and the
 *			loop body.
 */
			ejLexSaveInputState(ep, &condScript);
			if (parse(ep, STATE_COND, flags) != STATE_COND_DONE) {
				goto error;
			}
			cond = (*ep->result != '0');

			if (ejLexGetToken(ep, state) != TOK_SEMI) {
				goto error;
			}

/*
 *			Don't execute the loop increment statement or the body first time
 */
			forFlags = flags & ~FLAGS_EXE;
			ejLexSaveInputState(ep, &incrScript);
			if (parse(ep, STATE_EXPR, forFlags) != STATE_EXPR_DONE) {
				goto error;
			}
			if (ejLexGetToken(ep, state) != TOK_RPAREN) {
				goto error;
			}

/*
 *			Parse the body and remember the end of the body script
 */
			ejLexSaveInputState(ep, &bodyScript);
			if (parse(ep, STATE_STMT, forFlags) != STATE_STMT_DONE) {
				goto error;
			}
			ejLexSaveInputState(ep, &endScript);

/*
 *			Now actually do the for loop. Note loop has been rotated
 */
			while (cond && (flags & FLAGS_EXE) ) {
/*
 *				Evaluate the body
 */
				ejLexRestoreInputState(ep, &bodyScript);

				switch (parse(ep, STATE_STMT, flags)) {
				case STATE_RET:
					return STATE_RET;
				case STATE_STMT_DONE:
					break;
				default:
					goto error;
				}
/*
 *				Evaluate the increment script
 */
				ejLexRestoreInputState(ep, &incrScript);
				if (parse(ep, STATE_EXPR, flags) != STATE_EXPR_DONE) {
					goto error;
				}
/*
 *				Evaluate the condition
 */
				ejLexRestoreInputState(ep, &condScript);
				if (parse(ep, STATE_COND, flags) != STATE_COND_DONE) {
					goto error;
				}
				cond = (*ep->result != '0');
			}
			ejLexRestoreInputState(ep, &endScript);
			done++;
			break;

		case TOK_VAR:
			if (parse(ep, STATE_DEC_LIST, flags) != STATE_DEC_LIST_DONE) {
				goto error;
			}
			done++;
			break;

		case TOK_COMMA:
			ejLexPutbackToken(ep, TOK_EXPR, ep->token);
			done++;
			break;

		case TOK_LPAREN:
			if (state == STATE_EXPR) {
				if (parse(ep, STATE_RELEXP, flags) != STATE_RELEXP_DONE) {
					goto error;
				}
				if (ejLexGetToken(ep, state) != TOK_RPAREN) {
					goto error;
				}
				return STATE_EXPR_DONE;
			}
			done++;
			break;

		case TOK_RPAREN:
			ejLexPutbackToken(ep, tid, ep->token);
			return STATE_EXPR_DONE;

		case TOK_LBRACE:
/*
 *			This handles any code in braces except "if () {} else {}"
 */
			if (state != STATE_STMT) {
				goto error;
			}

/*
 *			Parse will return STATE_STMT_BLOCK_DONE when the RBRACE is seen
 */
			do {
				state = parse(ep, STATE_STMT, flags);
			} while (state == STATE_STMT_DONE);

/*
 *			Allow return statement.
 */
			if (state == STATE_RET) {
				return state;
			}

			if (ejLexGetToken(ep, state) != TOK_RBRACE) {
				goto error;
			}
			return STATE_STMT_DONE;

		case TOK_RBRACE:
			if (state == STATE_STMT) {
				ejLexPutbackToken(ep, tid, ep->token);
				return STATE_STMT_BLOCK_DONE;
			}
			goto error;

		case TOK_RETURN:
			if (parse(ep, STATE_RELEXP, flags) != STATE_RELEXP_DONE) {
				goto error;
			}
			if (flags & FLAGS_EXE) {
				while ( ejLexGetToken(ep, state) != TOK_EOF );
				done++;
				return STATE_RET;
			}
			break;
		}
	}

	if (expectSemi) {
		tid = ejLexGetToken(ep, state);
		if (tid != TOK_SEMI && tid != TOK_NEWLINE) {
			goto error;
		}

/*
 *		Skip newline after semi-colon
 */
		ejRemoveNewlines(ep, state);
	}

/*
 *	Free resources and return the correct status
 */
doneParse:
	if (tid == TOK_FOR) {
		ejLexFreeInputState(ep, &condScript);
		ejLexFreeInputState(ep, &incrScript);
		ejLexFreeInputState(ep, &endScript);
		ejLexFreeInputState(ep, &bodyScript);
	}

	if (state == STATE_STMT) {
		return STATE_STMT_DONE;
	} else if (state == STATE_DEC) {
		return STATE_DEC_DONE;
	} else if (state == STATE_EXPR) {
		return STATE_EXPR_DONE;
	} else if (state == STATE_EOF) {
		return state;
	} else {
		return STATE_ERR;
	}

/*
 *	Common error exit
 */
error:
	state = STATE_ERR;
	goto doneParse;
}
// Parts of this function mirror code in QQmlExpressionPrivate::value() and v8value().
// Changes made here may need to be made there and vice versa.
void QQmlBoundSignalExpression::evaluate(void **a)
{
    Q_ASSERT (context() && engine());

    if (invalidParameterName())
        return;

    QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine());
    QV4::Scope scope(ep->v4engine());

    ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
    {
        if (!expressionFunctionValid()) {
            Q_ASSERT(!m_extra.isNull());
            QString expression;

            // Add some leading whitespace to account for the binding's column offset.
            // It's 2 off because a, we start counting at 1 and b, the '(' below is not counted.
            expression.fill(QChar(QChar::Space), qMax(m_extra->m_sourceLocation.column, (quint16)2) - 2);
            expression += QStringLiteral("(function ");
            expression += m_extra->m_handlerName;
            expression += QLatin1Char('(');

            if (m_extra->m_parameterString.isEmpty()) {
                QString error;
                //TODO: look at using the property cache here (as in the compiler)
                //      for further optimization
                QMetaMethod signal = QMetaObjectPrivate::signal(m_target->metaObject(), m_index);
                expression += QQmlPropertyCache::signalParameterStringForJS(engine(), signal.parameterNames(), &error);

                if (!error.isEmpty()) {
                    qmlInfo(scopeObject()) << error;
                    setInvalidParameterName(true);
                    ep->dereferenceScarceResources();
                    return;
                }
            } else
                expression += m_extra->m_parameterString;

            expression += QStringLiteral(") { ");
            expression += m_extra->m_expression;
            expression += QStringLiteral(" })");

            m_extra->m_expression.clear();
            m_extra->m_handlerName.clear();
            m_extra->m_parameterString.clear();

            m_v8function = evalFunction(context(), scopeObject(), expression,
                                        m_extra->m_sourceLocation.sourceFile, m_extra->m_sourceLocation.line, &m_extra->m_v8qmlscope);

            if (m_v8function.isNullOrUndefined()) {
                ep->dereferenceScarceResources();
                return; // could not evaluate function.  Not valid.
            }

            setExpressionFunctionValid(true);
        }

        QV8Engine *engine = ep->v8engine();
        QVarLengthArray<int, 9> dummy;
        //TODO: lookup via signal index rather than method index as an optimization
        int methodIndex = QMetaObjectPrivate::signal(m_target->metaObject(), m_index).methodIndex();
        int *argsTypes = QQmlPropertyCache::methodParameterTypes(m_target, methodIndex, dummy, 0);
        int argCount = argsTypes ? *argsTypes : 0;

        QV4::ScopedValue f(scope, m_v8function.value());
        QV4::ScopedCallData callData(scope, argCount);
        for (int ii = 0; ii < argCount; ++ii) {
            int type = argsTypes[ii + 1];
            //### ideally we would use metaTypeToJS, however it currently gives different results
            //    for several cases (such as QVariant type and QObject-derived types)
            //args[ii] = engine->metaTypeToJS(type, a[ii + 1]);
            if (type == QMetaType::QVariant) {
                callData->args[ii] = engine->fromVariant(*((QVariant *)a[ii + 1]));
            } else if (type == QMetaType::Int) {
                //### optimization. Can go away if we switch to metaTypeToJS, or be expanded otherwise
                callData->args[ii] = QV4::Primitive::fromInt32(*reinterpret_cast<const int*>(a[ii + 1]));
            } else if (type == qMetaTypeId<QQmlV4Handle>()) {
                callData->args[ii] = *reinterpret_cast<QQmlV4Handle *>(a[ii + 1]);
            } else if (ep->isQObject(type)) {
                if (!*reinterpret_cast<void* const *>(a[ii + 1]))
                    callData->args[ii] = QV4::Primitive::nullValue();
                else
                    callData->args[ii] = QV4::QObjectWrapper::wrap(ep->v4engine(), *reinterpret_cast<QObject* const *>(a[ii + 1]));
            } else {
                callData->args[ii] = engine->fromVariant(QVariant(type, a[ii + 1]));
            }
        }

        QQmlJavaScriptExpression::evaluate(context(), f, callData, 0);
    }
    ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
}
예제 #13
0
bool
MidpointRule::integrate(real_type toTEnd)
{
    real_type rtol = 1e-12;
    real_type atol = 1e-10;

    Vector dy(mState.size());
    while (!reached(toTEnd)) {
        real_type t = getTime();
        real_type h = maxStepsize(toTEnd);

        // Often used values.
        real_type h2 = 0.5*h;

        // We assume that the problem is nonstiff.
        // This is a sensible assumption since this symmetric integrator is not
        // stiffly accurate anyway.
        // If it is not stiff, we solve the nonlinear equation
        // with fixpoint iteration.
        // The GNI papers suggest this anyway.

        // An initial guess for the fixpoint iteration.
        // Note that the polynomial coefficients p1 and p2 are set to zero at the
        // first step past a reset.
        if (mCollocationPolynomialValid) {
            dy = old_dy;
        } else {
            dy.clear();
        }

        // Solve the implicit equation
        bool converging;
        bool converged = false;
        unsigned maxit = 10;
        real_type prev_err = Limits<real_type>::max();
        do {
            // Compute new approximations to the state at the inner stages
            Vector y = mState + 0.5*dy;

            // Compute new approximations to the state derivatives
            evalFunction(t+h2, y, mDeriv);

            // Check if the increment is small enough ...
            real_type err = scaledDiff(y, mState + h2*mDeriv, atol, rtol);
            converged = err < 1;

            // Check if we do converge in any way.
            converging = err < prev_err;
            prev_err = err;

            // Use the new approximation
            dy = h*mDeriv;

            ++mStats.numIter;
        } while (!converged && 0 < --maxit && converging);

        if (converged) {
            // Update the solution
            mState += dy;

            // Compute the collocation polynomial.
            // Is used for a predictor of the next fixpoint iterate start guess.
            old_dy = dy;
            mCollocationPolynomialValid = true;

            ++mStats.numSteps;
        } else {
            // If we cannot solve the nonlinear equation, do an explicit euler step
            mCollocationPolynomialValid = false;

            Log(TimeStep, Warning) << "MidpointRule did not converge" << std::endl;

            evalFunction(t, mState, mDeriv);
            mState += h*mDeriv;

            ++mStats.numFailed;
            ++mStats.numSteps;
        }

        // Increment the simulation time ...
        mTime += h;
    }
    return true;
}
예제 #14
0
/** Create event workspace
 */
EventWorkspace_sptr CreateSampleWorkspace::createEventWorkspace(
    int numPixels, int numBins, int numEvents, double x0, double binDelta,
    int start_at_pixelID, Geometry::Instrument_sptr inst,
    const std::string &functionString, bool isRandom) {
  DateAndTime run_start("2010-01-01T00:00:00");

  // add one to the number of bins as this is histogram
  int numXBins = numBins + 1;

  EventWorkspace_sptr retVal(new EventWorkspace);
  retVal->initialize(numPixels, 1, 1);

  retVal->setInstrument(inst);

  // Create the x-axis for histogramming.
  MantidVecPtr x1;
  MantidVec &xRef = x1.access();
  xRef.resize(numXBins);
  for (int i = 0; i < numXBins; ++i) {
    xRef[i] = x0 + i * binDelta;
  }

  // Set all the histograms at once.
  retVal->setAllX(x1);

  std::vector<double> xValues(xRef.begin(), xRef.end() - 1);
  std::vector<double> yValues =
      evalFunction(functionString, xValues, isRandom ? 1 : 0);

  // we need to normalise the results and then multiply by the number of events
  // to find the events per bin
  double sum_of_elems = std::accumulate(yValues.begin(), yValues.end(), 0.0);
  double event_distrib_factor = numEvents / sum_of_elems;
  std::transform(yValues.begin(), yValues.end(), yValues.begin(),
                 std::bind1st(std::multiplies<double>(), event_distrib_factor));
  // the array should now contain the number of events required per bin

  // Make fake events
  size_t workspaceIndex = 0;

  const double hourInSeconds = 60 * 60;
  for (int wi = 0; wi < numPixels; wi++) {
    EventList &el = retVal->getEventList(workspaceIndex);
    el.setSpectrumNo(wi + 1);
    el.setDetectorID(wi + start_at_pixelID);

    // for each bin

    for (int i = 0; i < numBins; ++i) {
      // create randomised events within the bin to match the number required -
      // calculated in yValues earlier
      int eventsInBin = static_cast<int>(yValues[i]);
      for (int q = 0; q < eventsInBin; q++) {
        DateAndTime pulseTime =
            run_start + (m_randGen->nextValue() * hourInSeconds);
        el += TofEvent((i + m_randGen->nextValue()) * binDelta, pulseTime);
      }
    }
    workspaceIndex++;
  }

  return retVal;
}
예제 #15
0
// Parts of this function mirror code in QQmlExpressionPrivate::value() and v8value().
// Changes made here may need to be made there and vice versa.
void QQmlBoundSignalExpression::evaluate(void **a)
{
    Q_ASSERT (context() && engine());

    if (m_invalidParameterName)
        return;

    QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine());

    ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
    {
        v8::HandleScope handle_scope;
        v8::Context::Scope context_scope(ep->v8engine()->context());
        if (!m_expressionFunctionValid) {

            //TODO: look at using the property cache here (as in the compiler)
            //      for further optimization
            QMetaMethod signal = QMetaObjectPrivate::signal(m_target->metaObject(), m_index);
            QQmlRewrite::RewriteSignalHandler rewriter;

            QString expression;
            bool ok = true;

            if (m_expressionFunctionRewritten) {
                expression = QString::fromUtf8(m_expressionUtf8);

                //if we need parameters, and the rewrite doesn't include them,
                //create and insert the parameter string now
                if (m_parameterCountForJS == -1 && signal.parameterCount()) {
                    const QString &parameters = rewriter.createParameterString(signal.parameterNames(),
                                                ep->v8engine()->illegalNames());
                    int index = expression.indexOf(QLatin1Char('('), 1);
                    Q_ASSERT(index > -1);
                    expression.insert(index + 1, parameters);

                    setParameterCountForJS(rewriter.parameterCountForJS());
                }

                m_expressionUtf8.clear();
            } else {
                //expression is still in its original form, so perform a full rewrite
                expression = rewriter(m_expression, QString()/*no name hint available*/, &ok,
                                      signal.parameterNames(),
                                      ep->v8engine()->illegalNames());
                setParameterCountForJS(rewriter.parameterCountForJS());
                m_expression.clear();
            }

            if (rewriter.hasParameterError()) {
                qmlInfo(scopeObject()) << rewriter.parameterError();
                m_invalidParameterName = true;
                ep->dereferenceScarceResources();
                return;
            }

            if (ok) {
                m_v8function = evalFunction(context(), scopeObject(), expression,
                                            m_fileName, m_line, &m_v8qmlscope);
            }

            if (m_v8function.IsEmpty() || m_v8function->IsNull()) {
                ep->dereferenceScarceResources();
                return; // could not evaluate function.  Not valid.
            }

            setUseSharedContext(false);
            m_expressionFunctionValid = true;
        }

        if (!hasParameterInfo()) {
            QQmlJavaScriptExpression::evaluate(context(), m_v8function, 0);
        } else {
            QV8Engine *engine = ep->v8engine();
            QVarLengthArray<int, 9> dummy;
            //TODO: lookup via signal index rather than method index as an optimization
            int methodIndex = QMetaObjectPrivate::signal(m_target->metaObject(), m_index).methodIndex();
            int *argsTypes = QQmlPropertyCache::methodParameterTypes(m_target, methodIndex, dummy, 0);
            int argCount = argsTypes ? m_parameterCountForJS : 0;

            QVarLengthArray<v8::Handle<v8::Value>, 9> args(argCount);

            for (int ii = 0; ii < argCount; ++ii) {
                int type = argsTypes[ii + 1];
                //### ideally we would use metaTypeToJS, however it currently gives different results
                //    for several cases (such as QVariant type and QObject-derived types)
                //args[ii] = engine->metaTypeToJS(type, a[ii + 1]);
                if (type == QMetaType::QVariant) {
                    args[ii] = engine->fromVariant(*((QVariant *)a[ii + 1]));
                } else if (type == QMetaType::Int) {
                    //### optimization. Can go away if we switch to metaTypeToJS, or be expanded otherwise
                    args[ii] = v8::Integer::New(*reinterpret_cast<const int*>(a[ii + 1]));
                } else if (type == qMetaTypeId<QQmlV8Handle>()) {
                    args[ii] = reinterpret_cast<QQmlV8Handle *>(a[ii + 1])->toHandle();
                } else if (ep->isQObject(type)) {
                    if (!*reinterpret_cast<void* const *>(a[ii + 1]))
                        args[ii] = v8::Null();
                    else
                        args[ii] = engine->newQObject(*reinterpret_cast<QObject* const *>(a[ii + 1]));
                } else {
                    args[ii] = engine->fromVariant(QVariant(type, a[ii + 1]));
                }
            }

            QQmlJavaScriptExpression::evaluate(context(), m_v8function, argCount, args.data(), 0);
        }
    }
    ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
}