コード例 #1
0
ファイル: FunctionFactory.cpp プロジェクト: mducle/mantid
/**
 * Create a function from an expression.
 * @param expr :: The input expression
 * @param parentAttributes :: An output map filled with the attribute name &
 * values of the parent function
 * @return A pointer to the created function
 */
IFunction_sptr FunctionFactoryImpl::createSimple(
    const Expression &expr,
    std::map<std::string, std::string> &parentAttributes) const {
  if (expr.name() == "=" && expr.size() > 1) {
    return createFunction(expr.terms()[1].name());
  }

  if (expr.name() != "," || expr.size() == 0) {
    inputError(expr.str());
  }

  const std::vector<Expression> &terms = expr.terms();
  auto term = terms.cbegin();

  if (term->name() != "=")
    inputError(expr.str());
  if (term->terms()[0].name() != "name" &&
      term->terms()[0].name() != "composite") {
    throw std::invalid_argument(
        "Function name must be defined before its parameters");
  }
  std::string fnName = term->terms()[1].name();

  IFunction_sptr fun = createFunction(fnName);
  for (++term; term != terms.end();
       ++term) { // loop over function's parameters/attributes
    if (term->name() != "=")
      inputError(expr.str());
    std::string parName = term->terms()[0].name();
    std::string parValue = term->terms()[1].str();
    if (fun->hasAttribute(parName)) {
      // set attribute
      if (parValue.size() > 1 && parValue[0] == '"') {
        // remove the double quotes
        parValue = parValue.substr(1, parValue.size() - 2);
      }
      IFunction::Attribute att = fun->getAttribute(parName);
      att.fromString(parValue);
      fun->setAttribute(parName, att);
    } else if (parName.size() >= 10 && parName.substr(0, 10) == "constraint") {
      // or it can be a list of constraints
      addConstraints(fun, (*term)[1]);
    } else if (parName == "ties") {
      addTies(fun, (*term)[1]);
    } else if (!parName.empty() && parName[0] == '$') {
      parName.erase(0, 1);
      parentAttributes[parName] = parValue;
    } else {
      // set initial parameter value
      fun->setParameter(parName, atof(parValue.c_str()));
    }
  } // for term

  fun->applyTies();
  return fun;
}
コード例 #2
0
ファイル: ontology.cpp プロジェクト: ihh/wtfgenes
vguard<set<Ontology::TermIndex> > Ontology::transitiveClosure() const {
  vguard<set<TermIndex> > tc (terms());
  auto L = toposortTermIndex();
  for (TermIndex n : L) {
    tc[n].insert (n);
    for (TermIndex p : parents[n])
      tc[n].insert (tc[p].begin(), tc[p].end());
  }
  return tc;
}
コード例 #3
0
ファイル: nltool.c プロジェクト: dinkc64/mame
static void listdevices()
{
    netlist_tool_t nt;
    nt.init();
    const netlist::factory_list_t::list_t &list = nt.setup().factory().list();

    nt.setup().register_source(palloc(netlist::source_proc_t, "dummy", &netlist_dummy));
    nt.setup().include("dummy");

    nt.setup().start_devices();
    nt.setup().resolve_inputs();

    for (int i=0; i < list.size(); i++)
    {
        pstring out = pstring::sprintf("%-20s %s(<id>", list[i]->classname().cstr(),
                                       list[i]->name().cstr() );
        pstring terms("");

        netlist::base_factory_t *f = list[i];
        netlist::device_t *d = f->Create();
        d->init(nt, pstring::sprintf("dummy%d", i));
        d->start_dev();

        // get the list of terminals ...
        for (int j=0; j < d->m_terminals.size(); j++)
        {
            pstring inp = d->m_terminals[j];
            if (inp.startsWith(d->name() + "."))
                inp = inp.substr(d->name().len() + 1);
            terms += "," + inp;
        }

        if (list[i]->param_desc().startsWith("+"))
        {
            out += "," + list[i]->param_desc().substr(1);
            terms = "";
        }
        else if (list[i]->param_desc() == "-")
        {
            /* no params at all */
        }
        else
        {
            out += "," + list[i]->param_desc();
        }
        out += ")";
        printf("%s\n", out.cstr());
        if (terms != "")
            printf("Terminals: %s\n", terms.substr(1).cstr());
    }
}
コード例 #4
0
 TermInfosReaderThreadResourcesPtr TermInfosReader::getThreadResources()
 {
     TermInfosReaderThreadResourcesPtr resources(threadResources.get());
     if (!resources)
     {
         resources = newLucene<TermInfosReaderThreadResources>();
         resources->termEnum = terms();
         
         // Cache does not have to be thread-safe, it is only used by one thread at the same time
         resources->termInfoCache = newInstance<TermInfoCache>(DEFAULT_CACHE_SIZE);
         threadResources.set(resources);
     }
     return resources;
 }
