void SpringLayout::updateLayout(const MFUnrecComponentPtr* Components, const Component* ParentComponent) const
{
	Pnt2f ParentInsetsTopLeft, ParentInsetsBottomRight;
	dynamic_cast<const ComponentContainer*>(ParentComponent)->getInsideInsetsBounds(ParentInsetsTopLeft, ParentInsetsBottomRight);
    
    const_cast<SpringLayout*>(this)->setParent(const_cast<ComponentContainer*>(dynamic_cast<const
                                                                         ComponentContainer*>(ParentComponent)));
    
    SpringLayoutConstraintsRefPtr MyBoundsConstraints =
        getConstraint(const_cast<Component*>(ParentComponent));
    
    getDecycledSpring(MyBoundsConstraints->getX())->setValue(ParentInsetsTopLeft.x());
    getDecycledSpring(MyBoundsConstraints->getY())->setValue(ParentInsetsTopLeft.y());
    getDecycledSpring(MyBoundsConstraints->getWidth())->setValue( ParentInsetsBottomRight.x() - ParentInsetsTopLeft.x() );
    getDecycledSpring(MyBoundsConstraints->getHeight())->setValue( ParentInsetsBottomRight.y() - ParentInsetsTopLeft.y() );
    
    for (UInt32 i(0) ; i < Components->size() ; i++)
    {
        SpringLayoutConstraintsRefPtr TheConstraints = getConstraint( (*Components)[i] );
        Real32 x = getDecycledSpring(TheConstraints->getX())->getValue();
        Real32 y = getDecycledSpring(TheConstraints->getY())->getValue();
        Real32 width = getDecycledSpring(TheConstraints->getWidth())->getValue();
        Real32 height = getDecycledSpring(TheConstraints->getHeight())->getValue();
        
            (*Components)[i]->setPosition(Pnt2f(x,y));
            (*Components)[i]->setSize(Vec2f(width, height));
     }
}
示例#2
0
/*--------------------------- PLAYER INTERFACE */
void Creature::enterTurn()
{
	//Creature's turn-based constraints
	changeAttack({getConstraint(CC_TURN_ATTACK_CHANGE)});
	changeHealth({getConstraint(CC_TURN_HEALTH_CHANGE)});
	changeShield({getConstraint(CC_TURN_SHIELD_CHANGE)});
}
示例#3
0
    void MatchCreature::set(const btTransform& at) {
        getBodyPart(HEAD).setId(HEAD);
        getBodyPart(HEAD).setName("Head");
        getBodyPart(HEAD).setParentId(Creature::B_NONE);
        getBodyPart(HEAD).setShape(BodyPart::S_SPHERE);
        getBodyPart(HEAD).setSize(1.0, 1.0, 1.0);
        getBodyPart(HEAD).setMass(1.0);

        getBodyPart(STICK).setId(STICK);
        getBodyPart(STICK).setName("Stick");
        getBodyPart(STICK).setParentId(HEAD);
        getBodyPart(STICK).setShape(BodyPart::S_CAPSULE_X);
        getBodyPart(STICK).setSize(0.2, 2.0, 0.2);
        
        getBodyPart(STICK).setMass(1.5);

        getConstraint(NECK).setId(NECK);
        getConstraint(NECK).setType(Constraint::CT_CONE_TWIST);
        getConstraint(NECK).setName("Neck");
        getConstraint(NECK).setIdBodyA(getBodyPart(HEAD).getId());
        getConstraint(NECK).setIdBodyB(getBodyPart(STICK).getId());
        getConstraint(NECK).setConnectionA(Constraint::SPHERE_BOTTOM);
        getConstraint(NECK).setConnectionB(Constraint::CYLINDER_R3_FRONT);
        getConstraint(NECK).setConeSwingX(0);
        getConstraint(NECK).setConeTwistY(M_PI);
        getConstraint(NECK).setConeSwingZ(0);

        Creature::set(at);
    }
void NearestNeighborMapping:: computeMapping()
{
  preciceTrace1("computeMapping()", input()->vertices().size());
  assertion(input().get() != NULL);
  assertion(output().get() != NULL);
  if (getConstraint() == CONSISTENT){
    preciceDebug("Compute consistent mapping");
    size_t verticesSize = output()->vertices().size();
    _vertexIndices.resize(verticesSize);
    const mesh::Mesh::VertexContainer& outputVertices = output()->vertices();
    for ( size_t i=0; i < verticesSize; i++ ){
      const utils::DynVector& coords = outputVertices[i].getCoords();
      query::FindClosestVertex find(coords);
      find(*input());
      assertion(find.hasFound());
      _vertexIndices[i] = find.getClosestVertex().getID();
    }
  }
  else {
    assertion1(getConstraint() == CONSERVATIVE, getConstraint());
    preciceDebug("Compute conservative mapping");
    size_t verticesSize = input()->vertices().size();
    _vertexIndices.resize(verticesSize);
    const mesh::Mesh::VertexContainer& inputVertices = input()->vertices();
    for ( size_t i=0; i < verticesSize; i++ ){
      const utils::DynVector& coords = inputVertices[i].getCoords();
      query::FindClosestVertex find(coords);
      find(*output());
      assertion(find.hasFound());
      _vertexIndices[i] = find.getClosestVertex().getID();
    }
  }
  _hasComputedMapping = true;
}
示例#5
0
    Creature::Creature(int body_parts, int constraints,
            int hidden_layers, int neurons_per_layer)
    :
    _name(""),
    _number_of_body_parts(body_parts),
    _number_of_constraints(constraints),
    _body_parts(new BodyPart*[body_parts]),
    _constraints(new Constraint*[constraints]),
    _neural_network(NULL),
    _initial_position(btVector3(0.0, 0.0, 0.0)),
    _final_position(btVector3(0.0, 0.0, 0.0)),
    _fitness(0.0) {

        for (int i = 0; i < getNumberOfBodyParts(); ++i) {
            setBodyPart(i, new BodyPart());
            getBodyPart(i).setId(i);
            getBodyPart(i).setName("Body Part #" + TO_STRING(i));
        }
        for (int i = 0; i < getNumberOfConstraints(); ++i) {
            setConstraint(i, new Constraint());
            getConstraint(i).setId(i);
            getConstraint(i).setName("Constraint #" + TO_STRING(i));
        }

        _neural_network = new NeuralNetwork(4 * getNumberOfBodyParts(),
                hidden_layers, neurons_per_layer, 3 * (getNumberOfBodyParts() - 1));
        getNeuralNetwork().getInputLayer().setActivationFunction(Neuron::AF_NONE);
        for (int i = 1; i < getNeuralNetwork().getNumberOfLayers(); ++i) {
            getNeuralNetwork().getLayer(i).setActivationFunction(Neuron::AF_TANH);
        }
    }
