Ejemplo n.º 1
0
/** Remove a function
 * @param i :: The index of the function to remove
 */
void CompositeFunction::removeFunction(size_t i) {
  if (i >= nFunctions())
    throw std::out_of_range("Function index out of range.");

  IFunction_sptr fun = getFunction(i);

  size_t dnp = fun->nParams();

  for (size_t j = 0; j < nParams();) {
    ParameterTie *tie = getTie(j);
    if (tie && tie->findParametersOf(fun.get())) {
      removeTie(j);
    } else {
      j++;
    }
  }

  // Shift down the function indeces for parameters
  for (auto it = m_IFunction.begin(); it != m_IFunction.end();) {

    if (*it == i) {
      it = m_IFunction.erase(it);
    } else {
      if (*it > i) {
        *it -= 1;
      }
      ++it;
    }
  }

  m_nParams -= dnp;
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
    m_paramOffsets[j] -= dnp;
  }
  m_paramOffsets.erase(m_paramOffsets.begin() + i);

  m_functions.erase(m_functions.begin() + i);
}
Ejemplo n.º 2
0
bool FragmentProgramDecompiler::handle_scb(u32 opcode)
{
	switch (opcode)
	{
	case RSX_FP_OPCODE_ADD: SetDst("($0 + $1)"); return true;
	case RSX_FP_OPCODE_COS: SetDst("cos($0.xxxx)"); return true;
	case RSX_FP_OPCODE_DIVSQ: SetDst("($0 / sqrt($1).xxxx)"); return true;
	case RSX_FP_OPCODE_DP2: SetDst(getFunction(FUNCTION::FUNCTION_DP2)); return true;
	case RSX_FP_OPCODE_DP3: SetDst(getFunction(FUNCTION::FUNCTION_DP3)); return true;
	case RSX_FP_OPCODE_DP4: SetDst(getFunction(FUNCTION::FUNCTION_DP4)); return true;
	case RSX_FP_OPCODE_DP2A: SetDst(getFunction(FUNCTION::FUNCTION_DP2A)); return true;
	case RSX_FP_OPCODE_DST: SetDst("vec4(distance($0, $1))"); return true;
	case RSX_FP_OPCODE_REFL: LOG_ERROR(RSX, "Unimplemented SCB instruction: REFL"); return true; // TODO: Is this in the right category?
	case RSX_FP_OPCODE_EX2: SetDst("exp2($0.xxxx)"); return true;
	case RSX_FP_OPCODE_FLR: SetDst("floor($0)"); return true;
	case RSX_FP_OPCODE_FRC: SetDst(getFunction(FUNCTION::FUNCTION_FRACT)); return true;
	case RSX_FP_OPCODE_LIT: SetDst(getFloatTypeName(4) + "(1.0, $0.x, ($0.x > 0.0 ? exp($0.w * log2($0.y)) : 0.0), 1.0)"); return true;
	case RSX_FP_OPCODE_LIF: SetDst(getFloatTypeName(4) + "(1.0, $0.y, ($0.y > 0 ? pow(2.0, $0.w) : 0.0), 1.0)"); return true;
	case RSX_FP_OPCODE_LRP: LOG_ERROR(RSX, "Unimplemented SCB instruction: LRP"); return true; // TODO: Is this in the right category?
	case RSX_FP_OPCODE_LG2: SetDst("log2($0.xxxx)"); return true;
	case RSX_FP_OPCODE_MAD: SetDst("($0 * $1 + $2)"); return true;
	case RSX_FP_OPCODE_MAX: SetDst("max($0, $1)"); return true;
	case RSX_FP_OPCODE_MIN: SetDst("min($0, $1)"); return true;
	case RSX_FP_OPCODE_MOV: SetDst("$0"); return true;
	case RSX_FP_OPCODE_MUL: SetDst("($0 * $1)"); return true;
	case RSX_FP_OPCODE_PK2: SetDst("packSnorm2x16($0)"); return true; // TODO: More testing (Sonic The Hedgehog (NPUB-30442/NPEB-00478))
	case RSX_FP_OPCODE_PK4: SetDst("packSnorm4x8($0)"); return true; // TODO: More testing (Sonic The Hedgehog (NPUB-30442/NPEB-00478))
	case RSX_FP_OPCODE_PK16: LOG_ERROR(RSX, "Unimplemented SCB instruction: PK16"); return true;
	case RSX_FP_OPCODE_PKB: LOG_ERROR(RSX, "Unimplemented SCB instruction: PKB"); return true;
	case RSX_FP_OPCODE_PKG: LOG_ERROR(RSX, "Unimplemented SCB instruction: PKG"); return true;
	case RSX_FP_OPCODE_SEQ: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SEQ, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_SFL: SetDst(getFunction(FUNCTION::FUNCTION_SFL)); return true;
	case RSX_FP_OPCODE_SGE: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SGE, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_SGT: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SGT, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_SIN: SetDst("sin($0.xxxx)"); return true;
	case RSX_FP_OPCODE_SLE: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SLE, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_SLT: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SLT, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_SNE: SetDst(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SNE, "$0", "$1") + ")"); return true;
	case RSX_FP_OPCODE_STR: SetDst(getFunction(FUNCTION::FUNCTION_STR)); return true;
	}
	return false;
}
Ejemplo n.º 3
0
  /// Function you want to fit to. 
  /// @param domain :: The buffer for writing the calculated values. Must be big enough to accept dataSize() values
  void MultiDomainFunction::function(const FunctionDomain& domain, FunctionValues& values)const
  {
    // works only on CompositeDomain
    if (!dynamic_cast<const CompositeDomain*>(&domain))
    {
      throw std::invalid_argument("Non-CompositeDomain passed to MultiDomainFunction.");
    }
    const CompositeDomain& cd = dynamic_cast<const CompositeDomain&>(domain);
    // domain must not have less parts than m_maxIndex
    if (cd.getNParts() <= m_maxIndex)
    {
      throw std::invalid_argument("CompositeDomain has too few parts (" 
        + boost::lexical_cast<std::string>(cd.getNParts()) +
        ") for MultiDomainFunction (max index " + boost::lexical_cast<std::string>(m_maxIndex) + ").");
    }
    // domain and values must be consistent
    if (cd.size() != values.size())
    {
      throw std::invalid_argument("MultiDomainFunction: domain and values have different sizes.");
    }

    countValueOffsets(cd);
    // evaluate member functions
    values.zeroCalculated();
    for(size_t iFun = 0; iFun < nFunctions(); ++iFun)
    {
      // find the domains member function must be applied to
      std::vector<size_t> domains;
      getFunctionDomains(iFun, cd, domains);

      for(auto i = domains.begin(); i != domains.end(); ++i)
      {
        const FunctionDomain& d = cd.getDomain(*i);
        FunctionValues tmp(d);
        getFunction(iFun)->function( d, tmp );
        values.addToCalculated(m_valueOffsets[*i],tmp);
      }
    }
  }