コード例 #5
0
ファイル: nltool.cpp プロジェクト: fesh0r/mame-full
void tool_app_t::listdevices()
{
	netlist_tool_t nt(*this, "netlist");
	nt.init();

	nt.log().verbose.set_enabled(false);
	nt.log().info.set_enabled(false);
	nt.log().warning.set_enabled(false);

	netlist::factory::list_t &list = nt.setup().factory();

	nt.setup().register_source(plib::make_unique<netlist::source_proc_t>("dummy", &netlist_dummy));
	nt.setup().include("dummy");


	nt.setup().prepare_to_run();

	std::vector<netlist::pool_owned_ptr<netlist::core_device_t>> devs;

	for (auto & f : list)
	{
		pstring out = plib::pfmt("{1:-20} {2}(<id>")(f->classname())(f->name());

		f->macro_actions(nt.setup(), f->name() + "_lc");
		auto d = f->Create(nt.nlstate(), f->name() + "_lc");
		// get the list of terminals ...

		std::vector<pstring> terms(nt.setup().get_terminals_for_device_name(d->name()));

		out += "," + f->param_desc();
		for (const auto &p : plib::psplit(f->param_desc(),",") )
		{
			if (plib::startsWith(p, "+"))
			{
				plib::container::remove(terms, p.substr(1));
			}
		}
		out += ")";
		pout("{}\n", out);
		if (terms.size() > 0)
		{
			pstring t = "";
			for (auto & j : terms)
				t += "," + j;
			pout("\tTerminals: {}\n", t.substr(1));
		}
		devs.emplace_back(std::move(d));
	}
}
コード例 #6
0
ファイル: ontology.cpp プロジェクト: ihh/wtfgenes
vguard<Ontology::TermIndex> Ontology::toposortTermIndex() const {
  deque<TermIndex> S;
  vguard<TermIndex> L, nParents (terms());
  int edges = 0;
  for (TermIndex c = 0; c < terms(); ++c) {
    nParents[c] = parents[c].size();
    edges += nParents[c];
    if (nParents[c] == 0)
      S.push_back (c);
  }
  while (S.size()) {
    const TermIndex n = S.front();
    S.pop_front();
    L.push_back (n);
    for (auto m : children[n]) {
      --edges;
      if (--nParents[m] == 0)
	S.push_back (m);
    }
  }
  if (edges > 0)
    throw std::domain_error ("Ontology graph is cyclic, can't toposort");
  return L;
}
コード例 #7
0
ファイル: libprolog.c プロジェクト: howerj/libprolog
static node *rule(prolog_obj_t *o)
{       node *x = new_node(o, RULE);
        PDEBUG(x->type, "rule");
        x->o1 = term(o);
        if(o->sym == PERIOD)
                return x;
        if(o->sym == ASSIGN) { 
                next_sym(o);
                x->o2 = terms(o);
                if(o->sym != PERIOD) 
                        RECOVER(o, "expected '.'");
                return x;
        }
        RECOVER(o, "expected ':-' or '.'");
        return x;
}
コード例 #8
0
ファイル: reTrms.cpp プロジェクト: rforge/lme4
    Rcpp::List reTrms::condVar(double scale) {
	if (scale < 0 || !R_finite(scale))
	    throw runtime_error("scale must be non-negative and finite");
	int nf = d_flist.size();
	IntegerVector nc = ncols(), nl = nlevs(), nct = nctot(), off = offsets();
	
    	List ans(nf);
	CharacterVector nms = d_flist.names();
	ans.names() = clone(nms);
	
	for (int i = 0; i < nf; i++) {
	    int ncti = nct[i], nli = nl[i];
	    IntegerVector trms = terms(i);
	    int *cset = new int[ncti], nct2 = ncti * ncti;
	    
	    NumericVector ansi(Dimension(ncti, ncti, nli));
	    ans[i] = ansi;
	    double *ai = ansi.begin();
	    
	    for (int j = 0; j < nli; j++) {
		int kk = 0;
		for (int jj = 0; jj < trms.size(); jj++) {
		    int tjj = trms[jj];
		    for (int k = 0; k < nc[tjj]; k++)
			cset[kk++] = off[tjj] + j * nc[tjj] + k;
		}
		CHM_SP cols =
		    M_cholmod_submatrix(&d_Lambda, (int*)NULL, -1, cset, ncti,
					1/*values*/, 1/*sorted*/, &c);
		CHM_SP sol = d_L.spsolve(CHOLMOD_A, cols);
		CHM_SP tcols = M_cholmod_transpose(cols, 1/*values*/, &c);
		M_cholmod_free_sparse(&cols, &c);
		CHM_SP var = M_cholmod_ssmult(tcols, sol, 0/*stype*/,
					      1/*values*/, 1/*sorted*/, &c);
		M_cholmod_free_sparse(&sol, &c);
		M_cholmod_free_sparse(&tcols, &c);
		CHM_DN dvar = M_cholmod_sparse_to_dense(var, &c);
		M_cholmod_free_sparse(&var, &c);
		Memcpy(ai + j * nct2, (double*)dvar->x, nct2);
		M_cholmod_free_dense(&dvar, &c);
	    }
	    delete[] cset;
	    transform(ansi.begin(), ansi.end(), ansi.begin(),
		      bind2nd(multiplies<double>(), scale * scale));
	}
	return ans;
    }