示例#6
0
void Creature::removeFromBoard()
{
	_isOnBoard = false;
	//Creature's death-based constraints
	changeAttack({getConstraint(CC_DEATH_ATTACK_CHANGE)});
	changeHealth({getConstraint(CC_DEATH_HEALTH_CHANGE)});
	changeShield({getConstraint(CC_DEATH_ATTACK_CHANGE)});
}
示例#7
0
 Constraint * Creature::getConstraint(const BodyPart& a, const BodyPart & b) const {
     for (int i = 0; i < getNumberOfConstraints(); ++i) {
         if ((getConstraint(i).getIdBodyA() == a.getId() && getConstraint(i).getIdBodyB() == b.getId()) ||
                 (getConstraint(i).getIdBodyA() == b.getId() && getConstraint(i).getIdBodyB() == a.getId())) {
             return &getConstraint(i);
         }
     }
     return NULL;
 }
示例#8
0
/** @brief take into account changes of speed (either load or max) */
void CpuCas01::onSpeedChange() {
  lmm_variable_t var = nullptr;
  lmm_element_t elem = nullptr;

    lmm_update_constraint_bound(getModel()->getMaxminSystem(), getConstraint(),
                                coresAmount_ * speed_.scale * speed_.peak);
    while ((var = lmm_get_var_from_cnst(getModel()->getMaxminSystem(), getConstraint(), &elem))) {
      CpuCas01Action *action = static_cast<CpuCas01Action*>(lmm_variable_id(var));

      lmm_update_variable_bound(getModel()->getMaxminSystem(), action->getVariable(), speed_.scale * speed_.peak);
    }

  Cpu::onSpeedChange();
}
示例#9
0
 void Creature::set(const btTransform & at) {
     btTransform offset;
     offset.setIdentity();
     double avg_distance = 0.0;
     double max_height = getMaxHeight();
     for (int i = 0; i < getNumberOfBodyParts(); ++i) {
         avg_distance += (getBodyPart(i).getSizeX() + getBodyPart(i).getSizeY() +
                 getBodyPart(i).getSizeZ()) / 3.0;
     }
     avg_distance *= 2;
     avg_distance /= getNumberOfBodyParts();
     offset.setOrigin(btVector3(0.0, avg_distance, 0.0));
     float circle_fraction = 2 * M_PI / getNumberOfBodyParts();
     float next_fraction = 0.0;
     for (int i = 0; i < getNumberOfBodyParts(); ++i) {
         offset.setIdentity();
         if (getBodyPart(i).isRoot()) {
             offset.setOrigin(btVector3(0, max_height, 0));
         } else {
             offset.setOrigin(btVector3(cos(next_fraction) * avg_distance, max_height, sin(next_fraction) * avg_distance));
         }
         getBodyPart(i).set(at * offset);
         next_fraction += circle_fraction;
     }
     for (int i = 0; i < getNumberOfConstraints(); ++i) {
         getConstraint(i).set(*this);
     }
     calculateMaxTorque();
 }
示例#10
0
    void Creature::toXml(QDomDocument& xml, QDomElement * parent) const {
        QDomElement creature = xml.createElement("Creature");

        //        creature.setAttribute("id", getId());
        creature.setAttribute("name", QString(getName().c_str()));
        //        creature.setAttribute("type", QString::number(getType()));
        creature.setAttribute("body-parts", getNumberOfBodyParts());
        creature.setAttribute("constraints", getNumberOfConstraints());
        creature.setAttribute("hidden-layers", getNeuralNetwork().getNumberOfLayers() - 2);
        creature.setAttribute("neurons-per-layer", getNeuralNetwork().getLayer(1).getNumberOfNeurons());
        creature.setAttribute("initial-position", QString((
                TO_STRING(getInitialPosition().x()) + " ; " +
                TO_STRING(getInitialPosition().y()) + " ; " +
                TO_STRING(getInitialPosition().z())).c_str()));
        creature.setAttribute("final-position", QString((
                TO_STRING(getFinalPosition().x()) + " ; " +
                TO_STRING(getFinalPosition().y()) + " ; " +
                TO_STRING(getFinalPosition().z())).c_str()));
        creature.setAttribute("fitness", getFitness());

        for (int i = 0; i < getNumberOfBodyParts(); ++i) {
            getBodyPart(i).toXml(xml, &creature);
        }
        for (int i = 0; i < getNumberOfConstraints(); ++i) {
            getConstraint(i).toXml(xml, &creature);
        }
        getNeuralNetwork().toXml(xml, &creature);
        if (parent) {
            parent->appendChild(creature);
        } else {

            xml.appendChild(creature);
        }
    }
示例#11
0
void SpringLayout::putConstraint(const UInt32 e, ComponentRefPtr c, LayoutSpringRefPtr s)
{
    if(s != NULL)
    {
        getConstraint(c)->setConstraint(e,s);
    }
}
示例#12
0
 int Creature::getIndex(const Constraint & constraint) const {
     for (int i = 0; i < getNumberOfConstraints(); ++i) {
         if (&getConstraint(i) == &constraint) {
             return i;
         }
     }
     return -1;
 }
示例#13
0
ofxMSACollision* ofxMSAPhysics::makeCollision(ofxMSAParticle *a, ofxMSAParticle *b) {
	if(a==b) return NULL;
	if(getConstraint(a, b, OFX_MSA_CONSTRAINT_TYPE_COLLISION) != NULL) return NULL;	
	ofxMSACollision* c = new ofxMSACollision(a, b);
	addConstraint(c);
	c->release();	// cos addConstraint(c) retains it
	return c;
}
示例#14
0
 void Creature::reset() {
     for (int i = 0; i < getNumberOfConstraints(); ++i) {
         getConstraint(i).reset();
     }
     for (int i = 0; i < getNumberOfBodyParts(); ++i) {
         getBodyPart(i).reset();
     }
 }
示例#15
0
/**
 * Writes a string that can be used in Fit.IFunction to create a copy of this
 * IFunction
 * @return string representation of the function
 */