Ejemplo n.º 4
0
GenRet GotoStmt::codegen() {
  GenInfo* info = gGenInfo;
  FILE* outfile = info->cfile;
  GenRet ret;

  codegenStmt(this);
  if( outfile ) {
    info->cStatements.push_back("goto " + label->codegen().c + ";\n");
  } else {
#ifdef HAVE_LLVM
    llvm::Function *func = info->builder->GetInsertBlock()->getParent();

    const char *cname;
    if(isDefExpr(label)) {
      cname = toDefExpr(label)->sym->cname;
    }
    else {
      cname = toSymExpr(label)->symbol()->cname;
    }

    llvm::BasicBlock *blockLabel;
    if(!(blockLabel = info->lvt->getBlock(cname))) {
      blockLabel = llvm::BasicBlock::Create(info->module->getContext(), cname);
      info->lvt->addBlock(cname, blockLabel);
    }

    info->builder->CreateBr(blockLabel);

    getFunction()->codegenUniqueNum++;

    llvm::BasicBlock *afterGoto = llvm::BasicBlock::Create(
        info->module->getContext(), FNAME("afterGoto"));
    func->getBasicBlockList().push_back(afterGoto);
    info->builder->SetInsertPoint(afterGoto);

#endif
  }
  return ret;
}
Ejemplo n.º 5
0
/** Replace a function with a new one. The old function is deleted.
 * @param i :: The index of the function to replace
 * @param f :: A pointer to the new function
 */
void CompositeFunction::replaceFunction(size_t i, IFunction_sptr f) {
  if (i >= nFunctions())
    throw std::out_of_range("Function index out of range.");

  IFunction_sptr fun = getFunction(i);
  size_t np_old = fun->nParams();

  size_t np_new = f->nParams();

  // Modify function indeces: The new function may have different number of
  // parameters
  {
    auto itFun = std::find(m_IFunction.begin(), m_IFunction.end(), i);
    if (itFun != m_IFunction.end()) // functions must have at least 1 parameter
    {
      if (np_old > np_new) {
        m_IFunction.erase(itFun, itFun + np_old - np_new);
      } else if (np_old < np_new) {
        m_IFunction.insert(itFun, np_new - np_old, i);
      }
    } else if (np_new > 0) // it could happen if the old function is an empty
                           // CompositeFunction
    {
      itFun = std::find_if(m_IFunction.begin(), m_IFunction.end(),
                           std::bind2nd(std::greater<size_t>(), i));
      m_IFunction.insert(itFun, np_new, i);
    }
  }

  size_t dnp = np_new - np_old;
  m_nParams += dnp;
  // Shift the parameter offsets down by the total number of i-th function's
  // params
  for (size_t j = i + 1; j < nFunctions(); j++) {
    m_paramOffsets[j] += dnp;
  }

  m_functions[i] = f;
}
Ejemplo n.º 6
0
void Functions::add(QString name, QString term) {
    //check, if function name is already there
    if (getFunction(name) != nullptr) return;

    //if not, create a functiontree and use if for parsing
    FunctionTree* fTree = new FunctionTree(nullptr, true, name);

    //parse it
    generateTree(name, term, fTree);

    //skip unnessesary null-functions and id functions
    while (fTree->getRoot() != nullptr) fTree = fTree->getRoot();
    while (fTree->getFunc() == "id") {
        fTree = fTree->getLeft();
        delete (fTree->getRight());
        fTree->setRoot(nullptr, true);
    }

    //optimizesed it
    optimizeTree(fTree);
    fTrees.append(fTree);
}
Ejemplo n.º 7
0
 /**
   * Run a function given its call string, eg "doSomething(1,2,opt=True)"
   */
 boost::shared_ptr<Variable> ScriptModule::runFunction(const std::string& fnStr)
 {
   Kernel::EParser pars;
   pars.parse(fnStr);
   std::string fnName = pars.name();
   ScriptFunction_ptr fun = getFunction(fnName);
   if (fun)
   {
     bool keyWords = false;
     const std::vector<std::string>& argNames = fun->arguments();
     for(int i=0;i<pars.size();++i)
     {
       const Kernel::EParser& arg = pars[i];
       if (!keyWords){ keyWords = (arg.name() == "=");}
       if (!keyWords)
       {
         if (i >= argNames.size())
         {
           throw std::invalid_argument("Wrong number of arguments in "+fnName);
         }
         Expression valExpr(m_namespace,arg);
         fun->setArgument(argNames[i],valExpr.eval());
       }
       else
       {
         if (arg.name() != "=")
         {
           throw std::invalid_argument("Keyword argument expected in "+fnName);
         }
         Expression valExpr(m_namespace,arg[1]);
         fun->setArgument(arg[0].name(),valExpr.eval());
       }
     }
     fun->eval();
     Variable_ptr res = fun->getLocalNamespace_ptr()->getVariable("return");
     return res;
   }
   return Variable_ptr();
 }
