Beispiel #1
0
    // a1 < 0, a2 < 0, a3 < 0, a4 > 0
    // x >= t2/a2
    // x >= t3/a3
    // determine glb among these
    // the resolve glb with others.
    // e.g. t2/a2 >= t3/a3
    // then replace a3*x + t3 by t3/a3 - t2/a2 <= 0
    // 
    bound_type model_based_opt::maximize(rational& value) {
        SASSERT(invariant());
        unsigned_vector other;
        while (!objective().m_vars.empty()) {
            TRACE("opt", tout << "tableau\n";);
            var v = objective().m_vars.back();
            unsigned x = v.m_id;
            rational const& coeff = v.m_coeff;
            unsigned bound_row_index;
            rational bound_coeff;
            other.reset();
            if (find_bound(x, bound_row_index, bound_coeff, other, coeff.is_pos())) {
                SASSERT(!bound_coeff.is_zero());
                for (unsigned i = 0; i < other.size(); ++i) {
                    resolve(bound_row_index, bound_coeff, other[i], x);
                }
                // coeff*x + objective <= ub
                // a2*x + t2 <= 0
                // => coeff*x <= -t2*coeff/a2
                // objective + t2*coeff/a2 <= ub

                mul_add(m_objective_id, - coeff/bound_coeff, bound_row_index);
                m_rows[bound_row_index].m_alive = false;
            }
            else {
                return unbounded;
            }
        }
Beispiel #2
0
void QF3ObjectiveCombobox::saveSettings(QSettings& settings, QString property) {
    settings.setValue(property+"/id", cmbObjective->currentText());
    settings.setValue(property+"/manufacturer", objective().manufacturer);
    settings.setValue(property+"/name", objective().name);
    settings.setValue(property+"/magnification", objective().magnification);
    settings.setValue(property+"/na", objective().NA);
}
Beispiel #3
0
 param_type
 operator()(const Range& samples, std::size_t labels, std::size_t features) {
   conjugate_gradient<param_type> optimizer(
     new slope_binary_search<param_type>(1e-6, wolfe<T>::conjugate_gradient()),
     {1e-6, false}
   );
   param_ll_objective<softmax_ll<T>, Range> objective(
     samples,
     regul_ ? new l2_regularization<param_type>(regul_) : nullptr
   );
   optimizer.objective(&objective);
   optimizer.solution(param_type(labels, features, T(0)));
   for (std::size_t it = 0; !optimizer.converged() && it < max_iter_; ++it) {
     line_search_result<T> value = optimizer.iterate();
     if (verbose_) {
       std::cout << "Iteration " << it << ", " << value << std::endl;
     }
   }
   if (!optimizer.converged()) {
     std::cerr << "Warning: failed to converge" << std::endl;
   }
   if (verbose_) {
     std::cout << "Number of calls: " << objective.calls() << std::endl;
   }
   return optimizer.solution();
 }
Beispiel #4
0
mixed aa_ring(string str)
{
    int numrings;
    if (str!="bell" && str!="doorbell" && str!="door bell")
        return notify_fail("Ring what?\n");
    /* if "rung_bell" has not been set in the player, a query() for it
       will return UNDEFINED.  you CAN add 1 to an undefined to get 1.

       they just rang it one more time, so we'll take what was there and
       add one.  Then we'll put the new value back into the temp var
     **see note at bottom of file.
     */
    numrings=this_player()->GetProperty("rung_bell")+1;  
    this_player()->SetProperty("rung_bell",numrings);
    write("DONG!\nYou ring a doorbell! Don't do it too many times!\n");
    say("DONG!  A doorbell rings.\n");

    if ( numrings>5  )
    {
        if (!present("orc",this_object())) //nested if. see NOTE 2.
        {
            write("Now you've done it!  An orc walks in a bonks you on the head.\n");
            say("Now " + this_player()->GetName() + " has done it!  An orc walks in a bonks " +
              objective(this_player()) +  " on the head.\n");
            new(ORC)->eventMove(this_object());  //this_object IS -this- room!
        }
    }
Beispiel #5
0
int invoke_heal (string str) {
  object target, light, ob;
  int COST, flag = 0;

  seteuid(getuid());

  if (!str||str=="me"||str==(string)TP->query("name")) {
    target = TP;
  } else {
      target = present(str, environment(TP));
      if (!target) {
        write("Couldn't find "+capitalize(str)+" here.\n");
        return 1;
      }
      if (!living(target)) {
        write("The target must be alive.\n");
        return 1;
      }
     flag=1;
    }
  
COST = (target->query("max_hp") - target->query("hit_points")) ;
  if (COST < 1) {
    write("They are fully healed already!\n");
    return 1;
  }

  if (!TP->invoke_spell(COST)) {
    write("You cannot muster the energies to heal that much damage.\n");
    return 1;
  }

//Heal the target

ob = present("#FEEBLEMIND#", target);
if(ob) ob->remove();
ob = present("#WOUND_OB#", target);
if(ob) ob->remove();
target->receive_healing(COST);

// Tell the room and caster what happens...
  switch(flag){
  case 1 :  tell_object(target, TPN +
        " gestures at you and utters a strange incantation.\n"+
        "You feel a bit better!\n");
      write ("You cast heal upon "+target->query("cap_name")+".\n");
      message("spell", 
        TPN+" gestures at "+target->query("cap_name")+
        " and utters a strange incantation.\n", environment(TP),
        ({ TP, target }) );
      break;
    default :
      write("You cast a heal spell upon yourself.\n"+
        "You feel much better.\n");
      say(TPN+" utters a strange incantation.\n"+
        objective(TP->query("gender"))+" is healed.\n");
      break;
  }
Beispiel #6
0
 unsigned context::scoped_state::add(app* t, bool is_max) {
     app_ref tr(t, m);
     if (!m_bv.is_bv(t) && !m_arith.is_int_real(t)) {
         throw default_exception("Objective must be bit-vector, integer or real");   
     }
     unsigned index = m_objectives.size();
     m_objectives.push_back(objective(is_max, tr, index));
     return index;
 }
Beispiel #7
0
int DeathSequence(object killer, string cause, status nocorpse)
{
    tell_object(me,sprintf(
        "%s just tried to kill you.  You exact revenge.",
        killer->query_name()));
    tell_room(ENV(me),sprintf(
        "Just as %s is about to die, a protective shield surrounds %s!"
        "%s has his revenge on %s!\n",
        me->query_name(),objective(me),subjective(me),
        killer->query_name()),({me}));
Beispiel #8
0
/* L-BFGS proxy function for evaluating the objective function */
static lbfgsfloatval_t evaluate(void *instance, const lbfgsfloatval_t *x,
        lbfgsfloatval_t *g, int n, lbfgsfloatval_t step)
{
    int i;
    region_params_t *params = (region_params_t *)instance;

    for (i = 0; i < n; i++) {
        g[i] = diff(objective, x, params, n, i);
    }
    return objective(x, params);
}
void Newton::zeros(OBJFUNC&& objective, double &guesses){ //guess is modified and used as the "result"
    double prec2=1;
    AutoDiff guess(guesses, 1);
    int j=0;
    while(std::abs(prec2)>precision2 && j<maxNum){
        prec2=guesses;
        AutoDiff p=objective(guess);
        guesses=guesses-p.getStandard()/p.getDual();
        prec2=(guesses-prec2)/guesses;
        guess.setStandard(guesses);
        guess.setDual(1);
        j++;
    }
}
Beispiel #10
0
int reflect_me (string str) {
    object image;
    image = clone_object(FAIR_MON+"image.c");
    if(image && image_flag) {
	say(TPN+"'s image suddenly comes to life and attacks "+
	  objective(TP->query("gender") )+" !!\n");
	write("Your image suddenly comes to life and attacks you!!\n");
	image->move(environment(this_player() ) );
	image->kill_ob(this_player() );
	image_flag = 0;
    }
    else
	write("One eye, one nostril, ... Simply 'cute'. \n");
    say(TPN+" looks at "+POSS+" image on the mirror.\n");
    return 1;
}
Beispiel #11
0
 unsigned context::scoped_state::add(expr* f, rational const& w, symbol const& id) {
     if (w.is_neg()) {
         throw default_exception("Negative weight supplied. Weight should be positive");
     }
     if (w.is_zero()) {
         throw default_exception("Zero weight supplied. Weight should be positive");
     }
     if (!m.is_bool(f)) {
         throw default_exception("Soft constraint should be Boolean");
     }
     if (!m_indices.contains(id)) {
         m_objectives.push_back(objective(m, id));
         m_indices.insert(id, m_objectives.size() - 1);
     }
     SASSERT(m_indices.contains(id));        
     unsigned idx = m_indices[id];
     m_objectives[idx].m_terms.push_back(f);
     m_objectives[idx].m_weights.push_back(w);
     m_objectives_term_trail.push_back(idx);
     return idx;
 }
Beispiel #12
0
double
IlpSolver::min_surface(const Parameters& parameters) {

	std::size_t num_vars = _num_nodes*_num_levels;

	LOG_DEBUG(ilpsolverlog) << "creating objective for " << num_vars << " binary variables" << std::endl;
	LinearObjective objective(num_vars);

	LOG_DEBUG(ilpsolverlog) << "setting objective coefficients" << std::endl;
	for (GraphType::NodeIt n(_graph); n != lemon::INVALID; ++n) {

		double sum = 0;

		for (int l = 0; l < _num_levels; l++) {

			std::size_t var_num = _graph.id(n)*_num_levels + l;
			double costs = _level_costs[n][l];
			double accumulated_costs = costs - sum;
			sum += accumulated_costs;

			objective.setCoefficient(var_num, accumulated_costs);
		}
	}

	LinearConstraints constraints;

	// pick at least lowest level
	LOG_DEBUG(ilpsolverlog) << "adding indicator constraints" << std::endl;
	for (GraphType::NodeIt n(_graph); n != lemon::INVALID; ++n) {

		std::size_t var_num = _graph.id(n)*_num_levels;

		LinearConstraint indicator;
		indicator.setCoefficient(var_num, 1.0);
		indicator.setRelation(Equal);
		indicator.setValue(1.0);
		constraints.add(indicator);
	}

	// column inclusion constraints
	LOG_DEBUG(ilpsolverlog) << "adding column inclusion constraints" << std::endl;
	for (GraphType::NodeIt n(_graph); n != lemon::INVALID; ++n) {

		for (int l = 1; l < _num_levels; l++) {

			std::size_t upper_var_num = _graph.id(n)*_num_levels + l;
			std::size_t lower_var_num = _graph.id(n)*_num_levels + l - 1;

			LinearConstraint inclusion;
			inclusion.setCoefficient(upper_var_num,  1.0);
			inclusion.setCoefficient(lower_var_num, -1.0);
			inclusion.setRelation(LessEqual);
			inclusion.setValue(0.0);

			constraints.add(inclusion);
		}
	}

	// gradient constraints
	LOG_DEBUG(ilpsolverlog) << "adding gradient constraints" << std::endl;
	for (GraphType::EdgeIt e(_graph); e != lemon::INVALID; ++e) {

		GraphType::Node u = _graph.u(e);
		GraphType::Node v = _graph.v(e);

		for (auto& p : { std::make_pair(u, v), std::make_pair(v, u) }) {

			GraphType::Node u_ = p.first;
			GraphType::Node v_ = p.second;

			for (int l = _max_gradients[e]; l < _num_levels; l++) {

				std::size_t upper_var_num = _graph.id(u_)*_num_levels + l;
				std::size_t lower_var_num = _graph.id(v_)*_num_levels + l - _max_gradients[e];

				LinearConstraint inclusion;
				inclusion.setCoefficient(upper_var_num,  1.0);
				inclusion.setCoefficient(lower_var_num, -1.0);
				inclusion.setRelation(LessEqual);
				inclusion.setValue(0.0);

				constraints.add(inclusion);
			}
		}
	}

	if (parameters.enforce_zero_minimum) {

		LOG_USER(ilpsolverlog) << "enforcing minima of zero" << std::endl;

		if (parameters.num_neighbors < 0)
			UTIL_THROW_EXCEPTION(
					UsageError,
					"if 'enforce_zero_minimum' is set, 'num_neighbors' has to be set, too.");

		// for each indicator between 1 and _num_levels - 1: if top indicator t 
		// is 0, one of the neighbors n ∈ N must be zero, too:
		//
		//   t=0 ⇒ Σn<|N|
		//
		//   Σn - t ≤ |N| - 1 if t=0, one of neighbors has to be 0
		//                    if t=1, constraint always true

		for (GraphType::NodeIt n(_graph); n != lemon::INVALID; ++n) {

			for (int l = 1; l < _num_levels - 1; l++) {

				LinearConstraint zero_minimum;

				// Σn
				for (GraphType::IncEdgeIt e(_graph, n); e != lemon::INVALID; ++e) {

					GraphType::Node nb = _graph.oppositeNode(n, e);
					std::size_t nb_var_num = _graph.id(nb)*_num_levels + l;
					zero_minimum.setCoefficient(nb_var_num, 1.0);
				}

				// -t
				std::size_t t_var_num = _graph.id(n)*_num_levels + l + 1;
				zero_minimum.setCoefficient(t_var_num, -1.0);

				// ≤ |N| - 1
				zero_minimum.setRelation(LessEqual);
				zero_minimum.setValue(parameters.num_neighbors - 1);

				constraints.add(zero_minimum);
			}
		}
	}

	SolverFactory factory;
	_solver = std::unique_ptr<LinearSolverBackend>(factory.createLinearSolverBackend());

	LOG_DEBUG(ilpsolverlog) << "initialize solver" << std::endl;
	if (parameters.solve_relaxed_problem) {

		_solver->initialize(num_vars, Continuous);
		// we have to force values to be within 0 and 1
		for (std::size_t i = 0; i < num_vars; i++) {
			LinearConstraint lower_bound, upper_bound;
			lower_bound.setCoefficient(i, 1.0);
			lower_bound.setRelation(GreaterEqual);
			lower_bound.setValue(0.0);
			upper_bound.setCoefficient(i, 1.0);
			upper_bound.setRelation(LessEqual);
			upper_bound.setValue(1.0);
			constraints.add(lower_bound);
			constraints.add(upper_bound);
		}

	} else {

		_solver->initialize(num_vars, Binary);
	}
	LOG_DEBUG(ilpsolverlog) << "setting objective" << std::endl;
	_solver->setObjective(objective);
	LOG_DEBUG(ilpsolverlog) << "setting setting constraints" << std::endl;
	_solver->setConstraints(constraints);

	LOG_ALL(ilpsolverlog) << objective << std::endl;
	for (auto c : constraints)
		LOG_ALL(ilpsolverlog) << c << std::endl;

	LinearSolverBackend::Parameters solverParameters;
	solverParameters.numThreads = parameters.num_threads;
	solverParameters.verbose    = parameters.verbose;

	LOG_DEBUG(ilpsolverlog) << "solving" << std::endl;
	std::string message;
	if (!_solver->solve(_solution, message, solverParameters))
		UTIL_THROW_EXCEPTION(
				LinearSolverBackendException,
				"linear program could not be solved: " << message);

	LOG_ALL(ilpsolverlog) << _solution.getVector() << std::endl;

	return _solution.getValue();
}
Beispiel #13
0
void extra_create()
{
    string race, name, lastname, rankfirst, 
      ranksecond, rankthird, rankfourth, attk;
        
    int sex = random( 2 );
    
    if( sex == 1 )
    {
      set_gender( "male" );
      switch( random( 15 ) )
      {
        case 0  : name = "Gary";     break;
        case 1  : name = "Larry";    break;
        case 2  : name = "Sigmund";  break;
        case 3  : name = "Alfred";   break;
        case 4  : name = "Gregory";  break;
        case 5  : name = "Lester";   break;
        case 6  : name = "Arnold";   break;
        case 7  : name = "Homer";    break;
        case 8  : name = "James";    break;
        case 9  : name = "Atherton"; break;
        case 10 : name = "Eric";     break;
        case 11 : name = "Robert";   break;
        case 12 : name = "Mike";     break;
        case 13 : name = "Gabe";     break;
        case 14 : name = "Malcom";   break;
      }  
    } 
    if( sex == 0 )
    {
      set_gender( "female" );
      
      switch( random( 15 ) )
      {
        case 0  : name = "Gale";       break;
        case 1  : name = "Edith";      break;
        case 2  : name = "Marilyn";    break;
        case 3  : name = "Margo";      break;
        case 4  : name = "Agnes";      break;
        case 5  : name = "Nelly";      break;
        case 6  : name = "Mildred";    break;
        case 7  : name = "Charlotte";  break;
        case 8  : name = "Eva";        break;
        case 9  : name = "Victoria";   break;
        case 10 : name = "Stella";     break;
        case 11 : name = "Vivian";     break;
        case 12 : name = "Ruth";       break;
        case 13 : name = "Sophronia";  break;
        case 14 : name = "Virginia";   break;
      }
    }
    
    switch( random( 15 ) )
    {
      case 0  : lastname = "Masterson"; break;
      case 1  : lastname = "Laymon";    break;
      case 2  : lastname = "Wilson";    break;
      case 3  : lastname = "McCammon";  break;
      case 4  : lastname = "Bierce";    break;
      case 5  : lastname = "Blackwood"; break;
      case 6  : lastname = "Lovecraft"; break;
      case 7  : lastname = "Saul";      break;
      case 8  : lastname = "Poe";       break;
      case 9  : lastname = "Ketchum";   break;
      case 10 : lastname = "Koontz";    break;
      case 11 : lastname = "Lumley";    break;
      case 12 : lastname = "Lansdale";  break;
      case 13 : lastname = "Barker";    break;
      case 14 : lastname = "Bloch";     break;
    }
    
    switch( random( 4 ) )
    {
      case 0 : race = "drow_elf"; break;
      case 1 : race = "dwarf";    break;
      case 2 : race = "human";    break;
      case 3 : race = "gnome";    break;
    }
    
    switch( random( 4 ) )
    {
      case 0 : rankfirst = sprintf( "%s is tall and middle aged. %s "
        "shirt is wrinkled and %s looks dazed. ", name, 
        CAP( possessive( THISO ) ), subjective( THISO ) );      break;
      case 1 : rankfirst = sprintf( "%s is a bit overweight. %s presence "
        "is chilling. There is something dark about %s. ", 
        name, CAP( possessive( THISO ) ), objective( THISO ) ); break;
      case 2 : rankfirst = sprintf( "There is a silky shine to %s hair. %s "
        "looks clean and well groomed. Almost too well groomed. Like %s is "
        "hiding something. ", possessive( THISO ), CAP( subjective( THISO ) ), 
        subjective( THISO ) );                                  break;
      case 3 : rankfirst = sprintf( "%s has taut skin and well toned muscles. %s "
        "looks to only be around thirty, though you know %s is much older. ", name,
        CAP( subjective( THISO ) ), subjective( THISO ) );      break;
    }
    
    switch( random( 4 ) )
    {
      case 0 : ranksecond = sprintf( "%s dutifully concentrates on "
        "whatever %s task maybe. %s concentration is unwavering and intense. ", 
        CAP( subjective( THISO ) ), possessive( THISO ), 
        CAP( possessive( THISO ) ) );                                break;
      case 1 : ranksecond = sprintf( "%s moves with great agility. %s speed "
        "and grace is almost supernatural. As if %s wasn't fully of this world. ", 
        CAP( subjective( THISO ) ), CAP( possessive( THISO ) ), 
        subjective( THISO ) );                                       break;
      case 2 : ranksecond = sprintf( "%s refuses to pause for a moment. %s "
        "rushes forward lost in thought. ", CAP( subjective( THISO ) ), 
        CAP( subjective( THISO ) ) );                                break;
      case 3 : ranksecond = sprintf( "%s shoes are scuffed and the soles are almost "
        "worn through. %s proceeds relentlessly forwards driven by an unknown goal. ",
        CAP( possessive( THISO ) ), CAP( subjective( THISO ) ) );    break;
    }
      
    switch( random( 4 ) )
    {
      case 0 : rankthird = sprintf( "%s eyes are crisp and calculating. ", 
        CAP( possessive( THISO ) ) );                            break;
      case 1 : rankthird = sprintf( "%s eyes seem cold, yet relentless. ",
        CAP( possessive( THISO ) ) );                            break;
      case 2 : rankthird = sprintf( "%s eyes are tireless and unyielding. ",
        CAP( possessive( THISO ) ) );                            break;
      case 3 : rankthird = sprintf( "%s eyes intake the whole of the room, "
        "%s is searching for something. ", 
        CAP( possessive( THISO ) ), subjective( THISO ) );       break;
    }
    
    switch( random( 4 ) )
    {
      case 0 : rankfourth = sprintf( "%s only cares for work.",
        CAP( subjective( THISO ) ) );                      break;
      case 1 : rankfourth = sprintf( "%s licks %s lips at the sight of you.", 
        CAP( subjective( THISO ) ), possessive( THISO ) ); break;
      case 2 : rankfourth = sprintf( "%s is a tireless asset to this company.",
        CAP( subjective( THISO ) ) );                      break;
      case 3 : rankfourth = sprintf( "%s has no fear. No worry.",
        CAP( subjective( THISO ) ) );                      break;
    }
    
    switch( random( 100 ) )
    {
       case 0..20  : attk = "sympathy"; break;
       case 21..70 : attk = "shove";    break;
       case 71..76 : attk = "panic";    break;
       case 77..99 : attk = "eyeclaw";  break;
    }
    
    set_name( sprintf( "%s %s", name, lastname ) );
    
    add_alias( "researcher" );
    add_alias( "res" );
    add_alias( "doctor" );
    add_alias( lower_case( name ) );
    add_alias( lower_case( lastname ) );
    add_alias( sprintf( "%s %s", lower_case( name ), 
      lower_case( lastname ) ) );
    
    set_short( sprintf( "%s %s, a high level researcher", 
    name, lastname ) );
    
    set_long( sprintf( "%s %s %s %s", rankfirst, ranksecond, rankthird,
      rankfourth ) );
    
    set_race( race );
    
    set_alignment( NEUTRAL_AL );
    
    set_stat( "str", 120 + random( 30 ) );
    set_stat( "con", 100 + random( 30 ) );
    set_stat( "wil", 100 + random( 30 ) );
    set_stat( "int", 100 + random( 30 ) );
    set_stat( "dex", 100 + random( 30 ) );
    
    set_avoid_props( ({ NoWanderRoomP }) );
Beispiel #14
0
void ModelMFWt::hogTrain(const Data &data, Model &bestModel, 
    std::unordered_set<int>& invalidUsers,
    std::unordered_set<int>& invalidItems) {

  //copy passed known factors
  //uFac = data.origUFac;
  //iFac = data.origIFac;
  
  std::cout << "\nModelMFWt::hogTrain trainSeed: " << trainSeed;
  
  int nnz = data.trainNNZ;
  
  std::cout << "\nObj b4 svd: " << objective(data, invalidUsers, invalidItems) 
    << " Train RMSE: " << RMSE(data.trainMat) 
    << " Train nnz: " << nnz << std::endl;
  
  std::chrono::time_point<std::chrono::system_clock> startSVD, endSVD;
  startSVD = std::chrono::system_clock::now();
  //initialization with svd of the passed matrix
  //svdFrmSvdlibCSR(data.trainMat, facDim, uFac, iFac, false); 
  
  endSVD = std::chrono::system_clock::now();
  std::chrono::duration<double> durationSVD =  (endSVD - startSVD) ;
  std::cout << "\nsvd duration: " << durationSVD.count();

  int iter, bestIter = -1; 
  double bestObj, prevObj;
  double bestValRMSE, prevValRMSE;

  gk_csr_t *trainMat = data.trainMat;

 
  //vector to hold user gradient accumulation
  std::vector<std::vector<double>> uGradsAcc (nUsers, 
      std::vector<double>(facDim,0)); 

  //vector to hold item gradient accumulation
  std::vector<std::vector<double>> iGradsAcc (nItems, 
      std::vector<double>(facDim,0)); 

  //std::cout << "\nNNZ = " << nnz;
  prevObj = objective(data, invalidUsers, invalidItems);
  bestObj = prevObj;
  std::cout << "\nObj aftr svd: " << prevObj << " Train RMSE: " << RMSE(data.trainMat);


  std::chrono::time_point<std::chrono::system_clock> start, end;
  std::chrono::duration<double> duration;
  
  std::vector<std::unordered_set<int>> uISet(nUsers);
  genStats(trainMat, uISet, std::to_string(trainSeed));
  getInvalidUsersItems(trainMat, uISet, invalidUsers, invalidItems);
  
  std::unordered_set<int> headItems = getHeadItems(trainMat, 0.5);
  std::unordered_set<int> headUsers = getHeadItems(trainMat, 0.5);
  double lambda0 = 0.8;
  double lambda1 = 1.0 - lambda0;

  //random engine
  std::mt19937 mt(trainSeed);
  //get user-item ratings from training data
  auto uiRatings = getUIRatings(trainMat, invalidUsers, invalidItems);
  //index to above uiRatings pair
  std::vector<size_t> uiRatingInds(uiRatings.size());
  std::iota(uiRatingInds.begin(), uiRatingInds.end(), 0);


  std::cout << "\nTrain NNZ after removing invalid users and items: " 
    << uiRatings.size() << std::endl;
  double subIterDuration = 0;
  for (iter = 0; iter < maxIter; iter++) {  
    
    //shuffle the user item rating indexes
    std::shuffle(uiRatingInds.begin(), uiRatingInds.end(), mt);

    start = std::chrono::system_clock::now();
    const int indsSz = uiRatingInds.size();
#pragma omp parallel for
    for (int k = 0; k < indsSz; k++) {
      auto ind = uiRatingInds[k];
      //get user, item and rating
      int u       = std::get<0>(uiRatings[ind]);
      int item    = std::get<1>(uiRatings[ind]);
      float itemRat = std::get<2>(uiRatings[ind]);
      
      double r_ui_est = dotProd(uFac[u], iFac[item], facDim);
      double diff = itemRat - r_ui_est;

      if (headItems.find(item) != headItems.end()) {
        diff = diff*lambda0;
      } else {
        diff = diff*(lambda0 + lambda1);
      }

      //update user
      for (int i = 0; i < facDim; i++) {
        uFac[u][i] -= learnRate*(-2.0*diff*iFac[item][i] + 2.0*uReg*uFac[u][i]);
      }


      r_ui_est = dotProd(uFac[u], iFac[item], facDim);
      diff = itemRat - r_ui_est;
    
      if (headItems.find(item) != headItems.end()) {
        diff = diff*lambda0;
      } else {
        diff = diff*(lambda0 + lambda1);
      }

      //update item
      for (int i = 0; i < facDim; i++) {
        iFac[item][i] -= learnRate*(-2.0*diff*uFac[u][i] + 2.0*iReg*iFac[item][i]);
      }
    }
    end = std::chrono::system_clock::now();  
   
    duration =  end - start;
    subIterDuration = duration.count();

    //check objective
    if (iter % OBJ_ITER == 0 || iter == maxIter-1) {
      if (isTerminateModel(bestModel, data, iter, bestIter, bestObj, prevObj,
            invalidUsers, invalidItems)) {
        break; 
      }

      if (iter % 50 == 0) {
        std::cout << "ModelMFWt::train trainSeed: " << trainSeed
                  << " Iter: " << iter << " Objective: " << std::scientific << prevObj 
                  << " Train RMSE: " << RMSE(data.trainMat, invalidUsers, invalidItems)
                  << " Val RMSE: " << prevValRMSE
                  << " sub duration: " << subIterDuration
                  << std::endl;
      }

      if (iter % 500 == 0 || iter == maxIter - 1) {
        std::string modelFName = std::string(data.prefix);
        bestModel.saveFacs(modelFName);
      }

    }
     
  }
      
  //save best model found till now
  std::string modelFName = std::string(data.prefix);
  bestModel.saveFacs(modelFName);

  std::cout << "\nBest model validation RMSE: " << bestModel.RMSE(data.valMat, 
      invalidUsers, invalidItems);
}
Beispiel #15
0
int teleport_command(string cmd)
{
  if (!cmd) {
    if (!this_player()->query_battleob()) {
      if(!environment(this_player())->query_no_teleport()) {    
        object p = this_player();
        switch (this_player()->query_home_town()) {
        case "vaerlon":
        htst = "Vaerlon";
        destination = "/d/valkor/vaerlon/rooms/streets/h4.c";
        break;

        case "graemor":
        htst = "Graemor";
        destination = "/d/graemor/virtual/9,18.graemor-part1.c";
        break;

        case "teladan":
        htst = "Teladan";
        destination = "/u/t/tarak/areas/town/rooms/f8.c";
        break;
            
        case "cenedoiss":
        htst = "Cenedoiss";
        destination = "/u/b/belannaer/virtual/18,27.cenedoiss.c";
        break;
      
        //case "mahrakc": ?
  
        case "atherton":
        htst = "Atherton";
        destination = "/u/b/belannaer/virtual/14,13.atherton.c";
        break;

        default:
        htst = "Vaerlon";
        destination = "/d/valkor/vaerlon/rooms/streets/h4.c";
        break;
        }
        message("teleport", "You rub the Ring of Teleportation while thinking "+
        "of your hometown. The air around you shimmers and suddenly you find "+
        "yourself standing in the central square of "+htst+".\n", p);
        message("teleport", ""+p->query_cap_name()+" rubs "+possessive(p)+" "+
        "Ring of Teleportation. The air around "+objective(p)+" starts to "+
        "distort, and suddenly in the blink of an eye "+subjective(p)+" "+
        "disappears.\n", environment(p), p);
        p->move(destination);
        charges--;
        if (charges < 1) {
        call_out("destruct_me", 1);
        }
      } else {
        message("info", "Strange energy fluctuations in this room prevent "+
        "you from teleporting...\n", this_player()); 
      }
    } else {
	  message("info", "You are too busy fighting to do that!\n", this_player());   
    }
    return 1;
  }
}
Beispiel #16
0
int * Simulate(NODE *graph,int Max,int fault_node,int type_of_fault,int npi)
{
LIST *fanin,*temp;
LIST *frontier=NULL;
LIST *event = NULL;
LIST *improve = NULL;
char line[Mlin],str1[Mlin];
int i,j,length,output_number ,k,index;
int inp_value,inp_node;
int node_id,value,input_value,line_number,next_value;
int test,check,obj,eof_flag;
int f_node,f_value,detected,new_input,error,flag;
//error reports
int coverage,event_null,nodes_number;
coverage = event_null = nodes_number = 0;

	//init_node(graph , Max);
	depth(graph,Max);
controllability(graph,Max);

clock_t begin,end;
begin = clock();

int * vector = (int *) malloc(npi*sizeof(int));

nodes_number++;
	detected = 0;
	error = 0;
	f_node = node_id =fault_node;
	f_value = value = type_of_fault;
	while(detected != 1 && error != 1){
	new_input = 0;
	controllability(graph,Max);
	obj = objective(graph,Max,&node_id,&value,f_node,f_value,&frontier);
	backtrace(graph,node_id,value,&inp_value,&inp_node,&new_input);
	push (&event,inp_node);
	detected = Evaluation(graph,Max,inp_node,inp_value,f_node,f_value);
	d_frontier(graph,Max,&frontier);
		if(detected == 1){
			 //printf("\n------------------------DETECTED-----------------\n");
			for(j=0;j<=Max;j++){
				if(graph[j].Type == INPT){
					vector[j-1] = graph[j].Cval;
					//fprintf(fres,"%d",input_value);	
				}
			}
			coverage++;
		} else {
			if(obj == 1 && frontier == NULL){
				 if(detected != 1)
					//printf("\n----------NOT DETECTED--------------(path blocked)");
			error = 1;
			}
			if(obj == 3) {
				error = 1;
				//printf("\n----------NOT DETECTED--------------(fault masked)");
			} 
			if(new_input ==0 ) {
				error = 1;
				//printf("\n----------NOT NEW INPUT -----------");
			}
			while(error == 1){
				//printf("\n------------trying to backtrack-------------");
				inp_node = pop(&event);
				inp_value = invert(inp_value);
				frontier=NULL;
				detected = Evaluation(graph,Max,inp_node,inp_value,f_node,f_value);
				d_frontier(graph,Max,&frontier); 
				if(event == NULL){
					error = 0;
					detected = 1;
					//printf("\ncase event null");
					event_null++;
					push (&improve,f_node); 
				}else if(detected != 1 && frontier != NULL) {
					error = 0;
					//printf("\ncase continue");
				}else if(detected == 1){
					error = 0;
					detected = 1;
					for(j=0;j<=Max;j++){
						if(graph[j].Type == INPT){
							vector[j-1] = graph[j].Cval;
							//fprintf(fres,"%d",input_value);	
						}
					}
					//printf("\n------------------------DETECTED-----------------\n");
					coverage++;
				}else if(frontier == NULL) {
					error = 1;
					//printf("\ncase next value from event list");
				}
			}
		}
	}
	//init_node(graph , Max);
	if(frontier!=NULL) frontier=NULL; event = NULL;

/*
//try to improve the coverage
//printf("\n-----TRY to improve the coverage");
temp = improve;
while(temp!=NULL){
detected = 0;
error = 0;
f_node = node_id =temp->id;
f_value = value = type_of_fault;
	while(detected != 1 && error != 1){
	new_input = 0;
	controllability(graph,Max);
	obj = objective(graph,Max,&node_id,&value,f_node,f_value,&frontier);
	backtrace(graph,node_id,value,&inp_value,&inp_node,&new_input);
	push (&event,inp_node);
	detected = Evaluation(graph,Max,inp_node,inp_value,f_node,f_value);
	d_frontier(graph,Max,&frontier);
	if(detected == 1){
		//printf("\n------------------------DETECTED AT FIRST BACKTRACK-----------------\n");
			for(j=0;j<=Max;j++){
				if(graph[j].Type == INPT){
					vector[j-1] = graph[j].Cval;
					//fprintf(fres,"%d",input_value);	
				}
			}
		coverage++;
	} else {
		if(obj == 1 && frontier == NULL){
			 if(detected != 1) {
				//printf("\n----------NOT DETECTED--------------(path blocked)");
			} 
		error = 1;
		}
		if(obj == 3) {
			error = 1;
			//printf("\n----------NOT DETECTED--------------(fault masked)");
			} 
		if(new_input ==0 ) {
			error = 1;
			//printf("\n----------NOT NEW INPUT -----------");
			}
		if(error == 1){
			//printf("\n------------trying to backtrack-----------------");
			inp_node = pop(&event);
			graph[inp_node].Cval = 2;
			inp_node = pop(&event);
			inp_value = invert(inp_value);
			frontier=NULL;
			detected = Evaluation(graph,Max,inp_node,inp_value,f_node,f_value);
			d_frontier(graph,Max,&frontier); 
			if(event == NULL){
				error = 0;
				detected = 1;
				//printf("\ncase event null"); 
			}else if(detected != 1 && frontier != NULL) {
				error = 0;
				//printf("\ncase continue");
			}else if(detected == 1){
				error = 0;
				detected = 1;
				//printf("\n------------------------DETECTED AT FIRST BACKTRACK-----------------\n");
				for(j=0;j<=Max;j++){
					if(graph[j].Type == INPT){
						vector[j-1] = graph[j].Cval;
						//fprintf(fres,"%d",input_value);	
					}
				}
				coverage++;
			}else if(frontier == NULL) {
				error = 0;
			}
		}
	}
	}
	//init_node(graph , Max);
	if(frontier!=NULL) frontier=NULL; event = NULL;
temp = temp->next;
}*/
printf("\nTotal number of nodes %d and faults detected %d and event list is empty %d and not detected %d \n",nodes_number,coverage,event_null,nodes_number-coverage);
printf("------------------------RESULTS---------------------------\n\tTOTAl FAULTS->%d\n\tDETECTED->%d\n\tPERCENTAGE->%g\r\n",nodes_number,coverage,(((double)coverage)/nodes_number*100));
end = clock();
printf("\nTIME SPENT TO GENERATE THE PATTERNS %f\n",(double)(end-begin)/CLOCKS_PER_SEC);
return vector;
}//end of Simulate function
Beispiel #17
0
int logisticloss::logexp(int index, double* v, int n, double lambda, double* x, int MAXITER, double epsilon, int DISPLAY) {
    /* solution to - log exp(x(i))/sum(exp(x(j))) + lambda/2 ||x - v||_2^2 */
    /* n is length of v and x */
    /* writes over x */
    double alpha = 0.1;
    double beta = 0.5;
    int iter, i;
    double t, logsum, p, pu, pptil, decrement;
    double *u = (double *) malloc(n*sizeof(double));
    double *z = (double *) malloc(n*sizeof(double));
    double *grad = (double *) malloc(n*sizeof(double));
    double newobj=0.0, obj=0.0;
    obj = objective(index, x, v, n, lambda);

    for(iter=0;iter<MAXITER;iter++) {
        logsum = logsumexp(x,n);
        if(DISPLAY)
            printf("iter=%d, obj=%f\n", iter, obj);
        pu = 0.0;
        pptil = 0.0;
        for(i=0;i<n;i++) {
            p = exp(x[i] - logsum);
            grad[i] = p + lambda*(x[i] - v[i]);
            if(i==index)
                grad[i] += -1.0;
            u[i] = grad[i]/(p+lambda);
            pu += p*u[i];
            z[i] = p/(p+lambda);
            pptil += z[i]*p;
        }
        pptil = 1 - pptil;
        decrement = 0.0;
        for(i=0;i<n;i++) {
            u[i] -= (pu/pptil)*z[i];
            decrement += grad[i]*u[i];
        }
        if (decrement < 2*epsilon) {
        	// std::cout << "decrement =  " << decrement << std::endl;
            free(u);
            free(z);
            free(grad);
            return 0;
        }
        t = 1.0;
        while(1) {
            for(i=0;i<n;i++)
                z[i] = x[i] - t*u[i];
            newobj = objective(index, z, v, n, lambda);
            if (newobj <= obj + alpha*t*decrement)
                break;
            t = beta*t;
        }
        for(i=0;i<n;i++)
            x[i] = z[i];
            obj = newobj;
    }
    free(u);
    free(z);
    free(grad);
    return 1;
}
//-------------------------------------------------------
main() {
 int Gbs_x=map_x/Rbs; // Number of grids on y=1
 int Gbs_y=map_y/Rbs; // Number of grids on x=1
 int Nbs_x1=floor(Gbs_x/2);	//Number og BSs on y=1
 int Nbs_x2=floor(((map_x-Rbs)/Rbs)/2);	//Number og BSs on y=2
 int Nbs_y1=floor(Gbs_y/2);	//Number og BSs on x=1
 int Nbs_y2=floor(((map_y-Rbs)/Rbs)/2);	//Number og BSs on x=2
 int Tbs=(Nbs_x1*Nbs_y1)+(Nbs_x2*Nbs_y2);	//Total BS on map
 int length=Rbs/space;	//real length
 int Px=map_x/space;	//number of points on x-axis
 int Py=map_y/space;	//number of points on y-axis
 double TN;	//Thermal Noise
 int i,j;

 ptrD=&D[0][0];
 ptrBR=&BR[0];
 ptrModulation=&Modulation[0];
 ptrSensitivity=&Sensitivity[0];
 ptrDP=&DP[0];
 ptrSNR=&SNR[0];
 ptrBPL=&BPL[0];
 ptrLT=&LT[0];
 ptrDS=&DS[0];
 ptrPLT=&PathLossType[0][0];
 ptrPL=&PL[0][0];
 //ptrP=&P[0][0];
//printf("\n%d\n",Nbs_x1);printf("\n%d\n",Nbs_x2);printf("\n%d\n",Nbs_y1);printf("\n%d\n",Nbs_y2);printf("\n%d\n",Tbs);

 //for(counter=0;counter<_t;counter++)
	 //totalr+=R[counter];//totalr = 4+6+8+5+2


 //checkInputs();
 fillCoordinatesBSs(Xbs,Ybs,Gbs_x,Gbs_y,Nbs_x1,Nbs_x2,Nbs_y1,Nbs_y2,length); 
 /*for(i=1;i<=Tbs;i++)
	 printf("Xbs[%d],Ybs[%d]=(%d,%d)\n",i,i,Xbs[i],Ybs[i]);
 printf("\n");*/
 fillCoordinatesTPs(Xtp,Ytp,Px,Py,Tbs,Xbs,Ybs);
 /*for(i=1;i<=Ntp;i++)
	 printf("Xtp[%d],Ytp[%d]=(%d,%d)\n",i,i,Xtp[i],Ytp[i]);*/
 fillDistance(Xbs,Ybs,Xtp,Ytp,ptrD,Tbs);
 printf("\n");
/*for(i=1;i<=Tbs;i++)
	for(j=1;j<=Ntp;j++)
		printf("D[%d][%d]=%.2lf\n",i,j,D[i][j]);
printf("\n");	*/
 fillMs(ptrBR);
/* for(i=1;i<=Ntp;i++)
	 printf("BR[%d]:%.2lf Mbps\n",i,BR[i]);
 printf("\n");*/
 TN=ThermalNoise();
 //printf("%.2lf\n",TN);
 //printf("\n");
 modulation(TN,ptrBR,Modulation,Sensitivity,DP,SNR);
 //for(i=1;i<=Ntp;i++)
//	 printf("TP[%d] with modulation %d, DP: %.2lf, SNR: %.2lf, S: %.2lf\n",i,Modulation[i],DP[i],SNR[i],Sensitivity[i]);
 //printf("\n");
 LocationType(ptrLT,Xtp,Ytp);
 bpl(ptrLT,ptrBPL);
 //for(i=1;i<=Ntp;i++)
//	 printf("TP[%d]'s location type is %d, bpl is %d\n",i,LT[i],BPL[i]);
 DataSubcarriers(ptrDS,ptrBR,ptrDP);
 //printf("\n");
 //for(i=1;i<=Ntp;i++)
//	 printf("data subcarriers for TP[%d]:%d\n",i,DS[i]);
// printf("\n");
 
 PathLoss(ptrD,ptrPLT,ptrLT,Tbs,ptrPL);
power(Tbs,TN);
FixedCellSize(Tbs,DS,ptrD,P[0],ptrBR,Xbs,Ybs,Xtp,Ytp);

FILE *PowerSavingCPLEX;
if((PowerSavingCPLEX=fopen("PowerSavingCPLEX","w"))==NULL)
	printf("\nerror!Fail to open file!");
else
	printf("\nOpen PowerSavingCPLEX successfully!\n");
fprintf(PowerSavingCPLEX,"This is the input to CPLEX for power saving model.\n");
 objective(Tbs,PowerSavingCPLEX);
fprintf(PowerSavingCPLEX,"st\n");
 printf("st\n");
 constraint1(Tbs,ptrDS,PowerSavingCPLEX);
 constraint2(Tbs,PowerSavingCPLEX);
 constraint3(Tbs,PowerSavingCPLEX);
 constraint4(Tbs,PowerSavingCPLEX);
 constraint5(Tbs,PowerSavingCPLEX);
 //constraint5(nr,nt,totalr);
 constraint6(Tbs,PowerSavingCPLEX);
 constraint7(Tbs);
 constraint8(Tbs);
 constraint9(Tbs);
fprintf(PowerSavingCPLEX,"bounds\n");
 printf("bounds\n");
 bounds(Tbs,PowerSavingCPLEX);

 specifyTypes(Tbs,PowerSavingCPLEX);
fprintf(PowerSavingCPLEX,"end\n");
 printf("end\n");
fclose(PowerSavingCPLEX);
 checkMSsites(Tbs);
	heuristic(Tbs,P[0],Ntp,MP,DSt,BP,DS,Xbs,Ybs,Xtp,Ytp,ptrD,BR);
	printf("===================================================================================================================================\n");
	Sheuristic(Tbs,P[0],Ntp,MP,DSt,BP,DS,Xbs,Ybs,Xtp,Ytp,ptrD,BR); 

FILE *outfile, *outfile1;
 if ((outfile=fopen("outfile1.txt", "w")) == NULL)
printf("\n\nerror!Fail to open file!");
else
printf("\n\nOpen file successfully!\n");
fprintf(outfile,"BS%dMS%dBP%g\n",Tbs,Ntp,BP);
for(i=1;i<=Tbs;i++)
for(j=1;j<=Ntp;j++)
	fprintf(outfile,"%d. BS[%d]=%d,%d MS[%d]=%d,%d DS=%d power=%g mW BW=%g Mbps\n",(i-1)*Ntp+j,i,Xbs[i],Ybs[i],j,Xtp[j],Ytp[j],DS[j],P[i][j],BR[j]);
fclose(outfile);

if ((outfile1=fopen("coordinates.txt", "w")) == NULL)
printf("\n\nerror!Fail to open file!");
else
printf("\n\nOpen coordinates.txt successfully!\n");

fprintf(outfile1,"#BS%dMS%dBP%g\n",Tbs,Ntp,BP);
for(i=1;i<=Tbs;i++){
for(j=1;j<=Ntp;j++)
fprintf(outfile1,"%d. BS[%d] %d %d MS[%d] %d %d DS %d power %g mW BW %g Mbps\n",(i-1)*Ntp+j,i,Xbs[i],Ybs[i],j,Xtp[j],Ytp[j],DS[j],P[i][j],BR[j]);
}
fprintf(outfile1,"\n\n");
for(i=1;i<=Tbs;i++)
fprintf(outfile1," BS[%d]=%d,%d \n",i,Xbs[i],Ybs[i]);

fclose(outfile1);
 //system("pause");
 return;
}
Beispiel #19
0
void GaussianProcess::optimize()
{
	const double dp = 0.1;
	const double dp_squared = dp*dp;
	const double step_size = 0.1;
	double err = 1000000000000000.0;

// 	const double beta = 0.8;

	unsigned int iter = 0;
// 	VectorXd params(params_orig.size());
	VectorXd params = kernel->params;
	VectorXd params_orig = kernel->params;
	double base = objective(params_orig);

	VectorXd gradient(params.size());
	MatrixXd hessian(params.size(),params.size());
	double alpha = 10000;
	while (err > 0.0001 && iter < 5000){
// 	while (iter < 100){
		params_orig = params;	
		for (unsigned int i = 0; i < params.size(); ++i){
			params(i) = params_orig(i) + dp;
			std::cout << params.transpose() << std::endl;
			const double v1 = objective(params);
			params(i) = params_orig(i) - dp;
			const double v2 = objective(params);
			std::cout << v1 <<","<< v2<<std::endl;

			gradient(i) = (v1 - v2)/(2.*dp);
// 			hessian(i,i) = alpha + (v1 - 2.*base - v2)/dp_squared;
// 			alpha = 0.95*alpha;
			params(i) = params_orig(i);
/*
			for (unsigned j = i+1; j < params.size(); ++j){
				params(i) = params_orig(i) + dp;
				params(j) = params_orig(j) + dp;
				const double h1 = objective(params);

				params(i) = params_orig(i) + dp;
				params(j) = params_orig(j) - dp;
				const double h2 = objective(params);

				params(i) = params_orig(i) - dp;
				params(j) = params_orig(j) + dp;
				const double h3 = objective(params);
				
				params(i) = params_orig(i) - dp;
				params(j) = params_orig(j) - dp;
				const double h4 = objective(params);
	
				const double h_val = (h1 - h2 - h3 + h4)/(4.*dp_squared);
				hessian(i,j) = h_val;
				hessian(j,i) = h_val;
			}
*/
		}

// 		const VectorXd d_param = hessian.inverse()*gradient;
 		std::cout << "Before: " << params.transpose() << std::endl;
		const VectorXd d_param = step_size*gradient;
 		std::cout << d_param.transpose() << std::endl;
		params -= d_param; 
 		std::cout <<  "After: " << params.transpose() << std::endl;
		const double val = objective(params);
		std::cout << val <<std::endl;
		kernel->params = params;
		err = fabs(val - base);///fabs(base);
// 		std::cout << gradient.transpose() << std::endl;
// 		std::cout << err << ", " << val << std::endl;
		base = val;
		/*
		if (iter % 10){
			std::cout << val << " " << kernel->params.transpose() << std::endl;
		}
		*/
		iter += 1;
	} // end while (err > 0.0001)


	
}
Beispiel #20
0
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
	double *v, *x, sigma, *lambda, *pr; mwIndex *ir, *jc;
	char *mode; int imode;

    //Check Inputs
    if(nrhs < 1) {
        printInfo();        
        return;
    }   
    if(nrhs < 2) {
        mexErrMsgTxt("You must supply the callback mode and input vector.");
        return;
    }
    if(mxIsEmpty(prhs[0]) || !mxIsChar(prhs[0])) {
        mexErrMsgTxt("The mode must be a string!");
        return;
    }
    if(!mxIsEmpty(prhs[1])) {
        if(mxIsClass(prhs[1],"scipvar") || mxIsClass(prhs[1],"barvec")) {
            mexErrMsgTxt("SCIP and BARON cannot be used with this callback function - please specify 'mcode' via symbset as the cbmode.");
            return;
        }           
        if(!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1])) {
            mexErrMsgTxt("The input vector must be a dense real double vector!");
            return;
        }
    }
    else {
        mexErrMsgTxt("The input vector must be a dense real double vector!");
        return;
    }
	//Check x input size
	if(mxGetNumberOfElements(prhs[1]) != getNoVar()) {
		mexErrMsgTxt("The input vector is not the right size!");
	}
	//Get x
	x = mxGetPr(prhs[1]);
	
	//Determine input mode and setup return variable
	mode = mxArrayToString(prhs[0]);
	lower(mode);
	if(!strcmp(mode,"obj")) {
		imode = 0;
		plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
		v = mxGetPr(plhs[0]);
	}
	else if(!strcmp(mode,"grad")) {
		imode = 1;
		plhs[0] = mxCreateDoubleMatrix(1,getNoVar(), mxREAL);
		v = mxGetPr(plhs[0]);
	}
	else if(!strcmp(mode,"con")) {
		imode = 2;
		plhs[0] = mxCreateDoubleMatrix(getNoCon(),1, mxREAL);
		v = mxGetPr(plhs[0]);
	}
	else if(!strcmp(mode,"jac")) {
		imode = 3;
		plhs[0] = mxCreateSparse(getNoCon(),getNoVar(),getNNZJac(),mxREAL);   
		pr = mxGetPr(plhs[0]);
		ir = mxGetIr(plhs[0]);
		jc = mxGetJc(plhs[0]);
	}
	else if(!strcmp(mode,"hess")) {
		if(nrhs < 4) {
			mexErrMsgTxt("You must supply the callback mode, input vector, sigma and lambda for Hessian Evaluations.");
			return;
		}
		//Check length of Sigma
		if(mxIsEmpty(prhs[2]) || !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || mxGetNumberOfElements(prhs[2]) != 1)
			mexErrMsgTxt("Sigma must be a real, double scalar.");
		//Check length of Lambda
		if(!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || mxGetNumberOfElements(prhs[3]) != getNoCon())
			mexErrMsgTxt("Lambda must be a real, double, dense vector with ncon elements.");
		//Get Sigma, Lambda
		sigma = *mxGetPr(prhs[2]);
		lambda = mxGetPr(prhs[3]);
		imode = 4;
		plhs[0] = mxCreateSparse(getNoVar(),getNoVar(),getNNZHess(),mxREAL);   
		pr = mxGetPr(plhs[0]);
		ir = mxGetIr(plhs[0]);
		jc = mxGetJc(plhs[0]);
	}
	else
		mexErrMsgTxt("Unknown mode - options are 'obj', 'grad', 'con', 'jac', or 'hess'");
	mxFree(mode);
	
	
	//Call Req Callback
	switch(imode)
	{
		case 0: //objective
			*v = objective(x);
			break;
		case 1: //gradient
			gradient(x,v);
			break;
		case 2: //constraints
			constraints(x,v);
			break;
		case 3: //jacobian
			jacobian(x,pr,ir,jc);
			break;
		case 4: //hessian
			hessian(x,sigma,lambda,pr,ir,jc);
			break;
	}
}
Beispiel #21
0
void PathWorldState::Init()
{
	SetResourcesFilePath("Fonts/nokiafc22.ttf");
	fontSmall = FC_CreateFont();
	FC_LoadFont(fontSmall, display->renderer, resourcesFilePath, 30, FC_MakeColor(255, 255, 255, 255), TTF_STYLE_NORMAL);
	fontBig = FC_CreateFont();
	FC_LoadFont(fontBig, display->renderer, resourcesFilePath, 40, FC_MakeColor(255, 255, 255, 255), TTF_STYLE_NORMAL);
	// Initialize Graph Texture
	graphTexture = {};
	StaticTexture_Init(&graphTexture, FIXED_WIDTH, FIXED_HEIGHT, display->renderer);
	StaticTexture_StartDrawing(&graphTexture);
	arrowTexture = {};
	SetResourcesFilePath("Images/Arrow.png");
	if (Texture_LoadFromFile(&arrowTexture, display->renderer, resourcesFilePath) == false)
	{
		SDL_Log("Failed to load Image!\n");
	}
	boidTexture = {};
	SetResourcesFilePath("Images/Boid.png");
	if (Texture_LoadFromFile(&boidTexture, display->renderer, resourcesFilePath) == false)
	{
		SDL_Log("Failed to load Image!\n");
	}
	heroTexture = {};
	SetResourcesFilePath("Images/Player.png");
	if (Texture_LoadFromFile(&heroTexture, display->renderer, resourcesFilePath) == false)
	{
		SDL_Log("Failed to load Image!\n");
	}
	startX = 19;
	startY = 9;
	origin.x = 170;
	origin.y = 40;
	hero.position.x = 20 * labyrinth.cellSize + origin.x + 15;
	hero.position.y = 9 * labyrinth.cellSize + origin.y + 15;
	hero.width = heroTexture.width;
	hero.height = heroTexture.height;
	initMinotaur();

	objective();
	std::vector<Node*> camino = PathfindingUtils::PathfindAStar(&labyrinth, &labyrinth.array[startX][startY], &labyrinth.array[endX][endY]);
	way.pathOccupation = camino.size();
	
	for (int i = 0; i < camino.size(); i++)
	{
		way.pathArray[i] = camino[i]->position*labyrinth.cellSize;
		way.pathArray[i].x += origin.x + 10;
		way.pathArray[i].y += origin.y + 10;
	}
	
	StaticTexture_EndDrawing(&graphTexture);
	
	labyrinth = {};
	Grid_Init(&labyrinth);
	for (int i = 0; i < labyrinth.width; ++i)
	{
		for (int j = 0; j < labyrinth.height; ++j)
		{
			if (TEMPLATE_1[i][j] == 9)
			{
				labyrinth.array[i][j].isWall = true;
			}
			else
			{
				labyrinth.array[i][j].isWall = false;
				if (TEMPLATE_1[i][j] != 0)
				{
					labyrinth.array[i][j].weight = (float)TEMPLATE_1[i][j];
				}
			}
		}
	}
	hero.simplePath = &way;
	hero.SetBehaviour(Behaviour::SIMPLE_PATH_FOLLOWING);
}
Beispiel #22
0
                for (unsigned i = 0; i < other.size(); ++i) {
                    resolve(bound_row_index, bound_coeff, other[i], x);
                }
                // coeff*x + objective <= ub
                // a2*x + t2 <= 0
                // => coeff*x <= -t2*coeff/a2
                // objective + t2*coeff/a2 <= ub

                mul_add(m_objective_id, - coeff/bound_coeff, bound_row_index);
                m_rows[bound_row_index].m_alive = false;
            }
            else {
                return unbounded;
            }
        }
        value = objective().m_value;
        if (objective().m_type == t_lt) {
            return strict;
        }
        else {
            return non_strict;
        }
    }

    bool model_based_opt::find_bound(unsigned x, unsigned& bound_row_index, rational& bound_coeff, unsigned_vector& other, bool is_pos) {
        bound_row_index = UINT_MAX;
        rational lub_val;
        rational const& x_val = m_var2value[x];
        unsigned_vector const& row_ids = m_var2row_ids[x];
        for (unsigned i = 0; i < row_ids.size(); ++i) {
            unsigned row_id = row_ids[i];
Beispiel #23
0
int main(int argc, char **argv) {

  const int MAX_ITER  = 20;
  const double TOL = 1e-12;
  
  int rank;
  int size;
  int P = 8; // number of blocks to update P <= size

  /* -----------------------------------
     mode controls the selection schemes, 
       mode =0, fixed P
       mode =1, dynamic update P
     ----------------------------------*/
  int mode=1; // number of processors used to update each time
  double lambda = 0.1;
  srand (time(NULL));
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Determine current running process
  MPI_Comm_size(MPI_COMM_WORLD, &size); // Total number of processes
  
  // data directory (you need to change the path to your own data directory)
  char* dataCenterDir = "../Data/Gaussian";
  char* big_dir;
  if(argc==2)
    big_dir = argv[1];
  else
    big_dir = "big1";

  /* Read in local data */
  
  FILE *f, *test;
  int m, n, j;
  int row, col;
  double entry, startTime, endTime;
  double total_start_time, total_end_time;
  /*
   * Subsystem n will look for files called An.dat and bn.dat
   * in the current directory; these are its local data and do not need to be
   * visible to any other processes. Note that
   * m and n here refer to the dimensions of the *local* coefficient matrix.
   */
  
  /* ------------
     Read in A 
     ------------*/
  if(rank ==0){
    printf("=============================\n");
    printf("|    Start to load data!     |\n");
    printf("=============================\n");
  }
  char s[100];
  sprintf(s, "%s/%s/A%d.dat",dataCenterDir,big_dir, rank + 1);
  printf("[%d] reading %s\n", rank, s);
  f = fopen(s, "r");
  if (f == NULL) {
    printf("[%d] ERROR: %s does not exist, exiting.\n", rank, s);
    exit(EXIT_FAILURE);
  }
  mm_read_mtx_array_size(f, &m, &n);
  gsl_matrix *A = gsl_matrix_calloc(m, n);
  for (int i = 0; i < m*n; i++) {
    row = i % m;
    col = floor(i/m);
    fscanf(f, "%lf", &entry);
    gsl_matrix_set(A, row, col, entry);
  }
  fclose(f);
  
  /* ------------
      Read in b 
     -------------*/
  sprintf(s, "%s/%s/b.dat", dataCenterDir, big_dir);
  printf("[%d] reading %s\n", rank, s);
  f = fopen(s, "r");
  if (f == NULL) {
    printf("[%d] ERROR: %s does not exist, exiting.\n", rank, s);
    exit(EXIT_FAILURE);
  }
  mm_read_mtx_array_size(f, &m, &n);
  gsl_vector *b = gsl_vector_calloc(m);
  for (int i = 0; i < m; i++) {
    fscanf(f, "%lf", &entry);
    gsl_vector_set(b, i, entry);
  }
  fclose(f);
  
  /* ------------
     Read in xs 
     ------------*/
  sprintf(s, "%s/%s/xs%d.dat", dataCenterDir, big_dir, rank + 1);
  printf("[%d] reading %s\n", rank, s);
  f = fopen(s, "r");
  if (f == NULL) {
    printf("[%d] ERROR: %s does not exist, exiting.\n", rank, s);
    exit(EXIT_FAILURE);
  }
  mm_read_mtx_array_size(f, &m, &n);
  gsl_vector *xs = gsl_vector_calloc(m);
  
  for (int i = 0; i < m; i++) {
    fscanf(f, "%lf", &entry);
    gsl_vector_set(xs, i, entry);
  }
  fclose(f);
  
  m = A->size1;
  n = A->size2;
  MPI_Barrier(MPI_COMM_WORLD);
  
  /*----------------------------------------
   * These are all variables related to GRock
   ----------------------------------------*/
  
  struct value table[size];
  gsl_vector *x        = gsl_vector_calloc(n);
  gsl_vector *As       = gsl_vector_calloc(n);
  gsl_vector *invAs    = gsl_vector_calloc(n);
  gsl_vector *local_b  = gsl_vector_calloc(m);
  gsl_vector *beta     = gsl_vector_calloc(n);
  gsl_vector *tmp      = gsl_vector_calloc(n);
  gsl_vector *d        = gsl_vector_calloc(n);
  gsl_vector *absd     = gsl_vector_calloc(n);
  gsl_vector *oldx     = gsl_vector_calloc(n);
  gsl_vector *tmpx     = gsl_vector_calloc(n);
  gsl_vector *z        = gsl_vector_calloc(m);
  gsl_vector *tmpz     = gsl_vector_calloc(m);
  gsl_vector *Ax       = gsl_vector_calloc(m);
  gsl_vector *Atmpx    = gsl_vector_calloc(m);
  gsl_vector *xdiff    = gsl_vector_calloc(n);
  gsl_permutation *idx = gsl_permutation_calloc(n);
  double send[1]; 
  double recv[1]; 
  double err;

  int num_upd = (int)(n*0.08);
  double sigma = 0.01;

  double xs_local_nrm[1], xs_nrm[1];
  double local_old_obj, global_old_obj, local_new_obj, global_new_obj;
  //calculate the 2 norm of xs
  xs_local_nrm[0] = gsl_blas_dnrm2(xs);
  xs_local_nrm[0] *=xs_local_nrm[0];
  MPI_Allreduce(xs_local_nrm, xs_nrm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
  xs_nrm[0] = sqrt(xs_nrm[0]);
  
  // evaluate the two norm of the columns of A
  for(j=0;j<n;j++){
    gsl_vector_view column = gsl_matrix_column(A, j);
    double d;
    d = gsl_blas_dnrm2(&column.vector);
    gsl_vector_set(As, j, d*d);
    gsl_vector_set(invAs, j, 1./(d*d));
  }
  
  if (rank == 0) {
    printf("=============================\n");
    printf("|GRock start to solve Lasso!|\n");
    printf("|---------------------------|\n");
    printf("|lambda=%1.2f, m=%d, n=%d  |\n", lambda, m, n*size);
    if(mode==1) printf("| Mode: dynamic update P.   |\n");
    else  printf("|   Mode: fixed update P    |\n");
    printf("=============================\n");
    printf("%3s %8s %8s %5s\n", "iter", "rel_err", "obj", "P");
    startTime = MPI_Wtime();
    sprintf(s, "results/test%d.m", size);
    test = fopen(s, "w");
    fprintf(test,"res = [ \n");
  }
  
  /* Main BCD loop */
  total_start_time = MPI_Wtime();
  int iter = 0;
  while (iter < MAX_ITER) {
    startTime = MPI_Wtime();

    /*---------- restore the old x ------------*/
    gsl_vector_memcpy(oldx, x);
    
    /*------- calculate local_b = b - sum_{j \neq i} Aj*xj--------- */ 
    gsl_blas_dgemv(CblasNoTrans, 1, A, x, 0, Ax); // Ax = A * x
    MPI_Allreduce(Ax->data, z->data,  m, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    gsl_vector_sub(z, b); // z = Ax - b
    gsl_vector_memcpy(local_b, Ax);
    gsl_vector_sub(local_b, z);
    
    /* -------calculate beta ------------------*/
    gsl_blas_dgemv(CblasTrans, -1, A, z, 0, beta); // beta = A'(b - Ax) + ||A.s||^2 * xs
    gsl_vector_memcpy(tmp, As);    
    pointwise(tmp, x, n);
    gsl_vector_add(beta, tmp);
    shrink(beta, lambda);
    // x = 1/|xs|^2 * shrink(beta, lambda)
    gsl_vector_memcpy(x, beta);
    pointwise(x, invAs, n); 
  
    /* ------calcuate proposed decrease -------- */
    gsl_vector_memcpy(d,x);
    gsl_vector_sub(d, oldx);
    if(mode ==1){
      gsl_vector_memcpy(absd, d);
      abs_vector(absd, n);
      // sort the local array d
      gsl_vector_scale(absd, -1.0);
      gsl_sort_vector_index(idx, absd);

      //    printf("|d(0)| = %lf, |d(1)| = %lf \n", gsl_vector_get(absd,0), gsl_vector_get(absd, 3));
      // calculate current objective value;
      local_old_obj = objective(oldx, lambda, z, size);
      MPI_Allreduce(&local_old_obj, &global_old_obj, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
      num_upd = fmin(num_upd+1, (int)(0.1*n));    
      gsl_vector_memcpy(tmpx, oldx);
      int upd_idx;
      double local_delta = 0, delta=0.0;
      for(int i=0; i<num_upd; i++){
	upd_idx = gsl_permutation_get(idx, i);
	//      printf("%d\n", upd_idx);
	gsl_vector_set(tmpx, upd_idx, gsl_vector_get(x, upd_idx));
	local_delta += gsl_vector_get(d, upd_idx) * gsl_vector_get(d, upd_idx);
      }
      MPI_Allreduce(&local_delta, &delta,  1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);    
      gsl_blas_dgemv(CblasNoTrans, 1, A, tmpx, 0, Atmpx); // Ax = A * x
      MPI_Allreduce(Atmpx->data, tmpz->data,  m, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
      gsl_vector_sub(tmpz, b); // z = Ax - b
    
      local_new_obj = objective(tmpx, lambda, tmpz, size);
      MPI_Allreduce(&local_new_obj, &global_new_obj, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);

      while(global_new_obj - global_old_obj> -sigma * delta){
	num_upd = fmax(num_upd-1, 1);
	for(int i=0; i<num_upd; i++){
	  upd_idx = gsl_permutation_get(idx, i);
	  gsl_vector_set(tmpx, upd_idx, gsl_vector_get(x, upd_idx));
	  local_delta += gsl_vector_get(d, upd_idx) * gsl_vector_get(d, upd_idx);
	}
	MPI_Allreduce(&delta, &local_delta,  1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);    
	gsl_blas_dgemv(CblasNoTrans, 1, A, tmpx, 0, Atmpx); // Ax = A * x
	MPI_Allreduce(Atmpx->data, tmpz->data,  m, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
	gsl_vector_sub(tmpz, b); // z = Ax - b
	
	local_new_obj = objective(tmpx, lambda, tmpz, size);
	MPI_Allreduce(&local_new_obj, &global_new_obj, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
	
	if(num_upd==1)
	  break;
      }

      gsl_vector_memcpy(x, tmpx);
    }  

    if(mode==0){
      CBLAS_INDEX_t id = gsl_blas_idamax(d);
      double *store = (double*)calloc(size, sizeof(double));
      double foo[1];
      foo[0] = gsl_vector_get(d,id);
      MPI_Allgather(foo, 1, MPI_DOUBLE, store, 1, MPI_DOUBLE, MPI_COMM_WORLD);
      for(int i=0;i<size;i++){
	table[i].ID   = i;
	table[i].data = fabs(store[i]);
      }
      // quick sort to decide which block to update
      qsort((void *) & table, size, sizeof(struct value), (compfn)compare );
      gsl_vector_memcpy(x, oldx);
      
      if(size>P){
	for(int i=0;i<P;i++){
	  if(rank == table[i].ID)
	    gsl_vector_set(x, id, gsl_vector_get(oldx, id) + gsl_vector_get(d, id));
	}
      }else
	gsl_vector_set(x, id, gsl_vector_get(oldx, id) + gsl_vector_get(d, id));
      local_new_obj = objective(x, lambda, z, size);
      MPI_Allreduce(&local_new_obj, &global_new_obj, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    }
    
    /*------------------------------
      calculate the relative error
      ------------------------------*/
    gsl_vector_memcpy(xdiff,xs);
    gsl_vector_sub(xdiff, x);
    err = gsl_blas_dnrm2(xdiff);
    send[0] = err*err;
    MPI_Allreduce(send, recv, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    recv[0] = sqrt(recv[0])/xs_nrm[0];
 
    endTime = MPI_Wtime();
    if(mode==1) P = num_upd*size;
    if (rank == 0) {
      if(iter%5 == 0)
	printf("%3d %10.2e %10.4f %3d\n", iter,
	       recv[0],  global_new_obj, P);
      fprintf(test, "%e \n",recv[0]);
    }

    /* termination check */
    if(recv[0] < TOL){
      break;
    }
    iter++;
  }
  total_end_time = MPI_Wtime();  
  /* Have the master write out the results to disk */
  if (rank == 0) {
    printf("=============================\n");
    printf("|    GRock solved Lasso!    |\n");
    printf("|---------------------------|\n");
    printf("|Summary:                   |\n");
    printf("|   # of iteration: %d      |\n", iter);
    printf("|   relative error: %4.2e|\n", recv[0]);
    printf("|  objective value: %4.2f    |\n", global_new_obj);
    printf("|             time: %4.1es|\n", total_end_time - total_start_time);
    printf("=============================\n");
    
    fprintf(test,"] \n");
    fprintf(test,"semilogy(1:length(res),res); \n");
    fprintf(test,"xlabel('# of iteration'); ylabel('||x - xs||');\n");
    fclose(test);
    f = fopen("results/solution.dat", "w");
    fprintf(f,"x = [ \n");
    gsl_vector_fprintf(f, x, "%lf");
    fprintf(f,"] \n");
    fclose(f);
    endTime = MPI_Wtime();
  }
  
  MPI_Finalize(); /* Shut down the MPI execution environment */
  
  /* Clear memory */
  gsl_matrix_free(A);
  gsl_vector_free(b);
  gsl_vector_free(x);
  gsl_vector_free(z);
  gsl_vector_free(xdiff);
  gsl_vector_free(Ax);
  gsl_vector_free(As);
  gsl_vector_free(invAs);
  gsl_vector_free(tmpx);
  gsl_vector_free(oldx);
  gsl_vector_free(local_b);
  gsl_vector_free(beta);
  gsl_vector_free(tmpz);
  gsl_vector_free(absd);
  gsl_vector_free(Atmpx);
  gsl_permutation_free(idx);

  return 0;
}
Beispiel #24
0
int cast_light (string str, int obj) {
    object target, light;
    int flag = 0;

    seteuid(getuid());

    if (!str||str=="me"||str==(string)TP->query("name")) {
	target = TP;
    } else {
	if (str == "here") {
	    target = environment(TP);
	    flag = 1;
	} else {
	    target = present(str, environment(TP));
	    if (!target) {
		write("Couldn't find "+capitalize(str)+" here.\n");
		return 1;
	    }
	    if (!living(target)) {
		write("The target must be alive.\n");
		return 1;
	    }
	    flag = 2;
	}
    }

    if (present("#LIGHT_OBJECT#", target)) {
	if (flag==2) write("That person already has a light effect.\n");
	if (flag==1) write("There is already a light spell in the room.\n");
	if (!flag && present("#LIGHT_OBJECT#", TP)) 
	    write("You already have a light spell upon you.\n");
	return 1;
    }

    if (living(target) && target!=TP)
	if (!check_magic_resist(TP, target, COST, 0)) return 0;

    if (!obj) {
	if (!cast_spell(TP, COST)) return 1;
    } else {
	obj = query_caster_level(TP, "wizard");
    }

    // Clone the light object.
    light = clone_object(M_OBJ(light_ob));  
    if (!light) {
	write("Your spell fizzles. Notify Cyanide.\n");
	return 1;
    }

    // Tell the room and caster what happens...
    switch (flag) {
    case 1 :
	write("You cast light upon the room.\n");
	say(TPN+" utters a strange incantation.\n");
	tell_room(environment(TP), "The room suddenly gets brighter.\n");
	break;
    case 2 : 
	tell_object(target, TPN +
	  " gestures at you and utters a strange incantation.\n"+
	  "An aura of light springs up around you!\n");
	write ("You cast light upon "+target->query("cap_name")+".\n");
	message("spell", 
	  TPN+" gestures at "+target->query("cap_name")+
	  " and utters a strange incantation.\n", environment(TP),
	  ({ TP, target }) );
	break;
    default :
	write("You cast a light spell upon yourself.\n"+
	  "An aura of light springs up around you.\n");
	say(TPN+" utters a strange incantation.\nAn aura of light springs "+
	  "up around "+objective(TP->query("gender"))+".\n");
	break;
    }
Beispiel #25
0
int main(int argc, char **argv) {
	const int MAX_ITER  = 50;
	const double RELTOL = 1e-2;
	const double ABSTOL = 1e-4;

	/*
	 * Some bookkeeping variables for MPI. The 'rank' of a process is its numeric id
	 * in the process pool. For example, if we run a program via `mpirun -np 4 foo', then
	 * the process ranks are 0 through 3. Here, N and size are the total number of processes 
	 * running (in this example, 4).
	 */

	int rank;
	int size;

	MPI_Init(&argc, &argv);               // Initialize the MPI execution environment
	MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Determine current running process
	MPI_Comm_size(MPI_COMM_WORLD, &size); // Total number of processes
	double N = (double) size;             // Number of subsystems/slaves for ADMM

	/* Read in local data */

	int skinny;           // A flag indicating whether the matrix A is fat or skinny
	FILE *f;
	int m, n;
	int row, col;
	double entry;

	/*
	 * Subsystem n will look for files called An.dat and bn.dat 
	 * in the current directory; these are its local data and do not need to be
	 * visible to any other processes. Note that
	 * m and n here refer to the dimensions of the *local* coefficient matrix.
	 */

	/* Read A */
	char s[20];
	sprintf(s, "data/A%d.dat", rank + 1);
	printf("[%d] reading %s\n", rank, s);

	f = fopen(s, "r");
	if (f == NULL) {
		printf("[%d] ERROR: %s does not exist, exiting.\n", rank, s);
		exit(EXIT_FAILURE);
	}
	mm_read_mtx_array_size(f, &m, &n);	
	gsl_matrix *A = gsl_matrix_calloc(m, n);
	for (int i = 0; i < m*n; i++) {
		row = i % m;
		col = floor(i/m);
		fscanf(f, "%lf", &entry);
		gsl_matrix_set(A, row, col, entry);
	}
	fclose(f);

	/* Read b */
	sprintf(s, "data/b%d.dat", rank + 1);
	printf("[%d] reading %s\n", rank, s);

	f = fopen(s, "r");
	if (f == NULL) {
		printf("[%d] ERROR: %s does not exist, exiting.\n", rank, s);
		exit(EXIT_FAILURE);
	}
	mm_read_mtx_array_size(f, &m, &n);
	gsl_vector *b = gsl_vector_calloc(m);
	for (int i = 0; i < m; i++) {
		fscanf(f, "%lf", &entry);
		gsl_vector_set(b, i, entry);
	}
	fclose(f);

	m = A->size1;
	n = A->size2;
	skinny = (m >= n);

	/*
	 * These are all variables related to ADMM itself. There are many
	 * more variables than in the Matlab implementation because we also
	 * require vectors and matrices to store various intermediate results.
	 * The naming scheme follows the Matlab version of this solver.
	 */ 

	double rho = 1.0;

	gsl_vector *x      = gsl_vector_calloc(n);
	gsl_vector *u      = gsl_vector_calloc(n);
	gsl_vector *z      = gsl_vector_calloc(n);
	gsl_vector *y      = gsl_vector_calloc(n);
	gsl_vector *r      = gsl_vector_calloc(n);
	gsl_vector *zprev  = gsl_vector_calloc(n);
	gsl_vector *zdiff  = gsl_vector_calloc(n);

	gsl_vector *q      = gsl_vector_calloc(n);
	gsl_vector *w      = gsl_vector_calloc(n);
	gsl_vector *Aq     = gsl_vector_calloc(m);
	gsl_vector *p      = gsl_vector_calloc(m);

	gsl_vector *Atb    = gsl_vector_calloc(n);

	double send[3]; // an array used to aggregate 3 scalars at once
	double recv[3]; // used to receive the results of these aggregations

	double nxstack  = 0;
	double nystack  = 0;
	double prires   = 0;
	double dualres  = 0;
	double eps_pri  = 0;
	double eps_dual = 0;

	/* Precompute and cache factorizations */

	gsl_blas_dgemv(CblasTrans, 1, A, b, 0, Atb); // Atb = A^T b

	/*
	 * The lasso regularization parameter here is just hardcoded
	 * to 0.5 for simplicity. Using the lambda_max heuristic would require 
	 * network communication, since it requires looking at the *global* A^T b.
	 */

	double lambda = 0.5;
	if (rank == 0) {
		printf("using lambda: %.4f\n", lambda);
	}

	gsl_matrix *L;

	/* Use the matrix inversion lemma for efficiency; see section 4.2 of the paper */
	if (skinny) {
		/* L = chol(AtA + rho*I) */
		L = gsl_matrix_calloc(n,n);

		gsl_matrix *AtA = gsl_matrix_calloc(n,n);
		gsl_blas_dsyrk(CblasLower, CblasTrans, 1, A, 0, AtA);

		gsl_matrix *rhoI = gsl_matrix_calloc(n,n);
		gsl_matrix_set_identity(rhoI);
		gsl_matrix_scale(rhoI, rho);

		gsl_matrix_memcpy(L, AtA);
		gsl_matrix_add(L, rhoI);
		gsl_linalg_cholesky_decomp(L);

		gsl_matrix_free(AtA);
		gsl_matrix_free(rhoI);
	} else {
		/* L = chol(I + 1/rho*AAt) */
		L = gsl_matrix_calloc(m,m);

		gsl_matrix *AAt = gsl_matrix_calloc(m,m);
		gsl_blas_dsyrk(CblasLower, CblasNoTrans, 1, A, 0, AAt);
		gsl_matrix_scale(AAt, 1/rho);

		gsl_matrix *eye = gsl_matrix_calloc(m,m);
		gsl_matrix_set_identity(eye);

		gsl_matrix_memcpy(L, AAt);
		gsl_matrix_add(L, eye);
		gsl_linalg_cholesky_decomp(L);

		gsl_matrix_free(AAt);
		gsl_matrix_free(eye);
	}

	/* Main ADMM solver loop */

	int iter = 0;
	if (rank == 0) {
		printf("%3s %10s %10s %10s %10s %10s\n", "#", "r norm", "eps_pri", "s norm", "eps_dual", "objective");		
	}
    double startAllTime, endAllTime;
	startAllTime = MPI_Wtime();
	while (iter < MAX_ITER) {

        /* u-update: u = u + x - z */
		gsl_vector_sub(x, z);
		gsl_vector_add(u, x);

		/* x-update: x = (A^T A + rho I) \ (A^T b + rho z - y) */
		gsl_vector_memcpy(q, z);
		gsl_vector_sub(q, u);
		gsl_vector_scale(q, rho);
		gsl_vector_add(q, Atb);   // q = A^T b + rho*(z - u)


        double tmp, tmpq;
		gsl_blas_ddot(x, x, &tmp);
		gsl_blas_ddot(q, q, &tmpq);

		if (skinny) {
			/* x = U \ (L \ q) */
			gsl_linalg_cholesky_solve(L, q, x);
		} else {
			/* x = q/rho - 1/rho^2 * A^T * (U \ (L \ (A*q))) */
			gsl_blas_dgemv(CblasNoTrans, 1, A, q, 0, Aq);
			gsl_linalg_cholesky_solve(L, Aq, p);
			gsl_blas_dgemv(CblasTrans, 1, A, p, 0, x); /* now x = A^T * (U \ (L \ (A*q)) */
			gsl_vector_scale(x, -1/(rho*rho));
			gsl_vector_scale(q, 1/rho);
			gsl_vector_add(x, q);
		}

		/*
		 * Message-passing: compute the global sum over all processors of the
		 * contents of w and t. Also, update z.
		 */

		gsl_vector_memcpy(w, x);
		gsl_vector_add(w, u);   // w = x + u

		gsl_blas_ddot(r, r, &send[0]); 
		gsl_blas_ddot(x, x, &send[1]);
		gsl_blas_ddot(u, u, &send[2]);
		send[2] /= pow(rho, 2);

		gsl_vector_memcpy(zprev, z);

		// could be reduced to a single Allreduce call by concatenating send to w
		MPI_Allreduce(w->data, z->data,  n, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
		MPI_Allreduce(send,    recv,     3, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);

		prires  = sqrt(recv[0]);  /* sqrt(sum ||r_i||_2^2) */
		nxstack = sqrt(recv[1]);  /* sqrt(sum ||x_i||_2^2) */
		nystack = sqrt(recv[2]);  /* sqrt(sum ||y_i||_2^2) */

		gsl_vector_scale(z, 1/N);
		soft_threshold(z, lambda/(N*rho));

		/* Termination checks */

		/* dual residual */
		gsl_vector_memcpy(zdiff, z);
		gsl_vector_sub(zdiff, zprev);
		dualres = sqrt(N) * rho * gsl_blas_dnrm2(zdiff); /* ||s^k||_2^2 = N rho^2 ||z - zprev||_2^2 */

		/* compute primal and dual feasibility tolerances */
		eps_pri  = sqrt(n*N)*ABSTOL + RELTOL * fmax(nxstack, sqrt(N)*gsl_blas_dnrm2(z));
		eps_dual = sqrt(n*N)*ABSTOL + RELTOL * nystack;

		if (rank == 0) {
			printf("%3d %10.4f %10.4f %10.4f %10.4f %10.4f\n", iter, 
					prires, eps_pri, dualres, eps_dual, objective(A, b, lambda, z));
		}

		if (prires <= eps_pri && dualres <= eps_dual) {
			break;
		}

		/* Compute residual: r = x - z */
		gsl_vector_memcpy(r, x);
		gsl_vector_sub(r, z);

		iter++;
	}

	/* Have the master write out the results to disk */
	if (rank == 0) { 
        endAllTime = MPI_Wtime();
        printf("Elapsed time is: %lf \n", endAllTime - startAllTime);

		f = fopen("data/solution.dat", "w");
		gsl_vector_fprintf(f, z, "%lf");
		fclose(f);
	}

	MPI_Finalize(); /* Shut down the MPI execution environment */

	/* Clear memory */
	gsl_matrix_free(A);
	gsl_matrix_free(L);
	gsl_vector_free(b);
	gsl_vector_free(x);
	gsl_vector_free(u);
	gsl_vector_free(z);
	gsl_vector_free(y);
	gsl_vector_free(r);
	gsl_vector_free(w);
	gsl_vector_free(zprev);
	gsl_vector_free(zdiff);
	gsl_vector_free(q);
	gsl_vector_free(Aq);
	gsl_vector_free(Atb);
	gsl_vector_free(p);

	return EXIT_SUCCESS;
}
Beispiel #26
0
bool
ClpInterior::createWorkingData()
{
     bool goodMatrix = true;
     //check matrix
     if (!matrix_->allElementsInRange(this, 1.0e-12, 1.0e20)) {
          problemStatus_ = 4;
          goodMatrix = false;
     }
     int nTotal = numberRows_ + numberColumns_;
     delete [] solution_;
     solution_ = new CoinWorkDouble[nTotal];
     CoinMemcpyN(columnActivity_,	numberColumns_, solution_);
     CoinMemcpyN(rowActivity_,	numberRows_, solution_ + numberColumns_);
     delete [] cost_;
     cost_ = new CoinWorkDouble[nTotal];
     int i;
     CoinWorkDouble direction = optimizationDirection_ * objectiveScale_;
     // direction is actually scale out not scale in
     if (direction)
          direction = 1.0 / direction;
     const double * obj = objective();
     for (i = 0; i < numberColumns_; i++)
          cost_[i] = direction * obj[i];
     memset(cost_ + numberColumns_, 0, numberRows_ * sizeof(CoinWorkDouble));
     // do scaling if needed
     if (scalingFlag_ > 0 && !rowScale_) {
          if (matrix_->scale(this))
               scalingFlag_ = -scalingFlag_; // not scaled after all
     }
     delete [] lower_;
     delete [] upper_;
     lower_ = new CoinWorkDouble[nTotal];
     upper_ = new CoinWorkDouble[nTotal];
     rowLowerWork_ = lower_ + numberColumns_;
     columnLowerWork_ = lower_;
     rowUpperWork_ = upper_ + numberColumns_;
     columnUpperWork_ = upper_;
     CoinMemcpyN(rowLower_, numberRows_, rowLowerWork_);
     CoinMemcpyN(rowUpper_, numberRows_, rowUpperWork_);
     CoinMemcpyN(columnLower_, numberColumns_, columnLowerWork_);
     CoinMemcpyN(columnUpper_, numberColumns_, columnUpperWork_);
     // clean up any mismatches on infinity
     for (i = 0; i < numberColumns_; i++) {
          if (columnLowerWork_[i] < -1.0e30)
               columnLowerWork_[i] = -COIN_DBL_MAX;
          if (columnUpperWork_[i] > 1.0e30)
               columnUpperWork_[i] = COIN_DBL_MAX;
     }
     // clean up any mismatches on infinity
     for (i = 0; i < numberRows_; i++) {
          if (rowLowerWork_[i] < -1.0e30)
               rowLowerWork_[i] = -COIN_DBL_MAX;
          if (rowUpperWork_[i] > 1.0e30)
               rowUpperWork_[i] = COIN_DBL_MAX;
     }
     // check rim of problem okay
     if (!sanityCheck())
          goodMatrix = false;
     if(rowScale_) {
          for (i = 0; i < numberColumns_; i++) {
               CoinWorkDouble multiplier = rhsScale_ / columnScale_[i];
               cost_[i] *= columnScale_[i];
               if (columnLowerWork_[i] > -1.0e50)
                    columnLowerWork_[i] *= multiplier;
               if (columnUpperWork_[i] < 1.0e50)
                    columnUpperWork_[i] *= multiplier;

          }
          for (i = 0; i < numberRows_; i++) {
               CoinWorkDouble multiplier = rhsScale_ * rowScale_[i];
               if (rowLowerWork_[i] > -1.0e50)
                    rowLowerWork_[i] *= multiplier;
               if (rowUpperWork_[i] < 1.0e50)
                    rowUpperWork_[i] *= multiplier;
          }
     } else if (rhsScale_ != 1.0) {
          for (i = 0; i < numberColumns_ + numberRows_; i++) {
               if (lower_[i] > -1.0e50)
                    lower_[i] *= rhsScale_;
               if (upper_[i] < 1.0e50)
                    upper_[i] *= rhsScale_;

          }
     }
     assert (!errorRegion_);
     errorRegion_ = new CoinWorkDouble [numberRows_];
     assert (!rhsFixRegion_);
     rhsFixRegion_ = new CoinWorkDouble [numberRows_];
     assert (!deltaY_);
     deltaY_ = new CoinWorkDouble [numberRows_];
     CoinZeroN(deltaY_, numberRows_);
     assert (!upperSlack_);
     upperSlack_ = new CoinWorkDouble [nTotal];
     assert (!lowerSlack_);
     lowerSlack_ = new CoinWorkDouble [nTotal];
     assert (!diagonal_);
     diagonal_ = new CoinWorkDouble [nTotal];
     assert (!deltaX_);
     deltaX_ = new CoinWorkDouble [nTotal];
     CoinZeroN(deltaX_, nTotal);
     assert (!deltaZ_);
     deltaZ_ = new CoinWorkDouble [nTotal];
     CoinZeroN(deltaZ_, nTotal);
     assert (!deltaW_);
     deltaW_ = new CoinWorkDouble [nTotal];
     CoinZeroN(deltaW_, nTotal);
     assert (!deltaSU_);
     deltaSU_ = new CoinWorkDouble [nTotal];
     CoinZeroN(deltaSU_, nTotal);
     assert (!deltaSL_);
     deltaSL_ = new CoinWorkDouble [nTotal];
     CoinZeroN(deltaSL_, nTotal);
     assert (!primalR_);
     assert (!dualR_);
     // create arrays if we are doing KKT
     if (cholesky_->type() >= 20) {
          primalR_ = new CoinWorkDouble [nTotal];
          CoinZeroN(primalR_, nTotal);
          dualR_ = new CoinWorkDouble [numberRows_];
          CoinZeroN(dualR_, numberRows_);
     }
     assert (!rhsB_);
     rhsB_ = new CoinWorkDouble [numberRows_];
     CoinZeroN(rhsB_, numberRows_);
     assert (!rhsU_);
     rhsU_ = new CoinWorkDouble [nTotal];
     CoinZeroN(rhsU_, nTotal);
     assert (!rhsL_);
     rhsL_ = new CoinWorkDouble [nTotal];
     CoinZeroN(rhsL_, nTotal);
     assert (!rhsZ_);
     rhsZ_ = new CoinWorkDouble [nTotal];
     CoinZeroN(rhsZ_, nTotal);
     assert (!rhsW_);
     rhsW_ = new CoinWorkDouble [nTotal];
     CoinZeroN(rhsW_, nTotal);
     assert (!rhsC_);
     rhsC_ = new CoinWorkDouble [nTotal];
     CoinZeroN(rhsC_, nTotal);
     assert (!workArray_);
     workArray_ = new CoinWorkDouble [nTotal];
     CoinZeroN(workArray_, nTotal);
     assert (!zVec_);
     zVec_ = new CoinWorkDouble [nTotal];
     CoinZeroN(zVec_, nTotal);
     assert (!wVec_);
     wVec_ = new CoinWorkDouble [nTotal];
     CoinZeroN(wVec_, nTotal);
     assert (!dj_);
     dj_ = new CoinWorkDouble [nTotal];
     if (!status_)
          status_ = new unsigned char [numberRows_+numberColumns_];
     memset(status_, 0, numberRows_ + numberColumns_);
     return goodMatrix;
}
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels [use only 4 to make our lives a bit easier]
	const int M = 4;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	// Get the labeling
	VectorXs labeling = getLabeling( anno, W*H, M );
	const int N = W*H;
	
	// Get the logistic features (unary term)
	// Here we just use the color as a feature
  Eigen::MatrixXf logistic_feature( 4, N ), logistic_transform( M, 4 );
	logistic_feature.fill( 1.f );
	for( int i=0; i<N; i++ )
		for( int k=0; k<3; k++ )
			logistic_feature(k,i) = im[3*i+k] / 255.;
	
	for( int j=0; j<logistic_transform.cols(); j++ )
		for( int i=0; i<logistic_transform.rows(); i++ )
			logistic_transform(i,j) = 0.01*(1-2.*random()/RAND_MAX);
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Add a logistic unary term
	crf.setUnaryEnergy( logistic_transform, logistic_feature );
	
	// Add simple pairwise potts terms
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 1 ) );
	// Add a longer range label compatibility term
  crf.addPairwiseBilateral( 80.0f, 80.0f, 13.0f, 13.0f, 13.0f, &*im, new MatrixCompatibility::MatrixCompatibility( Eigen::MatrixXf::Identity(M,M) ) );
	
	// Choose your loss function
// 	LogLikelihood objective( labeling, 0.01 ); // Log likelihood loss
// 	Hamming objective( labeling, 0.0 ); // Global accuracy
// 	Hamming objective( labeling, 1.0 ); // Class average accuracy
// 	Hamming objective( labeling, 0.2 ); // Hamming loss close to intersection over union
	IntersectionOverUnion objective( labeling ); // Intersection over union accuracy
	
	int NIT = 5;
	const bool verbose = true;
	
  Eigen::MatrixXf learning_params( 3, 3 );
	// Optimize the CRF in 3 phases:
	//  * First unary only
	//  * Unary and pairwise
	//  * Full CRF
	learning_params<<1,0,0,
	                 1,1,0,
					 1,1,1;
	
	for( int i=0; i<learning_params.rows(); i++ ) {
		// Setup the energy
		CRFEnergy energy( crf, objective, NIT, learning_params(i,0), learning_params(i,1), learning_params(i,2) );
		energy.setL2Norm( 1e-3 );
		
		// Minimize the energy
		Eigen::VectorXf p = minimizeLBFGS( energy, 2, true );
		
		// Save the values
		int id = 0;
		if( learning_params(i,0) ) {
			crf.setUnaryParameters( p.segment( id, crf.unaryParameters().rows() ) );
			id += crf.unaryParameters().rows();
		}
		if( learning_params(i,1) ) {
			crf.setLabelCompatibilityParameters( p.segment( id, crf.labelCompatibilityParameters().rows() ) );
			id += crf.labelCompatibilityParameters().rows();
		}
		if( learning_params(i,2) )
			crf.setKernelParameters( p.segment( id, crf.kernelParameters().rows() ) );
	}
	// Return the parameters
	std::cout<<"Unary parameters: "<<crf.unaryParameters().transpose()<<std::endl;
	std::cout<<"Pairwise parameters: "<<crf.labelCompatibilityParameters().transpose()<<std::endl;
	std::cout<<"Kernel parameters: "<<crf.kernelParameters().transpose()<<std::endl;
	
	// Do map inference
	VectorXs map = crf.map(NIT);
	
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
Beispiel #28
0
inherit MONSTER;

void set_trap(object to);

void create() {
  mapping inv;
  ::create();
  set_name("weimic hunter");
  set_race("weimic");
  set_body_type("weimic");
  set_gender(({"male","female","female"})[random(3)]);
  set_id(({"weimic","hunter", "weimic hunter"}));
  set_short("weimic hunter");
  set_long("A nomad of the plains, this weimic is clad in "
    "only a leather tunic that marks "+objective(query_gender())+
    "as a hunter. "+nominative(query_gender())+" has a sleek "
    "feline body with sun-bleached yellow fur, and a muscular "
    "human torso.");
  set_property("autobag", "bag");

  set_class("fighter");
  set_subclass("ranger");
  set_level(40+random(3));

  set_skill("nature", 250);
  set_skill("stealth", 100);

  set_spells(({"throw spear", "spear", "impale", "spear"}));
  set_spell_chance(33);
Beispiel #29
0
/** Extract sub block number <code>n</code> from <code>problem</code>.
 * The constructor creates a representation of block number <code>n</code>
 * as described in <code>problem</code>.
 * The constructor will also connect the newly created block to a remote
 * object solver instance.
 * @param problem  The problem from which the block is to be extracted.
 * @param n        Index of the block to be extracted.
 * @param argc     Argument for IloCplex constructor.
 * @param argv     Argument for IloCplex constructor.
 * @param machines List of machines to which to connect. If the code is
 *                 compiled for the TCP/IP transport then the block will
 *                 be connected to <code>machines[n]</code>.
 */
BendersOpt::Block::Block(Problem const *problem, IloInt n, int argc, char const *const *argv,
                         std::vector<char const *> const &machines)
   : env(), number(n), vars(0), rows(0), cplex(0), cb(0)
{
   IloNumVarArray problemVars = problem->getVariables();
   IloRangeArray problemRanges = problem->getRows();

   // Create a map that maps variables in the original model to their
   // respective index in problemVars.
   std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> > origIdxMap;
   for (IloInt j = 0; j < problemVars.getSize(); ++j)
      origIdxMap.insert(std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> >::value_type(problemVars[j], j));

   // Copy non-fixed variables from original problem into primal problem.
   IloExpr primalObj(env);
   IloNumVarArray primalVars(env);
   IloRangeArray primalRows(env);
   IdxMap idxMap; // Index of original variable in block's primal model
   RowSet rowSet;
   for (IloInt j = 0; j < problemVars.getSize(); ++j) {
      IloNumVar x = problemVars[j];
      if ( problem->getBlock(x) == number ) {
         // Create column in block LP with exactly the same data.
         if ( x.getType() != IloNumVar::Float ) {
            std::stringstream s;
            s << "Cannot create non-continuous block variable " << x;
            std::cerr << s.str() << std::endl;
            throw s.str();
         }
         IloNumVar v(env, x.getLB(), x.getUB(), x.getType(), x.getName());
         // Normalize objective function to 'minimize'
         double coef = problem->getObjCoef(x);
         if ( problem->getObjSense() != IloObjective::Minimize )
            coef *= -1.0;
         primalObj += coef * v;
            
         // Record the index that the copied variable has in the
         // block model.
         idxMap.insert(IdxMap::value_type(x, primalVars.getSize()));
         primalVars.add(v);
            
         // Mark the rows that are intersected by this column
         // so that we can collect them later.
         RowSet const &intersected = problem->getIntersectedRows(x);
         for (RowSet::const_iterator it = intersected.begin();
              it != intersected.end(); ++it)
            rowSet.insert(*it);
      }
      else
         idxMap.insert(IdxMap::value_type(x, -1));
   }

   // Now copy all rows that intersect block variables.
   for (IloInt i = 0; i < problemRanges.getSize(); ++i) {
      IloRange r = problemRanges[i];
      if ( rowSet.find(r) == rowSet.end() )
         continue;

      // Create a copy of the row, normalizing it to '<='
      double factor = 1.0;
      if ( r.getLB() > -IloInfinity )
         factor = -1.0;
      IloRange primalR(env,
                       factor < 0 ? -r.getUB() : r.getLB(),
                       factor < 0 ? -r.getLB() : r.getUB(), r.getName());
      IloExpr lhs(env);
      for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it)
      {
         IloNumVar v = it.getVar();
         double const val = factor * it.getCoef();
         if ( problem->getBlock(v) != number ) {
            // This column is not explicitly in this block. This means
            // that it is a column that will be fixed by the master.
            // We collect all such columns so that we can adjust the
            // dual objective function according to concrete fixings.
            // Store information about variables in this block that
            // will be fixed by master solves.
            fixed.push_back(FixData(primalRows.getSize(), origIdxMap[v], -val));
         }
         else {
            // The column is an ordinary in this block. Just copy it.
            lhs += primalVars[idxMap[v]] * val;
         }
      }
      primalR.setExpr(lhs);
      primalRows.add(primalR);
      lhs.end();
   }

   // Create the dual of the primal model we just created.
   // Note that makeDual _always_ returns a 'maximize' objective.
   IloObjective objective(env, primalObj, IloObjective::Minimize);
      
   makeDual(objective, primalVars, primalRows,
            &obj, &vars, &rows);
   objective.end();
   primalRows.endElements();
   primalRows.end();
   primalVars.endElements();
   primalVars.end();
   primalObj.end();
   // Create a model.
   IloModel model(env);
   model.add(obj);
   model.add(vars);
   model.add(rows);
   for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it)
      objMap.insert(ObjMap::value_type(it.getVar(), it.getCoef()));

   // Finally create the IloCplex instance that will solve
   // the problems associated with this block.
   char const **transargv = new char const *[argc + 3];
   for (int i = 0; i < argc; ++i)
      transargv[i] = argv[i];
#if defined(USE_MPI)
   char extra[128];
   sprintf (extra, "-remoterank=%d", static_cast<int>(number + 1));
   transargv[argc++] = extra;
   (void)machines;
#elif defined(USE_PROCESS)
   char extra[128];
   sprintf (extra, "-logfile=block%04d.log", static_cast<int>(number));
   transargv[argc++] = extra;
   (void)machines;
#elif defined(USE_TCPIP)
   transargv[argc++] = machines[number];
#endif
   cplex = IloCplex(model, TRANSPORT, argc, transargv);
   delete[] transargv;

   // Suppress output from this block's solver.
   cplex.setOut(env.getNullStream());
   cplex.setWarning(env.getNullStream());
}
Beispiel #30
0
  int
  MilpRounding::solution(double &solutionValue, double *betterSolution)
  {
    if(model_->getCurrentPassNumber() > 1) return 0;
    if (model_->currentDepth() > 2 && (model_->getNodeCount()%howOften_)!=0)
      return 0;
 
    int returnCode = 0; // 0 means it didn't find a feasible solution

    OsiTMINLPInterface * nlp = NULL;
    if(setup_->getAlgorithm() == B_BB)
      nlp = dynamic_cast<OsiTMINLPInterface *>(model_->solver()->clone());
    else
      nlp = dynamic_cast<OsiTMINLPInterface *>(setup_->nonlinearSolver()->clone());

    TMINLP2TNLP* minlp = nlp->problem();
 
    // set tolerances
    double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance);
    //double primalTolerance = 1.0e-6;

    int n;
    int m;
    int nnz_jac_g;
    int nnz_h_lag;
    Ipopt::TNLP::IndexStyleEnum index_style;
    minlp->get_nlp_info(n, m, nnz_jac_g,
			nnz_h_lag, index_style);

    const Bonmin::TMINLP::VariableType* variableType = minlp->var_types();
    const double* x_sol = minlp->x_sol();
    const double* g_l = minlp->g_l();
    const double* g_u = minlp->g_u();

    const double * colsol = model_->solver()->getColSolution();


    // Get information about the linear and nonlinear part of the instance
    TMINLP* tminlp = nlp->model();
    vector<Ipopt::TNLP::LinearityType> c_lin(m);
    tminlp->get_constraints_linearity(m, c_lin());
    vector<int> c_idx(m);
    int n_lin = 0;
    for (int i=0;i<m;i++) {
      if (c_lin[i]==Ipopt::TNLP::LINEAR)
	c_idx[i] = n_lin++;
      else
	c_idx[i] = -1;
    }


    // Get the structure of the jacobian
    vector<int> indexRow(nnz_jac_g);
    vector<int> indexCol(nnz_jac_g);
    minlp->eval_jac_g(n, x_sol, false,
		      m, nnz_jac_g,
		      indexRow(), indexCol(), 0);

    // get the jacobian values 
    vector<double> jac_g(nnz_jac_g);
    minlp->eval_jac_g(n, x_sol, false,
                      m, nnz_jac_g,
                      NULL, NULL, jac_g());

    // Sort the matrix to column ordered
    vector<int> sortedIndex(nnz_jac_g);
    CoinIotaN(sortedIndex(), nnz_jac_g, 0);
    MatComp c;
    c.iRow = indexRow();
    c.jCol = indexCol();
    std::sort(sortedIndex.begin(), sortedIndex.end(), c);

    vector<int> row (nnz_jac_g);
    vector<double> value (nnz_jac_g);
    vector<int> columnStart(n,0); 
    vector<int> columnLength(n,0);
    int indexCorrection = (index_style == Ipopt::TNLP::C_STYLE) ? 0 : 1;
    int iniCol = -1;
    int nnz = 0;
    for(int i=0; i<nnz_jac_g; i++) {
      int thisIndexCol = indexCol[sortedIndex[i]]-indexCorrection;
      int thisIndexRow = c_idx[indexRow[sortedIndex[i]] - indexCorrection];
      if(thisIndexCol != iniCol) {
	iniCol = thisIndexCol;
	columnStart[thisIndexCol] = nnz;
	columnLength[thisIndexCol] = 0;
      }
      if(thisIndexRow == -1) continue;
      columnLength[thisIndexCol]++;
      row[nnz] = thisIndexRow;
      value[nnz] = jac_g[i];
      nnz++;
    }

    // Build the row lower and upper bounds
    vector<double> newRowLower(n_lin);
    vector<double> newRowUpper(n_lin);
    for(int i = 0 ; i < m ; i++){
      if(c_idx[i] == -1) continue;
      newRowLower[c_idx[i]] = g_l[i];
      newRowUpper[c_idx[i]] = g_u[i];
    }

    // Get solution array for heuristic solution
    vector<double> newSolution(n);
    std::copy(x_sol, x_sol + n, newSolution.begin());

    // Define the constraint matrix for MILP
    CoinPackedMatrix matrix(true,n_lin,n, nnz, value(), row(), columnStart(), columnLength());

      // create objective function and columns lower and upper bounds for MILP
      // and create columns for matrix in MILP
      //double alpha = 0;
      double beta = 1;
      vector<double> objective(n);
      vector<int> idxIntegers;
      idxIntegers.reserve(n);
      for(int i = 0 ; i < n ; i++){
         if(variableType[i] != Bonmin::TMINLP::CONTINUOUS){
            idxIntegers.push_back(i);
            objective[i] = beta*(1 - 2*colsol[i]);
         }
      }

#if 0
      // Get dual multipliers and build gradient of the lagrangean
      const double * duals = nlp->getRowPrice() + 2 *n;
      vector<double> grad(n, 0); 
      vector<int> indices(n, 0);
      tminlp->eval_grad_f(n, x_sol, false, grad());
      for(int i = 0 ; i < m ; i++){
        if(c_lin[i] == Ipopt::TNLP::LINEAR) continue;
        int nnz;
        tminlp->eval_grad_gi(n, x_sol, false, i, nnz, indices(), NULL);  
        tminlp->eval_grad_gi(n, x_sol, false, i, nnz, NULL, grad());
        for(int k = 0 ; k < nnz ; k++){
          objective[indices[k]] += alpha *duals[i] * grad[k];
        } 
      }
      for(int i = 0 ; i < n ; i++){
         if(variableType[i] != Bonmin::TMINLP::CONTINUOUS)
         objective[i] += alpha * grad[i];
         //if(fabs(objective[i]) < 1e-4) objective[i] = 0;
         else objective[i] = 0;
      }
      std::copy(objective.begin(), objective.end(), std::ostream_iterator<double>(std::cout, " "));
      std::cout<<std::endl;
#endif

      // load the problem to OSI
      OsiSolverInterface *si = mip_->solver();
      assert(si != NULL);
      CoinMessageHandler * handler = model_->messageHandler()->clone();
      si->passInMessageHandler(handler);
      si->messageHandler()->setLogLevel(1);

      si->loadProblem(matrix, model_->solver()->getColLower(), model_->solver()->getColUpper(), objective(), 
                      newRowLower(), newRowUpper());
      si->setInteger(idxIntegers(), static_cast<int>(idxIntegers.size()));
      si->applyCuts(noGoods);

      bool hasFractionnal = true;
      while(hasFractionnal){
        mip_->optimize(DBL_MAX, 0, 60);
        hasFractionnal = false;
#if 0
        bool feasible = false;
        if(mip_->getLastSolution()) {
  	const double* solution = mip_->getLastSolution();
          std::copy(solution, solution + n, newSolution.begin());
  	feasible = true;
  
        }

    if(feasible) {
      // fix the integer variables and solve the NLP
      // also add no good cut
      CoinPackedVector v;
      double lb = 1;
      for (int iColumn=0;iColumn<n;iColumn++) {
	if (variableType[iColumn] != Bonmin::TMINLP::CONTINUOUS) {
	  double value=newSolution[iColumn];
	  if (fabs(floor(value+0.5)-value)>integerTolerance) {
#ifdef DEBUG_BON_HEURISTIC_DIVE_MIP
	    cout<<"It should be infeasible because: "<<endl;
	    cout<<"variable "<<iColumn<<" is not integer"<<endl;
#endif
	    feasible = false;
	    break;
	  }
	  else {
	    value=floor(newSolution[iColumn]+0.5);
            if(value > 0.5){
              v.insert(iColumn, -1);
              lb -= value;
            }
	    minlp->SetVariableUpperBound(iColumn, value);
	    minlp->SetVariableLowerBound(iColumn, value);
	  }
	}
      }
      }
#endif
      }
      bool feasible = false;
      if(mip_->getLastSolution()) {
	const double* solution = mip_->getLastSolution();
        std::copy(solution, solution + n, newSolution.begin());
	feasible = true;

        delete handler;
      }
      

    if(feasible) {
      // fix the integer variables and solve the NLP
      // also add no good cut
      CoinPackedVector v;
      double lb = 1;
      for (int iColumn=0;iColumn<n;iColumn++) {
	if (variableType[iColumn] != Bonmin::TMINLP::CONTINUOUS) {
	  double value=newSolution[iColumn];
	  if (fabs(floor(value+0.5)-value)>integerTolerance) {
	    feasible = false;
	    break;
	  }
	  else {
	    value=floor(newSolution[iColumn]+0.5);
            if(value > 0.5){
              v.insert(iColumn, -1);
              lb -= value;
            }
	    minlp->SetVariableUpperBound(iColumn, value);
	    minlp->SetVariableLowerBound(iColumn, value);
	  }
	}
      }
      OsiRowCut c;
      c.setRow(v);
      c.setLb(lb);
      c.setUb(DBL_MAX);
      noGoods.insert(c);
      if(feasible) {
	nlp->initialSolve();
	if(minlp->optimization_status() != Ipopt::SUCCESS) {
	  feasible = false;
	}
	std::copy(x_sol,x_sol+n, newSolution.begin());
      }
    }
    if(feasible) {
      double newSolutionValue;
      minlp->eval_f(n, newSolution(), true, newSolutionValue); 
      if(newSolutionValue < solutionValue) {
        std::copy(newSolution.begin(), newSolution.end(), betterSolution);
	solutionValue = newSolutionValue;
	returnCode = 1;
      }
    }

    delete nlp;

#ifdef DEBUG_BON_HEURISTIC_DIVE_MIP
    std::cout<<"DiveMIP returnCode = "<<returnCode<<std::endl;
#endif

    return returnCode;
  }