コード例 #9
0
ファイル: nltool.cpp プロジェクト: gvsurenderreddy/mame
static void listdevices()
{
	netlist_tool_t nt("netlist");
	nt.init();
	netlist::factory_list_t &list = nt.setup().factory();

	nt.setup().register_source(std::make_shared<netlist::source_proc_t>("dummy", &netlist_dummy));
	nt.setup().include("dummy");

	nt.setup().start_devices();
	nt.setup().resolve_inputs();

	for (auto & f : list)
	{
		pstring out = plib::pfmt("{1} {2}(<id>")(f->classname(),"-20")(f->name());
		pstring terms("");

		auto d = f->Create(nt.setup().netlist(), "dummy");

		// get the list of terminals ...
		for (auto & inp :  d->m_terminals)
		{
			if (inp.startsWith(d->name() + "."))
				inp = inp.substr(d->name().len() + 1);
			terms += "," + inp;
		}

		if (f->param_desc().startsWith("+"))
		{
			out += "," + f->param_desc().substr(1);
			terms = "";
		}
		else if (f->param_desc() == "-")
		{
			/* no params at all */
		}
		else
		{
			out += "," + f->param_desc();
		}
		out += ")";
		printf("%s\n", out.cstr());
		if (terms != "")
			printf("Terminals: %s\n", terms.substr(1).cstr());
	}
}
コード例 #10
0
ファイル: ilp_problem.cpp プロジェクト: kazeto/phillip-wsc
void ilp_problem_t::add_constraints_of_transitive_unifications()
{
    std::list< const hash_set<term_t>* >
        clusters = m_graph->enumerate_variable_clusters();

    for( auto cl = clusters.begin(); cl != clusters.end(); ++cl )
    {
        if( (*cl)->size() <= 2 ) continue;

        std::vector<term_t> terms( (*cl)->begin(), (*cl)->end() );
        for( size_t i = 2; i < terms.size(); ++i )
        for( size_t j = 1; j < i;            ++j )
        for( size_t k = 0; k < j;            ++k )
        {
            add_constraints_of_transitive_unification(
                terms[i], terms[j], terms[k]);
        }
    }
}
コード例 #11
0
ファイル: ontology.cpp プロジェクト: ihh/wtfgenes
void Ontology::init (const TermParentsMap& termParents) {
  auto newTerm = [&](const TermName& term) -> void
    {
      termIndex[term] = terms();
      termName.push_back (term);
      parents.push_back (vguard<TermIndex>());
      children.push_back (vguard<TermIndex>());
    };
  for (auto& tp : termParents)
    newTerm (tp.first);
  for (auto& tp : termParents) {
    const TermIndex t = termIndex[tp.first];
    for (auto& pn : tp.second) {
      if (!termIndex.count(pn))
	newTerm (pn);
      const TermIndex p = termIndex[pn];
      parents[t].push_back (p);
      children[p].push_back (t);
    }
  }
}
コード例 #12
0
ファイル: Problem101.cpp プロジェクト: PeteyPii/Euler
int64 problem101(int64 n) {
  if (n <= 0) {
    return 0;
  }

  vector<vector<int64>> diffs((uint32)n + 1, vector<int64>((uint32)n + 1, -1));
  vector<int64> terms((uint32)n + 1);
  for (int64 x = 1; x <= n; x++) {
    int64 sum = 0;
    for (int64 i = 0; i <= n; i++) {
      if (i % 2 == 0) {
        sum += power(x, i);
      } else {
        sum -= power(x, i);
      }
    }
    diffs[0][x] = sum;
  }

  for (int64 term = 1; term < n; term++) {
    for (int64 x = 1; x <= n - term; x++) {
      diffs[term][x] = diffs[term - 1][x + 1] - diffs[term - 1][x];
    }
  }

  int64 diffResult = 0;
  for (int64 term = 1; term <= n; term++) {
    int64 expectedTerm = diffs[0][term];
    for (int64 i = term - 1; i >= 1; i--) {
      expectedTerm += diffs[term - i][i];
    }
    diffResult += expectedTerm;
  }

  return diffResult;
}
コード例 #13
0
ファイル: FunctionFactory.cpp プロジェクト: mducle/mantid
/**
 * Create a composite function from an expression.
 * @param expr :: The input expression
 * @param parentAttributes :: An output map filled with the attribute name &
 * values of the parent function
 * @return A pointer to the created function
 */
