Exemplo n.º 1
1
bool RKObjectListViewSettings::filterAcceptsRow (int source_row, const QModelIndex& source_parent) const {
//	RK_TRACE (APP);

	// So I tried to use a KRecursiveFilterProxyModel, but
	// a) we don't really want recursion to the full depth. Thus limiting it, here.
	// b) While we don't handle insertions / removals of source indices in the presence of a filter, correctly, with KRecursiveFilterProxyModel
	//    I got crashes on this (arguably with the depth-limit in place)
	if (acceptRow (source_row, source_parent)) return true;

	RObject *parent = static_cast<RObject*> (source_parent.internalPointer ());
	if (!parent) {
		RK_ASSERT (parent);    // should have been accepted, above
		return true;
	}
	RObject *object = parent->findChildByObjectModelIndex (source_row);
	if (!object) {
		RK_ASSERT (object);    // should have been accepted, above
		RK_DEBUG (APP, DL_ERROR, "row %d of %d in %s", source_row, sourceModel ()->rowCount (source_parent), qPrintable (parent->getShortName ()));
		return false;
	}

	if (object->isType (RObject::ToplevelEnv | RObject::Workspace) || ((depth_limit > 0) && parent->isType (RObject::ToplevelEnv | RObject::Workspace))) {
		QModelIndex source_index = sourceModel ()->index (source_row, 0, source_parent);
		for (int row = 0, rows = sourceModel()->rowCount (source_index); row < rows; ++row) {
			if (filterAcceptsRow (row, source_index)) return true;
		}
	}

	return false;
}
Exemplo n.º 2
0
RObject *RObjectList::findObject (const QString &name, bool is_canonified) {
	RK_TRACE (OBJECTS);

	QString canonified = name;
	if (!is_canonified) {
		canonified = RObject::canonifyName (name);
	}

	// TODO: there could be objects with "::" in their names!
	if (canonified.contains ("::")) {
		QString env = canonified.section ("::", 0, 0);
		QString remainder = canonified.section ("::", 1);

		RObjectMap::iterator it = childmap.find (env);
		if (it == childmap.end ()) return 0;

		RObject *found = it.data ();
		return (found->findObject (remainder, true));
	}

	// no environment specified, do regular search:
	// TODO: there could be objects with "$" in their names!
	QString current_level = canonified.section (QChar ('$'), 0, 0);
	QString remainder = canonified.section (QChar ('$'), 1);

	for (int i = 0; i < num_toplevel_environments; ++i) {
		RObject *found = toplevel_environments[i]->findChild (current_level);
		if (found) {
			if (remainder.isEmpty ()) return (found);
			return (found->findObject (remainder, true));
		}
	}
	return 0;
}
Exemplo n.º 3
0
void WeakRef::markThru()
{
    WeakRef::check();
    WRList newlive;
    // Step 2-3 of algorithm.  Mark the value and R finalizer if the
    // key is marked.
    {
	unsigned int marks_applied;
	do {
	    GCNode::Marker marker;
	    WRList::iterator lit = s_live->begin();
	    while (lit != s_live->end()) {
		WeakRef* wr = *lit++;
		RObject* key = wr->key();
		if (key->isMarked()) {
		    RObject* value = wr->value();
		    if (value)
			marker(value);
		    FunctionBase* Rfinalizer = wr->m_Rfinalizer;
		    if (Rfinalizer)
			marker(Rfinalizer);
		    wr->transfer(s_live, &newlive);
		}
	    }
	    marks_applied = marker.marksApplied();
	} while (marks_applied > 0);
    }
    // Step 4 of algorithm.  Process references with unmarked keys.
    {
	GCNode::Marker marker;
	WRList::iterator lit = s_live->begin();
	while (lit != s_live->end()) {
	    WeakRef* wr = *lit++;
	    FunctionBase* Rfinalizer = wr->m_Rfinalizer;
	    if (Rfinalizer)
		marker(Rfinalizer);
	    if (Rfinalizer || wr->m_Cfinalizer) {
		marker(wr);
		marker(wr->m_key);
		wr->m_ready_to_finalize = true;
		wr->transfer(s_live, s_f10n_pending);
	    }
	    else {
		wr->tombstone();
		// Expose to reference-counting collection:
		wr->m_self = 0;
	    }
	}
    }
    // Step 5 of algorithm.  Mark all live references with reachable keys.
    {
	GCNode::Marker marker;
	s_live->splice(s_live->end(), newlive);
	for (WRList::iterator lit = s_live->begin();
	     lit != s_live->end(); ++lit) {
	    WeakRef* wr = *lit;
	    marker(wr);
	}
    }
}
Exemplo n.º 4
0
RKEditor *RKWorkplace::editObject (RObject *object) {
	RK_TRACE (APP);

	RObject *iobj = object;
	RKEditor *ed = 0;
	RKEditor *existing_editor = RKGlobals::tracker ()->objectEditor (object);
	if (!existing_editor) {
		if (!iobj->isDataFrame ()) {
			if (iobj->isVariable () && iobj->getContainer ()->isDataFrame ()) {
				iobj = iobj->getContainer ();
			} else {
				return 0;
			}
		}

		unsigned long size = 1;
		foreach (int dim, iobj->getDimensions ()) {
			size *= dim;
		}
		if ((RKSettingsModuleGeneral::warnLargeObjectThreshold () != 0) && (size > RKSettingsModuleGeneral::warnLargeObjectThreshold ())) {
			if (KMessageBox::warningContinueCancel (view (), i18n ("You are about to edit object \"%1\", which is very large (%2 fields). RKWard is not optimized to handle very large objects in the built in data editor. This will use a lot of memory, and - depending on your system - might be very slow. For large objects it is generally recommended to edit using command line means or to split into smaller chunks before editing. On the other hand, if you have enough memory, or the data is simple enough (numeric data is easier to handle, than factor), editing may not be a problem at all. You can configure this warning (or turn it off entirely) under Settings->Configure RKWard->General.\nReally edit object?", iobj->getFullName (), size), i18n ("About to edit very large object")) != KMessageBox::Continue) {
				return 0;
			}
		}

		ed = new RKEditorDataFrame (static_cast<RContainerObject*> (iobj), 0);
		addWindow (ed);
	} else {
Exemplo n.º 5
0
bool Promise::isMissingSymbol() const
{
    bool ans = false;
    /* This is wrong but I'm not clear why - arr
    if (m_value == Symbol::missingArgument())
     	return true;
    */
    if (m_value == Symbol::unboundValue() && m_valgen) {
	RObject* prexpr = PREXPR(const_cast<Promise*>(this));
	if (prexpr->sexptype() == SYMSXP) {
	    // According to Luke Tierney's comment to R_isMissing() in CR,
	    // if a cycle is found then a missing argument has been
	    // encountered, so the return value is true.
	    if (m_under_evaluation)
		return true;
	    try {
		const Symbol* promsym
		    = static_cast<const Symbol*>(prexpr);
		m_under_evaluation = true;
		ans = isMissingArgument(promsym, environment()->frame());
	    }
	    catch (...) {
		m_under_evaluation = false;
		throw;
	    }
	    m_under_evaluation = false;
	}
    }
    return ans;
}
Exemplo n.º 6
0
std::pair<FunctionBase*, bool>
S3Launcher::findMethod(const Symbol* symbol, Environment* call_env,
		       Environment* table_env)
{
    FunctionBase* fun = findFunction(symbol, call_env);
    if (fun)
	return make_pair(fun, true);
    if (!table_env)
	return pair<FunctionBase*, bool>(nullptr, false);
    Environment* table = nullptr;
    // Look for S3 methods table:
    {
	Frame::Binding* tblbdg
	    = table_env->frame()->binding(S3MethodsTableSymbol);
	if (tblbdg) {
	    RObject* tblbdgval = tblbdg->forcedValue();
	    if (tblbdgval && tblbdgval->sexptype() == ENVSXP)
		table = static_cast<Environment*>(tblbdgval);
	}
    }
    // Look up method in table:
    if (table) {
	Frame::Binding* symbdg = table->frame()->binding(symbol);
	if (symbdg) {
	    RObject* symbdgval = symbdg->forcedValue();
	    // Assume that the result is a FunctionBase:
	    return make_pair(static_cast<FunctionBase*>(symbdgval), false);
	}
    }
    return pair<FunctionBase*, bool>(nullptr, false);
}
void RKObjectListModel::fetchMore (const QModelIndex &parent) {
	RK_TRACE (OBJECTS);

	RObject *object = static_cast<RObject*> (parent.internalPointer ());
	RK_ASSERT (object && object->isType (RObject::Incomplete));
	object->fetchMoreIfNeeded ();
}
Exemplo n.º 8
0
pair<bool, RObject*> ArgList::firstArg(Environment* env)
{
    const PairList* elt = list();
    if (!elt)
	return pair<bool, RObject*>(false, 0);
    if (m_status == EVALUATED)
	return make_pair(true, elt->car());
    while (elt) {
	RObject* arg1 = elt->car();
	if (!arg1)
	    return pair<bool, RObject*>(true, 0);
	if (arg1 != DotsSymbol) {
	    m_first_arg = Evaluator::evaluate(arg1, env);
	    m_first_arg_env = env;
	    return make_pair(true, m_first_arg.get());
	}
	// If we get here it must be DotSymbol.
	Frame::Binding* bdg = env->findBinding(DotsSymbol);
	if (bdg && bdg->origin() != Frame::Binding::MISSING) {
	    RObject* val = bdg->forcedValue();
	    if (val) {
		if (val->sexptype() != DOTSXP)
		    Rf_error(_("'...' used in an incorrect context"));
		RObject* dots1 = static_cast<DottedArgs*>(val)->car();
		if (dots1->sexptype() != PROMSXP)
		    Rf_error(_("value in '...' is not a promise"));
		m_first_arg = Evaluator::evaluate(dots1, env);
		m_first_arg_env = env;
		return make_pair(true, m_first_arg.get());
	    }
	}
	elt = elt->tail();  // elt was unbound or missing DotsSymbol
    }
    return pair<bool, RObject*>(false, 0);
}
Exemplo n.º 9
0
RcppExport SEXP getDeformationField (SEXP _transform, SEXP _jacobian)
{
BEGIN_RCPP
    RObject transform(_transform);
    RObject result;
    NiftiImage targetImage(SEXP(transform.attr("target")));
    DeformationField field;
    
    if (transform.inherits("affine"))
    {
        AffineMatrix affine = AffineMatrix(SEXP(transform));
        field = DeformationField(targetImage, affine);
    }
    else
    {
        NiftiImage transformationImage(_transform);
        field = DeformationField(targetImage, transformationImage);
    }
    
    result = field.getFieldImage().toPointer("Deformation field");
    result.attr("source") = transform.attr("source");
    result.attr("target") = transform.attr("target");
    
    if (as<bool>(_jacobian))
        result.attr("jacobian") = field.getJacobian().toPointer("Jacobian of deformation field");
    
    return result;
END_RCPP
}
Exemplo n.º 10
0
void Subscripting::setVectorAttributes(VectorBase* subset,
				       const VectorBase* source,
				       const Indices& indices)
{
    // Names:
    {
	const StringVector* sourcenames = source->names();
	if (!sourcenames) {
	    // Use row names if this is a one-dimensional array:
	    const ListVector* dimnames = source->dimensionNames();
	    if (dimnames && dimnames->size() == 1)
		sourcenames = static_cast<const StringVector*>((*dimnames)[0].get());
	}
	if (sourcenames)
	    subset->setNames(vectorSubset(sourcenames, indices));
    }
    // R_SrcrefSymbol:
    {
	RObject* attrib = source->getAttribute(SrcrefSymbol);
	if (attrib && attrib->sexptype() == VECSXP) {
	    const ListVector* srcrefs = static_cast<const ListVector*>(attrib);
	    subset->setAttribute(SrcrefSymbol, vectorSubset(srcrefs, indices));
	}
    }
}
Exemplo n.º 11
0
// Extract the label attr from an R object
// Only works for a character label (will crash in case of an integer value)
std::string get_label(RObject x){
    std::string label = "<EMPTY>";
    if (x.hasAttribute("label")) {
        label = as<std::string>(x.attr( "label" )) ;
    }
    return label; // either TRUE or FALSE. But often, if it exists - it is TRUE.
}
Exemplo n.º 12
0
RObject *RObjectList::findObjects (const QStringList &path, RObjectSearchMap *matches, const QString &op) {
	RK_TRACE (OBJECTS);
	RK_ASSERT (op == "$");

	if (path.value (1) == "::") {
		RObject *environment = findPackage (path[0]);
		if (!environment) return 0;
		
		return environment->findObjects (path.mid (2), matches, "$");
	} else if (path.value (1) == ":::") {
		RObject *environment = findPackage (path[0]);
		if (environment) environment = static_cast<REnvironmentObject*> (environment)->namespaceEnvironment ();
		if (!environment) environment = orphan_namespaces->findOrphanNamespace (path[0]);
		if (!environment) return 0;

		return environment->findObjects (path.mid (2), matches, "$");
	} else if (path.value (0) == ".GlobalEnv") {
		if (path.length () > 1) return getGlobalEnv ()->findObjects (path.mid (2), matches, "$");
		else if (matches) matches->insert (path.value (0), getGlobalEnv ());	// no return, here: At least one more match will be found in base
		else return getGlobalEnv ();
	}

	// no namespace given. Search all environments for matches
	RObject *found = getGlobalEnv ()->findObjects (path, matches, "$");
	if (found && !matches) return found;
	for (int i = 0; i < childmap.size (); ++i) {
		found = childmap[i]->findObjects (path, matches, "$");
		if (found && !matches) return found;
	}
	return 0;
}
QModelIndex RKObjectListModel::parent (const QModelIndex& index) const {
	RK_TRACE (OBJECTS);

	if (!index.isValid ()) return QModelIndex ();
	RObject* child = static_cast<RObject*> (index.internalPointer ());
	RK_ASSERT (child);
	return (indexFor (child->parentObject ()));
}
Exemplo n.º 14
0
		RleIter(RObject& rle):
			rlens(as<IntegerVector>(rle.slot("lengths"))),
			values(as<IntegerVector>(rle.slot("values"))),
			names(as<CharacterVector>(values.attr("levels"))),
			run(0), rpos(-1)
		{
			next();
		}
void
StdDispatch_Test::nameArgs()
{
  const char* cn = "acdk/tools/aunit/DmiTestClass";
  RObject o = (RObject)StdDispatch::New("acdk/tools/aunit/DmiTestClass");

  
  
  int iarg = 42;
  RString sarg = new String("sarg");
  RStringBuffer sbarg = new StringBuffer("sbarg");

  {
    ScriptVarArray args;
    args.push_back(ScriptVar(iarg));
    args.push_back(ScriptVar(&sarg));
    args.push_back(ScriptVar(&sbarg));
    ScriptVar erg = o->invokeMethod( "namedArgsMethod"
                                    , args
                                    , ::acdk::lang::dmi::AcdkDmiClient::getDmiClient()
                                    , Nil
                                    );
    testAssert(erg.getBoolVar() == true);
  }
  {
    StringArray namedArgs(2);
    namedArgs[0] = new String("sarg");
    namedArgs[1] = new String("sbarg");
    ScriptVarArray args;
    args.push_back(ScriptVar(iarg));
    args.push_back(ScriptVar(&sarg));
    args.push_back(ScriptVar(&sbarg));
    ScriptVar erg = o->invokeMethod( "namedArgsMethod"
                                    , args
                                    , ::acdk::lang::dmi::AcdkDmiClient::getDmiClient()
                                    , &namedArgs
                                    );
    testAssert(erg.getBoolVar() == true);
  }

  // order of call is different
  {
    StringArray namedArgs(2);
    namedArgs[0] = new String("sbarg");
    namedArgs[1] = new String("sarg");
    ScriptVarArray args;
    args.push_back(ScriptVar(iarg));
    args.push_back(ScriptVar(&sbarg));
    args.push_back(ScriptVar(&sarg));
    ScriptVar erg = o->invokeMethod( "namedArgsMethod"
                                    , args
                                    , ::acdk::lang::dmi::AcdkDmiClient::getDmiClient()
                                    , &namedArgs
                                    );
    testAssert(erg.getBoolVar() == true);
  }
}
Exemplo n.º 16
0
bool RKObjectListViewSettings::acceptRow (int source_row, const QModelIndex& source_parent) const {
//	RK_TRACE (APP);

	// always show the root item
	if (!source_parent.isValid ()) return true;

	RObject* object = static_cast<RObject*> (source_parent.internalPointer ());
	// always show global env and search path
	if (!object) return true;
	if (!object->findChildByObjectModelIndex (source_row)) {
		return true;
	}
	object = object->findChildByObjectModelIndex (source_row);
	RK_ASSERT (object);

	if (!persistent_settings[ShowObjectsHidden]) {
		if (object->getShortName ().startsWith ('.')) return false;
		if (object == reinterpret_cast<RObject*> (RObjectList::getObjectList ()->orphanNamespacesObject ())) return false;
	}

	if (hide_functions && object->isType (RObject::Function)) return false;
	if (hide_non_functions && !object->isType (RObject::Function)) return false;

	if (filterRegExp ().isEmpty ()) return true;
	if (filter_on_name && object->getShortName ().contains (filterRegExp ())) return true;
	if (filter_on_label && object->getLabel ().contains (filterRegExp ())) return true;
	if (filter_on_class) {
		QStringList cnames = object->classNames ();
		for (int i = cnames.length () - 1; i >= 0; --i) {
			if (cnames[i].contains (filterRegExp ())) return true;
		}
	}

	return false;
}
QVariant RKObjectListModel::data (const QModelIndex& index, int role) const {
	RK_TRACE (OBJECTS);

	int col = index.column ();
	RObject *object = static_cast<RObject*> (index.internalPointer ());

	if ((!object) || (col >= ColumnCount)) {
		RK_ASSERT (false);
		return QVariant ();
	}

	if (role == Qt::DisplayRole) {
		if (col == NameColumn) return object->getShortName ();
		if (col == LabelColumn) return object->getLabel ();
		if (col == TypeColumn) {
			if (object->isVariable ()) return RObject::typeToText (object->getDataType ());
			return QVariant ();
		}
		if ((col == ClassColumn) && (!object->isPseudoObject ())) return object->makeClassString ("; ");
	} else if (role == Qt::FontRole) {
		if (col == NameColumn && object->isPseudoObject ()) {
			QFont font;
			font.setItalic (true);
			return (font);
		}
	} else if (role == Qt::DecorationRole) {
		if (col == NameColumn) return RKStandardIcons::iconForObject (object);
	} else if (role == Qt::ToolTipRole) {
		return object->getObjectDescription ();
	}

	return QVariant ();
}
Exemplo n.º 18
0
void ArgList::wrapInPromises(Environment* env)
{
    if (m_status == PROMISED)
	Rf_error("Internal error:"
		 " ArgList already wrapped in Promises");
    if (m_status == EVALUATED)
	env = 0;
    else if (m_first_arg_env && env != m_first_arg_env)
	Rf_error("Internal error: first arg of ArgList"
		 " previously evaluated in different environment");
    GCStackRoot<const PairList> oldargs(list());
    setList(0);
    PairList* lastout = 0;

    for (const PairList* inp = oldargs; inp; inp = inp->tail()) {
	RObject* rawvalue = inp->car();
	if (rawvalue == DotsSymbol) {
	    Frame::Binding* binding = env->findBinding(DotsSymbol);
	    if (binding) {
		RObject* dval = binding->forcedValue();
		if (!dval || dval->sexptype() == DOTSXP) {
		    ConsCell* dotlist = static_cast<ConsCell*>(dval);
		    while (dotlist) {
			Promise* prom;
			if (!m_first_arg_env)
			    prom = new Promise(dotlist->car(), env);
			else {
			    prom = new Promise(m_first_arg, 0);
			    m_first_arg = 0;
			    m_first_arg_env = 0;
			}
			prom->expose();
			const Symbol* tag = tag2Symbol(dotlist->tag());
			PairList* cell = PairList::cons(prom, 0, tag);
			lastout = append(cell, lastout);
			dotlist = dotlist->tail();
		    }
		} else if (dval != Symbol::missingArgument())
		    Rf_error(_("'...' used in an incorrect context"));
	    }
	} else {
	    const Symbol* tag = tag2Symbol(inp->tag());
	    RObject* value = Symbol::missingArgument();
	    if (m_first_arg_env) {
		value = CXXR_NEW(Promise(m_first_arg, 0));
		m_first_arg = 0;
		m_first_arg_env = 0;
	    } else if (rawvalue != Symbol::missingArgument())
		value = CXXR_NEW(Promise(rawvalue, env));
	    PairList* cell = PairList::cons(value, 0, tag);
	    lastout = append(cell, lastout);
	}
    }
    m_status = PROMISED;
}
Exemplo n.º 19
0
         QScriptValue
        REcmaObject::setUndone
        (QScriptContext* context, QScriptEngine* engine) 
        
        {
            //REcmaHelper::functionStart("REcmaObject::setUndone", context, engine);
            //qDebug() << "ECMAScript WRAPPER: REcmaObject::setUndone";
            //QCoreApplication::processEvents();

            QScriptValue result = engine->undefinedValue();
            
                    // public function: can be called from ECMA wrapper of ECMA shell:
                    RObject* self = 
                        getSelf("setUndone", context);
                  

                //Q_ASSERT(self!=NULL);
                if (self==NULL) {
                    return REcmaHelper::throwError("self is NULL", context);
                }
                
    
    if( context->argumentCount() ==
    1 && (
            context->argument(0).isBool()
        ) /* type: bool */
    
    ){
    // prepare arguments:
    
                    // argument isStandardType
                    bool
                    a0 =
                    (bool)
                    
                    context->argument( 0 ).
                    toBool();
                
    // end of arguments

    // call C++ function:
    // return type 'void'
    
               self->setUndone(a0);
    } else


        
            {
               return REcmaHelper::throwError("Wrong number/types of arguments for RObject.setUndone().",
                   context);
            }
            //REcmaHelper::functionEnd("REcmaObject::setUndone", context, engine);
            return result;
        }
Exemplo n.º 20
0
void RKVarEditDataFrameModel::childAdded (int index, RObject* parent) {
	RK_TRACE (EDITOR);

	if (parent == dataframe) {
		RObject* child = dataframe->findChildByIndex (index);
		RK_ASSERT (child);

		if (child->isVariable ()) addObject (index + var_col_offset, static_cast<RKVariable*> (child));
		else RK_ASSERT (false);
	}
}
Exemplo n.º 21
0
/**
 * Sets the property with the given name to the given value or to 'mixed'
 * if that property exists already with a different value.
 *
 * \param propertyTypeId: Id of the property in the format "Group|Property".
 * \param property: Value and attributes of the property.
 */
void RPropertyEditor::updateProperty(const RPropertyTypeId& propertyTypeId,
        RObject& object, RDocument* document) {

    RPropertyTypeId pid = propertyTypeId;

    QString propertyGroupTitle = propertyTypeId.getPropertyGroupTitle();
    QString propertyTitle = propertyTypeId.getPropertyTitle();

    if (guiUpToDate) {
        combinedProperties.clear();
        guiUpToDate = false;
    }

    // existing group:
    if (combinedProperties.count(propertyGroupTitle) > 0) {
        RPropertyMap& propertyMap = combinedProperties[propertyGroupTitle];

        // existing property in existing group:
        if (propertyMap.count(propertyTitle) > 0) {
            QPair<QVariant, RPropertyAttributes> property =
                object.getProperty(pid, true, true);

            // mixed value:
            if (!RS::compare(propertyMap[propertyTitle], property)) {
                propertyMap[propertyTitle].first = property.first;
                propertyMap[propertyTitle].second.setMixed(true);
            }
        } else {
            // new property in existing group:
            QPair<QVariant, RPropertyAttributes> property =
                object.getProperty(pid, true);
            if (property.second.isInvisible()) {
                return;
            }
            property.second.setPropertyTypeId(propertyTypeId);
            propertyMap[propertyTitle] = property;
            propertyOrder[propertyGroupTitle].push_back(propertyTitle);
        }
    } else {
        // new property in new group:
        QPair<QVariant, RPropertyAttributes> property = object.getProperty(pid,
                document, true);
        if (property.second.isInvisible()) {
            return;
        }
        property.second.setPropertyTypeId(propertyTypeId);
        RPropertyMap propertyMap;
        propertyMap[propertyTitle] = property;
        combinedProperties[propertyGroupTitle] = propertyMap;
        groupOrder.push_back(propertyGroupTitle);
        propertyOrder[propertyGroupTitle].push_back(propertyTitle);
    }
}
Exemplo n.º 22
0
    bool SetValue(RContext &context, const IValue *value) const {
        RVariable *var = context.GetVariable(this->variableName);
        if ( var == NULL )
            return false;

        RObject *obj = var->getCurrent();
        if ( obj == NULL )
            return false;

        RValue val(value->getValueType(), value->toString());
        return obj->SetAttribute(this->attributeName, &val);
    }
Exemplo n.º 23
0
RcppExport SEXP composeTransforms (SEXP _transform1, SEXP _transform2)
{
BEGIN_RCPP
    RObject transform1(_transform1);
    RObject transform2(_transform2);
    RObject result;
    
    if (transform1.inherits("affine") && transform2.inherits("affine"))
    {
        Eigen::MatrixXd matrix = as<Eigen::MatrixXd>(_transform2) * as<Eigen::MatrixXd>(_transform1);
        result = AffineMatrix(matrix);
    }
    else
    {
        DeformationField field1, field2;
        
        NiftiImage targetImage1(SEXP(transform1.attr("target")));
        NiftiImage targetImage2(SEXP(transform2.attr("target")));
        
        if (transform1.inherits("affine"))
        {
            AffineMatrix transformMatrix(_transform1);
            field1 = DeformationField(targetImage1, transformMatrix, true);
        }
        else
        {
            NiftiImage transformImage(_transform1);
            field1 = DeformationField(targetImage1, transformImage, true);
        }
        
        if (transform2.inherits("affine"))
        {
            AffineMatrix transformMatrix(_transform2);
            field2 = DeformationField(targetImage2, transformMatrix, true);
        }
        else
        {
            NiftiImage transformImage(_transform2);
            field2 = DeformationField(targetImage2, transformImage, true);
        }
        
        // Order of composition is possibly not as expected
        field2.compose(field1);
        result = field2.getFieldImage().toPointer("Deformation field");
    }
    
    result.attr("source") = transform1.attr("source");
    result.attr("target") = transform2.attr("target");
    
    return result;
END_RCPP
}
Exemplo n.º 24
0
REnvironmentObject* RObjectList::findPackage (const QString &namespacename) const {
	RK_TRACE (OBJECTS);

	for (int i = childmap.size () - 1; i >= 0; --i) {
		RObject* child = childmap[i];
		if (!child->isType (PackageEnv)) continue;	// Skip Autoloads
		REnvironmentObject* env = static_cast<REnvironmentObject *> (child);
		if (env->packageName () == namespacename) {
			return env;
		}
	}
	return 0;
}
Exemplo n.º 25
0
  int variable(int index, readstat_variable_t *variable, const char *val_labels) {

    names_[index] = readstat_variable_get_name(variable);

    switch(readstat_variable_get_type(variable)) {
    case READSTAT_TYPE_LONG_STRING:
    case READSTAT_TYPE_STRING:
      output_[index] = CharacterVector(nrows_);
      break;
    case READSTAT_TYPE_CHAR:
    case READSTAT_TYPE_INT16:
    case READSTAT_TYPE_INT32:
      output_[index] = IntegerVector(nrows_);
      break;
    case READSTAT_TYPE_FLOAT:
    case READSTAT_TYPE_DOUBLE:
      output_[index] = NumericVector(nrows_);
      break;
    }

    RObject col = output_[index];

    const char* var_label = readstat_variable_get_label(variable);
    if (var_label != NULL && strcmp(var_label, "") != 0) {
      col.attr("label") = CharacterVector::create(Rf_mkCharCE(var_label, CE_UTF8));
    }

    if (val_labels != NULL)
      val_labels_[index] = val_labels;

    const char* var_format = readstat_variable_get_format(variable);
    VarType var_type = numType(type_, var_format);
    // Rcout << var_name << ": " << var_format << " [" << var_type << "]\n";
    var_types_[index] = var_type;
    switch(var_type) {
    case HAVEN_DATE:
      col.attr("class") = "Date";
      break;
    case HAVEN_TIME:
      col.attr("class") = "hms";
      break;
    case HAVEN_DATETIME:
      col.attr("class") = CharacterVector::create("POSIXct", "POSIXt");
      col.attr("tzone") = "UTC";
      break;
    default:
      break;
    }

    return 0;
  }
Exemplo n.º 26
0
         QScriptValue
        REcmaObject::getPropertyTypeIds
        (QScriptContext* context, QScriptEngine* engine) 
        
        {
            //REcmaHelper::functionStart("REcmaObject::getPropertyTypeIds", context, engine);
            //qDebug() << "ECMAScript WRAPPER: REcmaObject::getPropertyTypeIds";
            //QCoreApplication::processEvents();

            QScriptValue result = engine->undefinedValue();
            
                    // public function: can be called from ECMA wrapper of ECMA shell:
                    RObject* self = 
                        getSelf("getPropertyTypeIds", context);
                  

                //Q_ASSERT(self!=NULL);
                if (self==NULL) {
                    return REcmaHelper::throwError("self is NULL", context);
                }
                
    
    if( context->argumentCount() ==
    0
    ){
    // prepare arguments:
    
    // end of arguments

    // call C++ function:
    // return type 'QSet < RPropertyTypeId >'
    QSet < RPropertyTypeId > cppResult =
        
               self->getPropertyTypeIds();
        // return type: QSet < RPropertyTypeId >
                // QSet (convert to QVariantList):
                result = REcmaHelper::setToScriptValue(engine, cppResult);

                
    } else


        
            {
               return REcmaHelper::throwError("Wrong number/types of arguments for RObject.getPropertyTypeIds().",
                   context);
            }
            //REcmaHelper::functionEnd("REcmaObject::getPropertyTypeIds", context, engine);
            return result;
        }
Exemplo n.º 27
0
// [[Rcpp::export]]
List matrixToDataFrame(RObject x) {
  SEXPTYPE type = TYPEOF(x);

  if (!x.hasAttribute("dim"))
    stop("`x` is not a matrix");

  IntegerVector dim = x.attr("dim");
  if (dim.size() != 2)
    stop("`x` is not a matrix");

  int nrow = dim[0], ncol = dim[1];

  List out = List(ncol);
  for (int j = 0; j < ncol; ++j) {
    out[j] = Rf_allocVector(type, nrow);
    SEXP col = out[j];
    Rf_copyMostAttrib(x, col);
    int offset = j * nrow;
    for (int i = 0; i < nrow; ++i) {
      switch(type) {
      case LGLSXP:
      case INTSXP:
        INTEGER(col)[i] = INTEGER(x)[offset + i];
        break;
      case REALSXP:
        REAL(col)[i] = REAL(x)[offset + i];
        break;
      case CPLXSXP:
        COMPLEX(col)[i] = COMPLEX(x)[offset + i];
        break;
      case STRSXP:
        SET_STRING_ELT(col, i, STRING_ELT(x, offset + i));
        break;
      case VECSXP:
        SET_VECTOR_ELT(col, i, VECTOR_ELT(x, offset + i));
        break;
      }
    }
  }

  if (x.hasAttribute("dimnames")) {
    List dimnames = x.attr("dimnames");
    out.attr("names") = dimnames[1];
  }

  out.attr("class") = "data.frame";
  out.attr("row.names") = IntegerVector::create(NA_INTEGER, -nrow);

  return out;
}
Exemplo n.º 28
0
void RObjectList::updateEnvironments (const QStringList &_env_names, bool force_globalenv_update) {
	RK_TRACE (OBJECTS);

	RObjectMap newchildmap;
	QStringList env_names = _env_names;
	if (!env_names.isEmpty ()) {
		QString dummy = env_names.takeFirst ();
		RK_ASSERT (dummy == ".GlobalEnv");
		if (force_globalenv_update) {
			// for now, we only update the .GlobalEnv. All others we assume to be static
			getGlobalEnv ()->updateFromR (update_chain);
		}
	} else {
		RK_ASSERT (!env_names.isEmpty ());
	}

	// find which items are new, and copy the old ones
	for (int i = 0; i < env_names.count (); ++i) {
		QString name = env_names[i];

		RObject *obj = findChildByName (name);
		if (obj && (i > 0) && (env_names.lastIndexOf (name, i-1) > -1)) {		// duplicate environment names can happen (e.g. if a data.frame is attached multiple times)
			obj = 0;	// only copy the old item once
		}
		if (!obj) {
			obj = createTopLevelEnvironment (name);
			RKGlobals::tracker ()->beginAddObject (obj, this, i);
			childmap.insert (i, obj);
			RKGlobals::tracker ()->endAddObject (obj, this, i);
		}
		newchildmap.insert (i, obj);
	}

	// check which envs have been removed or changed position
	for (int i = 0; i < childmap.size (); ++i) {	// do *not* cache the childmap.size ()! We may change it in the loop.
		RObject *obj = childmap[i];
		int new_pos = newchildmap.indexOf (obj);
		
		if (new_pos < 0) {	// environment is gone
			RK_DEBUG (OBJECTS, DL_INFO, "removing toplevel environment %s from list", obj->getShortName ().toLatin1 ().data ());
			if (RKGlobals::tracker ()->removeObject (obj, 0, true)) --i;
			else (newchildmap.insert (i, obj));
		} else if (new_pos != i) {
			// this call is rather expensive, all in all, but fortunately called very rarely
			moveChild (obj, i, new_pos);
		}
	}

	RK_DO (RK_ASSERT (childmap == newchildmap), OBJECTS, DL_DEBUG);	// this is an expensive assert, hence wrapping it inside RK_DO
}
Exemplo n.º 29
0
         QScriptValue
        REcmaObject::getHandle
        (QScriptContext* context, QScriptEngine* engine) 
        
        {
            //REcmaHelper::functionStart("REcmaObject::getHandle", context, engine);
            //qDebug() << "ECMAScript WRAPPER: REcmaObject::getHandle";
            //QCoreApplication::processEvents();

            QScriptValue result = engine->undefinedValue();
            
                    // public function: can be called from ECMA wrapper of ECMA shell:
                    RObject* self = 
                        getSelf("getHandle", context);
                  

                //Q_ASSERT(self!=NULL);
                if (self==NULL) {
                    return REcmaHelper::throwError("self is NULL", context);
                }
                
    
    if( context->argumentCount() ==
    0
    ){
    // prepare arguments:
    
    // end of arguments

    // call C++ function:
    // return type 'RObject::Handle'
    RObject::Handle cppResult =
        
               self->getHandle();
        // return type: RObject::Handle
                // not standard type nor reference
                result = qScriptValueFromValue(engine, cppResult);
            
    } else


        
            {
               return REcmaHelper::throwError("Wrong number/types of arguments for RObject.getHandle().",
                   context);
            }
            //REcmaHelper::functionEnd("REcmaObject::getHandle", context, engine);
            return result;
        }
Exemplo n.º 30
0
         QScriptValue
        REcmaObject::isSelectedForPropertyEditing
        (QScriptContext* context, QScriptEngine* engine) 
        
        {
            //REcmaHelper::functionStart("REcmaObject::isSelectedForPropertyEditing", context, engine);
            //qDebug() << "ECMAScript WRAPPER: REcmaObject::isSelectedForPropertyEditing";
            //QCoreApplication::processEvents();

            QScriptValue result = engine->undefinedValue();
            
                    // public function: can be called from ECMA wrapper of ECMA shell:
                    RObject* self = 
                        getSelf("isSelectedForPropertyEditing", context);
                  

                //Q_ASSERT(self!=NULL);
                if (self==NULL) {
                    return REcmaHelper::throwError("self is NULL", context);
                }
                
    
    if( context->argumentCount() ==
    0
    ){
    // prepare arguments:
    
    // end of arguments

    // call C++ function:
    // return type 'bool'
    bool cppResult =
        
               self->isSelectedForPropertyEditing();
        // return type: bool
                // standard Type
                result = QScriptValue(cppResult);
            
    } else


        
            {
               return REcmaHelper::throwError("Wrong number/types of arguments for RObject.isSelectedForPropertyEditing().",
                   context);
            }
            //REcmaHelper::functionEnd("REcmaObject::isSelectedForPropertyEditing", context, engine);
            return result;
        }