void        print_struct_testing_stats(SAMPLE sample, STRUCTMODEL *sm,
				       STRUCT_LEARN_PARM *sparm, 
				       STRUCT_TEST_STATS *teststats)
{
  /* This function is called after making all test predictions in
     svm_struct_classify and allows computing and printing any kind of
     evaluation (e.g. precision/recall) you might want. You can use
     the function eval_prediction to accumulate the necessary
     statistics for each prediction. */
  PyObject *pFunc, *pValue, *pArgs;
  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_PRINT_TESTING_STATS);
  pArgs = Py_BuildValue
    ("NNNO", Sample_FromSample(sample), StructModel_FromStructModel(sm),
     Sparm_FromSparm(sparm), (PyObject*)teststats->pyobj);
  pValue = PyObject_CallObject(pFunc, pArgs);
  Py_DECREF((PyObject*)teststats->pyobj);
  teststats->pyobj=NULL;
  Py_DECREF(pArgs);
  PY_RUNCHECK;
  Py_DECREF(pValue);
}
LABEL       classify_struct_example(PATTERN x, STRUCTMODEL *sm, 
				    STRUCT_LEARN_PARM *sparm)
{
  /* Finds the label yhat for pattern x that scores the highest
     according to the linear evaluation function in sm, especially the
     weights sm.w. The returned label is taken as the prediction of sm
     for the pattern x. The weights correspond to the features defined
     by psi() and range from index 1 to index sm->sizePsi. If the
     function cannot find a label, it shall return an empty label as
     recognized by the function empty_label(y). */
  PyObject *pFunc, *pValue;
  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_CLASSIFY_EXAMPLE);
  pValue = PyObject_CallFunction(pFunc, "ONN", (PyObject*)x.py_x,
				 StructModel_FromStructModel(sm),
				 Sparm_FromSparm(sparm));
  PY_RUNCHECK;
  // Store and return the appropriate Y label.
  LABEL y;
  y.py_y = pValue;
  return(y);
}
Ejemplo n.º 10
0
ConstitutiveModel::ConstitutiveModel(const InputParameters & parameters)
  :Material(parameters),
   _has_temp(isCoupled("temp")),
   _temperature(_has_temp ? coupledValue("temp") : _zero),
   _temperature_old(_has_temp ? coupledValueOld("temp") : _zero),
   _alpha(parameters.isParamValid("thermal_expansion") ? getParam<Real>("thermal_expansion") : 0.),
   _alpha_function(parameters.isParamValid("thermal_expansion_function") ? &getFunction("thermal_expansion_function") : NULL),
   _has_stress_free_temp(isParamValid("stress_free_temperature")),
   _stress_free_temp(_has_stress_free_temp ? getParam<Real>("stress_free_temperature") : 0.0),
   _ref_temp(0.0)
{
  if (parameters.isParamValid("thermal_expansion_function_type"))
  {
    if (!_alpha_function)
      mooseError("thermal_expansion_function_type can only be set when thermal_expansion_function is used");
    MooseEnum tec = getParam<MooseEnum>("thermal_expansion_function_type");
    if (tec == "mean")
      _mean_alpha_function = true;
    else if (tec == "instantaneous")
      _mean_alpha_function = false;
    else
      mooseError("Invalid option for thermal_expansion_function_type");
  }
  else
    _mean_alpha_function = false;

  if (parameters.isParamValid("thermal_expansion_reference_temperature"))
  {
    if (!_alpha_function)
      mooseError("thermal_expansion_reference_temperature can only be set when thermal_expansion_function is used");
    if (!_mean_alpha_function)
      mooseError("thermal_expansion_reference_temperature can only be set when thermal_expansion_function_type = mean");
    _ref_temp = getParam<Real>("thermal_expansion_reference_temperature");
    if (!_has_temp)
      mooseError("Cannot specify thermal_expansion_reference_temperature without coupling to temperature");
  }
  else if (_mean_alpha_function)
    mooseError("Must specify thermal_expansion_reference_temperature if thermal_expansion_function_type = mean");
}
Ejemplo n.º 11
0
CircuitDirichletPotential::CircuitDirichletPotential(const InputParameters & parameters)
  : NodalBC(parameters),
    _current(getPostprocessorValue("current")),
    _surface_potential(getFunction("surface_potential")),
    _surface(getParam<std::string>("surface")),
    _resist(getParam<Real>("resist")),
    _coulomb_charge(1.6e-19),
    _N_A(6.02e23),
    _potential_units(getParam<std::string>("potential_units")),
    _r_units(1. / getParam<Real>("position_units")),
    _convert_moles(getParam<bool>("use_moles")),
    _A(getParam<Real>("A"))
{
  if (_surface.compare("anode") == 0)
    _current_sign = -1.;
  else if (_surface.compare("cathode") == 0)
    _current_sign = 1.;
  if (_potential_units.compare("V") == 0)
    _voltage_scaling = 1.;
  else if (_potential_units.compare("kV") == 0)
    _voltage_scaling = 1000;
}
Ejemplo n.º 12
0
SbaDirichletBC::SbaDirichletBC(const std::string & name, InputParameters parameters)
  :NodalBC(name, parameters),
    // Cross section function
    _area(isParamValid("area") ? &getFunction("area") : NULL),
    // Initial pressure values:
    _p_left(getParam<Real>("pressure_init_left")),
    _p_right(getParam<Real>("pressure_init_right")),
    // Initial velocity values:
    _v_left(getParam<Real>("vel_init_left")),
    _v_right(getParam<Real>("vel_init_right")),
    // Initial temperature values:
    _t_left(isParamValid("temp_init_left") ? getParam<Real>("temp_init_left") : 0.),
    _t_right(isParamValid("temp_init_right") ? getParam<Real>("temp_init_right") : 0.),
    // Initial density values:
    _rho_left(isParamValid("rho_init_left") ? getParam<Real>("rho_init_left") : 0.),
    _rho_right(isParamValid("rho_init_right") ? getParam<Real>("rho_init_right") : 0.),
    // Initial liquid volume fraction values:
    _liq_vf_left(getParam<Real>("liq_vf_init_left")),
    _liq_vf_right(getParam<Real>("liq_vf_init_right")),
    // Equation of State:
    _eos(getUserObject<EquationOfState>("eos")),
    // Boolean:
    _isLiquid(getParam<bool>("isLiquid")),
    _isLeft(getParam<bool>("leftBoundary"))
{
  // Determine the initial condition type:
  if (parameters.isParamValid("rho_init_left") && parameters.isParamValid("pressure_init_right"))
    _ics_type = 0;
  else if (parameters.isParamValid("temp_init_left") && parameters.isParamValid("pressure_init_right"))
    _ics_type = 1;
  else if (parameters.isParamValid("rho_init_left") && parameters.isParamValid("temp_init_left"))
    _ics_type = 2;
  else
    mooseError("The input values provided in the input file '"<<_name<<"' are incomplete.");

  // Boolean for area function
  _isArea = parameters.isParamValid("area") ? true : false;
}
Ejemplo n.º 13
0
// readdir is meant only to display all function directories and their docs to user
// 
// filler(buf, fileName, NULL, 0) are just for output for ls. Even we got rid of their filler, files still exist
// We add +1 to functions[i] to rid the first character, which in many cases is the '/' char.
static int test_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
		off_t offset, struct fuse_file_info *fi)
{
	(void) offset;
	printf("readDir Here\n");
	(void) fi;
	int i =0;
	for(i=1;i<8;i++){
		if (strcmp(path,functions[i])==0){
			filler(buf, ".", NULL, 0); // if path == "/"
			filler(buf, "..", NULL, 0);
			filler(buf, "doc", NULL, 0);
			return 0; //important. without this, a directory wont have it
		}
	}
	if(strcmp(path,"/")==0){
		filler(buf, ".", NULL, 0); // if path == "/"
		filler(buf, "..", NULL, 0);
		int i;
		for(i=1;i<8;i++){
			filler(buf, functions[i] + 1, NULL, 0);
		}
		return 0;
	}
	char** ptr = parse(path);
	int choice = getFunction(ptr);
	if((((choice>=1 && choice<=4) || choice==6) && isNumber(ptr[1])!=0 && ptr[2]==NULL) || 
			((choice ==7 || choice == 5) && ptr[1]==NULL && ptr[2]==NULL)){
		filler(buf, ".", NULL, 0);
		filler(buf, "..", NULL, 0);
		return 0;
	}
	//should recursively assign filler "." and ".." in every possible directory
	else{
		return -ENOENT;
	}
	return 0;
}
Ejemplo n.º 14
0
 /**
  * Initialize the function with the workspace(s).
  * @param function :: A function to initialize.
  */
 void MultiDomainCreator::initFunction(API::IFunction_sptr function)
 {
   auto mdFunction = boost::dynamic_pointer_cast<API::MultiDomainFunction>(function);
   if ( mdFunction )
   {
     // loop over member functions and init them
     for(size_t iFun = 0; iFun < mdFunction->nFunctions(); ++iFun)
     {
       std::vector<size_t> domainIndices;
       // get domain indices for this function
       mdFunction->getDomainIndices(iFun,m_creators.size(),domainIndices);
       if ( !domainIndices.empty() )
       {
         if ( domainIndices.size() != 1 )
         {
           g_log.warning() << "Function #" << iFun << " applies to multiple domains." << std::endl;
           g_log.warning() << "Only one of the domains is used to set workspace." << std::endl;
         }
         size_t index = domainIndices[0];
         if ( index >= m_creators.size() )
         {
           std::stringstream msg;
           msg << "Domain index is out of range. (Function #" << iFun << ")";
           throw std::runtime_error(msg.str());
         }
         m_creators[index]->initFunction( mdFunction->getFunction(iFun) );
       }
       else
       {
         g_log.warning() << "Function #" << iFun << " doesn't apply to any domain" << std::endl;
       }
     }
   }
   else
   {
     IDomainCreator::initFunction(function);
   }
 }