std::string IFunction::asString() const {
  std::ostringstream ostr;
  ostr << "name=" << this->name();
  // print the attributes
  std::vector<std::string> attr = this->getAttributeNames();
  for (const auto &attName : attr) {
    std::string attValue = this->getAttribute(attName).value();
    if (!attValue.empty() && attValue != "\"\"") {
      ostr << ',' << attName << '=' << attValue;
    }
  }
  // print the parameters
  for (size_t i = 0; i < nParams(); i++) {
    const ParameterTie *tie = getTie(i);
    if (!tie || !tie->isDefault()) {
      ostr << ',' << parameterName(i) << '=' << getParameter(i);
    }
  }
  // collect non-default constraints
  std::string constraints;
  for (size_t i = 0; i < nParams(); i++) {
    const IConstraint *c = getConstraint(i);
    if (c && !c->isDefault()) {
      std::string tmp = c->asString();
      if (!tmp.empty()) {
        if (!constraints.empty()) {
          constraints += ",";
        }
        constraints += tmp;
      }
    }
  }
  // print constraints
  if (!constraints.empty()) {
    ostr << ",constraints=(" << constraints << ")";
  }
  // collect the non-default ties
  std::string ties;
  for (size_t i = 0; i < nParams(); i++) {
    const ParameterTie *tie = getTie(i);
    if (tie && !tie->isDefault()) {
      std::string tmp = tie->asString(this);
      if (!tmp.empty()) {
        if (!ties.empty()) {
          ties += ",";
        }
        ties += tmp;
      }
    }
  }
  // print the ties
  if (!ties.empty()) {
    ostr << ",ties=(" << ties << ")";
  }
  return ostr.str();
}
void NearestNeighborMapping:: map
(
  int inputDataID,
  int outputDataID )
{
  preciceTrace2 ( "map()", inputDataID, outputDataID );
  const utils::DynVector& inputValues = input()->data(inputDataID)->values();
  utils::DynVector& outputValues = output()->data(outputDataID)->values();
  //assign(outputValues) = 0.0;
  int valueDimensions = input()->data(inputDataID)->getDimensions();
  assertion2 ( valueDimensions == output()->data(outputDataID)->getDimensions(),
              valueDimensions, output()->data(outputDataID)->getDimensions() );
  assertion3 ( inputValues.size() / valueDimensions == (int)input()->vertices().size(),
               inputValues.size(), valueDimensions, input()->vertices().size() );
  assertion3 ( outputValues.size() / valueDimensions == (int)output()->vertices().size(),
               outputValues.size(), valueDimensions, output()->vertices().size() );
  if (getConstraint() == CONSISTENT){
    preciceDebug("Map consistent");
    size_t outSize = output()->vertices().size();
    for ( size_t i=0; i < outSize; i++ ){
      int inputIndex = _vertexIndices[i] * valueDimensions;
      for ( int dim=0; dim < valueDimensions; dim++ ){
        outputValues[(i*valueDimensions)+dim] = inputValues[inputIndex+dim];
      }
    }
  }
  else {
    assertion1(getConstraint() == CONSERVATIVE, getConstraint());
    preciceDebug("Map conservative");
    size_t inSize = input()->vertices().size();
    for ( size_t i=0; i < inSize; i++ ){
      int outputIndex = _vertexIndices[i] * valueDimensions;
      for ( int dim=0; dim < valueDimensions; dim++ ){
        outputValues[outputIndex+dim] += inputValues[(i*valueDimensions)+dim];
      }
    }
  }
}
示例#17
0
    Creature * Creature::clone() const {
        Creature* result = new Creature(getNumberOfBodyParts(), getNumberOfConstraints(),
                getNeuralNetwork());
        for (int i = 0; i < result->getNumberOfBodyParts(); ++i) {
            result->setBodyPart(i, getBodyPart(i).clone());
        }
        for (int i = 0; i < result->getNumberOfConstraints(); ++i) {
            result->setConstraint(i, getConstraint(i).clone());
        }
        result->setFinalPosition(getFinalPosition());
        result->setInitialPosition(getInitialPosition());
        result->setFitness(getFitness());
        result->setName(getName());

        return result;
    }
示例#18
0
void addConstraints(int n, SimpleConstraintChecker<FT>& scheck, GOFactory<FT>& fact, GOInitialData<FT>& id)
{
  int m = 1 << n;
  for(int i = 0; i < m; i ++) {
    C *c = getConstraint(i, n);
    scheck.addInequalityConstraint(c, DELTA);
    LipzGradDiscarder<FT> *dscgc = new LipzGradDiscarder<FT>();
    dscgc->setObjective(c);
    dscgc->setInitialData(&id);
//    dscgc->getDebugOptions() |= LipzGradDiscarder<FT>::DebugOptions::PRINT_BOUNDS;
    std::ostringstream os;
    os << "Constraint " << i;
    dscgc->setName(os.str());
    dscgc->getOptions() |= LipzGradDiscarder<FT>::Options::DO_PRIMARY_BALL_CUT;

    fact.addDiscarder(dscgc);
  }
}
示例#19
0
void Creature::makeAttack(Creature& victim)
{
	bool isParalyzed = getConstraintBool(CC_TEMP_IS_PARALYZED);
	if(isParalyzed) //Creature can not be used
		return;

	bool attackDisabled = getConstraintBool(CC_TEMP_DISABLE_ATTACKS);
	if(attackDisabled) //Creature can not attack
		return;

	int attackForced = getConstraint(CC_TEMP_FORCE_ATTACKS);

	bool attackBackfires = getConstraintBool(CC_TEMP_BACKFIRE_ATTACKS);
	if(attackBackfires)	//Attack turns agains the creature
		changeHealth({_attack, attackForced});
	else
		victim.receiveAttack(*this, _attack, attackForced);
}
示例#20
0
void CpuCas01::apply_event(tmgr_trace_iterator_t event, double value)
{
  if (event == speed_.event) {
    /* TODO (Hypervisor): do the same thing for constraint_core[i] */
    xbt_assert(coresAmount_ == 1, "FIXME: add speed scaling code also for constraint_core[i]");

    speed_.scale = value;
    onSpeedChange();

    tmgr_trace_event_unref(&speed_.event);
  } else if (event == stateEvent_) {
    /* TODO (Hypervisor): do the same thing for constraint_core[i] */
    xbt_assert(coresAmount_ == 1, "FIXME: add state change code also for constraint_core[i]");

    if (value > 0) {
      if(isOff())
        host_that_restart.push_back(getHost());
      turnOn();
    } else {
      lmm_constraint_t cnst = getConstraint();
      lmm_variable_t var = nullptr;
      lmm_element_t elem = nullptr;
      double date = surf_get_clock();

      turnOff();

      while ((var = lmm_get_var_from_cnst(getModel()->getMaxminSystem(), cnst, &elem))) {
        Action *action = static_cast<Action*>(lmm_variable_id(var));

        if (action->getState() == Action::State::running ||
            action->getState() == Action::State::ready ||
            action->getState() == Action::State::not_in_the_system) {
          action->setFinishTime(date);
          action->setState(Action::State::failed);
        }
      }
    }
    tmgr_trace_event_unref(&stateEvent_);

  } else {
    xbt_die("Unknown event!\n");
  }
}
示例#21
0
void	btDiscreteDynamicsWorld::debugDrawWorld()
{
	BT_PROFILE("debugDrawWorld");

	btCollisionWorld::debugDrawWorld();

	bool drawConstraints = false;
	if (getDebugDrawer())
	{
		int mode = getDebugDrawer()->getDebugMode();
		if(mode  & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits))
		{
			drawConstraints = true;
		}
	}
	if(drawConstraints)
	{
		for(int i = getNumConstraints()-1; i>=0 ;i--)
		{
			btTypedConstraint* constraint = getConstraint(i);
			debugDrawConstraint(constraint);
		}
	}



    if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawNormals)))
	{
		int i;

		if (getDebugDrawer() && getDebugDrawer()->getDebugMode())
		{
			for (i=0;i<m_actions.size();i++)
			{
				m_actions[i]->debugDraw(m_debugDrawer);
			}
		}
	}
    if (getDebugDrawer())
        getDebugDrawer()->flushLines();

}
示例#22
0
    Creature::Creature(int body_parts, int constraints, const NeuralNetwork & neural_network)
    :
    _name(""),
    _number_of_body_parts(body_parts),
    _number_of_constraints(constraints),
    _body_parts(new BodyPart*[body_parts]),
    _constraints(new Constraint*[constraints]),
    _neural_network(NULL),
    _initial_position(btVector3(0.0, 0.0, 0.0)),
    _final_position(btVector3(0.0, 0.0, 0.0)),
    _fitness(0.0) {
        for (int i = 0; i < getNumberOfBodyParts(); ++i) {
            setBodyPart(i, new BodyPart());
            getBodyPart(i).setName("Body Part #" + TO_STRING(i));
        }
        for (int i = 0; i < getNumberOfConstraints(); ++i) {
            setConstraint(i, new Constraint());
            getConstraint(i).setName("Constraint #" + TO_STRING(i));
        }

        setNeuralNetwork(neural_network.clone());
    }