CompositeFunction_sptr FunctionFactoryImpl::createComposite(
    const Expression &expr,
    std::map<std::string, std::string> &parentAttributes) const {
  if (expr.name() != ";")
    inputError(expr.str());

  if (expr.size() == 0) {
    return CompositeFunction_sptr();
  }

  const std::vector<Expression> &terms = expr.terms();
  auto it = terms.cbegin();
  const Expression &term = it->bracketsRemoved();

  CompositeFunction_sptr cfun;
  if (term.name() == "=") {
    if (term.terms()[0].name() == "composite") {
      cfun = boost::dynamic_pointer_cast<CompositeFunction>(
          createFunction(term.terms()[1].name()));
      if (!cfun)
        inputError(expr.str());
      ++it;
    } else if (term.terms()[0].name() == "name") {
      cfun = boost::dynamic_pointer_cast<CompositeFunction>(
          createFunction("CompositeFunction"));
      if (!cfun)
        inputError(expr.str());
    } else {
      inputError(expr.str());
    }
  } else if (term.name() == ",") {
    auto firstTerm = term.terms().cbegin();
    if (firstTerm->name() == "=") {
      if (firstTerm->terms()[0].name() == "composite") {
        cfun = boost::dynamic_pointer_cast<CompositeFunction>(
            createSimple(term, parentAttributes));
        if (!cfun)
          inputError(expr.str());
        ++it;
      } else if (firstTerm->terms()[0].name() == "name") {
        cfun = boost::dynamic_pointer_cast<CompositeFunction>(
            createFunction("CompositeFunction"));
        if (!cfun)
          inputError(expr.str());
      } else {
        inputError(expr.str());
      }
    }
  } else if (term.name() == ";") {
    cfun = boost::dynamic_pointer_cast<CompositeFunction>(
        createFunction("CompositeFunction"));
    if (!cfun)
      inputError(expr.str());
  } else {
    inputError(expr.str());
  }

  if (!cfun)
    inputError(expr.str());

  for (; it != terms.end(); ++it) {
    const Expression &term = it->bracketsRemoved();
    IFunction_sptr fun;
    std::map<std::string, std::string> pAttributes;
    if (term.name() == ";") {
      fun = createComposite(term, pAttributes);
      if (!fun)
        continue;
    } else {
      std::string parName = term[0].name();
      if (parName.size() >= 10 && parName.substr(0, 10) == "constraint") {
        addConstraints(cfun, term[1]);
        continue;
      } else if (parName == "ties") {
        addTies(cfun, term[1]);
        continue;
      } else {
        fun = createSimple(term, pAttributes);
      }
    }
    cfun->addFunction(fun);
    size_t i = cfun->nFunctions() - 1;
    for (auto &pAttribute : pAttributes) {
      // Apply parent attributes of the child function to this function. If this
      // function doesn't have those attributes, they get passed up the chain to
      // this function's parent.
      if (cfun->hasLocalAttribute(pAttribute.first)) {
        cfun->setLocalAttributeValue(i, pAttribute.first, pAttribute.second);
      } else {
        parentAttributes[pAttribute.first] = pAttribute.second;
      }
    }
  }

  if (cfun) {
    cfun->applyTies();
  }
  return cfun;
}
コード例 #14
0
ファイル: nltool.cpp プロジェクト: dinoue/mame
static void listdevices()
{
	netlist_tool_t nt("netlist");
	nt.init();
	netlist::factory_list_t &list = nt.setup().factory();

	nt.setup().register_source(std::make_shared<netlist::source_proc_t>("dummy", &netlist_dummy));
	nt.setup().include("dummy");

	nt.setup().start_devices();
	nt.setup().resolve_inputs();

	std::vector<plib::owned_ptr<netlist::core_device_t>> devs;

	for (auto & f : list)
	{
		pstring out = plib::pfmt("{1} {2}(<id>")(f->classname(),"-20")(f->name());
		pstring terms("");

		auto d = f->Create(nt.setup().netlist(), f->name() + "_lc");
		// get the list of terminals ...

		for (auto & t : nt.setup().m_terminals)
		{
			if (t.second->name().startsWith(d->name()))
			{
				pstring tn(t.second->name().substr(d->name().len()+1));
				if (tn.find(".")<0)
					terms += ", " + tn;
			}
		}

		for (auto & t : nt.setup().m_alias)
		{
			if (t.first.startsWith(d->name()))
			{
				pstring tn(t.first.substr(d->name().len()+1));
				if (tn.find(".")<0)
					terms += ", " + tn;
			}
		}

		if (f->param_desc().startsWith("+"))
		{
			out += "," + f->param_desc().substr(1);
			terms = "";
		}
		else if (f->param_desc() == "-")
		{
			/* no params at all */
		}
		else
		{
			out += "," + f->param_desc();
		}
		out += ")";
		printf("%s\n", out.cstr());
		if (terms != "")
			printf("Terminals: %s\n", terms.substr(1).cstr());
		devs.push_back(std::move(d));
	}
}
コード例 #15
0
ファイル: InputRewriter.cpp プロジェクト: dave90/Dlv_safe2
void BaseInputRewriter::translateChoice(Rule*& rule,vector<Rule*>& ruleRewrited) {

	unsigned id=IdGenerator::getInstance()->getId();
	unsigned counter=1;

	// Create an auxiliary rule in order to ground the body only once.
	// First the variables shared between the atoms in the body
	// and the choice atom are found, these variables will be
	// the term of the auxiliary atom in the head of the auxiliary rule

	Atom* choice =rule->getAtomInHead(0);

	Atom *auxiliaryAtomBody=nullptr;
	if(rule->getSizeBody()>1){

		set_term variables_in_choice=choice->getVariable();
		set_term variables_in_body;

		for(unsigned i=0;i<rule->getSizeBody();++i){
			auto atom=rule->getAtomInBody(i);
			if(atom->isNegative())continue;
			set_term variables;
			if(atom->isAggregateAtom())
				variables=atom->getGuardVariable();
			else
				variables=atom->getVariable();
			variables_in_body.insert(variables.begin(),variables.end());
		}

		set_term variables_intersection;
		Utils::intersectionSet(variables_in_choice,variables_in_body,variables_intersection);

		Rule * body_rule=new Rule;

		if(rule->isMustBeRewritedForAggregates()) body_rule->setMustBeRewritedForAggregates(true);

		//Body
		body_rule->setBody(rule->getBody());

		//Head
		string predicate_name=AUXILIARY+SEPARATOR+to_string(id)+SEPARATOR+to_string(counter);
		vector<Term*> terms(variables_intersection.begin(),variables_intersection.end());
		auxiliaryAtomBody=generateNewAuxiliaryAtom(predicate_name,terms);
		body_rule->addInHead(auxiliaryAtomBody);

		ruleRewrited.push_back(body_rule);
		counter++;

	}else{
		if(rule->getSizeBody()==1)
			auxiliaryAtomBody=rule->getAtomInBody(0);
	}

	// For each choice element a new disjunctive auxiliary rule is created.
	// Each rule has in the head a disjunction with a the first atom of the choice element and a new auxiliary atom
	// having the same terms of the first atom, while in the body it contains the remaining atoms of the choice element
	// and the auxiliary atom previously created for the body.
	// Also, the aggregate elements for the constraint rule are created (see below)
	vector<AggregateElement*> elements = rewriteChoiceElements(id, counter,choice, auxiliaryAtomBody, ruleRewrited);

	// Finally a constraint rule is created.
	// It has as body the auxiliary atom previously created for the body, and a negated count aggregate
	// whose guard are the same of the choice atom and inside contains the first atom of each choice element
	// and as aggregate terms all its terms
	rewriteChoiceConstraint(elements, auxiliaryAtomBody, choice, ruleRewrited);

	if(rule->getSizeBody()==1)
		delete auxiliaryAtomBody;

	rule->deleteBody([](Atom* atom){
		return 0;
	});
	rule->deleteHead([](Atom* atom){
		return 1;
	});
	delete rule;
	rule=0;
}