Ejemplo n.º 15
0
Q2PPiecewiseLinearSink::Q2PPiecewiseLinearSink(const InputParameters & parameters)
  : IntegratedBC(parameters),
    _use_mobility(getParam<bool>("use_mobility")),
    _use_relperm(getParam<bool>("use_relperm")),
    _sink_func(getParam<std::vector<Real>>("pressures"),
               getParam<std::vector<Real>>("bare_fluxes")),
    _m_func(getFunction("multiplying_fcn")),
    _density(getUserObject<RichardsDensity>("fluid_density")),
    _relperm(getUserObject<RichardsRelPerm>("fluid_relperm")),
    _other_var_nodal(coupledNodalValue("other_var")),
    _other_var_num(coupled("other_var")),
    _var_is_pp(getParam<bool>("var_is_porepressure")),
    _viscosity(getParam<Real>("fluid_viscosity")),
    _permeability(getMaterialProperty<RealTensorValue>("permeability")),
    _num_nodes(0),
    _pp(0),
    _sat(0),
    _nodal_density(0),
    _dnodal_density_dp(0),
    _nodal_relperm(0),
    _dnodal_relperm_ds(0)
{
}
Ejemplo n.º 16
0
void DOMTransaction::callFunction(const char* propertyName)
{
    if (!m_undoManager || !m_undoManager->document())
        return;

    Frame* frame = m_undoManager->document()->frame();
    if (!frame || !frame->script()->canExecuteScripts(AboutToExecuteScript))
        return;

    v8::Handle<v8::Function> function = getFunction(propertyName);
    if (function.IsEmpty())
        return;

    v8::Local<v8::Context> v8Context = m_worldContext.adjustedContext(frame->script());
    if (v8Context.IsEmpty())
        return;

    v8::Handle<v8::Object> receiver = v8::Handle<v8::Object>::Cast(toV8(m_undoManager));
    if (receiver.IsEmpty())
        return;
    v8::Handle<v8::Value> parameters[0] = { };
    frame->script()->callFunction(function, receiver, 0, parameters);
}
Ejemplo n.º 17
0
void CEvaluator::visit ( CApply* e )
{
	CFunction *f= getFunction(e->getFunction());
	if(!f) {
		throw(EvaluationError("function \""+e->getFunction()+"\" is not defined."));
	}
	if(!f || (f->getNumArguments() != e->getNumArguments())) {
		throw(EvaluationError("number of arguments for function \""+e->getFunction()+"\" does not match declaration."));
	}
	map<string,int> *newContext= new map<string,int>();
	for(int i=0; i<f->getNumArguments();i++) {
		string tmp=f->getArgument(i)->getName();
		e->getArgument(i)->accept(this);
		int value=result;
	//	cout << "  "<< tmp <<"="<<value<<endl;
		(*newContext)[tmp]=value;
	}
	pushContext(newContext);
	CExpr *e2 = f->getExpression();
	e2->accept(this);
	delete popContext();
	//return result;
}
Ejemplo n.º 18
0
TensorMechanicsMaterial::TensorMechanicsMaterial(const std::string & name,
                                                 InputParameters parameters) :
    Material(name, parameters),
    _grad_disp_x(coupledGradient("disp_x")),
    _grad_disp_y(coupledGradient("disp_y")),
    _grad_disp_z(_mesh.dimension() == 3 ? coupledGradient("disp_z") : _grad_zero),
    _grad_disp_x_old(_fe_problem.isTransient() ? coupledGradientOld("disp_x") : _grad_zero),
    _grad_disp_y_old(_fe_problem.isTransient() ? coupledGradientOld("disp_y") : _grad_zero),
    _grad_disp_z_old(_fe_problem.isTransient() && _mesh.dimension() == 3 ? coupledGradientOld("disp_z") : _grad_zero),
    _base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : "" ),

    _stress(declareProperty<RankTwoTensor>(_base_name + "stress")),
    _total_strain(declareProperty<RankTwoTensor>(_base_name + "total_strain")),
    _elastic_strain(declareProperty<RankTwoTensor>(_base_name + "elastic_strain")),

    _elasticity_tensor_name(_base_name + "elasticity_tensor"),
    _elasticity_tensor(declareProperty<ElasticityTensorR4>(_elasticity_tensor_name)),

    _Jacobian_mult(declareProperty<ElasticityTensorR4>(_base_name + "Jacobian_mult")),

    _Euler_angles(getParam<Real>("euler_angle_1"),
                  getParam<Real>("euler_angle_2"),
                  getParam<Real>("euler_angle_3")),

    _Cijkl(getParam<std::vector<Real> >("C_ijkl"), (RankFourTensor::FillMethod)(int)getParam<MooseEnum>("fill_method")),
    _prefactor_function(isParamValid("elasticity_tensor_prefactor") ? &getFunction("elasticity_tensor_prefactor") : NULL)
{
  const std::vector<FunctionName> & fcn_names(getParam<std::vector<FunctionName> >("initial_stress"));
  const unsigned num = fcn_names.size();

  if (!(num == 0 || num == 3*3))
    mooseError("Either zero or " << 3*3 << " initial stress functions must be provided to TensorMechanicsMaterial.  You supplied " << num << "\n");

  _initial_stress.resize(num);
  for (unsigned i = 0 ; i < num ; ++i)
    _initial_stress[i] = &getFunctionByName(fcn_names[i]);
}
Ejemplo n.º 19
0
/**
 * Installs function into symbol table
 *
 * @param std::string*				function name
 * @param FunctionType				function type
 * @param std::vector<SymbolType>	list of symbol types
 * @param bool						flag if function is defined or declared
 * @return std::string*		key to the symbol table
 */