示例#23
0
void SpringLayout::setParent(ComponentContainerRefPtr p)
{
    resetCyclicStatuses();

    SpringLayoutConstraintsRefPtr constraints = getConstraint(p);

    constraints->setWest(LayoutSpring::constant(0));
    constraints->setNorth(LayoutSpring::constant(0));

    LayoutSpringRefPtr Width = constraints->getWidth();
    if(Width->getType() == ComponentWidthLayoutSpring::getClassType() &&
        dynamic_pointer_cast<ComponentWidthLayoutSpring>(Width)->getComponent() == p)
    {
        constraints->setWidth(LayoutSpring::constant(0,0,TypeTraits<Real32>::getMax()));
    }
    
    LayoutSpringRefPtr Height = constraints->getHeight();
    if(Height->getType() == ComponentHeightLayoutSpring::getClassType() &&
        dynamic_pointer_cast<ComponentHeightLayoutSpring>(Height)->getComponent() == p)
    {
        constraints->setHeight(LayoutSpring::constant(0,0,TypeTraits<Real32>::getMax()));
    }
}
示例#24
0
bool CpuCas01::isUsed()
{
  return lmm_constraint_used(getModel()->getMaxminSystem(), getConstraint());
}
示例#25
0
int main(int argc, char *argv[])
{
  struct        RNAcofold_args_info args_info;
  unsigned int  input_type;
  char          *string, *input_string;
  char    *structure, *cstruc, *rec_sequence, *orig_sequence, *rec_id, **rec_rest;
  char    fname[FILENAME_MAX_LENGTH], ffname[FILENAME_MAX_LENGTH];
  char    *ParamFile;
  char    *ns_bases, *c;
  char    *Concfile;
  int     i, length, l, sym, r, cl;
  double  min_en;
  double  kT, sfact, betaScale;
  int     pf, istty;
  int     noconv, noPS;
  int     doT;    /*compute dimere free energies etc.*/
  int     doC;    /*toggle to compute concentrations*/
  int     doQ;    /*toggle to compute prob of base being paired*/
  int     cofi;   /*toggle concentrations stdin / file*/
  plist   *prAB;
  plist   *prAA;   /*pair probabilities of AA dimer*/
  plist   *prBB;
  plist   *prA;
  plist   *prB;
  plist   *mfAB;
  plist   *mfAA;   /*pair mfobabilities of AA dimer*/
  plist   *mfBB;
  plist   *mfA;
  plist   *mfB;
  double  *ConcAandB;
  unsigned int    rec_type, read_opt;
  pf_paramT       *pf_parameters;
  model_detailsT  md;


  /*
  #############################################
  # init variables and parameter options
  #############################################
  */
  dangles       = 2;
  sfact         = 1.07;
  bppmThreshold = 1e-5;
  noconv        = 0;
  noPS          = 0;
  do_backtrack  = 1;
  pf            = 0;
  doT           = 0;
  doC           = 0;
  doQ           = 0;
  cofi          = 0;
  betaScale     = 1.;
  gquad         = 0;
  ParamFile     = NULL;
  pf_parameters = NULL;
  string        = NULL;
  Concfile      = NULL;
  structure     = NULL;
  cstruc        = NULL;
  ns_bases      = NULL;
  rec_type      = read_opt = 0;
  rec_id        = rec_sequence = orig_sequence = NULL;
  rec_rest      = NULL;

  set_model_details(&md);
  /*
  #############################################
  # check the command line prameters
  #############################################
  */
  if(RNAcofold_cmdline_parser (argc, argv, &args_info) != 0) exit(1);
  /* temperature */
  if(args_info.temp_given)            temperature = args_info.temp_arg;
  /* structure constraint */
  if(args_info.constraint_given)      fold_constrained=1;
  /* do not take special tetra loop energies into account */
  if(args_info.noTetra_given)         md.special_hp = tetra_loop=0;
  /* set dangle model */
  if(args_info.dangles_given){
    if((args_info.dangles_arg < 0) || (args_info.dangles_arg > 3))
      warn_user("required dangle model not implemented, falling back to default dangles=2");
    else
     md.dangles = dangles = args_info.dangles_arg;
  }
  /* do not allow weak pairs */
  if(args_info.noLP_given)            md.noLP = noLonelyPairs = 1;
  /* do not allow wobble pairs (GU) */
  if(args_info.noGU_given)            md.noGU = noGU = 1;
  /* do not allow weak closing pairs (AU,GU) */
  if(args_info.noClosingGU_given)     md.noGUclosure = no_closingGU = 1;
  /* gquadruplex support */
  if(args_info.gquad_given)           md.gquad = gquad = 1;
  /* enforce canonical base pairs in any case? */
  if(args_info.canonicalBPonly_given) md.canonicalBPonly = canonicalBPonly = 1;
  /* do not convert DNA nucleotide "T" to appropriate RNA "U" */
  if(args_info.noconv_given)          noconv = 1;
  /* set energy model */
  if(args_info.energyModel_given)     energy_set = args_info.energyModel_arg;
  /*  */
  if(args_info.noPS_given)            noPS = 1;
  /* take another energy parameter set */
  if(args_info.paramFile_given)       ParamFile = strdup(args_info.paramFile_arg);
  /* Allow other pairs in addition to the usual AU,GC,and GU pairs */
  if(args_info.nsp_given)             ns_bases = strdup(args_info.nsp_arg);
  /* set pf scaling factor */
  if(args_info.pfScale_given)         sfact = args_info.pfScale_arg;

  if(args_info.all_pf_given)          doT = pf = 1;
  /* concentrations from stdin */
  if(args_info.concentrations_given)  doC = doT = pf = 1;
  /* set the bppm threshold for the dotplot */
  if(args_info.bppmThreshold_given)
    bppmThreshold = MIN2(1., MAX2(0.,args_info.bppmThreshold_arg));
  /* concentrations in file */
  if(args_info.betaScale_given)       betaScale = args_info.betaScale_arg;
  if(args_info.concfile_given){
    Concfile = strdup(args_info.concfile_arg);
    doC = cofi = doT = pf = 1;
  }
  /* partition function settings */
  if(args_info.partfunc_given){
    pf = 1;
    if(args_info.partfunc_arg != -1)
      do_backtrack = args_info.partfunc_arg;
  }
  /* free allocated memory of command line data structure */
  RNAcofold_cmdline_parser_free (&args_info);


  /*
  #############################################
  # begin initializing
  #############################################
  */
  if(pf && gquad){
    nrerror("G-Quadruplex support is currently not available for partition function computations");
  }

  if (ParamFile != NULL)
    read_parameter_file(ParamFile);

  if (ns_bases != NULL) {
    nonstandards = space(33);
    c=ns_bases;
    i=sym=0;
    if (*c=='-') {
      sym=1; c++;
    }
    while (*c!='\0') {
      if (*c!=',') {
        nonstandards[i++]=*c++;
        nonstandards[i++]=*c;
        if ((sym)&&(*c!=*(c-1))) {
          nonstandards[i++]=*c;
          nonstandards[i++]=*(c-1);
        }
      }
      c++;
    }
  }
  istty = isatty(fileno(stdout))&&isatty(fileno(stdin));

  /* print user help if we get input from tty */
  if(istty){
    printf("Use '&' to connect 2 sequences that shall form a complex.\n");
    if(fold_constrained){
      print_tty_constraint(VRNA_CONSTRAINT_DOT | VRNA_CONSTRAINT_X | VRNA_CONSTRAINT_ANG_BRACK | VRNA_CONSTRAINT_RND_BRACK);
      print_tty_input_seq_str("Input sequence (upper or lower case) followed by structure constraint\n");
    }
    else print_tty_input_seq();
  }

  /* set options we wanna pass to read_record */
  if(istty)             read_opt |= VRNA_INPUT_NOSKIP_BLANK_LINES;
  if(!fold_constrained) read_opt |= VRNA_INPUT_NO_REST;

  /*
  #############################################
  # main loop: continue until end of file
  #############################################
  */
  while(
    !((rec_type = read_record(&rec_id, &rec_sequence, &rec_rest, read_opt))
        & (VRNA_INPUT_ERROR | VRNA_INPUT_QUIT))){

    /*
    ########################################################
    # init everything according to the data we've read
    ########################################################
    */
    if(rec_id){
      if(!istty) printf("%s\n", rec_id);
      (void) sscanf(rec_id, ">%" XSTR(FILENAME_ID_LENGTH) "s", fname);
    }
    else fname[0] = '\0';

    cut_point = -1;

    rec_sequence  = tokenize(rec_sequence); /* frees input_string and sets cut_point */
    length    = (int) strlen(rec_sequence);
    structure = (char *) space((unsigned) length+1);

    /* parse the rest of the current dataset to obtain a structure constraint */
    if(fold_constrained){
      cstruc = NULL;
      int cp = cut_point;
      unsigned int coptions = (rec_id) ? VRNA_CONSTRAINT_MULTILINE : 0;
      coptions |= VRNA_CONSTRAINT_DOT | VRNA_CONSTRAINT_X | VRNA_CONSTRAINT_ANG_BRACK | VRNA_CONSTRAINT_RND_BRACK;
      getConstraint(&cstruc, (const char **)rec_rest, coptions);
      cstruc = tokenize(cstruc);
      if(cut_point != cp) nrerror("cut point in sequence and structure constraint differs");
      cl = (cstruc) ? (int)strlen(cstruc) : 0;

      if(cl == 0)           warn_user("structure constraint is missing");
      else if(cl < length)  warn_user("structure constraint is shorter than sequence");
      else if(cl > length)  nrerror("structure constraint is too long");

      if(cstruc) strncpy(structure, cstruc, sizeof(char)*(cl+1));
    }

    /* convert DNA alphabet to RNA if not explicitely switched off */
    if(!noconv) str_DNA2RNA(rec_sequence);
    /* store case-unmodified sequence */
    orig_sequence = strdup(rec_sequence);
    /* convert sequence to uppercase letters only */
    str_uppercase(rec_sequence);

    if(istty){
      if (cut_point == -1)
        printf("length = %d\n", length);
      else
        printf("length1 = %d\nlength2 = %d\n", cut_point-1, length-cut_point+1);
    }

    /*
    ########################################################
    # begin actual computations
    ########################################################
    */

    if (doC) {
      FILE *fp;
      if (cofi) { /* read from file */
        fp = fopen(Concfile, "r");
        if (fp==NULL) {
          fprintf(stderr, "could not open concentration file %s", Concfile);
          nrerror("\n");
        }
        ConcAandB = read_concentrations(fp);
        fclose(fp);
      } else {
        printf("Please enter concentrations [mol/l]\n format: ConcA ConcB\n return to end\n");
        ConcAandB = read_concentrations(stdin);
      }
    }
    /*compute mfe of AB dimer*/
    min_en = cofold(rec_sequence, structure);
    assign_plist_from_db(&mfAB, structure, 0.95);

    {
      char *pstring, *pstruct;
      if (cut_point == -1) {
        pstring = strdup(orig_sequence);
        pstruct = strdup(structure);
      } else {
        pstring = costring(orig_sequence);
        pstruct = costring(structure);
      }
      printf("%s\n%s", pstring, pstruct);
      if (istty)
        printf("\n minimum free energy = %6.2f kcal/mol\n", min_en);
      else
        printf(" (%6.2f)\n", min_en);

      (void) fflush(stdout);

      if (!noPS) {
        char annot[512] = "";
        if (fname[0]!='\0') {
          strcpy(ffname, fname);
          strcat(ffname, "_ss.ps");
        } else {
          strcpy(ffname, "rna.ps");
        }
        if (cut_point >= 0)
          sprintf(annot,
                  "1 %d 9  0 0.9 0.2 omark\n%d %d 9  1 0.1 0.2 omark\n",
                  cut_point-1, cut_point+1, length+1);
        if(gquad){
          if (!noPS) (void) PS_rna_plot_a_gquad(pstring, pstruct, ffname, annot, NULL);
        } else {
          if (!noPS) (void) PS_rna_plot_a(pstring, pstruct, ffname, annot, NULL);
        }
      }
      free(pstring);
      free(pstruct);
    }

    if (length>2000)  free_co_arrays();

    /*compute partition function*/
    if (pf) {
      cofoldF AB, AA, BB;
      FLT_OR_DBL *probs;
      if (dangles==1) {
        dangles=2;   /* recompute with dangles as in pf_fold() */
        min_en = energy_of_structure(rec_sequence, structure, 0);
        dangles=1;
      }

      kT = (betaScale*((temperature+K0)*GASCONST))/1000.; /* in Kcal */
      pf_scale = exp(-(sfact*min_en)/kT/length);
      if (length>2000) fprintf(stderr, "scaling factor %f\n", pf_scale);

      pf_parameters = get_boltzmann_factors(temperature, betaScale, md, pf_scale);

      if (cstruc!=NULL)
        strncpy(structure, cstruc, length+1);
      AB = co_pf_fold_par(rec_sequence, structure, pf_parameters, do_backtrack, fold_constrained);

      if (do_backtrack) {
        char *costruc;
        costruc = (char *) space(sizeof(char)*(strlen(structure)+2));
        if (cut_point<0) printf("%s", structure);
        else {
          strncpy(costruc, structure, cut_point-1);
          strcat(costruc, "&");
          strcat(costruc, structure+cut_point-1);
          printf("%s", costruc);
        }
        if (!istty) printf(" [%6.2f]\n", AB.FAB);
        else printf("\n");/*8.6.04*/
      }
      if ((istty)||(!do_backtrack))
        printf(" free energy of ensemble = %6.2f kcal/mol\n", AB.FAB);
      printf(" frequency of mfe structure in ensemble %g",
             exp((AB.FAB-min_en)/kT));

      printf(" , delta G binding=%6.2f\n", AB.FcAB - AB.FA - AB.FB);

      probs = export_co_bppm();
      assign_plist_from_pr(&prAB, probs, length, bppmThreshold);

      /* if (doQ) make_probsum(length,fname); */ /*compute prob of base paired*/
      /* free_co_arrays(); */
      if (doT) { /* cofold of all dimers, monomers */
        int Blength, Alength;
        char  *Astring, *Bstring, *orig_Astring, *orig_Bstring;
        char *Newstring;
        char Newname[30];
        char comment[80];
        if (cut_point<0) {
          printf("Sorry, i cannot do that with only one molecule, please give me two or leave it\n");
          free(mfAB);
          free(prAB);
          continue;
        }
        if (dangles==1) dangles=2;
        Alength=cut_point-1;        /*length of first molecule*/
        Blength=length-cut_point+1; /*length of 2nd molecule*/

        Astring=(char *)space(sizeof(char)*(Alength+1));/*Sequence of first molecule*/
        Bstring=(char *)space(sizeof(char)*(Blength+1));/*Sequence of second molecule*/
        strncat(Astring,rec_sequence,Alength);
        strncat(Bstring,rec_sequence+Alength,Blength);

        orig_Astring=(char *)space(sizeof(char)*(Alength+1));/*Sequence of first molecule*/
        orig_Bstring=(char *)space(sizeof(char)*(Blength+1));/*Sequence of second molecule*/
        strncat(orig_Astring,orig_sequence,Alength);
        strncat(orig_Bstring,orig_sequence+Alength,Blength);

        /* compute AA dimer */
        AA=do_partfunc(Astring, Alength, 2, &prAA, &mfAA, pf_parameters);
        /* compute BB dimer */
        BB=do_partfunc(Bstring, Blength, 2, &prBB, &mfBB, pf_parameters);
        /*free_co_pf_arrays();*/

        /* compute A monomer */
        do_partfunc(Astring, Alength, 1, &prA, &mfA, pf_parameters);

        /* compute B monomer */
        do_partfunc(Bstring, Blength, 1, &prB, &mfB, pf_parameters);

        compute_probabilities(AB.F0AB, AB.FA, AB.FB, prAB, prA, prB, Alength);
        compute_probabilities(AA.F0AB, AA.FA, AA.FA, prAA, prA, prA, Alength);
        compute_probabilities(BB.F0AB, BB.FA, BB.FA, prBB, prA, prB, Blength);
        printf("Free Energies:\nAB\t\tAA\t\tBB\t\tA\t\tB\n%.6f\t%6f\t%6f\t%6f\t%6f\n",
               AB.FcAB, AA.FcAB, BB.FcAB, AB.FA, AB.FB);

        if (doC) {
          do_concentrations(AB.FcAB, AA.FcAB, BB.FcAB, AB.FA, AB.FB, ConcAandB);
          free(ConcAandB);/*freeen*/
        }

        if (fname[0]!='\0') {
          strcpy(ffname, fname);
          strcat(ffname, "_dp5.ps");
        } else strcpy(ffname, "dot5.ps");
        /*output of the 5 dot plots*/

        /*AB dot_plot*/
        /*write Free Energy into comment*/
        sprintf(comment,"\n%%Heterodimer AB FreeEnergy= %.9f\n", AB.FcAB);
        /*reset cut_point*/
        cut_point=Alength+1;
        /*write New name*/
        strcpy(Newname,"AB");
        strcat(Newname,ffname);
        (void)PS_dot_plot_list(orig_sequence, Newname, prAB, mfAB, comment);

        /*AA dot_plot*/
        sprintf(comment,"\n%%Homodimer AA FreeEnergy= %.9f\n",AA.FcAB);
        /*write New name*/
        strcpy(Newname,"AA");
        strcat(Newname,ffname);
        /*write AA sequence*/
        Newstring=(char*)space((2*Alength+1)*sizeof(char));
        strcpy(Newstring,orig_Astring);
        strcat(Newstring,orig_Astring);
        (void)PS_dot_plot_list(Newstring, Newname, prAA, mfAA, comment);
        free(Newstring);

        /*BB dot_plot*/
        sprintf(comment,"\n%%Homodimer BB FreeEnergy= %.9f\n",BB.FcAB);
        /*write New name*/
        strcpy(Newname,"BB");
        strcat(Newname,ffname);
        /*write BB sequence*/
        Newstring=(char*)space((2*Blength+1)*sizeof(char));
        strcpy(Newstring,orig_Bstring);
        strcat(Newstring,orig_Bstring);
        /*reset cut_point*/
        cut_point=Blength+1;
        (void)PS_dot_plot_list(Newstring, Newname, prBB, mfBB, comment);
        free(Newstring);

        /*A dot plot*/
        /*reset cut_point*/
        cut_point=-1;
        sprintf(comment,"\n%%Monomer A FreeEnergy= %.9f\n",AB.FA);
        /*write New name*/
        strcpy(Newname,"A");
        strcat(Newname,ffname);
        /*write BB sequence*/
        (void)PS_dot_plot_list(orig_Astring, Newname, prA, mfA, comment);

        /*B monomer dot plot*/
        sprintf(comment,"\n%%Monomer B FreeEnergy= %.9f\n",AB.FB);
        /*write New name*/
        strcpy(Newname,"B");
        strcat(Newname,ffname);
        /*write BB sequence*/
        (void)PS_dot_plot_list(orig_Bstring, Newname, prB, mfB, comment);
        free(Astring); free(Bstring); free(orig_Astring); free(orig_Bstring);
        free(prAB); free(prAA); free(prBB); free(prA); free(prB);
        free(mfAB); free(mfAA); free(mfBB); free(mfA); free(mfB);

      } /*end if(doT)*/

      free(pf_parameters);
    }/*end if(pf)*/


    if (do_backtrack) {
      if (fname[0]!='\0') {
        strcpy(ffname, fname);
        strcat(ffname, "_dp.ps");
      } else strcpy(ffname, "dot.ps");

      if (!doT) {
        if (pf) {          (void) PS_dot_plot_list(rec_sequence, ffname, prAB, mfAB, "doof");
        free(prAB);}
        free(mfAB);
      }
    }
    if (!doT) free_co_pf_arrays();

    (void) fflush(stdout);
    
    /* clean up */
    if(cstruc) free(cstruc);
    if(rec_id) free(rec_id);
    free(rec_sequence);
    free(orig_sequence);
    free(structure);
    /* free the rest of current dataset */
    if(rec_rest){
      for(i=0;rec_rest[i];i++) free(rec_rest[i]);
      free(rec_rest);
    }
    rec_id = rec_sequence = orig_sequence = structure = cstruc = NULL;
    rec_rest = NULL;

    /* print user help for the next round if we get input from tty */
    if(istty){
      printf("Use '&' to connect 2 sequences that shall form a complex.\n");
      if(fold_constrained){
        print_tty_constraint(VRNA_CONSTRAINT_DOT | VRNA_CONSTRAINT_X | VRNA_CONSTRAINT_ANG_BRACK | VRNA_CONSTRAINT_RND_BRACK);
        print_tty_input_seq_str("Input sequence (upper or lower case) followed by structure constraint\n");
      }
      else print_tty_input_seq();
    }
  }
  return EXIT_SUCCESS;
}
  if (getConstraint() == CONSISTENT){
    preciceDebug("Compute consistent mapping");
    _weights.resize(output()->vertices().size());
    for ( size_t i=0; i < output()->vertices().size(); i++ ){
      query::FindClosest findClosest(output()->vertices()[i].getCoords());
      findClosest(*input());
      assertion(findClosest.hasFound());
      const query::ClosestElement& closest = findClosest.getClosest();
      _weights[i].clear();
      foreach ( const query::InterpolationElement& elem, closest.interpolationElements ){
        _weights[i].push_back(elem);
      }
    }
  }
  else {
    assertion1(getConstraint() == CONSERVATIVE, getConstraint());
    preciceDebug("Compute conservative mapping");
    _weights.resize(input()->vertices().size());
    for ( size_t i=0; i < input()->vertices().size(); i++ ){
      query::FindClosest findClosest(input()->vertices()[i].getCoords());
      findClosest(*output());
      assertion(findClosest.hasFound());
      const query::ClosestElement& closest = findClosest.getClosest();
      _weights[i].clear();
      foreach ( const query::InterpolationElement& elem, closest.interpolationElements ){
        _weights[i].push_back(elem);
      }
    }
  }
  _hasComputedMapping = true;
}
示例#27
0
void
Model::removeDuplicateTopLevelAnnotations()
{
  unsigned int i, n;
  this->removeDuplicateAnnotations();

  if (getNumFunctionDefinitions() > 0)
  {
    getListOfFunctionDefinitions()->removeDuplicateAnnotations();
    for (i = 0; i < getNumFunctionDefinitions(); i++)
    {
      getFunctionDefinition(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumUnitDefinitions() > 0)
  {
    getListOfUnitDefinitions()->removeDuplicateAnnotations();
    for (i = 0; i < getNumUnitDefinitions(); i++)
    {
      getUnitDefinition(i)->removeDuplicateAnnotations();
      getUnitDefinition(i)->getListOfUnits()->removeDuplicateAnnotations();
      for (n = 0; n < getUnitDefinition(i)->getNumUnits(); n++)
      {
        getUnitDefinition(i)->getUnit(n)->removeDuplicateAnnotations();
      }
    }
  }
  if (getNumCompartmentTypes() > 0)
  {
    getListOfCompartmentTypes()->removeDuplicateAnnotations();
    for (i = 0; i < getNumCompartmentTypes(); i++)
    {
      getCompartmentType(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumSpeciesTypes() > 0)
  {
    getListOfSpeciesTypes()->removeDuplicateAnnotations();
    for (i = 0; i < getNumSpeciesTypes(); i++)
    {
      getSpeciesType(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumCompartments() > 0)
  {
    getListOfCompartments()->removeDuplicateAnnotations();
    for (i = 0; i < getNumCompartments(); i++)
    {
      getCompartment(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumSpecies() > 0)
  {
    getListOfSpecies()->removeDuplicateAnnotations();
    for (i = 0; i < getNumSpecies(); i++)
    {
      getSpecies(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumParameters() > 0)
  {
    getListOfParameters()->removeDuplicateAnnotations();
    for (i = 0; i < getNumParameters(); i++)
    {
      getParameter(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumInitialAssignments() > 0)
  {
    getListOfInitialAssignments()->removeDuplicateAnnotations();
    for (i = 0; i < getNumInitialAssignments(); i++)
    {
      getInitialAssignment(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumConstraints() > 0)
  {
    getListOfConstraints()->removeDuplicateAnnotations();
    for (i = 0; i < getNumConstraints(); i++)
    {
      getConstraint(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumRules() > 0)
  {
    getListOfRules()->removeDuplicateAnnotations();
    for (i = 0; i < getNumRules(); i++)
    {
      getRule(i)->removeDuplicateAnnotations();
    }
  }
  if (getNumReactions() > 0)
  {
    getListOfReactions()->removeDuplicateAnnotations();
    for (i = 0; i < getNumReactions(); i++)
    {
      Reaction * r = getReaction(i);
      r->removeDuplicateAnnotations();
      if (r->getNumReactants() > 0)
      {
        r->getListOfReactants()->removeDuplicateAnnotations();
        for (n = 0; n < r->getNumReactants(); n++)
        {
          r->getReactant(n)->removeDuplicateAnnotations();
        }
      }
      if (r->getNumProducts() > 0)
      {
        r->getListOfProducts()->removeDuplicateAnnotations();
        for (n = 0; n < r->getNumProducts(); n++)
        {
          r->getProduct(n)->removeDuplicateAnnotations();
        }
      }
      if (r->getNumModifiers() > 0)
      {
        r->getListOfModifiers()->removeDuplicateAnnotations();
        for (n = 0; n < r->getNumModifiers(); n++)
        {
          r->getModifier(n)->removeDuplicateAnnotations();
        }
      }
      if (r->isSetKineticLaw())
      {
        r->getKineticLaw()->removeDuplicateAnnotations();
        if (r->getKineticLaw()->getNumParameters() > 0)
        {
          r->getKineticLaw()->getListOfParameters()
                            ->removeDuplicateAnnotations();
          for (n = 0; n < r->getKineticLaw()->getNumParameters(); n++)
          {
            r->getKineticLaw()->getParameter(n)->removeDuplicateAnnotations();
          }
        }
      }
    }
  }
  if (getNumEvents() > 0)
  {
    getListOfEvents()->removeDuplicateAnnotations();
    for (i = 0; i < getNumEvents(); i++)
    {
      getEvent(i)->removeDuplicateAnnotations();
      if (getEvent(i)->getNumEventAssignments() > 0)
      {
        getEvent(i)->getListOfEventAssignments()->removeDuplicateAnnotations();
        for (n = 0; n < getEvent(i)->getNumEventAssignments(); n++)
        {
          getEvent(i)->getEventAssignment(n)->removeDuplicateAnnotations();
        }
      }
    }
  }
}
示例#28
0
CpuAction *CpuCas01::execution_start(double size)
{
  return new CpuCas01Action(getModel(), size, isOff(), speed_.scale * speed_.peak, getConstraint());
}
示例#29
0
CpuAction *CpuCas01::sleep(double duration)
{
  if (duration > 0)
    duration = MAX(duration, sg_surf_precision);

  XBT_IN("(%s,%g)", getName(), duration);
  CpuCas01Action *action = new CpuCas01Action(getModel(), 1.0, isOff(), speed_.scale * speed_.peak, getConstraint());

  // FIXME: sleep variables should not consume 1.0 in lmm_expand
  action->maxDuration_ = duration;
  action->suspended_ = 2;
  if (duration == NO_MAX_DURATION) {
    /* Move to the *end* of the corresponding action set. This convention is used to speed up update_resource_state */
    action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
    action->stateSet_ = static_cast<CpuCas01Model*>(getModel())->p_cpuRunningActionSetThatDoesNotNeedBeingChecked;
    action->getStateSet()->push_back(*action);
  }

  lmm_update_variable_weight(getModel()->getMaxminSystem(), action->getVariable(), 0.0);
  if (getModel()->getUpdateMechanism() == UM_LAZY) {     // remove action from the heap
    action->heapRemove(getModel()->getActionHeap());
    // this is necessary for a variable with weight 0 since such variables are ignored in lmm and we need to set its
    // max_duration correctly at the next call to share_resources
    getModel()->getModifiedSet()->push_front(*action);
  }

  XBT_OUT();
  return action;
}
//----------------------------------------------------------------------------------------------
/// Execute the algorithm.
void EstimateFitParameters::execConcrete() {
  auto costFunction = getCostFunctionInitialized();
  auto func = costFunction->getFittingFunction();

  // Use additional constraints on parameters tied in some way
  // to the varied parameters to exculde unwanted results.
  std::vector<std::unique_ptr<IConstraint>> constraints;
  std::string constraintStr = getProperty("Constraints");
  if (!constraintStr.empty()) {
    Expression expr;
    expr.parse(constraintStr);
    expr.toList();
    for (auto &term : expr.terms()) {
      IConstraint *c =
          ConstraintFactory::Instance().createInitialized(func.get(), term);
      constraints.push_back(std::unique_ptr<IConstraint>(c));
    }
  }

  // Ranges to use with random number generators: one for each free parameter.
  std::vector<std::pair<double, double>> ranges;
  ranges.reserve(costFunction->nParams());
  for (size_t i = 0; i < func->nParams(); ++i) {
    if (!func->isActive(i)) {
      continue;
    }
    auto constraint = func->getConstraint(i);
    if (constraint == nullptr) {
      func->fix(i);
      continue;
    }
    auto boundary = dynamic_cast<Constraints::BoundaryConstraint *>(constraint);
    if (boundary == nullptr) {
      throw std::runtime_error("Parameter " + func->parameterName(i) +
                               " must have a boundary constraint. ");
    }
    if (!boundary->hasLower()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have a lower bound.");
    }
    if (!boundary->hasUpper()) {
      throw std::runtime_error("Constraint of " + func->parameterName(i) +
                               " must have an upper bound.");
    }
    // Use the lower and upper bounds of the constraint to set the range
    // of a generator with uniform distribution.
    ranges.push_back(std::make_pair(boundary->lower(), boundary->upper()));
  }
  // Number of parameters could have changed
  costFunction->reset();
  if (costFunction->nParams() == 0) {
    throw std::runtime_error("No parameters are given for which to estimate "
                             "initial values. Set boundary constraints to "
                             "parameters that need to be estimated.");
  }

  size_t nSamples = static_cast<int>(getProperty("NSamples"));
  unsigned int seed = static_cast<int>(getProperty("Seed"));

  if (getPropertyValue("Type") == "Monte Carlo") {
    int nOutput = getProperty("NOutputs");
    auto outputWorkspaceProp = getPointerToProperty("OutputWorkspace");
    if (outputWorkspaceProp->isDefault() || nOutput <= 0) {
      nOutput = 1;
    }
    auto output = runMonteCarlo(*costFunction, ranges, constraints, nSamples,
                                static_cast<size_t>(nOutput), seed);

    if (!outputWorkspaceProp->isDefault()) {
      auto table = API::WorkspaceFactory::Instance().createTable();
      auto column = table->addColumn("str", "Name");
      column->setPlotType(6);
      for (size_t i = 0; i < output.size(); ++i) {
        column = table->addColumn("double", std::to_string(i + 1));
        column->setPlotType(2);
      }

      for (size_t i = 0, ia = 0; i < m_function->nParams(); ++i) {
        if (m_function->isActive(i)) {
          TableRow row = table->appendRow();
          row << m_function->parameterName(i);
          for (auto &j : output) {
            row << j[ia];
          }
          ++ia;
        }
      }
      setProperty("OutputWorkspace", table);
    }
  } else {
    size_t nSelection = static_cast<int>(getProperty("Selection"));
    size_t nIterations = static_cast<int>(getProperty("NIterations"));
    runCrossEntropy(*costFunction, ranges, constraints, nSamples, nSelection,
                    nIterations, seed);
  }
  bool fixBad = getProperty("FixBadParameters");
  if (fixBad) {
    fixBadParameters(*costFunction, ranges);
  }
}