std::string *SymbolTable::installFunction(std::string *name, FunctionType type, std::vector<SymbolType> *types, bool defined, std::string &error) {
	// try to find function in table
	FunctionRecord *funRec = getFunction(name);

	if(funRec != (FunctionRecord*) NULL) {	// found
		if(funRec->defined == true or funRec->defined == defined) {
			error = "Function '" + *name + "' already defined";
			return (std::string*) NULL;		// already defined or trying another declaration -> return NULL pointer
		}

		if(funRec->paramsType != *types) {	// mismatch parameter types
			error = "Mismatch parameter types.";
			return (std::string*) NULL;
		}

		if(funRec->type != type) {			// mismatch function type
			error = "Mismatch function type.";
			return (std::string*) NULL;
		}

		funRec->defined = true;	// set defined to true

	} else {	// not found
		funRec = new FunctionRecord;

		funRec->name = name;
		funRec->type = type;
		funRec->key = "fun:" + *name;
		if(types != (std::vector<SymbolType>*) NULL)
			funRec->paramsType = *types;
		funRec->defined = defined;

		funTable.insert(std::pair<std::string, FunctionRecord*>(*name, funRec));
	}

	return name;	// name of the function is key to the table :)
}
Ejemplo n.º 20
0
/// Derivatives of function with respect to active parameters
void MultiDomainFunction::functionDeriv(const FunctionDomain &domain,
                                        Jacobian &jacobian) {
  // works only on CompositeDomain
  if (!dynamic_cast<const CompositeDomain *>(&domain)) {
    throw std::invalid_argument(
        "Non-CompositeDomain passed to MultiDomainFunction.");
  }

  if (getAttribute("NumDeriv").asBool()) {
    calNumericalDeriv(domain, jacobian);
  } else {
    const CompositeDomain &cd = dynamic_cast<const CompositeDomain &>(domain);
    // domain must not have less parts than m_maxIndex
    if (cd.getNParts() < m_maxIndex) {
      throw std::invalid_argument(
          "CompositeDomain has too few parts (" +
          boost::lexical_cast<std::string>(cd.getNParts()) +
          ") for MultiDomainFunction (max index " +
          boost::lexical_cast<std::string>(m_maxIndex) + ").");
    }

    countValueOffsets(cd);
    // evaluate member functions derivatives
    for (size_t iFun = 0; iFun < nFunctions(); ++iFun) {
      // find the domains member function must be applied to
      std::vector<size_t> domains;
      getDomainIndices(iFun, cd.getNParts(), domains);

      for (auto i = domains.begin(); i != domains.end(); ++i) {
        const FunctionDomain &d = cd.getDomain(*i);
        PartialJacobian J(&jacobian, m_valueOffsets[*i], paramOffset(iFun));
        getFunction(iFun)->functionDeriv(d, J);
      }
    }
  }
}
Ejemplo n.º 21
0
/* this is the ftp server function */
int ftp(int fd, int hit) {
	int j, file_fd, filedesc;
	long i, ret, len;
	char * fstr;
	char buffer[BUFSIZE + 1] = {0};

	ret = read(fd, buffer, BUFSIZE); // read FTP request

	if (ret == 0 || ret == -1) { /* read failure stop now */
		close(fd);
		return 1;
	}
	if (ret > 0 && ret < BUFSIZE) /* return code is valid chars */
		buffer[ret] = 0; /* terminate the buffer */
	else
		buffer[0] = 0;

	for (i = 0; i < ret; i++) /* remove CF and LF characters */
		if (buffer[i] == '\r' || buffer[i] == '\n')
			buffer[i] = '*';

	printf("LOG request %s - hit %d\n", buffer, hit);

	/* null terminate after the second space to ignore extra stuff */
	/*for (i = 4; i < BUFSIZE; i++) {
		if (buffer[i] == ' ') { // string is "GET URL " +lots of other stuff
			buffer[i] = 0;
			break;
		}
	}*/

	if (!strncmp(buffer, "get ", 4)) {
		// GET
		if((buffer[5] == '.' && buffer[6] == '.') || buffer[5] == '|') {
			sprintf(buffer, "%s", "negado");
			write(fd,buffer,BUFSIZE);
			close(fd);
		} else {
			getFunction(fd, &buffer[4]);
		}
	} else if (!strncmp(buffer, "put ", 4)) {
		// PUT
		putFunction(fd,&buffer[5]);
	} else if (!strncmp(buffer, "ls ", 3)) {
		// LS
		lsFunction(fd,&buffer[3]);
	} else if (!strncmp(buffer, "mget ", 4)) {
		// MGET
		mgetFunction(fd, &buffer[5]);
	} else if (!strncmp(buffer, "cd ", 3)) {
		// CD
		cdFunction(fd,&buffer[3]);
	} else if (!strncmp(buffer, "reset ", 5)) {
		// RESET CD
		cdResetFunction(fd);
	}

	sleep(1); /* allow socket to drain before signalling the socket is closed */
	close(fd);
	return 0;
}
Ejemplo n.º 22
0
DiffTensorKernel::DiffTensorKernel(const InputParameters & parameters)
  : Kernel(parameters), _k_comp(getFunction("conductivity"))
{
}
Ejemplo n.º 23
0
AnisoHeatConductionMaterial::AnisoHeatConductionMaterial(const InputParameters & parameters)
  : Material(parameters),

    _has_temp(isCoupled("temp")),
    _temperature(_has_temp ? coupledValue("temp") : _zero),

    _my_thermal_conductivity_x(
        isParamValid("thermal_conductivity_x") ? getParam<Real>("thermal_conductivity_x") : -1),
    _my_thermal_conductivity_y(
        isParamValid("thermal_conductivity_y") ? getParam<Real>("thermal_conductivity_y") : -1),
    _my_thermal_conductivity_z(
        isParamValid("thermal_conductivity_z") ? getParam<Real>("thermal_conductivity_z") : -1),

    _thermal_conductivity_x_pp(isParamValid("thermal_conductivity_x_pp")
                                   ? &getPostprocessorValue("thermal_conductivity_x_pp")
                                   : NULL),
    _thermal_conductivity_y_pp(isParamValid("thermal_conductivity_y_pp")
                                   ? &getPostprocessorValue("thermal_conductivity_y_pp")
                                   : NULL),
    _thermal_conductivity_z_pp(isParamValid("thermal_conductivity_z_pp")
                                   ? &getPostprocessorValue("thermal_conductivity_z_pp")
                                   : NULL),

    _my_specific_heat(isParamValid("specific_heat") ? getParam<Real>("specific_heat") : 0),

    _thermal_conductivity_x(&declareProperty<Real>("thermal_conductivity_x")),
    _thermal_conductivity_x_dT(&declareProperty<Real>("thermal_conductivity_x_dT")),
    _thermal_conductivity_y(isParamValid("thermal_conductivity_y") ||
                                    isParamValid("thermal_conductivity_y_pp")
                                ? &declareProperty<Real>("thermal_conductivity_y")
                                : NULL),
    _thermal_conductivity_y_dT(
        _thermal_conductivity_y ? &declareProperty<Real>("thermal_conductivity_y_dT") : NULL),
    _thermal_conductivity_z(isParamValid("thermal_conductivity_z") ||
                                    isParamValid("thermal_conductivity_z_pp")
                                ? &declareProperty<Real>("thermal_conductivity_z")
                                : NULL),
    _thermal_conductivity_z_dT(
        _thermal_conductivity_z ? &declareProperty<Real>("thermal_conductivity_z_dT") : NULL),

    _specific_heat(declareProperty<Real>("specific_heat")),
    _specific_heat_temperature_function(
        getParam<FunctionName>("specific_heat_temperature_function") != ""
            ? &getFunction("specific_heat_temperature_function")
            : NULL)
{
  bool k_x = isParamValid("thermal_conductivity_x") || (NULL != _thermal_conductivity_x_pp);
  bool k_y = isParamValid("thermal_conductivity_y") || (NULL != _thermal_conductivity_y_pp);
  bool k_z = isParamValid("thermal_conductivity_z") || (NULL != _thermal_conductivity_z_pp);

  if (!k_x || (_subproblem.mesh().dimension() > 1 && !k_y) ||
      (_subproblem.mesh().dimension() > 2 && !k_z))
  {
    mooseError("Incomplete set of orthotropic thermal conductivity parameters");
  }
  if (_specific_heat_temperature_function && !_has_temp)
  {
    mooseError("Must couple with temperature if using specific heat function");
  }
  if (isParamValid("specific_heat") && _specific_heat_temperature_function)
  {
    mooseError("Cannot define both specific heat and specific heat temperature function");
  }

  k_x = isParamValid("thermal_conductivity_x") && (NULL != _thermal_conductivity_x_pp);
  k_y = isParamValid("thermal_conductivity_y") && (NULL != _thermal_conductivity_y_pp);
  k_z = isParamValid("thermal_conductivity_z") && (NULL != _thermal_conductivity_z_pp);
  if (k_x || k_y || k_z)
  {
    mooseError("Cannot define thermal conductivity value and Postprocessor");
  }
}
Ejemplo n.º 24
0
FunctionIC::FunctionIC(const std::string & name, InputParameters parameters) :
    InitialCondition(name, parameters),
    _func(getFunction("function"))
{
}
Ejemplo n.º 25
0
MyFunctionIC::MyFunctionIC(const InputParameters & parameters) :
    FunctionIC(parameters),
    _func(getFunction("function")),
    _input_real_value(getParam<Real>("real_input"))
{
}
Ejemplo n.º 26
0
CoefDiffusion::CoefDiffusion(const InputParameters & parameters)
  : Kernel(parameters),
    _coef(getParam<Real>("coef")),
    _func(parameters.isParamValid("function") ? &getFunction("function") : NULL)
{
}
Ejemplo n.º 27
0
std::string VertexProgramDecompiler::Decompile()
{
	for (unsigned i = 0; i < PF_PARAM_COUNT; i++)
		m_parr.params[i].clear();
	m_instr_count = 0;

	for (int i = 0; i < m_max_instr_count; ++i)
	{
		m_instructions[i].reset();
	}

	bool is_has_BRA = false;

	for (u32 i = 1; m_instr_count < m_max_instr_count; m_instr_count++)
	{
		m_cur_instr = &m_instructions[m_instr_count];

		if (is_has_BRA)
		{
			d3.HEX = m_data[i];
			i += 4;
		}
		else
		{
			d1.HEX = m_data[i++];

			switch (d1.sca_opcode)
			{
			case 0x08: //BRA
				LOG_ERROR(RSX, "BRA found. Please report to RPCS3 team.");
				is_has_BRA = true;
				m_jump_lvls.clear();
				d3.HEX = m_data[++i];
				i += 4;
				break;

			case 0x09: //BRI
				d2.HEX = m_data[i++];
				d3.HEX = m_data[i];
				i += 2;
				m_jump_lvls.emplace(GetAddr());
				break;

			default:
				d3.HEX = m_data[++i];
				i += 2;
				break;
			}
		}

		if (d3.end)
		{
			m_instr_count++;

			if (i < m_data.size())
			{
				LOG_ERROR(RSX, "Program end before buffer end.");
			}

			break;
		}
	}

	uint jump_position = 0;

	if (is_has_BRA || !m_jump_lvls.empty())
	{
		m_cur_instr = &m_instructions[0];
		AddCode("int jump_position = 0;");
		AddCode("while (true)");
		AddCode("{");
		m_cur_instr->open_scopes++;

		AddCode(fmt::format("if (jump_position <= %u)", jump_position++));
		AddCode("{");
		m_cur_instr->open_scopes++;
	}

	for (u32 i = 0; i < m_instr_count; ++i)
	{
		m_cur_instr = &m_instructions[i];

		d0.HEX = m_data[i * 4 + 0];
		d1.HEX = m_data[i * 4 + 1];
		d2.HEX = m_data[i * 4 + 2];
		d3.HEX = m_data[i * 4 + 3];

		src[0].src0l = d2.src0l;
		src[0].src0h = d1.src0h;
		src[1].src1 = d2.src1;
		src[2].src2l = d3.src2l;
		src[2].src2h = d2.src2h;

		if (i && (is_has_BRA || std::find(m_jump_lvls.begin(), m_jump_lvls.end(), i) != m_jump_lvls.end()))
		{
			m_cur_instr->close_scopes++;
			AddCode("}");
			AddCode("");

			AddCode(fmt::format("if (jump_position <= %u)", jump_position++));
			AddCode("{");
			m_cur_instr->open_scopes++;
		}

		if (!d1.sca_opcode && !d1.vec_opcode)
		{
			AddCode("//nop");
		}

		switch (d1.sca_opcode)
		{
		case RSX_SCA_OPCODE_NOP: break;
		case RSX_SCA_OPCODE_MOV: SetDSTSca("$s"); break;
		case RSX_SCA_OPCODE_RCP: SetDSTSca("(1.0 / $s)"); break;
		case RSX_SCA_OPCODE_RCC: SetDSTSca("clamp(1.0 / $s, 5.42101e-20, 1.884467e19)"); break;
		case RSX_SCA_OPCODE_RSQ: SetDSTSca("(1.f / sqrt($s))"); break;
		case RSX_SCA_OPCODE_EXP: SetDSTSca("exp($s)"); break;
		case RSX_SCA_OPCODE_LOG: SetDSTSca("log($s)"); break;
		case RSX_SCA_OPCODE_LIT: SetDSTSca(getFloatTypeName(4) + "(1.0, $s.x, ($s.x > 0.0 ? exp($s.w * log2($s.y)) : 0.0), 1.0)"); break;
		case RSX_SCA_OPCODE_BRA:
		{
			AddCode("$if ($cond)");
			AddCode("{");
			m_cur_instr->open_scopes++;
			AddCode("jump_position = $a$am;");
			AddCode("continue;");
			m_cur_instr->close_scopes++;
			AddCode("}");
		}
		break;
		case RSX_SCA_OPCODE_BRI: // works differently (BRI o[1].x(TR) L0;)
		{
			u32 jump_position = 1;

			if (is_has_BRA)
			{
				jump_position = GetAddr();
			}
			else
			{
				u32 addr = GetAddr();

				for (auto pos : m_jump_lvls)
				{
					if (addr == pos)
						break;

					++jump_position;
				}
			}

			AddCode("$ifcond ");
			AddCode("{");
			m_cur_instr->open_scopes++;
			AddCode(fmt::format("jump_position = %u;", jump_position));
			AddCode("continue;");
			m_cur_instr->close_scopes++;
			AddCode("}");
		}
		break;
		case RSX_SCA_OPCODE_CAL:
			// works same as BRI
			AddCode("$ifcond $f(); //CAL");
			break;
		case RSX_SCA_OPCODE_CLI:
			// works same as BRI
			AddCode("$ifcond $f(); //CLI");
			break;
		case RSX_SCA_OPCODE_RET:
			// works like BRI but shorter (RET o[1].x(TR);)
			AddCode("$ifcond return;");
			break;
		case RSX_SCA_OPCODE_LG2: SetDSTSca("log2($s)"); break;
		case RSX_SCA_OPCODE_EX2: SetDSTSca("exp2($s)"); break;
		case RSX_SCA_OPCODE_SIN: SetDSTSca("sin($s)"); break;
		case RSX_SCA_OPCODE_COS: SetDSTSca("cos($s)"); break;
		case RSX_SCA_OPCODE_BRB:
			// works differently (BRB o[1].x !b0, L0;)
			LOG_ERROR(RSX, "Unimplemented sca_opcode BRB");
			break;
		case RSX_SCA_OPCODE_CLB: break;
			// works same as BRB
			LOG_ERROR(RSX, "Unimplemented sca_opcode CLB");
			break;
		case RSX_SCA_OPCODE_PSH: break;
			// works differently (PSH o[1].x A0;)
			LOG_ERROR(RSX, "Unimplemented sca_opcode PSH");
			break;
		case RSX_SCA_OPCODE_POP: break;
			// works differently (POP o[1].x;)
			LOG_ERROR(RSX, "Unimplemented sca_opcode POP");
			break;

		default:
			AddCode(fmt::format("//Unknown vp sca_opcode 0x%x", u32{ d1.sca_opcode }));
			LOG_ERROR(RSX, "Unknown vp sca_opcode 0x%x", u32{ d1.sca_opcode });
			Emu.Pause();
			break;
		}

		switch (d1.vec_opcode)
		{
		case RSX_VEC_OPCODE_NOP: break;
		case RSX_VEC_OPCODE_MOV: SetDSTVec("$0"); break;
		case RSX_VEC_OPCODE_MUL: SetDSTVec("($0 * $1)"); break;
		case RSX_VEC_OPCODE_ADD: SetDSTVec("($0 + $2)"); break;
		case RSX_VEC_OPCODE_MAD: SetDSTVec("($0 * $1 + $2)"); break;
		case RSX_VEC_OPCODE_DP3: SetDSTVec(getFunction(FUNCTION::FUNCTION_DP3)); break;
		case RSX_VEC_OPCODE_DPH: SetDSTVec(getFunction(FUNCTION::FUNCTION_DPH)); break;
		case RSX_VEC_OPCODE_DP4: SetDSTVec(getFunction(FUNCTION::FUNCTION_DP4)); break;
		case RSX_VEC_OPCODE_DST: SetDSTVec("vec4(distance($0, $1))"); break;
		case RSX_VEC_OPCODE_MIN: SetDSTVec("min($0, $1)"); break;
		case RSX_VEC_OPCODE_MAX: SetDSTVec("max($0, $1)"); break;
		case RSX_VEC_OPCODE_SLT: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SLT, "$0", "$1") + ")"); break;
		case RSX_VEC_OPCODE_SGE: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SGE, "$0", "$1") + ")"); break;
			// Note: It looks like ARL opcode ignore input/output swizzle mask (SH3)
		case RSX_VEC_OPCODE_ARL: AddCode("$ifcond $awm = " + getIntTypeName(4) + "($0);");  break;
		case RSX_VEC_OPCODE_FRC: SetDSTVec(getFunction(FUNCTION::FUNCTION_FRACT)); break;
		case RSX_VEC_OPCODE_FLR: SetDSTVec("floor($0)"); break;
		case RSX_VEC_OPCODE_SEQ: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SEQ, "$0", "$1") + ")"); break;
		case RSX_VEC_OPCODE_SFL: SetDSTVec(getFunction(FUNCTION::FUNCTION_SFL)); break;
		case RSX_VEC_OPCODE_SGT: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SGT, "$0", "$1") + ")"); break;
		case RSX_VEC_OPCODE_SLE: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SLE, "$0", "$1") + ")"); break;
		case RSX_VEC_OPCODE_SNE: SetDSTVec(getFloatTypeName(4) + "(" + compareFunction(COMPARE::FUNCTION_SNE, "$0", "$1") + ")"); break;
		case RSX_VEC_OPCODE_STR: SetDSTVec(getFunction(FUNCTION::FUNCTION_STR)); break;
		case RSX_VEC_OPCODE_SSG: SetDSTVec("sign($0)"); break;
		case RSX_VEC_OPCODE_TXL: SetDSTVec("texture($t, $0.xy)"); break;

		default:
			AddCode(fmt::format("//Unknown vp opcode 0x%x", u32{ d1.vec_opcode }));
			LOG_ERROR(RSX, "Unknown vp opcode 0x%x", u32{ d1.vec_opcode });
			Emu.Pause();
			break;
		}
	}

	if (is_has_BRA || !m_jump_lvls.empty())
	{
		m_cur_instr = &m_instructions[m_instr_count - 1];
		m_cur_instr->close_scopes++;
		AddCode("}");
		AddCode("break;");
		m_cur_instr->close_scopes++;
		AddCode("}");
	}

	std::string result = BuildCode();

	m_jump_lvls.clear();
	m_body.clear();
	if (m_funcs.size() > 2)
	{
		m_funcs.erase(m_funcs.begin() + 2, m_funcs.end());
	}
	return result;
}
Ejemplo n.º 28
0
/// Executes the algorithm
void PoldiFitPeaks2D::exec() {
  std::vector<PoldiPeakCollection_sptr> peakCollections =
      getPeakCollectionsFromInput();

  // Try to setup the 2D data and poldi instrument
  MatrixWorkspace_sptr ws = getProperty("InputWorkspace");
  setDeltaTFromWorkspace(ws);

  setPoldiInstrument(boost::make_shared<PoldiInstrumentAdapter>(ws));
  setTimeTransformerFromInstrument(m_poldiInstrument);

  // If a profile function is selected, set it on the peak collections.
  Property *profileFunctionProperty =
      getPointerToProperty("PeakProfileFunction");
  if (!profileFunctionProperty->isDefault()) {
    for (auto &peakCollection : peakCollections) {
      peakCollection->setProfileFunctionName(profileFunctionProperty->value());
    }
  }

  // Perform 2D-fit and return Fit algorithm to extract various information
  IAlgorithm_sptr fitAlgorithm = calculateSpectrum(peakCollections, ws);

  // The FitFunction is used to generate...
  IFunction_sptr fitFunction = getFunction(fitAlgorithm);

  // ...a calculated 1D-spectrum...
  MatrixWorkspace_sptr outWs1D = get1DSpectrum(fitFunction, ws);

  // ...a vector of peak collections.
  std::vector<PoldiPeakCollection_sptr> integralPeaks =
      getCountPeakCollections(fitFunction);

  for (size_t i = 0; i < peakCollections.size(); ++i) {
    assignMillerIndices(peakCollections[i], integralPeaks[i]);
  }

  // Get the calculated 2D workspace
  setProperty("OutputWorkspace", getWorkspace(fitAlgorithm));

  // Set the output peaks depending on whether it's one or more workspaces
  if (integralPeaks.size() == 1) {
    setProperty("RefinedPoldiPeakWorkspace",
                integralPeaks.front()->asTableWorkspace());
  } else {
    WorkspaceGroup_sptr peaksGroup = boost::make_shared<WorkspaceGroup>();

    for (auto &integralPeak : integralPeaks) {
      peaksGroup->addWorkspace(integralPeak->asTableWorkspace());
    }

    setProperty("RefinedPoldiPeakWorkspace", peaksGroup);
  }

  // Set the 1D-spectrum output
  setProperty("Calculated1DSpectrum", outWs1D);

  // If it was a PawleyFit, also produce one or more cell parameter tables.
  bool isPawleyFit = getProperty("PawleyFit");
  if (isPawleyFit) {
    Poldi2DFunction_sptr poldi2DFunction =
        boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);

    std::vector<ITableWorkspace_sptr> cells;

    if (poldi2DFunction) {
      for (size_t i = 0; i < poldi2DFunction->nFunctions(); ++i) {
        try {
          ITableWorkspace_sptr cell =
              getRefinedCellParameters(poldi2DFunction->getFunction(i));
          cells.push_back(cell);
        } catch (const std::invalid_argument &) {
          // do nothing
        }
      }

      if (cells.size() == 1) {
        setProperty("RefinedCellParameters", cells.front());
      } else {
        WorkspaceGroup_sptr cellsGroup = boost::make_shared<WorkspaceGroup>();

        for (auto &cell : cells) {
          cellsGroup->addWorkspace(cell);
        }

        setProperty("RefinedCellParameters", cellsGroup);
      }

    } else {
      g_log.warning() << "Warning: Cell parameter table is empty.";
    }
  }

  // Optionally output the raw fitting parameters.
  Property *rawFitParameters = getPointerToProperty("RawFitParameters");
  if (!rawFitParameters->isDefault()) {
    ITableWorkspace_sptr parameters =
        fitAlgorithm->getProperty("OutputParameters");
    setProperty("RawFitParameters", parameters);
  }
}
Ejemplo n.º 29
0
GenRet DoWhileStmt::codegen()
{
  GenInfo* info    = gGenInfo;
  FILE*    outfile = info->cfile;
  GenRet   ret;

  codegenStmt(this);

  if (outfile)
  {
    codegenOrderIndependence();

    info->cStatements.push_back("do ");

    if (this != getFunction()->body)
      info->cStatements.push_back("{\n");

    body.codegen("");

    std::string ftr= "} while (" + codegenValue(condExprGet()).c + ");\n";

    info->cStatements.push_back(ftr);
  }

  else
  {
#ifdef HAVE_LLVM
    llvm::Function*   func             = info->builder->GetInsertBlock()->getParent();

    llvm::BasicBlock* blockStmtBody    = NULL;
    llvm::BasicBlock* blockStmtEnd     = NULL;
    llvm::BasicBlock* blockStmtEndCond = NULL;

    getFunction()->codegenUniqueNum++;

    blockStmtBody = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_body"));
    blockStmtEnd  = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_end"));

    info->builder->CreateBr(blockStmtBody);

    // Now add the body.
    func->getBasicBlockList().push_back(blockStmtBody);

    info->builder->SetInsertPoint(blockStmtBody);
    info->lvt->addLayer();

    body.codegen("");

    info->lvt->removeLayer();

    // Add the condition block.
    blockStmtEndCond = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_end_cond"));

    func->getBasicBlockList().push_back(blockStmtEndCond);

    // Insert an explicit branch from the body block to the loop condition.
    info->builder->CreateBr(blockStmtEndCond);

    // set insert point
    info->builder->SetInsertPoint(blockStmtEndCond);

    GenRet       condValueRet = codegenValue(condExprGet());
    llvm::Value* condValue    = condValueRet.val;

    if (condValue->getType() != llvm::Type::getInt1Ty(info->module->getContext()))
    {
      condValue = info->builder->CreateICmpNE(condValue,
                                              llvm::ConstantInt::get(condValue->getType(), 0),
                                              FNAME("condition"));
    }

    info->builder->CreateCondBr(condValue, blockStmtBody, blockStmtEnd);

    func->getBasicBlockList().push_back(blockStmtEnd);

    info->builder->SetInsertPoint(blockStmtEnd);

    if (blockStmtBody   ) INT_ASSERT(blockStmtBody->getParent()    == func);
    if (blockStmtEndCond) INT_ASSERT(blockStmtEndCond->getParent() == func);
    if (blockStmtEnd    ) INT_ASSERT(blockStmtEnd->getParent()     == func);
#endif
  }

  return ret;
}
Ejemplo n.º 30
0
 void visitLoop(Loop* loop) {
   // We accumulate all the code we can move out, and will place it
   // in a block just preceding the loop.
   std::vector<Expression*> movedCode;
   // Accumulate effects of things we can't move out - things
   // we move out later must cross them, so we must verify it
   // is ok to do so.
   EffectAnalyzer effectsSoFar(getPassOptions());
   // The loop's total effects also matter. For example, a store
   // in the loop means we can't move a load outside.
   // FIXME: we look at the loop "tail" area too, after the last
   //        possible branch back, which can cause false positives
   //        for bad effect interactions.
   EffectAnalyzer loopEffects(getPassOptions(), loop);
   // Note all the sets in each loop, and how many per index. Currently
   // EffectAnalyzer can't do that, and we need it to know if we
   // can move a set out of the loop (if there is another set
   // still there, we can't). Another possible option here is for
   // LocalGraph to track interfering sets. TODO
   // FIXME: also the loop tail issue from above.
   auto numLocals = getFunction()->getNumLocals();
   std::vector<Index> numSetsForIndex(numLocals);
   std::fill(numSetsForIndex.begin(), numSetsForIndex.end(), 0);
   LoopSets loopSets;
   {
     FindAll<SetLocal> finder(loop);
     for (auto* set : finder.list) {
       numSetsForIndex[set->index]++;
       loopSets.insert(set);
     }
   }
   // Walk along the loop entrance, while all the code there
   // is executed unconditionally. That is the code we want to
   // move out - anything that might or might not be executed
   // may be best left alone anyhow.
   std::vector<Expression**> work;
   work.push_back(&loop->body);
   while (!work.empty()) {
     auto** currp = work.back();
     work.pop_back();
     auto* curr = *currp;
     // Look into blocks.
     if (auto* block = curr->dynCast<Block>()) {
       auto& list = block->list;
       Index i = list.size();
       while (i > 0) {
         i--;
         work.push_back(&list[i]);
       }
       continue;
       // Note that if the block had a merge at the end, we would have seen
       // a branch to it anyhow, so we would stop before that point anyhow.
     }
     // If this may branch, we are done.
     EffectAnalyzer effects(getPassOptions(), curr);
     if (effects.branches) {
       break;
     }
     if (interestingToMove(curr)) {
       // Let's see if we can move this out.
       // Global side effects would prevent this - we might end up
       // executing them just once.
       // And we must also move across anything not moved out already,
       // so check for issues there too.
       // The rest of the loop's effects matter too, we must also
       // take into account global state like interacting loads and
       // stores.
       bool unsafeToMove = effects.hasGlobalSideEffects() ||
                           effectsSoFar.invalidates(effects) ||
                           (effects.noticesGlobalSideEffects() &&
                            loopEffects.hasGlobalSideEffects());
       if (!unsafeToMove) {
         // So far so good. Check if our local dependencies are all
         // outside of the loop, in which case everything is good -
         // either they are before the loop and constant for us, or
         // they are after and don't matter.
         if (effects.localsRead.empty() || !hasGetDependingOnLoopSet(curr, loopSets)) {
           // We have checked if our gets are influenced by sets in the loop, and
           // must also check if our sets interfere with them. To do so, assume
           // temporarily that we are moving curr out; see if any sets remain for
           // its indexes.
           FindAll<SetLocal> currSets(curr);
           for (auto* set : currSets.list) {
             assert(numSetsForIndex[set->index] > 0);
             numSetsForIndex[set->index]--;
           }
           bool canMove = true;
           for (auto* set : currSets.list) {
             if (numSetsForIndex[set->index] > 0) {
               canMove = false;
               break;
             }
           }
           if (!canMove) {
             // We failed to move the code, undo those changes.
             for (auto* set : currSets.list) {
               numSetsForIndex[set->index]++;
             }
           } else {
             // We can move it! Leave the changes, move the code, and update
             // loopSets.
             movedCode.push_back(curr);
             *currp = Builder(*getModule()).makeNop();
             for (auto* set : currSets.list) {
               loopSets.erase(set);
             }
             continue;
           }
         }
       }
     }
     // We did not move this item. Accumulate its effects.
     effectsSoFar.mergeIn(effects);
   }
   // If we moved the code out, finish up by emitting it
   // outside of the loop.
   // Note that this works with nested loops - after moving outside
   // of an inner loop, we can encounter it again in an outer loop,
   // and move it further outside, without requiring any extra pass.
   if (!movedCode.empty()) {
     // Finish the moving by emitting the code outside.
     Builder builder(*getModule());
     auto* ret = builder.makeBlock(movedCode);
     ret->list.push_back(loop);
     ret->finalize(loop->type);
     replaceCurrent(ret);
     // Note that we do not need to modify the localGraph - we keep
     // each get in a position to be influenced by exactly the same
     // sets as before.
   }
 }