Ejemplo n.º 1
0
bool InexactSearchDirCalculator::InitializeImpl(
   const OptionsList& options,
   const std::string& prefix
   )
{
   options.GetNumericValue("local_inf_Ac_tol", local_inf_Ac_tol_, prefix);
   Index enum_int;
   options.GetEnumValue("inexact_step_decomposition", enum_int, prefix);
   decomposition_type_ = DecompositionTypeEnum(enum_int);

   bool compute_normal = false;
   switch( decomposition_type_ )
   {
      case ALWAYS:
         compute_normal = true;
         break;
      case ADAPTIVE:
      case SWITCH_ONCE:
         compute_normal = false;
         break;
   }

   InexData().set_compute_normal(compute_normal);
   InexData().set_next_compute_normal(compute_normal);

   bool retval = inexact_pd_solver_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(), options, prefix);
   if( !retval )
   {
      return false;
   }
   return normal_step_calculator_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(), options, prefix);
}
  bool PDFullSpaceSolver::InitializeImpl(const OptionsList& options,
                                         const std::string& prefix)
  {
    // Check for the algorithm options
    options.GetIntegerValue("min_refinement_steps", min_refinement_steps_, prefix);
    options.GetIntegerValue("max_refinement_steps", max_refinement_steps_, prefix);
    ASSERT_EXCEPTION(max_refinement_steps_ >= min_refinement_steps_, OPTION_INVALID,
                     "Option \"max_refinement_steps\": This value must be larger than or equal to min_refinement_steps (default 1)");

    options.GetNumericValue("residual_ratio_max", residual_ratio_max_, prefix);
    options.GetNumericValue("residual_ratio_singular", residual_ratio_singular_, prefix);
    ASSERT_EXCEPTION(residual_ratio_singular_ >= residual_ratio_max_, OPTION_INVALID,
                     "Option \"residual_ratio_singular\": This value must be not smaller than residual_ratio_max.");
    options.GetNumericValue("residual_improvement_factor", residual_improvement_factor_, prefix);
    options.GetNumericValue("neg_curv_test_tol", neg_curv_test_tol_, prefix);
    options.GetBoolValue("neg_curv_test_reg", neg_curv_test_reg_, prefix);

    // Reset internal flags and data
    augsys_improved_ = false;

    if (!augSysSolver_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                   options, prefix)) {
      return false;
    }

    return perturbHandler_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                       options, prefix);
  }
Ejemplo n.º 3
0
  void InexactLSAcceptor::ResetSlacks()
  {
    DBG_START_METH("InexactLSAcceptor::ResetSlacks",
                   dbg_verbosity);

    DBG_PRINT_VECTOR(1, "sorig", *IpData().trial()->s());
    DBG_PRINT_VECTOR(1, "dtrial", *IpCq().trial_d());
    SmartPtr<Vector> new_s = IpData().trial()->s()->MakeNew();
    SmartPtr<Vector> tmp_d = IpNLP().d_L()->MakeNew();
    IpNLP().Pd_L()->TransMultVector(1., *IpCq().trial_d(), 0., *tmp_d);
    SmartPtr<Vector> tmp_s = IpNLP().d_L()->MakeNew();
    IpNLP().Pd_L()->TransMultVector(1., *IpData().trial()->s(), 0., *tmp_s);
    tmp_s->ElementWiseMax(*tmp_d);
    IpNLP().Pd_L()->MultVector(1., *tmp_s, 0., *new_s);
    tmp_d = IpNLP().d_U()->MakeNew();
    IpNLP().Pd_U()->TransMultVector(1., *IpCq().trial_d(), 0., *tmp_d);
    tmp_s = IpNLP().d_U()->MakeNew();
    IpNLP().Pd_U()->TransMultVector(1., *IpData().trial()->s(), 0., *tmp_s);
    tmp_s->ElementWiseMin(*tmp_d);
    IpNLP().Pd_U()->MultVector(1., *tmp_s, 1., *new_s);
    SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer();
    trial->Set_s(*new_s);
    IpData().set_trial(trial);
    DBG_PRINT_VECTOR(1, "new_s", *IpData().trial()->s());
  }
Ejemplo n.º 4
0
 bool PDSearchDirCalculator::InitializeImpl(const OptionsList& options,
     const std::string& prefix)
 {
   options.GetBoolValue("fast_step_computation", fast_step_computation_,
                        prefix);
   options.GetBoolValue("mehrotra_algorithm", mehrotra_algorithm_, prefix);
   return pd_solver_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                 options, prefix);
 }
Ejemplo n.º 5
0
  bool AugRestoSystemSolver::InitializeImpl(const OptionsList& options,
      const std::string& prefix)
  {
    bool retval = true;
    if (!skip_orig_aug_solver_init_) {
      retval = orig_aug_solver_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                            options, prefix);
    }

    return retval;
  }
Ejemplo n.º 6
0
bool LowRankAugSystemSolver::InitializeImpl(
   const OptionsList& options,
   const std::string& prefix
   )
{
   first_call_ = true;
   J1_ = NULL;
   J2_ = NULL;
   Vtilde1_ = NULL;
   Utilde2_ = NULL;
   Wdiag_ = NULL;
   compound_sol_vecspace_ = NULL;

   return aug_system_solver_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(), options, prefix);
}
Ejemplo n.º 7
0
  bool RestoIterationOutput::InitializeImpl(const OptionsList& options,
      const std::string& prefix)
  {
    options.GetBoolValue("print_info_string", print_info_string_, prefix);
    Index enum_int;
    options.GetEnumValue("inf_pr_output", enum_int, prefix);
    inf_pr_output_ = InfPrOutput(enum_int);

    bool retval = true;
    if (IsValid(resto_orig_iteration_output_)) {
      retval = resto_orig_iteration_output_->Initialize(Jnlst(), IpNLP(),
               IpData(), IpCq(),
               options, prefix);
    }
    return retval;
  }
Ejemplo n.º 8
0
  bool RestoIterateInitializer::InitializeImpl(const OptionsList& options,
      const std::string& prefix)
  {
    if (!options.GetNumericValue("constr_mult_init_max", constr_mult_init_max_, prefix)) {
      // By default, we want to set this to zero. Seems to work better
      // as initialization for the restoration phase
      constr_mult_init_max_ = 0.;
    }

    bool retvalue = true;
    if (IsValid(resto_eq_mult_calculator_)) {
      retvalue = resto_eq_mult_calculator_->Initialize(Jnlst(),
                 IpNLP(), IpData(),
                 IpCq(), options, prefix);
    }
    return retvalue;
  }
  bool MinC_1NrmRestorationPhase::InitializeImpl(const OptionsList& options,
      const std::string& prefix)
  {
    // keep a copy of these options to use when setting up the
    // restoration phase
    resto_options_ = new OptionsList(options);

    options.GetNumericValue("constr_mult_reset_threshold",
                            constr_mult_reset_threshold_,
                            prefix);
    options.GetNumericValue("bound_mult_reset_threshold",
                            bound_mult_reset_threshold_,
                            prefix);
    options.GetBoolValue("expect_infeasible_problem",
                         expect_infeasible_problem_,
                         prefix);

    // This is registered in OptimalityErrorConvergenceCheck
    options.GetNumericValue("constr_viol_tol", constr_viol_tol_, prefix);

    // Avoid that the restoration phase is trigged by user option in
    // first iteration of the restoration phase
    resto_options_->SetStringValue("resto.start_with_resto", "no");

    // We want the default for the theta_max_fact in the restoration
    // phase higher than for the regular phase
    Number theta_max_fact;
    if (!options.GetNumericValue("resto.theta_max_fact",
                                 theta_max_fact, "")) {
      resto_options_->SetNumericValue("resto.theta_max_fact", 1e8);
    }

    if (!options.GetNumericValue("resto_failure_feasibility_threshold",
                                 resto_failure_feasibility_threshold_, prefix)) {
      resto_failure_feasibility_threshold_ = 1e2*IpData().tol();
    }

    count_restorations_ = 0;

    bool retvalue = true;
    if (IsValid(eq_mult_calculator_)) {
      retvalue = eq_mult_calculator_->Initialize(Jnlst(), IpNLP(), IpData(),
                 IpCq(), options, prefix);
    }
    return retvalue;
  }
  bool GenAugSystemSolver::InitializeImpl(const OptionsList& options,
                                          const std::string& prefix)
  {
    // This option is registered by OrigIpoptNLP
    options.GetBoolValue("warm_start_same_structure",
                         warm_start_same_structure_, prefix);

    if (!warm_start_same_structure_) {
      delete [] dx_vals_copy_;
      delete [] ds_vals_copy_;
      delete [] dc_vals_copy_;
      delete [] dd_vals_copy_;
    }

    return solver_interface_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                         options, prefix);
  }
Ejemplo n.º 11
0
  void MonotoneMuUpdate::CalcNewMuAndTau(Number &new_mu,
                                         Number &new_tau)
  {
    // update the barrier parameter
    Number mu = IpData().curr_mu();
    Number tol = IpData().tol();

    // Here we need the complementarity tolerance that is posed to the
    // scaled problem
    Number compl_inf_tol =
      IpNLP().NLP_scaling()->apply_obj_scaling(compl_inf_tol_);

    new_mu = Min( mu_linear_decrease_factor_*mu,
                  pow(mu, mu_superlinear_decrease_power_) );
    new_mu = Max(new_mu, Min(tol, compl_inf_tol)/(barrier_tol_factor_+1.));

    // update the fraction to the boundary parameter
    new_tau = Max(tau_min_, 1.-new_mu);
  }
Ejemplo n.º 12
0
  void SensAlgorithm::UnScaleIteratesVector(SmartPtr<IteratesVector> *V) {

    // unscale the iterates vector
    // pretty much a copy from IpOrigIpopt::finalize_solution
    
    SmartPtr<const Vector> unscaled_x;
    unscaled_x = IpNLP().NLP_scaling()->unapply_vector_scaling_x((*V)->x());
    DBG_ASSERT(IsValid(unscaled_x));
    (*V)->Set_x(*unscaled_x);
    unscaled_x = NULL ;

    SmartPtr<const Matrix> Px_L = IpNLP().Px_L();
    SmartPtr<const Matrix> Px_U = IpNLP().Px_U();
    SmartPtr<const VectorSpace> x_space = IpNLP().x_space();

    SmartPtr<const Vector> y_c = (*V)->y_c();
    SmartPtr<const Vector> y_d = (*V)->y_d();
    
    SmartPtr<const Vector> z_L = (*V)->z_L();
    SmartPtr<const Vector> z_U = (*V)->z_U();

    
    // unscale y_c
    SmartPtr<const Vector> unscaled_yc;
    SmartPtr<const Vector> unscaled_yd;
    SmartPtr<const Vector> unscaled_z_L;
    SmartPtr<const Vector> unscaled_z_U;


    Number obj_unscale_factor = IpNLP().NLP_scaling()->unapply_obj_scaling(1.);
    if (obj_unscale_factor!=1.) {
      
      SmartPtr<Vector> tmp = IpNLP().NLP_scaling()->apply_vector_scaling_x_LU_NonConst(*Px_L, z_L, *x_space);
      tmp->Scal(obj_unscale_factor);
      unscaled_z_L = ConstPtr(tmp);    
      
      tmp = IpNLP().NLP_scaling()->apply_vector_scaling_x_LU_NonConst(*Px_U, z_U, *x_space);
      tmp->Scal(obj_unscale_factor);
      unscaled_z_U = ConstPtr(tmp);

      tmp = IpNLP().NLP_scaling()->apply_vector_scaling_c_NonConst(y_c);
      tmp->Scal(obj_unscale_factor);
      unscaled_yc = ConstPtr(tmp);
      
      tmp = IpNLP().NLP_scaling()->apply_vector_scaling_d_NonConst(y_d);
      tmp->Scal(obj_unscale_factor);
      unscaled_yd = ConstPtr(tmp);
      
    }
    else {
      
      unscaled_z_L = IpNLP().NLP_scaling()->apply_vector_scaling_x_LU(*Px_L, z_L, *x_space);
      unscaled_z_U = IpNLP().NLP_scaling()->apply_vector_scaling_x_LU(*Px_U, z_U, *x_space);
      unscaled_yc = IpNLP().NLP_scaling()->apply_vector_scaling_c(y_c);
      unscaled_yd = IpNLP().NLP_scaling()->apply_vector_scaling_d(y_d);
      
    }

    (*V)->Set_z_U(*unscaled_z_U);
    (*V)->Set_z_L(*unscaled_z_L);
    (*V)->Set_y_c(*unscaled_yc);
    (*V)->Set_y_d(*unscaled_yd);
    
  }
Ejemplo n.º 13
0
  void IpoptAlgorithm::AcceptTrialPoint()
  {
    DBG_START_METH("IpoptAlgorithm::AcceptTrialPoint", dbg_verbosity);
    // If the line search didn't determine a new acceptable trial
    // point, do not accept a new iterate
    if (line_search_->CheckSkippedLineSearch()) {
      Jnlst().Printf(J_SUMMARY, J_MAIN,
                     "Line search didn't find acceptable trial point.\n");
      return;
    }

    // Adjust the bounds if necessary
    Index adjusted_slacks = IpCq().AdjustedTrialSlacks();
    DBG_PRINT((1, "adjusted_slacks = %d\n", adjusted_slacks));
    if (adjusted_slacks>0) {
      IpCq().ResetAdjustedTrialSlacks();
      if (adjusted_slacks==1) {
        Jnlst().Printf(J_WARNING, J_MAIN,
                       "In iteration %d, %d Slack too small, adjusting variable bound\n",
                       IpData().iter_count(), adjusted_slacks);
      }
      else {
        Jnlst().Printf(J_WARNING, J_MAIN,
                       "In iteration %d, %d Slacks too small, adjusting variable bounds\n",
                       IpData().iter_count(), adjusted_slacks);
      }
      if (Jnlst().ProduceOutput(J_VECTOR, J_MAIN)) {
        IpNLP().x_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "old_x_L");
        IpNLP().x_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "old_x_U");
        IpNLP().d_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "old_d_L");
        IpNLP().d_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "old_d_U");
      }

      SmartPtr<Vector> new_x_l = IpNLP().x_L()->MakeNew();
      IpNLP().Px_L()->TransMultVector(1.0, *IpData().trial()->x(),
                                      0.0, *new_x_l);
      new_x_l->Axpy(-1.0, *IpCq().trial_slack_x_L());

      SmartPtr<Vector> new_x_u = IpNLP().x_U()->MakeNew();
      IpNLP().Px_U()->TransMultVector(1.0, *IpData().trial()->x(),
                                      0.0, *new_x_u);
      new_x_u->Axpy(1.0, *IpCq().trial_slack_x_U());

      SmartPtr<Vector> new_d_l = IpNLP().d_L()->MakeNew();
      IpNLP().Pd_L()->TransMultVector(1.0, *IpData().trial()->s(),
                                      0.0, *new_d_l);
      new_d_l->Axpy(-1.0, *IpCq().trial_slack_s_L());

      SmartPtr<Vector> new_d_u = IpNLP().d_U()->MakeNew();
      IpNLP().Pd_U()->TransMultVector(1.0, *IpData().trial()->s(),
                                      0.0, *new_d_u);
      new_d_u->Axpy(1.0, *IpCq().trial_slack_s_U());

      IpNLP().AdjustVariableBounds(*new_x_l, *new_x_u, *new_d_l, *new_d_u);

      if (Jnlst().ProduceOutput(J_VECTOR, J_MAIN)) {
        IpNLP().x_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "new_x_L");
        IpNLP().x_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "new_x_U");
        IpNLP().d_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "new_d_L");
        IpNLP().d_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "new_d_U");
      }

    }

    // Make sure that bound multipliers are not too far from \mu * S^{-1}
    // (see kappa_sigma in paper)
    bool corrected = false;
    Number max_correction;
    SmartPtr<const Vector> new_z_L;
    max_correction = correct_bound_multiplier(
                       *IpData().trial()->z_L(),
                       *IpCq().trial_slack_x_L(),
                       *IpCq().trial_compl_x_L(),
                       new_z_L);
    if (max_correction>0.) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Some value in z_L becomes too large - maximal correction = %8.2e\n",
                     max_correction);
      corrected = true;
    }
    SmartPtr<const Vector> new_z_U;
    max_correction = correct_bound_multiplier(
                       *IpData().trial()->z_U(),
                       *IpCq().trial_slack_x_U(),
                       *IpCq().trial_compl_x_U(),
                       new_z_U);
    if (max_correction>0.) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Some value in z_U becomes too large - maximal correction = %8.2e\n",
                     max_correction);
      corrected = true;
    }
    SmartPtr<const Vector> new_v_L;
    max_correction = correct_bound_multiplier(
                       *IpData().trial()->v_L(),
                       *IpCq().trial_slack_s_L(),
                       *IpCq().trial_compl_s_L(),
                       new_v_L);
    if (max_correction>0.) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Some value in v_L becomes too large - maximal correction = %8.2e\n",
                     max_correction);
      corrected = true;
    }
    SmartPtr<const Vector> new_v_U;
    max_correction = correct_bound_multiplier(
                       *IpData().trial()->v_U(),
                       *IpCq().trial_slack_s_U(),
                       *IpCq().trial_compl_s_U(),
                       new_v_U);
    if (max_correction>0.) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Some value in v_U becomes too large - maximal correction = %8.2e\n",
                     max_correction);
      corrected = true;
    }
    SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer();
    trial->Set_bound_mult(*new_z_L, *new_z_U, *new_v_L, *new_v_U);
    IpData().set_trial(trial);

    if (corrected) {
      IpData().Append_info_string("z");
    }

    // Accept the step
    IpData().AcceptTrialPoint();

    // If we want to recalculate the multipliers (e.g., as least
    // square estimates), call the calculator for that
    if (recalc_y_) {
      // There is no point in doing this if there are no constraints
      if (IpData().curr()->y_c()->Dim()+IpData().curr()->y_d()->Dim()==0) {
        recalc_y_ = false;
      }
    }
    if (recalc_y_ && IpCq().curr_constraint_violation()<recalc_y_feas_tol_) {
      if (Jnlst().ProduceOutput(J_MOREDETAILED, J_MAIN)) {
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "dual infeasisibility before least square multiplier update = %e\n",
                       IpCq().curr_dual_infeasibility(NORM_MAX));
      }
      IpData().Append_info_string("y ");
      DBG_ASSERT(IsValid(eq_multiplier_calculator_));
      if (IpData().curr()->y_c()->Dim()+IpData().curr()->y_d()->Dim()>0) {
        SmartPtr<Vector> y_c = IpData().curr()->y_c()->MakeNew();
        SmartPtr<Vector> y_d = IpData().curr()->y_d()->MakeNew();
        bool retval =
          eq_multiplier_calculator_->CalculateMultipliers(*y_c, *y_d);
        if (retval) {
          SmartPtr<const IteratesVector> curr = IpData().curr();
          SmartPtr<IteratesVector> iterates = curr->MakeNewContainer();
          iterates->Set_x(*curr->x());
          iterates->Set_s(*curr->s());
          iterates->Set_z_L(*curr->z_L());
          iterates->Set_z_U(*curr->z_U());
          iterates->Set_v_L(*curr->v_L());
          iterates->Set_v_U(*curr->v_U());
          iterates->Set_y_c(*y_c);
          iterates->Set_y_d(*y_d);
          IpData().set_trial(iterates);
          IpData().AcceptTrialPoint();
        }
        else {
          Jnlst().Printf(J_DETAILED, J_MAIN,
                         "Recalculation of y multipliers skipped because eq_mult_calc returned false.\n");
        }
      }
    }
  }
Ejemplo n.º 14
0
  bool AdaptiveMuUpdate::UpdateBarrierParameter()
  {
    DBG_START_METH("AdaptiveMuUpdate::UpdateBarrierParameter",
                   dbg_verbosity);

    // if min_mu_ has not been given, we now set the default (can't do
    // that earlier, because during call of InitializeImpl, the
    // scaling in the NLP is not yet determined).  We compute this
    // here in every iteration, since the tolerance might be changed
    // (e.g. in the restoration phase)
    if (mu_min_default_) {
      mu_min_ = Min(mu_min_, 0.5*Min(IpData().tol(),
                                     IpNLP().NLP_scaling()->apply_obj_scaling(compl_inf_tol_)));
    }

    // if mu_max has not yet been computed, do so now, based on the
    // current average complementarity
    if (mu_max_<0.) {
      mu_max_ = mu_max_fact_*IpCq().curr_avrg_compl();
      Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                     "Setting mu_max to %e.\n", mu_max_);
    }

    // if there are not bounds, we always return the minimum MU value
    if (!check_if_no_bounds_) {
      Index n_bounds = IpData().curr()->z_L()->Dim() + IpData().curr()->z_U()->Dim()
                       + IpData().curr()->v_L()->Dim() + IpData().curr()->v_U()->Dim();

      if (n_bounds==0) {
        no_bounds_ = true;
        IpData().Set_mu(mu_min_);
        IpData().Set_tau(tau_min_);
      }

      check_if_no_bounds_ = true;
    }

    if (no_bounds_)
      return true;

    bool tiny_step_flag = IpData().tiny_step_flag();
    IpData().Set_tiny_step_flag(false);
    if (!IpData().FreeMuMode()) {
      // if we are in the fixed mu mode, we need to check if the
      // current iterate is good enough to continue with the free mode
      bool sufficient_progress = CheckSufficientProgress();
      if (sufficient_progress && !tiny_step_flag) {
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "Switching back to free mu mode.\n");
        IpData().SetFreeMuMode(true);
        // Skipping Restoration phase?
        RememberCurrentPointAsAccepted();
      }
      else {
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "Remaining in fixed mu mode.\n");

        // ToDo decide whether we want this for all options
        Number sub_problem_error = IpCq().curr_barrier_error();
        Number mu = IpData().curr_mu();
        if (sub_problem_error <= barrier_tol_factor_ * mu ||
            tiny_step_flag) {
          // If the current barrier problem has been solved sufficiently
          // well, decrease mu
          // ToDo combine this code with MonotoneMuUpdate
          Number tol = IpData().tol();
          Number compl_inf_tol =
            IpNLP().NLP_scaling()->apply_obj_scaling(compl_inf_tol_);

          Number new_mu = Min( mu_linear_decrease_factor_*mu,
                               pow(mu, mu_superlinear_decrease_power_) );
          DBG_PRINT((1,"new_mu = %e, compl_inf_tol = %e tol = %e\n", new_mu, compl_inf_tol, tol));
          new_mu = Max(new_mu,
                       Min(compl_inf_tol, tol)/(barrier_tol_factor_+1.));
          if (tiny_step_flag && new_mu == mu) {
            THROW_EXCEPTION(TINY_STEP_DETECTED,
                            "Problem solved to best possible numerical accuracy");
          }
          Number new_tau = Compute_tau_monotone(mu);
          IpData().Set_mu(new_mu);
          IpData().Set_tau(new_tau);
          Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                         "Reducing mu to %24.16e in fixed mu mode. Tau becomes %24.16e\n", new_mu, new_tau);
          linesearch_->Reset();
        }
      }
    }
    else {
      // Here we are in the free mu mode.
      bool sufficient_progress = CheckSufficientProgress();
      if (linesearch_->CheckSkippedLineSearch() || tiny_step_flag ) {
        sufficient_progress = false;
      }
      if (sufficient_progress) {
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "Staying in free mu mode.\n");
        RememberCurrentPointAsAccepted();
      }
      else {
        IpData().SetFreeMuMode(false);

        if (restore_accepted_iterate_) {
          // Restore most recent accepted iterate to start fixed mode from
          Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                         "Restoring most recent accepted point.\n");
          SmartPtr<IteratesVector> prev_iter = accepted_point_->MakeNewContainer();
          IpData().set_trial(prev_iter);
          IpData().AcceptTrialPoint();
        }

        // Set the new values for mu and tau and tell the linesearch
        // to reset its memory
        Number mu = NewFixedMu();
        Number tau = Compute_tau_monotone(mu);

        if (tiny_step_flag && mu==IpData().curr_mu()) {
          THROW_EXCEPTION(TINY_STEP_DETECTED,
                          "Problem solved to best possible numerical accuracy");
        }

        IpData().Set_mu(mu);
        IpData().Set_tau(tau);
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "Switching to fixed mu mode with mu = %24.16e and tau = %24.16e.\n", mu, tau);
        linesearch_->Reset();
        // Skipping Restoration phase?
      }
    }

    if (IpData().FreeMuMode()) {

      // Choose the fraction-to-the-boundary parameter for the current
      // iteration
      // ToDo: Is curr_nlp_error really what we should use here?
      Number tau = Max(tau_min_, 1.-IpCq().curr_nlp_error());
      IpData().Set_tau(tau);

      // Compute the new barrier parameter via the oracle
      Number mu;
      bool retval = free_mu_oracle_->CalculateMu(Max(mu_min_, mu_target_),
                    mu_max_, mu);
      if (!retval) {
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "The mu oracle could not compute a new value of the barrier parameter.\n");
        return false;
      }

      mu = Max(mu, mu_min_);
      Number mu_lower_safe = lower_mu_safeguard();
      if (mu < mu_lower_safe) {
        Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                       "mu = %e smaller than safeguard = %e. Increasing mu.\n",
                       mu, mu_lower_safe);
        mu = mu_lower_safe;
        IpData().Append_info_string("m");
      }

      Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                     "Barrier parameter mu computed by oracle is %e\n",
                     mu);

      // Apply safeguards if appropriate
      mu = Min(mu, mu_max_);
      Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE,
                     "Barrier parameter mu after safeguards is %e\n",
                     mu);

      // Set the new values
      IpData().Set_mu(mu);

      linesearch_->Reset();
      // Uncomment the next line if the line search should not switch to
      // the restoration phase in the free mode

      // linesearch_->SetRigorousLineSearch(false);
    }
    else {
      IpData().Append_info_string("F");
      linesearch_->SetRigorousLineSearch(true);
    }

    return true;
  }
Ejemplo n.º 15
0
  bool AdaptiveMuUpdate::InitializeImpl(const OptionsList& options,
                                        const std::string& prefix)
  {
    options.GetNumericValue("mu_max_fact", mu_max_fact_, prefix);
    if (!options.GetNumericValue("mu_max", mu_max_, prefix)) {
      // Set to a negative value as a hint that this value still has
      // to be computed
      mu_max_ = -1.;
    }
    options.GetNumericValue("tau_min", tau_min_, prefix);
    options.GetNumericValue("adaptive_mu_safeguard_factor", adaptive_mu_safeguard_factor_, prefix);
    options.GetNumericValue("adaptive_mu_kkterror_red_fact", refs_red_fact_, prefix);
    options.GetIntegerValue("adaptive_mu_kkterror_red_iters", num_refs_max_, prefix);
    Index enum_int;
    options.GetEnumValue("adaptive_mu_globalization", enum_int, prefix);
    adaptive_mu_globalization_ = AdaptiveMuGlobalizationEnum(enum_int);
    options.GetNumericValue("filter_max_margin", filter_max_margin_, prefix);
    options.GetNumericValue("filter_margin_fact", filter_margin_fact_, prefix);
    options.GetBoolValue("adaptive_mu_restore_previous_iterate", restore_accepted_iterate_, prefix);

    bool retvalue = free_mu_oracle_->Initialize(Jnlst(), IpNLP(), IpData(),
                    IpCq(), options, prefix);
    if (!retvalue) {
      return retvalue;
    }

    if (IsValid(fix_mu_oracle_)) {
      retvalue = fix_mu_oracle_->Initialize(Jnlst(), IpNLP(), IpData(),
                                            IpCq(), options, prefix);
      if (!retvalue) {
        return retvalue;
      }
    }

    options.GetNumericValue("adaptive_mu_monotone_init_factor", adaptive_mu_monotone_init_factor_, prefix);
    options.GetNumericValue("barrier_tol_factor", barrier_tol_factor_, prefix);
    options.GetNumericValue("mu_linear_decrease_factor", mu_linear_decrease_factor_, prefix);
    options.GetNumericValue("mu_superlinear_decrease_power", mu_superlinear_decrease_power_, prefix);

    options.GetEnumValue("quality_function_norm_type", enum_int, prefix);
    adaptive_mu_kkt_norm_ = QualityFunctionMuOracle::NormEnum(enum_int);
    options.GetEnumValue("quality_function_centrality", enum_int, prefix);
    adaptive_mu_kkt_centrality_ = QualityFunctionMuOracle::CentralityEnum(enum_int);
    options.GetEnumValue("quality_function_balancing_term", enum_int, prefix);
    adaptive_mu_kkt_balancing_term_ = QualityFunctionMuOracle::BalancingTermEnum(enum_int);
    options.GetNumericValue("compl_inf_tol", compl_inf_tol_, prefix);
    if (prefix == "resto.") {
      if (!options.GetNumericValue("mu_min", mu_min_, prefix)) {
        // For restoration phase, we choose a more conservative mu_min
        mu_min_ = 1e2*mu_min_;
        // Compute mu_min based on tolerance (once the NLP scaling is known)
        mu_min_default_ = true;
      }
      else {
        mu_min_default_ = false;
      }
    }
    else {
      if (!options.GetNumericValue("mu_min", mu_min_, prefix)) {
        // Compute mu_min based on tolerance (once the NLP scaling is known)
        mu_min_default_ = true;
      }
      else {
        mu_min_default_ = false;
      }
    }
    options.GetNumericValue("mu_target", mu_target_, prefix);

    init_dual_inf_ = -1.;
    init_primal_inf_ = -1.;

    refs_vals_.clear();
    check_if_no_bounds_ = false;
    no_bounds_ = false;
    filter_.Clear();
    IpData().SetFreeMuMode(true);

    accepted_point_ = NULL;

    // The following lines are only here so that
    // IpoptCalculatedQuantities::CalculateSafeSlack and the first
    // output line have something to work with
    IpData().Set_mu(1.);
    IpData().Set_tau(0.);

    return retvalue;
  }
  bool PDFullSpaceSolver::Solve(Number alpha,
                                Number beta,
                                const IteratesVector& rhs,
                                IteratesVector& res,
                                bool allow_inexact,
                                bool improve_solution /* = false */)
  {
    DBG_START_METH("PDFullSpaceSolver::Solve",dbg_verbosity);
    DBG_ASSERT(!allow_inexact || !improve_solution);
    DBG_ASSERT(!improve_solution || beta==0.);

    // Timing of PDSystem solver starts here
    IpData().TimingStats().PDSystemSolverTotal().Start();

    DBG_PRINT_VECTOR(2, "rhs_x", *rhs.x());
    DBG_PRINT_VECTOR(2, "rhs_s", *rhs.s());
    DBG_PRINT_VECTOR(2, "rhs_c", *rhs.y_c());
    DBG_PRINT_VECTOR(2, "rhs_d", *rhs.y_d());
    DBG_PRINT_VECTOR(2, "rhs_zL", *rhs.z_L());
    DBG_PRINT_VECTOR(2, "rhs_zU", *rhs.z_U());
    DBG_PRINT_VECTOR(2, "rhs_vL", *rhs.v_L());
    DBG_PRINT_VECTOR(2, "rhs_vU", *rhs.v_U());
    DBG_PRINT_VECTOR(2, "res_x in", *res.x());
    DBG_PRINT_VECTOR(2, "res_s in", *res.s());
    DBG_PRINT_VECTOR(2, "res_c in", *res.y_c());
    DBG_PRINT_VECTOR(2, "res_d in", *res.y_d());
    DBG_PRINT_VECTOR(2, "res_zL in", *res.z_L());
    DBG_PRINT_VECTOR(2, "res_zU in", *res.z_U());
    DBG_PRINT_VECTOR(2, "res_vL in", *res.v_L());
    DBG_PRINT_VECTOR(2, "res_vU in", *res.v_U());

    // if beta is nonzero, keep a copy of the incoming values in res_ */
    SmartPtr<IteratesVector> copy_res;
    if (beta != 0.) {
      copy_res = res.MakeNewIteratesVectorCopy();
    }

    // Receive data about matrix
    SmartPtr<const Vector> x = IpData().curr()->x();
    SmartPtr<const Vector> s = IpData().curr()->s();
    SmartPtr<const SymMatrix> W = IpData().W();
    SmartPtr<const Matrix> J_c = IpCq().curr_jac_c();
    SmartPtr<const Matrix> J_d = IpCq().curr_jac_d();
    SmartPtr<const Matrix> Px_L = IpNLP().Px_L();
    SmartPtr<const Matrix> Px_U = IpNLP().Px_U();
    SmartPtr<const Matrix> Pd_L = IpNLP().Pd_L();
    SmartPtr<const Matrix> Pd_U = IpNLP().Pd_U();
    SmartPtr<const Vector> z_L = IpData().curr()->z_L();
    SmartPtr<const Vector> z_U = IpData().curr()->z_U();
    SmartPtr<const Vector> v_L = IpData().curr()->v_L();
    SmartPtr<const Vector> v_U = IpData().curr()->v_U();
    SmartPtr<const Vector> slack_x_L = IpCq().curr_slack_x_L();
    SmartPtr<const Vector> slack_x_U = IpCq().curr_slack_x_U();
    SmartPtr<const Vector> slack_s_L = IpCq().curr_slack_s_L();
    SmartPtr<const Vector> slack_s_U = IpCq().curr_slack_s_U();
    SmartPtr<const Vector> sigma_x = IpCq().curr_sigma_x();
    SmartPtr<const Vector> sigma_s = IpCq().curr_sigma_s();
    DBG_PRINT_VECTOR(2, "Sigma_x", *sigma_x);
    DBG_PRINT_VECTOR(2, "Sigma_s", *sigma_s);

    bool done = false;
    // The following flag is set to true, if we asked the linear
    // solver to improve the quality of the solution in
    // the next solve
    bool resolve_with_better_quality = false;
    // the following flag is set to true, if iterative refinement
    // failed and we want to try if a modified system is able to
    // remedy that problem by pretending the matrix is singular
    bool pretend_singular = false;
    bool pretend_singular_last_time = false;

    // Beginning of loop for solving the system (including all
    // modifications for the linear system to ensure good solution
    // quality)
    while (!done) {

      // if improve_solution is true, we are given already a solution
      // from the calling function, so we can skip the first solve
      bool solve_retval = true;
      if (!improve_solution) {
        solve_retval =
          SolveOnce(resolve_with_better_quality, pretend_singular,
                    *W, *J_c, *J_d, *Px_L, *Px_U, *Pd_L, *Pd_U, *z_L, *z_U,
                    *v_L, *v_U, *slack_x_L, *slack_x_U, *slack_s_L, *slack_s_U,
                    *sigma_x, *sigma_s, 1., 0., rhs, res);
        resolve_with_better_quality = false;
        pretend_singular = false;
      }
      improve_solution = false;

      if (!solve_retval) {
        // If system seems not to be solvable, we return with false
        // and let the calling routine deal with it.
        IpData().TimingStats().PDSystemSolverTotal().End();
        return false;
      }

      if (allow_inexact) {
        // no safety checks required
        if (Jnlst().ProduceOutput(J_MOREDETAILED, J_LINEAR_ALGEBRA)) {
          SmartPtr<IteratesVector> resid = res.MakeNewIteratesVector(true);
          ComputeResiduals(*W, *J_c, *J_d, *Px_L, *Px_U, *Pd_L, *Pd_U,
                           *z_L, *z_U, *v_L, *v_U, *slack_x_L, *slack_x_U,
                           *slack_s_L, *slack_s_U, *sigma_x, *sigma_s,
                           alpha, beta, rhs, res, *resid);
        }
        break;
      }

      // Get space for the residual
      SmartPtr<IteratesVector> resid = res.MakeNewIteratesVector(true);

      // ToDo don't to that after max refinement?
      ComputeResiduals(*W, *J_c, *J_d, *Px_L, *Px_U, *Pd_L, *Pd_U,
                       *z_L, *z_U, *v_L, *v_U, *slack_x_L, *slack_x_U,
                       *slack_s_L, *slack_s_U, *sigma_x, *sigma_s,
                       alpha, beta, rhs, res, *resid);

      Number residual_ratio =
        ComputeResidualRatio(rhs, res, *resid);
      Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                     "residual_ratio = %e\n", residual_ratio);
      Number residual_ratio_old = residual_ratio;

      // Beginning of loop for iterative refinement
      Index num_iter_ref = 0;
      bool quit_refinement = false;
      while (!allow_inexact && !quit_refinement &&
             (num_iter_ref < min_refinement_steps_ ||
              residual_ratio > residual_ratio_max_) ) {

        // To the next back solve
        solve_retval =
          SolveOnce(resolve_with_better_quality, false,
                    *W, *J_c, *J_d, *Px_L, *Px_U, *Pd_L, *Pd_U, *z_L, *z_U,
                    *v_L, *v_U, *slack_x_L, *slack_x_U, *slack_s_L, *slack_s_U,
                    *sigma_x, *sigma_s, -1., 1., *resid, res);
        ASSERT_EXCEPTION(solve_retval, INTERNAL_ABORT,
                         "SolveOnce returns false during iterative refinement.");

        ComputeResiduals(*W, *J_c, *J_d, *Px_L, *Px_U, *Pd_L, *Pd_U,
                         *z_L, *z_U, *v_L, *v_U, *slack_x_L, *slack_x_U,
                         *slack_s_L, *slack_s_U, *sigma_x, *sigma_s,
                         alpha, beta, rhs, res, *resid);

        residual_ratio =
          ComputeResidualRatio(rhs, res, *resid);
        Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                       "residual_ratio = %e\n", residual_ratio);

        num_iter_ref++;
        // Check if we have to give up on iterative refinement
        if (residual_ratio > residual_ratio_max_ &&
            num_iter_ref>min_refinement_steps_ &&
            (num_iter_ref>max_refinement_steps_ ||
             residual_ratio>residual_improvement_factor_*residual_ratio_old)) {

          Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                         "Iterative refinement failed with residual_ratio = %e\n", residual_ratio);
          quit_refinement = true;

          // Pretend singularity only once - if it didn't help, we
          // have to live with what we got so far
          resolve_with_better_quality = false;
          DBG_PRINT((1, "pretend_singular = %d\n", pretend_singular));
          if (!pretend_singular_last_time) {
            // First try if we can ask the augmented system solver to
            // improve the quality of the solution (only if that hasn't
            // been done before for this linear system)
            if (!augsys_improved_) {
              Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                             "Asking augmented system solver to improve quality of its solutions.\n");
              augsys_improved_ = augSysSolver_->IncreaseQuality();
              if (augsys_improved_) {
                IpData().Append_info_string("q");
                resolve_with_better_quality = true;
              }
              else {
                // solver said it cannot improve quality, so let
                // possibly conclude that the current modification is
                // singular
                pretend_singular = true;
              }
            }
            else {
              // we had already asked the solver before to improve the
              // quality of the solution, so let's now pretend that the
              // modification is possibly singular
              pretend_singular = true;
            }
            pretend_singular_last_time = pretend_singular;
            if (pretend_singular) {
              // let's only conclude that the current linear system
              // including modifications is singular, if the residual is
              // quite bad
              if (residual_ratio < residual_ratio_singular_) {
                pretend_singular = false;
                IpData().Append_info_string("S");
                Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                               "Just accept current solution.\n");
              }
              else {
                IpData().Append_info_string("s");
                Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                               "Pretend that the current system (including modifications) is singular.\n");
              }
            }
          }
          else {
            pretend_singular = false;
            DBG_PRINT((1,"Resetting pretend_singular to false.\n"));
          }
        }

        residual_ratio_old = residual_ratio;
      } // End of loop for iterative refinement

      done = !(resolve_with_better_quality) && !(pretend_singular);

    } // End of loop for solving the linear system (incl. modifications)

    // Finally let's assemble the res result vectors
    if (alpha != 0.) {
      res.Scal(alpha);
    }

    if (beta != 0.) {
      res.Axpy(beta, *copy_res);
    }

    DBG_PRINT_VECTOR(2, "res_x", *res.x());
    DBG_PRINT_VECTOR(2, "res_s", *res.s());
    DBG_PRINT_VECTOR(2, "res_c", *res.y_c());
    DBG_PRINT_VECTOR(2, "res_d", *res.y_d());
    DBG_PRINT_VECTOR(2, "res_zL", *res.z_L());
    DBG_PRINT_VECTOR(2, "res_zU", *res.z_U());
    DBG_PRINT_VECTOR(2, "res_vL", *res.v_L());
    DBG_PRINT_VECTOR(2, "res_vU", *res.v_U());

    IpData().TimingStats().PDSystemSolverTotal().End();

    return true;
  }
Ejemplo n.º 17
0
  bool PDSearchDirCalculator::ComputeSearchDirection()
  {
    DBG_START_METH("PDSearchDirCalculator::ComputeSearchDirection",
                   dbg_verbosity);

    bool improve_solution = false;
    if (IpData().HaveDeltas()) {
      improve_solution = true;
    }

    bool retval;
    if (improve_solution && fast_step_computation_) {
      retval = true;
    }
    else {
      SmartPtr<IteratesVector> rhs = IpData().curr()->MakeNewContainer();
      rhs->Set_x(*IpCq().curr_grad_lag_with_damping_x());
      rhs->Set_s(*IpCq().curr_grad_lag_with_damping_s());
      rhs->Set_y_c(*IpCq().curr_c());
      rhs->Set_y_d(*IpCq().curr_d_minus_s());
      Index nbounds = IpNLP().x_L()->Dim()+ IpNLP().x_U()->Dim() +
                      IpNLP().d_L()->Dim()+ IpNLP().d_U()->Dim();
      if (nbounds>0 && mehrotra_algorithm_) {
        // set up the right hand side a la Mehrotra
        DBG_ASSERT(IpData().HaveAffineDeltas());
        DBG_ASSERT(!IpData().HaveDeltas());
        const SmartPtr<const IteratesVector> delta_aff = IpData().delta_aff();

        SmartPtr<Vector> tmpvec = delta_aff->z_L()->MakeNew();
        IpNLP().Px_L()->TransMultVector(1., *delta_aff->x(), 0., *tmpvec);
        tmpvec->ElementWiseMultiply(*delta_aff->z_L());
        tmpvec->Axpy(1., *IpCq().curr_relaxed_compl_x_L());
        rhs->Set_z_L(*tmpvec);

        tmpvec = delta_aff->z_U()->MakeNew();
        IpNLP().Px_U()->TransMultVector(-1., *delta_aff->x(), 0., *tmpvec);
        tmpvec->ElementWiseMultiply(*delta_aff->z_U());
        tmpvec->Axpy(1., *IpCq().curr_relaxed_compl_x_U());
        rhs->Set_z_U(*tmpvec);

        tmpvec = delta_aff->v_L()->MakeNew();
        IpNLP().Pd_L()->TransMultVector(1., *delta_aff->s(), 0., *tmpvec);
        tmpvec->ElementWiseMultiply(*delta_aff->v_L());
        tmpvec->Axpy(1., *IpCq().curr_relaxed_compl_s_L());
        rhs->Set_v_L(*tmpvec);

        tmpvec = delta_aff->v_U()->MakeNew();
        IpNLP().Pd_U()->TransMultVector(-1., *delta_aff->s(), 0., *tmpvec);
        tmpvec->ElementWiseMultiply(*delta_aff->v_U());
        tmpvec->Axpy(1., *IpCq().curr_relaxed_compl_s_U());
        rhs->Set_v_U(*tmpvec);
      }
      else {
        rhs->Set_z_L(*IpCq().curr_relaxed_compl_x_L());
        rhs->Set_z_U(*IpCq().curr_relaxed_compl_x_U());
        rhs->Set_v_L(*IpCq().curr_relaxed_compl_s_L());
        rhs->Set_v_U(*IpCq().curr_relaxed_compl_s_U());
      }

      DBG_PRINT_VECTOR(2, "rhs", *rhs);

      // Get space for the search direction
      SmartPtr<IteratesVector> delta =
        IpData().curr()->MakeNewIteratesVector(true);

      if (improve_solution) {
        // We can probably avoid copying and scaling...
        delta->AddOneVector(-1., *IpData().delta(), 0.);
      }

      bool& allow_inexact = fast_step_computation_;
      retval = pd_solver_->Solve(-1.0, 0.0, *rhs, *delta, allow_inexact,
                                 improve_solution);
      if (retval) {
        // Store the search directions in the IpData object
        IpData().set_delta(delta);
      }
    }
    return retval;
  }
Ejemplo n.º 18
0
  void RestoIterationOutput::WriteOutput()
  {
    // Get pointers to the Original NLP objects
    const RestoIpoptNLP* resto_ipopt_nlp =
      static_cast<const RestoIpoptNLP*>(&IpNLP());
    DBG_ASSERT(resto_ipopt_nlp);

    SmartPtr<IpoptData> orig_ip_data = &resto_ipopt_nlp->OrigIpData();
    SmartPtr<IpoptNLP> orig_ip_nlp = &resto_ipopt_nlp->OrigIpNLP();
    SmartPtr<IpoptCalculatedQuantities> orig_ip_cq =
      &resto_ipopt_nlp->OrigIpCq();

    // Set the iteration counter for the original NLP to the current value
    Index iter = IpData().iter_count();
    orig_ip_data->Set_iter_count(iter);

    // If a resto_orig_iteration_output object was given, first do the
    // WriteOutput method with that one
    if (IsValid(resto_orig_iteration_output_)) {
      resto_orig_iteration_output_->WriteOutput();
    }

    //////////////////////////////////////////////////////////////////////
    //         First print the summary line for the iteration           //
    //////////////////////////////////////////////////////////////////////

    std::string header =
      "iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls\n";
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "\n\n**************************************************\n");
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "*** Summary of Iteration %d for original NLP:", IpData().iter_count());
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "\n**************************************************\n\n");
    if (iter%10 == 0 && !IsValid(resto_orig_iteration_output_)) {
      // output the header
      Jnlst().Printf(J_ITERSUMMARY, J_MAIN, header.c_str());
    }
    else {
      Jnlst().Printf(J_DETAILED, J_MAIN, header.c_str());
    }

    // For now, just print the total NLP error for the restoration
    // phase problem in the dual infeasibility column
    Number inf_du =
      IpCq().curr_dual_infeasibility(NORM_MAX);

    Number mu = IpData().curr_mu();
    Number dnrm = 0.;
    if (IsValid(IpData().delta()) && IsValid(IpData().delta()->x()) && IsValid(IpData().delta()->s())) {
      dnrm = Max(IpData().delta()->x()->Amax(), IpData().delta()->s()->Amax());
    }

    // Set  the trial  values  for  the original  Data  object to  the
    // current restoration phase values
    SmartPtr<const Vector> x = IpData().curr()->x();
    const CompoundVector* cx =
      static_cast<const CompoundVector*>(GetRawPtr(x));
    DBG_ASSERT(cx);

    SmartPtr<IteratesVector> trial = orig_ip_data->trial()->MakeNewContainer();
    trial->Set_x(*cx->GetComp(0));
    trial->Set_s(*IpData().curr()->s());
    orig_ip_data->set_trial(trial);

    // Compute primal infeasibility
    Number inf_pr;
    switch (inf_pr_output_) {
    case INTERNAL:
      inf_pr = orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
      break;
    case ORIGINAL:
      inf_pr = orig_ip_cq->unscaled_trial_nlp_constraint_violation(NORM_MAX);
      break;
    }
    // Compute original objective function
    Number f = orig_ip_cq->unscaled_trial_f();

    // Retrieve some information set in the different parts of the algorithm
    char info_iter='r';

    Number alpha_primal = IpData().info_alpha_primal();
    char alpha_primal_char = IpData().info_alpha_primal_char();
    Number alpha_dual = IpData().info_alpha_dual();
    Number regu_x = IpData().info_regu_x();
    char regu_x_buf[8];
    char dashes[]="   - ";
    char *regu_x_ptr;
    if (regu_x==.0) {
      regu_x_ptr = dashes;
    }
    else {
      Snprintf(regu_x_buf, 7, "%5.1f", log10(regu_x));
      regu_x_ptr = regu_x_buf;
    }
    Index ls_count = IpData().info_ls_count();
    const std::string info_string = IpData().info_string();

    Jnlst().Printf(J_ITERSUMMARY, J_MAIN,
                   "%4d%c%14.7e %7.2e %7.2e %5.1f %7.2e %5s %7.2e %7.2e%c%3d",
                   iter, info_iter, f, inf_pr, inf_du, log10(mu), dnrm, regu_x_ptr,
                   alpha_dual, alpha_primal, alpha_primal_char,
                   ls_count);
    if (print_info_string_) {
      Jnlst().Printf(J_ITERSUMMARY, J_MAIN, " %s", info_string.c_str());
    }
    else {
      Jnlst().Printf(J_DETAILED, J_MAIN, " %s", info_string.c_str());
    }
    Jnlst().Printf(J_ITERSUMMARY, J_MAIN, "\n");

    //////////////////////////////////////////////////////////////////////
    //           Now if desired more detail on the iterates             //
    //////////////////////////////////////////////////////////////////////

    if (Jnlst().ProduceOutput(J_DETAILED, J_MAIN)) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "\n**************************************************\n");
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "*** Beginning Iteration %d from the following point:",
                     IpData().iter_count());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "\n**************************************************\n\n");

      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Primal infeasibility for restoration phase problem = %.16e\n",
                     IpCq().curr_primal_infeasibility(NORM_MAX));
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "Dual infeasibility for restoration phase problem   = %.16e\n",
                     IpCq().curr_dual_infeasibility(NORM_MAX));

      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_x||_inf   = %.16e\n", IpData().curr()->x()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_s||_inf   = %.16e\n", IpData().curr()->s()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_y_c||_inf = %.16e\n", IpData().curr()->y_c()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_y_d||_inf = %.16e\n", IpData().curr()->y_d()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_z_L||_inf = %.16e\n", IpData().curr()->z_L()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_z_U||_inf = %.16e\n", IpData().curr()->z_U()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_v_L||_inf = %.16e\n", IpData().curr()->v_L()->Amax());
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "||curr_v_U||_inf = %.16e\n", IpData().curr()->v_U()->Amax());
    }
    if (Jnlst().ProduceOutput(J_MOREDETAILED, J_MAIN)) {
      if (IsValid(IpData().delta())) {
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "\n||delta_x||_inf   = %.16e\n", IpData().delta()->x()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_s||_inf   = %.16e\n", IpData().delta()->s()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_y_c||_inf = %.16e\n", IpData().delta()->y_c()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_y_d||_inf = %.16e\n", IpData().delta()->y_d()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_z_L||_inf = %.16e\n", IpData().delta()->z_L()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_z_U||_inf = %.16e\n", IpData().delta()->z_U()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_v_L||_inf = %.16e\n", IpData().delta()->v_L()->Amax());
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "||delta_v_U||_inf = %.16e\n", IpData().delta()->v_U()->Amax());
      }
      else {
        Jnlst().Printf(J_MOREDETAILED, J_MAIN,
                       "\nNo search direction has been computed yet.\n");
      }
    }
    if (Jnlst().ProduceOutput(J_VECTOR, J_MAIN)) {
      IpData().curr()->x()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_x");
      IpData().curr()->s()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_s");

      IpData().curr()->y_c()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_y_c");
      IpData().curr()->y_d()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_y_d");

      IpCq().curr_slack_x_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_slack_x_L");
      IpCq().curr_slack_x_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_slack_x_U");
      IpData().curr()->z_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_z_L");
      IpData().curr()->z_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_z_U");

      IpCq().curr_slack_s_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_slack_s_L");
      IpCq().curr_slack_s_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_slack_s_U");
      IpData().curr()->v_L()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_v_L");
      IpData().curr()->v_U()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_v_U");
    }
    if (Jnlst().ProduceOutput(J_MOREVECTOR, J_MAIN)) {
      IpCq().curr_grad_lag_x()->Print(Jnlst(), J_MOREVECTOR, J_MAIN, "curr_grad_lag_x");
      IpCq().curr_grad_lag_s()->Print(Jnlst(), J_MOREVECTOR, J_MAIN, "curr_grad_lag_s");
      if (IsValid(IpData().delta())) {
        IpData().delta()->Print(Jnlst(), J_MOREVECTOR, J_MAIN, "delta");
      }
    }

    if (Jnlst().ProduceOutput(J_DETAILED, J_MAIN)) {
      Jnlst().Printf(J_DETAILED, J_MAIN,
                     "\n\n***Current NLP Values for Iteration (Restoration phase problem) %d:\n",
                     IpData().iter_count());
      Jnlst().Printf(J_DETAILED, J_MAIN, "\n                                   (scaled)                 (unscaled)\n");
      Jnlst().Printf(J_DETAILED, J_MAIN, "Objective...............: %24.16e  %24.16e\n", IpCq().curr_f(), IpCq().unscaled_curr_f());
      Jnlst().Printf(J_DETAILED, J_MAIN, "Dual infeasibility......: %24.16e  %24.16e\n", IpCq().curr_dual_infeasibility(NORM_MAX), IpCq().unscaled_curr_dual_infeasibility(NORM_MAX));
      Jnlst().Printf(J_DETAILED, J_MAIN, "Constraint violation....: %24.16e  %24.16e\n", IpCq().curr_nlp_constraint_violation(NORM_MAX), IpCq().unscaled_curr_nlp_constraint_violation(NORM_MAX));
      Jnlst().Printf(J_DETAILED, J_MAIN, "Complementarity.........: %24.16e  %24.16e\n", IpCq().curr_complementarity(0., NORM_MAX), IpCq().unscaled_curr_complementarity(0., NORM_MAX));
      Jnlst().Printf(J_DETAILED, J_MAIN, "Overall NLP error.......: %24.16e  %24.16e\n\n", IpCq().curr_nlp_error(), IpCq().unscaled_curr_nlp_error());
    }
    if (Jnlst().ProduceOutput(J_VECTOR, J_MAIN)) {
      IpCq().curr_grad_f()->Print(Jnlst(), J_VECTOR, J_MAIN, "grad_f");
      IpCq().curr_c()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_c");
      IpCq().curr_d()->Print(Jnlst(), J_VECTOR, J_MAIN, "curr_d");
      IpCq().curr_d_minus_s()->Print(Jnlst(), J_VECTOR, J_MAIN,
                                     "curr_d - curr_s");
    }

    if (Jnlst().ProduceOutput(J_MATRIX, J_MAIN)) {
      IpCq().curr_jac_c()->Print(Jnlst(), J_MATRIX, J_MAIN, "jac_c");
      IpCq().curr_jac_d()->Print(Jnlst(), J_MATRIX, J_MAIN, "jac_d");
      IpData().W()->Print(Jnlst(), J_MATRIX, J_MAIN, "W");
    }

    Jnlst().Printf(J_DETAILED, J_MAIN, "\n\n");
  }
Ejemplo n.º 19
0
  bool IpoptAlgorithm::InitializeImpl(const OptionsList& options,
                                      const std::string& prefix)
  {
    DBG_START_METH("IpoptAlgorithm::InitializeImpl",
                   dbg_verbosity);

    SmartPtr<const OptionsList> my_options;
    options.GetBoolValue("mehrotra_algorithm", mehrotra_algorithm_, prefix);
    if (mehrotra_algorithm_) {
      // Verify a few options and set a few new ones.  But we better
      // make a copy of the incoming options.
      SmartPtr<OptionsList> new_options = new OptionsList(options);
      // Check required options are set correctly
      std::string string_option;
      if (new_options->GetStringValue("adaptive_mu_globalization", string_option, prefix)) {
        ASSERT_EXCEPTION(string_option=="never-monotone-mode", OPTION_INVALID,
                         "If mehrotra_algorithm=yes, adaptive_mu_globalization must be \"never-monotone-mode\".");
      }
      else {
        new_options->SetStringValue("adaptive_mu_globalization",
                                    "never-monotone-mode", false);
      }
      // The corrector step is already taken case of in
      // ComputeSearchDirection below
      if (new_options->GetStringValue("corrector_type", string_option, prefix)) {
        ASSERT_EXCEPTION(string_option=="none", OPTION_INVALID,
                         "If mehrotra_algorithm=yes, corrector_type must be \"none\".");
      }
      else {
        new_options->SetStringValue("corrector_type", "none", false);
      }
      if (new_options->GetStringValue("accept_every_trial_step", string_option, prefix)) {
        ASSERT_EXCEPTION(string_option=="yes", OPTION_INVALID,
                         "If mehrotra_algorithm=yes, accept_every_trial_step must be \"yes\".");
      }
      else {
        new_options->SetStringValue("accept_every_trial_step", "yes", false);
      }

      // Change some default options
      new_options->SetNumericValueIfUnset("bound_push", 10.);
      new_options->SetNumericValueIfUnset("bound_frac", 0.2);
      new_options->SetNumericValueIfUnset("bound_mult_init_val", 10.);
      new_options->SetNumericValueIfUnset("constr_mult_init_max", 0.);
      new_options->SetStringValueIfUnset("alpha_for_y", "bound_mult");
      new_options->SetStringValueIfUnset("least_square_init_primal", "yes");

      my_options = ConstPtr(new_options);
    }
    else {
      my_options = &options;
    }
    bool bval;
    options.GetBoolValue("sb", bval, prefix);
    if (bval) {
      copyright_message_printed = true;
    }

    // Store which linear solver is chosen for later output
    options.GetStringValue("linear_solver", linear_solver_, prefix);

    // Read the IpoptAlgorithm options
    // Initialize the Data object
    bool retvalue = IpData().Initialize(Jnlst(), *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the IpIpoptData object failed to initialize.");

    // Initialize the CQ object
    retvalue = IpCq().Initialize(Jnlst(), *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the IpIpoptCalculatedQuantities object failed to initialize.");

    // Initialize the NLP object
    retvalue = IpNLP().Initialize(Jnlst(), *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the IpIpoptNLP object failed to initialize.");

    // Initialize all the strategies
    retvalue = iterate_initializer_->Initialize(Jnlst(), IpNLP(), IpData(),
               IpCq(), *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the iterate_initializer strategy failed to initialize.");

    retvalue = mu_update_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                      *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the mu_update strategy failed to initialize.");

    retvalue = search_dir_calculator_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
               options,prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the search_direction_calculator strategy failed to initialize.");
    retvalue = line_search_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                        *my_options,prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the line_search strategy failed to initialize.");

    retvalue = conv_check_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                       *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the conv_check strategy failed to initialize.");

    retvalue = iter_output_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                        *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the iter_output strategy failed to initialize.");

    retvalue = hessian_updater_->Initialize(Jnlst(), IpNLP(), IpData(), IpCq(),
                                            *my_options, prefix);
    ASSERT_EXCEPTION(retvalue, FAILED_INITIALIZATION,
                     "the hessian_updater strategy failed to initialize.");

    my_options->GetNumericValue("kappa_sigma", kappa_sigma_, prefix);
    if (!my_options->GetBoolValue("recalc_y", recalc_y_, prefix)) {
      Index enum_int;
      if (my_options->GetEnumValue("hessian_approximation", enum_int, prefix)) {
        HessianApproximationType hessian_approximation =
          HessianApproximationType(enum_int);
        if (hessian_approximation==LIMITED_MEMORY) {
          recalc_y_ = true;
        }
      }
    }
    if (recalc_y_) {
      my_options->GetNumericValue("recalc_y_feas_tol", recalc_y_feas_tol_,
                                  prefix);
    }

    if (prefix=="resto.") {
      skip_print_problem_stats_ = true;
    }
    else {
      skip_print_problem_stats_ = false;
    }

    return true;
  }
Ejemplo n.º 20
0
  char CGPenaltyLSAcceptor::UpdatePenaltyParameter()
  {
    DBG_START_METH("CGPenaltyLSAcceptor::UpdatePenaltyParameter",
                   dbg_verbosity);
    char info_alpha_primal_char = 'n';
    // We use the new infeasibility here...
    Number trial_inf = IpCq().trial_primal_infeasibility(NORM_2);
    Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                   "trial infeasibility = %8.2\n", trial_inf);
    if (curr_eta_<0.) {
      // We need to initialize the eta tolerance
      curr_eta_ = Max(eta_min_, Min(gamma_tilde_,
                                    gamma_hat_*IpCq().curr_nlp_error()));
    }
    // Check if the penalty parameter is to be increased
    Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                   "Starting tests for penalty parameter update:\n");
    bool increase = (trial_inf >= penalty_update_infeasibility_tol_);
    if (!increase) {
      info_alpha_primal_char='i';
    }
    if (increase) {
      Number max_step = Max(CGPenData().delta_cgpen()->x()->Amax(),
                            CGPenData().delta_cgpen()->s()->Amax());
      Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                     "Max norm of step = %8.2\n", max_step);
      increase = (max_step <= curr_eta_);
      if (!increase) {
        info_alpha_primal_char='d';
      }
    }
    // Lifeng: Should we use the new complementarity here?  If so, I
    // have to restructure BacktrackingLineSearch
    Number mu = IpData().curr_mu();
    if (increase) {
      Number min_compl = mu;
      Number max_compl = mu;
      if (IpNLP().x_L()->Dim()>0) {
        SmartPtr<const Vector> compl_x_L = IpCq().curr_compl_x_L();
        min_compl = Min(min_compl, compl_x_L->Min());
        max_compl = Max(max_compl, compl_x_L->Max());
      }
      if (IpNLP().x_U()->Dim()>0) {
        SmartPtr<const Vector> compl_x_U = IpCq().curr_compl_x_U();
        min_compl = Min(min_compl, compl_x_U->Min());
        max_compl = Max(max_compl, compl_x_U->Max());
      }
      if (IpNLP().d_L()->Dim()>0) {
        SmartPtr<const Vector> compl_s_L = IpCq().curr_compl_s_L();
        min_compl = Min(min_compl, compl_s_L->Min());
        max_compl = Max(max_compl, compl_s_L->Max());
      }
      if (IpNLP().d_U()->Dim()>0) {
        SmartPtr<const Vector> compl_s_U = IpCq().curr_compl_s_U();
        min_compl = Min(min_compl, compl_s_U->Min());
        max_compl = Max(max_compl, compl_s_U->Max());
      }
      Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                     "Minimal compl = %8.2\n", min_compl);
      Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                     "Maximal compl = %8.2\n", max_compl);
      increase = (min_compl >= mu*penalty_update_compl_tol_ &&
                  max_compl <= mu/penalty_update_compl_tol_);
      if (!increase) {
        info_alpha_primal_char='c';
      }
    }
    // Lifeng: Here I'm using the information from the current step
    // and the current infeasibility
    if (increase) {
      SmartPtr<Vector> vec = IpData().curr()->y_c()->MakeNewCopy();
      vec->AddTwoVectors(1., *CGPenData().delta_cgpen()->y_c(),
                         -1./CGPenCq().curr_cg_pert_fact(), *IpCq().curr_c(),
                         1.);
      Number omega_test = vec->Amax();
      Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                     "omega_test for c = %8.2\n", omega_test);
      increase = (omega_test < curr_eta_);
      if (increase) {
        SmartPtr<Vector> vec = IpData().curr()->y_d()->MakeNewCopy();
        vec->AddTwoVectors(1., *IpData().delta()->y_d(),
                           -1./CGPenCq().curr_cg_pert_fact(), *IpCq().curr_d_minus_s(),
                           1.);
        omega_test = vec->Amax();
        Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                       "omega_test for d = %8.2\n", omega_test);
        increase = (omega_test < curr_eta_);
      }
      if (!increase) {
        info_alpha_primal_char='m';
      }
    }
    if (increase) {
      // Ok, now we should increase the penalty parameter
      counter_first_type_penalty_updates_++;
      // Update the eta tolerance
      curr_eta_ = Max(eta_min_, curr_eta_/2.);
      Jnlst().Printf(J_MOREDETAILED, J_LINE_SEARCH,
                     "Updating eta to = %8.2\n", curr_eta_);
      Number penalty = CGPenData().curr_kkt_penalty();
      Number y_full_step_max;
      SmartPtr<Vector> vec = IpData().curr()->y_c()->MakeNew();
      vec->AddTwoVectors(1., *IpData().curr()->y_c(),
                         1., *CGPenData().delta_cgpen()->y_c(), 0.);
      y_full_step_max = vec->Amax();
      vec = IpData().curr()->y_d()->MakeNew();
      vec->AddTwoVectors(1., *IpData().curr()->y_d(),
                         1., *CGPenData().delta_cgpen()->y_d(), 0.);
      y_full_step_max = Max(y_full_step_max, vec->Amax());
      if (IpCq().curr_primal_infeasibility(NORM_2) >= epsilon_c_) {
        penalty = Max(chi_hat_*penalty, y_full_step_max + 1.);
        info_alpha_primal_char = 'l';
      }
      else {
        penalty = Max(chi_tilde_*penalty, chi_cup_*y_full_step_max);
        info_alpha_primal_char = 's';
      }
      if (penalty > penalty_max_) {
        THROW_EXCEPTION(IpoptException, "Penalty parameter becomes too large.");
      }
      CGPenData().Set_kkt_penalty(penalty);
      if (CGPenData().NeverTryPureNewton()) {
        CGPenData().Set_penalty(penalty);
      }
    }

    // Second heuristic update for penalty parameters
    if (IpData().curr()->y_c()->Dim() + IpData().curr()->y_d()->Dim() > 0 &&
        !never_use_piecewise_penalty_ls_) {
      Number scaled_y_Amax = CGPenCq().curr_scaled_y_Amax();
      if (scaled_y_Amax <= 1e4 ||
          counter_second_type_penalty_updates_ < 5) {
        Number result;
        SmartPtr<const Vector> ty_c = IpData().curr()->y_c();
        SmartPtr<const Vector> ty_d = IpData().curr()->y_d();
        SmartPtr<const Vector> dy_c = IpData().delta()->y_c();
        SmartPtr<const Vector> dy_d = IpData().delta()->y_d();
        Number curr_inf = IpCq().curr_primal_infeasibility(NORM_2);
        result = dy_c->Dot(*IpCq().curr_c()) + dy_d->Dot(*IpCq().curr_d_minus_s());
        if (!CGPenData().HaveCgFastDeltas()) {
          result += ty_c->Dot(*IpCq().curr_c()) + ty_d->Dot(*IpCq().curr_d_minus_s());
        }
        Number k_pen = CGPenData().curr_kkt_penalty();
        if (result > 0.5*k_pen*curr_inf || result < -0.5*k_pen*curr_inf) {
          Number nrm2_y = CGPenCq().curr_added_y_nrm2();
          result = 5.*nrm2_y;
          CGPenData().Set_kkt_penalty(result);
          if (CGPenData().NeverTryPureNewton()) {
            CGPenData().Set_penalty(result);
          }
          if (scaled_y_Amax > 1e4) {
            counter_second_type_penalty_updates_++;
          }
        }
      }
    }
    return info_alpha_primal_char;
  }
Ejemplo n.º 21
0
  bool StdStepCalculator::BoundCheck(IteratesVector& sol,
				     std::vector<Index>& x_bound_violations_idx,
				     std::vector<Number>& x_bound_violations_du)
  {
    DBG_START_METH("StdStepCalculator::BoundCheck", dbg_verbosity);
    DBG_ASSERT(x_bound_violations_idx.empty());
    DBG_ASSERT(x_bound_violations_du.empty());

    // find bound violations in x vector
    const Number* x_val = dynamic_cast<const DenseVector*>(GetRawPtr(IpData().curr()->x()))->Values();
    const Number* sol_val = dynamic_cast<const DenseVector*>(GetRawPtr(sol.x()))->Values();

    SmartPtr<Vector> x_L_exp = IpData().curr()->x()->MakeNew();
    SmartPtr<Vector> x_U_exp = IpData().curr()->x()->MakeNew();

    SmartPtr<Vector> x_L_comp = IpNLP().x_L()->MakeNew();
    SmartPtr<Vector> x_U_comp = IpNLP().x_U()->MakeNew();

    IpNLP().Px_L()->TransMultVector(1.0, *sol.x(), 0.0, *x_L_comp);
    IpNLP().Px_U()->TransMultVector(1.0, *sol.x(), 0.0, *x_U_comp);

    x_L_comp->Print(Jnlst(),J_VECTOR,J_USER1,"x_L_comp");
    x_U_comp->Print(Jnlst(),J_VECTOR,J_USER1,"x_U_comp");
    //    return false;

    Number* x_L_val = dynamic_cast<DenseVector*>(GetRawPtr(x_L_comp))->Values();
    Number* x_U_val = dynamic_cast<DenseVector*>(GetRawPtr(x_U_comp))->Values();

    const Number* x_L_bound = dynamic_cast<const DenseVector*>(GetRawPtr(IpNLP().x_L()))->Values();
    const Number* x_U_bound = dynamic_cast<const DenseVector*>(GetRawPtr(IpNLP().x_U()))->Values();

    for (Index i=0; i<x_L_comp->Dim(); ++i) {
      x_L_val[i] -= x_L_bound[i];
    }

    for (Index i=0; i<x_U_comp->Dim(); ++i) {
      x_U_val[i] -= x_U_bound[i];
    }

    // project back
    IpNLP().Px_L()->MultVector(1.0, *x_L_comp, 0.0, *x_L_exp);
    IpNLP().Px_U()->MultVector(1.0, *x_U_comp, 0.0, *x_U_exp);

    const Number* x_L_exp_val = dynamic_cast<DenseVector*>(GetRawPtr(x_L_exp))->Values();
    const Number* x_U_exp_val = dynamic_cast<DenseVector*>(GetRawPtr(x_U_exp))->Values();

    for (Index i=0; i<x_L_exp->Dim(); ++i) {
      if (x_L_exp_val[i]<-bound_eps_) {
	x_bound_violations_idx.push_back(i);
	x_bound_violations_du.push_back(-x_L_exp_val[i]+sol_val[i]-x_val[i]); // this is just an awkward way to compute x_bound[i] - x_curr_val[i].
      } else if (-x_U_exp_val[i]<-bound_eps_) {
	x_bound_violations_idx.push_back(i);
	x_bound_violations_du.push_back(-x_U_exp_val[i]+sol_val[i]-x_val[i]);
      }
    }

    // z_L and z_U bound violations -> These are much easier since there is no projecting back and forth
    SmartPtr<const DenseVector> z_L = dynamic_cast<const DenseVector*>(GetRawPtr(sol.z_L()));
    SmartPtr<const DenseVector> z_U = dynamic_cast<const DenseVector*>(GetRawPtr(sol.z_U()));
    z_L->Print(Jnlst(),J_VECTOR,J_USER1,"z_L_boundcheck");
    z_U->Print(Jnlst(),J_VECTOR,J_USER1,"z_U_boundcheck");
    const Number* z_L_val = z_L->Values();
    const Number* z_U_val = z_U->Values();

    SmartPtr<const DenseVector> z_L_trial = dynamic_cast<const DenseVector*>(GetRawPtr(IpData().trial()->z_L()));
    SmartPtr<const DenseVector> z_U_trial = dynamic_cast<const DenseVector*>(GetRawPtr(IpData().trial()->z_U()));
    const Number* z_L_trial_val = z_L_trial->Values();
    const Number* z_U_trial_val = z_U_trial->Values();

    // find absolute index of z_L and z_U in IteratesVector
    Index z_L_ItVec_idx = 0;
    for (Index i=0; i<4; ++i) {
      z_L_ItVec_idx += (sol.GetComp(i))->Dim();
    }
    Index z_U_ItVec_idx = z_L_ItVec_idx + sol.z_L()->Dim();

    for (Index i=0; i<z_L->Dim(); ++i) {
      if (z_L_val[i]<-bound_eps_) {
	x_bound_violations_idx.push_back(i+z_L_ItVec_idx);
	x_bound_violations_du.push_back(-z_L_trial_val[i]);
	//printf("Lower Bound Mult. no. i=%d invalid: delta_u=%f\n", i+z_L_ItVec_idx, z_L_val[i]);
      }
    }

    for (Index i=0; i<z_U->Dim(); ++i) {
      if (z_U_val[i]<-bound_eps_) {
	x_bound_violations_idx.push_back(i+z_U_ItVec_idx);
	x_bound_violations_du.push_back(-z_U_trial_val[i]);
	//printf("Upper Bound Mult. no. i=%d invalid: delta_u=%f\n", i+z_U_ItVec_idx, z_U_val[i]);
      }
    }

    //    if (x_bound_violations_idx.empty() || z_L_bound_violations_idx.empty() || z_U_bound_violations_idx.empty()) {
    if (x_bound_violations_idx.empty()) {
      return false;
    }
    else {
      return true;
    }
  }
Ejemplo n.º 22
0
ConvergenceCheck::ConvergenceStatus
RestoConvergenceCheck::CheckConvergence(bool call_intermediate_callback /*= true*/)
{
    // Get pointers to the Original NLP objects
    const RestoIpoptNLP* resto_ipopt_nlp =
        static_cast<const RestoIpoptNLP*>(&IpNLP());
    DBG_ASSERT(dynamic_cast<const RestoIpoptNLP*>(&IpNLP()));

    SmartPtr<IpoptData> orig_ip_data = &resto_ipopt_nlp->OrigIpData();
    SmartPtr<IpoptCalculatedQuantities> orig_ip_cq =
        &resto_ipopt_nlp->OrigIpCq();

    // set the trial point for the original problem
    SmartPtr<const Vector> x = IpData().curr()->x();
    const CompoundVector* cx =
        static_cast<const CompoundVector*>(GetRawPtr(x));
    DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(x)));
    SmartPtr<const Vector> s = IpData().curr()->s();
    const CompoundVector* cs =
        static_cast<const CompoundVector*>(GetRawPtr(s));
    DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(s)));
    DBG_ASSERT(cs->NComps() == 1);

    SmartPtr<IteratesVector> trial = orig_ip_data->curr()->MakeNewContainer();
    trial->Set_x(*cx->GetComp(0));
    trial->Set_s(*cs->GetComp(0));
    orig_ip_data->set_trial(trial);

    if (call_intermediate_callback) {
        // Check if user requested termination by calling the intermediate
        // user callback function
        AlgorithmMode mode = RestorationPhaseMode;
        // Gather the information also used in the iteration output
        Index iter = IpData().iter_count();
        Number inf_pr = orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
        Number inf_du = IpCq().curr_dual_infeasibility(NORM_MAX);
        Number mu = IpData().curr_mu();
        Number dnrm;
        if (IsValid(IpData().delta()) && IsValid(IpData().delta()->x()) && IsValid(IpData().delta()->s())) {
            dnrm = Max(IpData().delta()->x()->Amax(), IpData().delta()->s()->Amax());
        }
        else {
            // This is the first iteration - no search direction has been
            // computed yet.
            dnrm = 0.;
        }
        Number alpha_primal = IpData().info_alpha_primal();
        Number alpha_dual = IpData().info_alpha_dual();
        Number regu_x = IpData().info_regu_x();
        Number unscaled_f = orig_ip_cq->unscaled_trial_f();
        Index ls_count = IpData().info_ls_count();
        bool request_stop =
            !IpNLP().IntermediateCallBack(mode, iter, unscaled_f, inf_pr, inf_du,
                                          mu, dnrm, regu_x, alpha_dual,
                                          alpha_primal, ls_count,
                                          &IpData(), &IpCq());

        if (request_stop) {
            return ConvergenceCheck::USER_STOP;
        }
    }

    if (IpData().iter_count() >= maximum_iters_) {
        return ConvergenceCheck::MAXITER_EXCEEDED;
    }

    if (successive_resto_iter_ > maximum_resto_iters_) {
        Jnlst().Printf(J_WARNING, J_MAIN,
                       "More than %d successive iterations taken in restoration phase.\n",
                       maximum_resto_iters_);
        return ConvergenceCheck::MAXITER_EXCEEDED;
    }
    successive_resto_iter_++;

    // First check if the point is now acceptable for the outer filter
    ConvergenceStatus status;

    // Calculate the f and theta for the original problem
    Number orig_trial_theta = orig_ip_cq->trial_constraint_violation();
    Number orig_curr_theta = orig_ip_cq->curr_constraint_violation();

    // check acceptability to the filter
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "orig_curr_theta = %8.2e, orig_trial_theta = %8.2e\n",
                   orig_curr_theta, orig_trial_theta);

    // ToDo: In the following we might want to be more careful with the lower bound

    Number orig_curr_inf_pr = orig_ip_cq->curr_primal_infeasibility(NORM_MAX);
    Number orig_trial_inf_pr = orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "orig_curr_inf_pr = %8.2e, orig_trial_inf_pr = %8.2e\n",
                   orig_curr_inf_pr, orig_trial_inf_pr);


    Number orig_inf_pr_max = Max(kappa_resto_*orig_curr_inf_pr,
                                 Min(orig_ip_data->tol(),
                                     orig_constr_viol_tol_));
    if (kappa_resto_ == 0.) {
        orig_inf_pr_max = 0.;
    }

    if (first_resto_iter_) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "This is the first iteration - continue to take at least one step.\n");
        status = CONTINUE;
    }
    else if (orig_ip_cq->IsSquareProblem() &&
             orig_trial_inf_pr <=
             Min(orig_ip_data->tol(), orig_constr_viol_tol_)) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Restoration phase found points satisfying feasibility tolerance in square problem.\n");
        status = CONVERGED;
    }
    else if (orig_trial_inf_pr > orig_inf_pr_max) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Point does not provide sufficient reduction w.r.t the original constraint violation (orig_inf_pr_max=%e).\n", orig_inf_pr_max);
        status = CONTINUE;
    }
    else {
        Number orig_trial_barr = orig_ip_cq->trial_barrier_obj();

        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "orig_trial_barr = %8.2e\n", orig_trial_barr);
        status = TestOrigProgress(orig_trial_barr, orig_trial_theta);
    }

    // If the point is not yet acceptable to the filter, check if the problem
    // is maybe locally infeasible

    if (status==CONTINUE) {
        Jnlst().Printf(J_DETAILED, J_MAIN,
                       "Checking convergence for restoration phase problem...\n");
        status = OptimalityErrorConvergenceCheck::CheckConvergence(false);
        if (status == CONVERGED || status == CONVERGED_TO_ACCEPTABLE_POINT) {
            Number orig_trial_primal_inf =
                orig_ip_cq->trial_primal_infeasibility(NORM_MAX);
            // ToDo make the factor in following line an option
            if (orig_trial_primal_inf <= 1e2*IpData().tol()) {
                //        if (orig_trial_primal_inf <= 1e2*orig_ip_data->tol()) {
                if (IpData().tol() > 1e-1*orig_ip_data->tol()) {
                    // For once, we tighten the convergence tolerance for the
                    // restoration phase problem in case the problem is only
                    // very slightly infeasible.
                    IpData().Set_tol(1e-2*IpData().tol());
                    status = CONTINUE;
                    Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                                   "Tightening restoration phase tolerance to %e.\n",
                                   IpData().tol());
                    IpData().Append_info_string("!");
                }
                else {
                    Jnlst().Printf(J_WARNING, J_LINE_SEARCH,
                                   "Restoration phase converged to a feasible point that is\n"
                                   "unacceptable to the filter for the original problem.\n");
                    THROW_EXCEPTION(RESTORATION_CONVERGED_TO_FEASIBLE_POINT,
                                    "Restoration phase converged to a feasible point that is "
                                    "unacceptable to the filter for the original problem.");
                }
            }
            else {
                THROW_EXCEPTION(LOCALLY_INFEASIBLE,
                                "Restoration phase converged to a point of local infeasibility");
            }
        }
    }

    first_resto_iter_ = false;

    return status;
}
Ejemplo n.º 23
0
  ConvergenceCheck::ConvergenceStatus
  OptimalityErrorConvergenceCheck::CheckConvergence(bool call_intermediate_callback /*= true*/)
  {
    DBG_START_METH("OptimalityErrorConvergenceCheck::CheckConvergence", dbg_verbosity);

    if (call_intermediate_callback) {
      // Check if user requested termination by calling the intermediate
      // user callback function
      AlgorithmMode mode = RegularMode;
      // Gather the information also used in the iteration output
      Index iter = IpData().iter_count();
      Number inf_pr = IpCq().curr_primal_infeasibility(NORM_MAX);
      Number inf_du = IpCq().curr_dual_infeasibility(NORM_MAX);
      Number mu = IpData().curr_mu();
      Number dnrm;
      if (IsValid(IpData().delta()) && IsValid(IpData().delta()->x()) && IsValid(IpData().delta()->s())) {
        dnrm = Max(IpData().delta()->x()->Amax(), IpData().delta()->s()->Amax());
      }
      else {
        // This is the first iteration - no search direction has been
        // computed yet.
        dnrm = 0.;
      }
      Number alpha_primal = IpData().info_alpha_primal();
      Number alpha_dual = IpData().info_alpha_dual();
      Number regu_x = IpData().info_regu_x();
      Number unscaled_f = IpCq().unscaled_curr_f();
      Index ls_count = IpData().info_ls_count();
      bool request_stop =
        !IpNLP().IntermediateCallBack(mode, iter, unscaled_f, inf_pr, inf_du,
                                      mu, dnrm, regu_x, alpha_dual,
                                      alpha_primal, ls_count,
                                      &IpData(), &IpCq());

      if (request_stop) {
        return ConvergenceCheck::USER_STOP;
      }
    }

    if (IpData().iter_count() >= max_iterations_) {
      return ConvergenceCheck::MAXITER_EXCEEDED;
    }

    Number overall_error = IpCq().curr_nlp_error();
    Number dual_inf = IpCq().unscaled_curr_dual_infeasibility(NORM_MAX);
    Number constr_viol = IpCq().unscaled_curr_nlp_constraint_violation(NORM_MAX);
    Number compl_inf = IpCq().unscaled_curr_complementarity(0., NORM_MAX);

    if (IpData().curr()->x()->Dim()==IpData().curr()->y_c()->Dim()) {
      // the problem is square, there is no point in looking at dual
      // infeasibility and complementarity as termination criterion
      dual_inf_tol_ = 1e300;
      compl_inf_tol_ = 1e300;
    }

    if (overall_error <= IpData().tol() &&
        dual_inf <= dual_inf_tol_ &&
        constr_viol <= constr_viol_tol_ &&
        compl_inf <= compl_inf_tol_) {
      return ConvergenceCheck::CONVERGED;
    }

    if (acceptable_iter_>0 && CurrentIsAcceptable()) {
      IpData().Append_info_string("A");
      acceptable_counter_++;
      if (acceptable_counter_ >= acceptable_iter_) {
        return ConvergenceCheck::CONVERGED_TO_ACCEPTABLE_POINT;
      }
    }
    else {
      acceptable_counter_ = 0;
    }

    if (IpData().curr()->x()->Amax() > diverging_iterates_tol_) {
      return ConvergenceCheck::DIVERGING;
    }

    return ConvergenceCheck::CONTINUE;
  }
Ejemplo n.º 24
0
  bool RestoIterateInitializer::SetInitialIterates()
  {
    DBG_START_METH("RestoIterateInitializer::SetInitialIterates",
                   dbg_verbosity);

    // Get a grip on the restoration phase NLP and obtain the pointers
    // to the original NLP data
    SmartPtr<RestoIpoptNLP> resto_ip_nlp =
      static_cast<RestoIpoptNLP*> (&IpNLP());
    SmartPtr<IpoptNLP> orig_ip_nlp =
      static_cast<IpoptNLP*> (&resto_ip_nlp->OrigIpNLP());
    SmartPtr<IpoptData> orig_ip_data =
      static_cast<IpoptData*> (&resto_ip_nlp->OrigIpData());
    SmartPtr<IpoptCalculatedQuantities> orig_ip_cq =
      static_cast<IpoptCalculatedQuantities*> (&resto_ip_nlp->OrigIpCq());

    // Set the value of the barrier parameter
    Number resto_mu;
    resto_mu = Max(orig_ip_data->curr_mu(),
                   orig_ip_cq->curr_c()->Amax(),
                   orig_ip_cq->curr_d_minus_s()->Amax());
    IpData().Set_mu(resto_mu);
    Jnlst().Printf(J_DETAILED, J_INITIALIZATION,
                   "Initial barrier parameter resto_mu = %e\n", resto_mu);

    /////////////////////////////////////////////////////////////////////
    //                   Initialize primal varialbes                   //
    /////////////////////////////////////////////////////////////////////

    // initialize the data structures in the restoration phase NLP
    IpData().InitializeDataStructures(IpNLP(), false, false, false,
                                      false, false);

    SmartPtr<Vector> new_x = IpData().curr()->x()->MakeNew();
    SmartPtr<CompoundVector> Cnew_x =
      static_cast<CompoundVector*> (GetRawPtr(new_x));

    // Set the trial x variables from the original NLP
    Cnew_x->GetCompNonConst(0)->Copy(*orig_ip_data->curr()->x());

    // Compute the initial values for the n and p variables for the
    // equality constraints
    Number rho = resto_ip_nlp->Rho();
    DBG_PRINT((1,"rho = %e\n", rho));
    SmartPtr<Vector> nc = Cnew_x->GetCompNonConst(1);
    SmartPtr<Vector> pc = Cnew_x->GetCompNonConst(2);
    SmartPtr<const Vector> cvec = orig_ip_cq->curr_c();
    DBG_PRINT_VECTOR(2, "cvec", *cvec);
    SmartPtr<Vector> a = nc->MakeNew();
    SmartPtr<Vector> b = nc->MakeNew();
    a->Set(resto_mu/(2.*rho));
    a->Axpy(-0.5, *cvec);
    b->Copy(*cvec);
    b->Scal(resto_mu/(2.*rho));
    DBG_PRINT_VECTOR(2, "a", *a);
    DBG_PRINT_VECTOR(2, "b", *b);
    solve_quadratic(*a, *b, *nc);
    pc->Copy(*cvec);
    pc->Axpy(1., *nc);
    DBG_PRINT_VECTOR(2, "nc", *nc);
    DBG_PRINT_VECTOR(2, "pc", *pc);

    // initial values for the n and p variables for the inequality
    // constraints
    SmartPtr<Vector> nd = Cnew_x->GetCompNonConst(3);
    SmartPtr<Vector> pd = Cnew_x->GetCompNonConst(4);
    cvec = orig_ip_cq->curr_d_minus_s();
    a = nd->MakeNew();
    b = nd->MakeNew();
    a->Set(resto_mu/(2.*rho));
    a->Axpy(-0.5, *cvec);
    b->Copy(*cvec);
    b->Scal(resto_mu/(2.*rho));
    solve_quadratic(*a, *b, *nd);
    pd->Copy(*cvec);
    pd->Axpy(1., *nd);
    DBG_PRINT_VECTOR(2, "nd", *nd);
    DBG_PRINT_VECTOR(2, "pd", *pd);

    // Leave the slacks unchanged
    SmartPtr<const Vector> new_s = orig_ip_data->curr()->s();

    // Now set the primal trial variables
    DBG_PRINT_VECTOR(2,"new_s",*new_s);
    DBG_PRINT_VECTOR(2,"new_x",*new_x);
    SmartPtr<IteratesVector> trial = IpData().curr()->MakeNewContainer();
    trial->Set_primal(*new_x, *new_s);
    IpData().set_trial(trial);

    DBG_PRINT_VECTOR(2, "resto_c", *IpCq().trial_c());
    DBG_PRINT_VECTOR(2, "resto_d_minus_s", *IpCq().trial_d_minus_s());

    /////////////////////////////////////////////////////////////////////
    //                   Initialize bound multipliers                  //
    /////////////////////////////////////////////////////////////////////

    SmartPtr<Vector> new_z_L = IpData().curr()->z_L()->MakeNew();
    SmartPtr<CompoundVector> Cnew_z_L =
      static_cast<CompoundVector*> (GetRawPtr(new_z_L));
    DBG_ASSERT(IsValid(Cnew_z_L));
    SmartPtr<Vector> new_z_U = IpData().curr()->z_U()->MakeNew();
    SmartPtr<Vector> new_v_L = IpData().curr()->v_L()->MakeNew();
    SmartPtr<Vector> new_v_U = IpData().curr()->v_U()->MakeNew();

    // multipliers for the original bounds are
    SmartPtr<const Vector> orig_z_L = orig_ip_data->curr()->z_L();
    SmartPtr<const Vector> orig_z_U = orig_ip_data->curr()->z_U();
    SmartPtr<const Vector> orig_v_L = orig_ip_data->curr()->v_L();
    SmartPtr<const Vector> orig_v_U = orig_ip_data->curr()->v_U();

    // Set the new multipliers to the min of the penalty parameter Rho
    // and their current value
    SmartPtr<Vector> Cnew_z_L0 = Cnew_z_L->GetCompNonConst(0);
    Cnew_z_L0->Set(rho);
    Cnew_z_L0->ElementWiseMin(*orig_z_L);
    new_z_U->Set(rho);
    new_z_U->ElementWiseMin(*orig_z_U);
    new_v_L->Set(rho);
    new_v_L->ElementWiseMin(*orig_v_L);
    new_v_U->Set(rho);
    new_v_U->ElementWiseMin(*orig_v_U);

    // Set the multipliers for the p and n bounds to the "primal" multipliers
    SmartPtr<Vector> Cnew_z_L1 = Cnew_z_L->GetCompNonConst(1);
    Cnew_z_L1->Set(resto_mu);
    Cnew_z_L1->ElementWiseDivide(*nc);
    SmartPtr<Vector> Cnew_z_L2 = Cnew_z_L->GetCompNonConst(2);
    Cnew_z_L2->Set(resto_mu);
    Cnew_z_L2->ElementWiseDivide(*pc);
    SmartPtr<Vector> Cnew_z_L3 = Cnew_z_L->GetCompNonConst(3);
    Cnew_z_L3->Set(resto_mu);
    Cnew_z_L3->ElementWiseDivide(*nd);
    SmartPtr<Vector> Cnew_z_L4 = Cnew_z_L->GetCompNonConst(4);
    Cnew_z_L4->Set(resto_mu);
    Cnew_z_L4->ElementWiseDivide(*pd);

    // Set those initial values to be the trial values in Data
    trial = IpData().trial()->MakeNewContainer();
    trial->Set_bound_mult(*new_z_L, *new_z_U, *new_v_L, *new_v_U);
    IpData().set_trial(trial);

    /////////////////////////////////////////////////////////////////////
    //           Initialize equality constraint multipliers            //
    /////////////////////////////////////////////////////////////////////

    DefaultIterateInitializer::least_square_mults(
      Jnlst(), IpNLP(), IpData(), IpCq(),
      resto_eq_mult_calculator_, constr_mult_init_max_);

    // upgrade the trial to the current point
    IpData().AcceptTrialPoint();

    DBG_PRINT_VECTOR(2, "y_c", *IpData().curr()->y_c());
    DBG_PRINT_VECTOR(2, "y_d", *IpData().curr()->y_d());

    DBG_PRINT_VECTOR(2, "z_L", *IpData().curr()->z_L());
    DBG_PRINT_VECTOR(2, "z_U", *IpData().curr()->z_U());
    DBG_PRINT_VECTOR(2, "v_L", *IpData().curr()->v_L());
    DBG_PRINT_VECTOR(2, "v_U", *IpData().curr()->v_U());

    return true;
  }
  bool IterativePardisoSolverInterface::InitializeImpl(const OptionsList& options,
      const std::string& prefix)
  {
    Index enum_int;
    options.GetEnumValue("pardiso_matching_strategy", enum_int, prefix);
    match_strat_ = PardisoMatchingStrategy(enum_int);
    options.GetBoolValue("pardiso_redo_symbolic_fact_only_if_inertia_wrong",
                         pardiso_redo_symbolic_fact_only_if_inertia_wrong_,
                         prefix);
    options.GetBoolValue("pardiso_repeated_perturbation_means_singular",
                         pardiso_repeated_perturbation_means_singular_,
                         prefix);
    Index pardiso_out_of_core_power;
    options.GetIntegerValue("pardiso_out_of_core_power",
                            pardiso_out_of_core_power, prefix);
    options.GetBoolValue("pardiso_skip_inertia_check",
                         skip_inertia_check_, prefix);

    // PD system
    options.GetIntegerValue("pardiso_max_iter", pardiso_max_iter_, prefix);
    options.GetNumericValue("pardiso_iter_relative_tol",
                            pardiso_iter_relative_tol_, prefix);
    options.GetIntegerValue("pardiso_iter_coarse_size",
                            pardiso_iter_coarse_size_, prefix);
    options.GetIntegerValue("pardiso_iter_max_levels",
                            pardiso_iter_max_levels_, prefix);
    options.GetNumericValue("pardiso_iter_dropping_factor",
                            pardiso_iter_dropping_factor_, prefix);
    options.GetNumericValue("pardiso_iter_dropping_schur",
                            pardiso_iter_dropping_schur_, prefix);
    options.GetIntegerValue("pardiso_iter_max_row_fill",
                            pardiso_iter_max_row_fill_, prefix);
    options.GetNumericValue("pardiso_iter_inverse_norm_factor",
                            pardiso_iter_inverse_norm_factor_, prefix);
    // Normal system
    options.GetIntegerValue("pardiso_max_iter", normal_pardiso_max_iter_,
                            prefix+"normal.");
    options.GetNumericValue("pardiso_iter_relative_tol",
                            normal_pardiso_iter_relative_tol_,
                            prefix+"normal.");
    options.GetIntegerValue("pardiso_iter_coarse_size",
                            normal_pardiso_iter_coarse_size_,
                            prefix+"normal.");
    options.GetIntegerValue("pardiso_iter_max_levels",
                            normal_pardiso_iter_max_levels_,
                            prefix+"normal.");
    options.GetNumericValue("pardiso_iter_dropping_factor",
                            normal_pardiso_iter_dropping_factor_,
                            prefix+"normal.");
    options.GetNumericValue("pardiso_iter_dropping_schur",
                            normal_pardiso_iter_dropping_schur_,
                            prefix+"normal.");
    options.GetIntegerValue("pardiso_iter_max_row_fill",
                            normal_pardiso_iter_max_row_fill_,
                            prefix+"normal.");
    options.GetNumericValue("pardiso_iter_inverse_norm_factor",
                            normal_pardiso_iter_inverse_norm_factor_,
                            prefix+"normal.");

    int pardiso_msglvl;
    options.GetIntegerValue("pardiso_msglvl", pardiso_msglvl, prefix);
    options.GetIntegerValue("pardiso_max_droptol_corrections",
                            pardiso_max_droptol_corrections_, prefix);

    // Number value = 0.0;

    // Tell Pardiso to release all memory if it had been used before
    if (initialized_) {
      ipfint PHASE = -1;
      ipfint N = dim_;
      ipfint NRHS = 0;
      ipfint ERROR;
      ipfint idmy;
      double ddmy;
      F77_FUNC(pardiso,PARDISO)(PT_, &MAXFCT_, &MNUM_, &MTYPE_, &PHASE, &N,
                                &ddmy, &idmy, &idmy, &idmy, &NRHS, IPARM_,
                                &MSGLVL_, &ddmy, &ddmy, &ERROR, DPARM_) ;
      DBG_ASSERT(ERROR==0);
    }

    // Reset all private data
    dim_=0;
    nonzeros_=0;
    have_symbolic_factorization_=false;
    initialized_=false;
    delete[] a_;
    a_ = NULL;

#ifdef HAVE_PARDISO_OLDINTERFACE
    THROW_EXCEPTION(OPTION_INVALID, "The inexact version works only with a new version of Pardiso (at least 4.0)");
#endif

    // Call Pardiso's initialization routine
    IPARM_[0] = 0;  // Tell it to fill IPARM with default values(?)
    ipfint ERROR = 0;
    ipfint SOLVER = 1; // initialze only direct solver
    F77_FUNC(pardisoinit,PARDISOINIT)(PT_, &MTYPE_, &SOLVER,
                                      IPARM_, DPARM_, &ERROR);

    // Set some parameters for Pardiso
    IPARM_[0] = 1;  // Don't use the default values

#if defined(HAVE_PARDISO_PARALLEL) || ! defined(HAVE_PARDISO)
    // Obtain the numbers of processors from the value of OMP_NUM_THREADS
    char    *var = getenv("OMP_NUM_THREADS");
    int      num_procs = 1;
    if (var != NULL) {
      sscanf( var, "%d", &num_procs );
      if (num_procs < 1) {
        Jnlst().Printf(J_ERROR, J_LINEAR_ALGEBRA,
                       "Invalid value for OMP_NUM_THREADS (\"%s\").\n", var);
        return false;
      }
      Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                     "Using environment OMP_NUM_THREADS = %d as the number of processors.\n", num_procs);
    }
#ifdef HAVE_PARDISO
    // If we run Pardiso through the linear solver loader,
    // we do not know whether it is the parallel version, so we do not report an error if OMP_NUM_THREADS is not set.
    else {
      Jnlst().Printf(J_ERROR, J_LINEAR_ALGEBRA,
                     "You need to set environment variable OMP_NUM_THREADS to the number of processors used in Pardiso (e.g., 1).\n\n");
      return false;
    }
#endif
    IPARM_[2] = num_procs;  // Set the number of processors
#else

    IPARM_[2] = 1;
#endif

    IPARM_[1] = 5;
    IPARM_[5] = 1;  // Overwrite right-hand side
    // ToDo: decide if we need iterative refinement in Pardiso.  For
    // now, switch it off ?
    IPARM_[7] = 0;

    // Options suggested by Olaf Schenk
    IPARM_[9] = 12;
    IPARM_[10] = 2; // Results in better scaling
    // Matching information:  IPARM_[12] = 1 seems ok, but results in a
    // large number of pivot perturbation
    // Matching information:  IPARM_[12] = 2 robust,  but more  expensive method
    IPARM_[12] = (int)match_strat_;
    Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA,
                   "Pardiso matching strategy (IPARM(13)): %d\n", IPARM_[12]);

    IPARM_[20] = 3; // Results in better accuracy
    IPARM_[23] = 1; // parallel fac
    IPARM_[24] = 1; // parallel solve
    IPARM_[28] = 0; // 32-bit factorization
    IPARM_[29] = 1; // we need this for IPOPT interface

    IPARM_[31] = 1 ;  // iterative solver
    MSGLVL_ = pardiso_msglvl;

    pardiso_iter_dropping_factor_used_ = pardiso_iter_dropping_factor_;
    pardiso_iter_dropping_schur_used_ = pardiso_iter_dropping_schur_;
    normal_pardiso_iter_dropping_factor_used_ = normal_pardiso_iter_dropping_factor_;
    normal_pardiso_iter_dropping_schur_used_ = normal_pardiso_iter_dropping_schur_;

    // TODO Make option
    decr_factor_ = 1./3.;

    // Option for the out of core variant
    // IPARM_[49] = pardiso_out_of_core_power;

    SetIpoptCallbackFunction(&IpoptTerminationTest);

    bool retval = normal_tester_->Initialize(Jnlst(), IpNLP(), IpData(),
                  IpCq(), options, prefix);
    if (retval) {
      retval = pd_tester_->Initialize(Jnlst(), IpNLP(), IpData(),
                                      IpCq(), options, prefix);
    }

    return retval;
  }
Ejemplo n.º 26
0
Number ProbingMuOracle::CalculateAffineMu(
   Number                alpha_primal,
   Number                alpha_dual,
   const IteratesVector& step
   )
{
   // Get the current values of the slack variables and bound multipliers
   SmartPtr<const Vector> slack_x_L = IpCq().curr_slack_x_L();
   SmartPtr<const Vector> slack_x_U = IpCq().curr_slack_x_U();
   SmartPtr<const Vector> slack_s_L = IpCq().curr_slack_s_L();
   SmartPtr<const Vector> slack_s_U = IpCq().curr_slack_s_U();

   SmartPtr<const Vector> z_L = IpData().curr()->z_L();
   SmartPtr<const Vector> z_U = IpData().curr()->z_U();
   SmartPtr<const Vector> v_L = IpData().curr()->v_L();
   SmartPtr<const Vector> v_U = IpData().curr()->v_U();

   SmartPtr<Vector> tmp_slack;
   SmartPtr<Vector> tmp_mult;
   SmartPtr<const Matrix> P;
   Index ncomp = 0;
   Number sum = 0.;

   // For each combination of slack and multiplier, compute the new
   // values and their dot products.

   // slack_x_L
   if( slack_x_L->Dim() > 0 )
   {
      ncomp += slack_x_L->Dim();

      P = IpNLP().Px_L();
      tmp_slack = slack_x_L->MakeNew();
      tmp_slack->Copy(*slack_x_L);
      P->TransMultVector(alpha_primal, *step.x(), 1.0, *tmp_slack);

      tmp_mult = z_L->MakeNew();
      tmp_mult->Copy(*z_L);
      tmp_mult->Axpy(alpha_dual, *step.z_L());

      sum += tmp_slack->Dot(*tmp_mult);
   }

   // slack_x_U
   if( slack_x_U->Dim() > 0 )
   {
      ncomp += slack_x_U->Dim();

      P = IpNLP().Px_U();
      tmp_slack = slack_x_U->MakeNew();
      tmp_slack->Copy(*slack_x_U);
      P->TransMultVector(-alpha_primal, *step.x(), 1.0, *tmp_slack);

      tmp_mult = z_U->MakeNew();
      tmp_mult->Copy(*z_U);
      tmp_mult->Axpy(alpha_dual, *step.z_U());

      sum += tmp_slack->Dot(*tmp_mult);
   }

   // slack_s_L
   if( slack_s_L->Dim() > 0 )
   {
      ncomp += slack_s_L->Dim();

      P = IpNLP().Pd_L();
      tmp_slack = slack_s_L->MakeNew();
      tmp_slack->Copy(*slack_s_L);
      P->TransMultVector(alpha_primal, *step.s(), 1.0, *tmp_slack);

      tmp_mult = v_L->MakeNew();
      tmp_mult->Copy(*v_L);
      tmp_mult->Axpy(alpha_dual, *step.v_L());

      sum += tmp_slack->Dot(*tmp_mult);
   }

   // slack_s_U
   if( slack_s_U->Dim() > 0 )
   {
      ncomp += slack_s_U->Dim();

      P = IpNLP().Pd_U();
      tmp_slack = slack_s_U->MakeNew();
      tmp_slack->Copy(*slack_s_U);
      P->TransMultVector(-alpha_primal, *step.s(), 1.0, *tmp_slack);

      tmp_mult = v_U->MakeNew();
      tmp_mult->Copy(*v_U);
      tmp_mult->Axpy(alpha_dual, *step.v_U());

      sum += tmp_slack->Dot(*tmp_mult);
   }

   DBG_ASSERT(ncomp > 0);

   return sum / ((Number) ncomp);
}
Ejemplo n.º 27
0
  bool
  MinC_1NrmRestorationPhase::PerformRestoration()
  {
    DBG_START_METH("MinC_1NrmRestorationPhase::PerformRestoration",
                   dbg_verbosity);

    // Increase counter for restoration phase calls
    count_restorations_++;
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "Starting Restoration Phase for the %d. time\n",
                   count_restorations_);

    DBG_ASSERT(IpCq().curr_constraint_violation()>0.);

    // ToDo set those up during initialize?
    // Create the restoration phase NLP etc objects
    SmartPtr<IpoptData> resto_ip_data = new IpoptData();
    SmartPtr<IpoptNLP> resto_ip_nlp =
      new RestoIpoptNLP(IpNLP(), IpData(), IpCq());
    SmartPtr<IpoptCalculatedQuantities> resto_ip_cq =
      new IpoptCalculatedQuantities(resto_ip_nlp, resto_ip_data);

    // Determine if this is a square problem
    bool square_problem = IpCq().IsSquareProblem();

    // Decide if we want to use the original option or want to make
    // some changes
    SmartPtr<OptionsList> actual_resto_options = resto_options_;
    if(square_problem) {
      actual_resto_options = new OptionsList(*resto_options_);
      // If this is a square problem, the want the restoration phase
      // never to be left until the problem is converged
      actual_resto_options->SetNumericValue("resto.required_infeasibility_reduction", 0.);
    }
    else if (expect_infeasible_problem_ && count_restorations_==1) {
      if (IpCq().curr_constraint_violation()>1e-3) {
        actual_resto_options = new OptionsList(*resto_options_);
        // Ask for significant reduction of infeasibility, in the hope
        // that we do not return from the restoration phase is the
        // problem is infeasible
        actual_resto_options->SetNumericValue("resto.required_infeasibility_reduction", 1e-3);
      }
    }

    // Initialize the restoration phase algorithm
    resto_alg_->Initialize(Jnlst(), *resto_ip_nlp, *resto_ip_data,
                           *resto_ip_cq, *actual_resto_options, "resto.");

    // Set iteration counter and info field for the restoration phase
    resto_ip_data->Set_iter_count(IpData().iter_count()+1);
    resto_ip_data->Set_info_regu_x(IpData().info_regu_x());
    resto_ip_data->Set_info_alpha_primal(IpData().info_alpha_primal());
    resto_ip_data->Set_info_alpha_primal_char(IpData().info_alpha_primal_char());
    resto_ip_data->Set_info_alpha_dual(IpData().info_alpha_dual());
    resto_ip_data->Set_info_ls_count(IpData().info_ls_count());

    // Call the optimization algorithm to solve the restoration phase
    // problem
    SolverReturn resto_status    = resto_alg_->Optimize();

    int retval=-1;

    if (resto_status == SUCCESS) {
      if (Jnlst().ProduceOutput(J_DETAILED, J_LINE_SEARCH)) {
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "\nRESTORATION PHASE RESULTS\n");
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "\n\nOptimal solution found! \n");
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "Optimal Objective Value = %.16E\n", resto_ip_cq->curr_f());
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "Number of Iterations = %d\n", resto_ip_data->iter_count());
      }
      if (Jnlst().ProduceOutput(J_VECTOR, J_LINE_SEARCH)) {
        resto_ip_data->curr()->Print(Jnlst(), J_VECTOR, J_LINE_SEARCH, "curr");
      }

      retval = 0;
    }
    else if (resto_status == STOP_AT_TINY_STEP ||
             resto_status == STOP_AT_ACCEPTABLE_POINT) {
      Number orig_primal_inf =
        IpCq().curr_primal_infeasibility(NORM_MAX);
      // ToDo make the factor in following line an option
      if (orig_primal_inf <= 1e2*IpData().tol()) {
        Jnlst().Printf(J_WARNING, J_LINE_SEARCH,
                       "Restoration phase converged to a point with small primal infeasibility.\n");
        THROW_EXCEPTION(RESTORATION_CONVERGED_TO_FEASIBLE_POINT,
                        "Restoration phase converged to a point with small primal infeasibility");
      }
      else {
        THROW_EXCEPTION(LOCALLY_INFEASIBLE,
                        "Restoration phase converged to a point of local infeasibility");
      }
    }
    else if (resto_status == MAXITER_EXCEEDED) {
      THROW_EXCEPTION(RESTORATION_MAXITER_EXCEEDED,
                      "Maximal number of iterations exceeded in restoration phase.");
    }
    else if (resto_status == LOCAL_INFEASIBILITY) {
      // converged to locally infeasible point - pass this on to the outer algorithm...
      THROW_EXCEPTION(LOCALLY_INFEASIBLE, "Restoration phase converged to a point of local infeasibility");
    }
    else if (resto_status == RESTORATION_FAILURE) {
      Jnlst().Printf(J_WARNING, J_LINE_SEARCH,
                     "Restoration phase in the restoration phase failed.\n");
      THROW_EXCEPTION(RESTORATION_FAILED, "Restoration phase in the restoration phase failed.");
    }
    else if (resto_status == USER_REQUESTED_STOP) {
      // Use requested stop during restoration phase - rethrow exception
      THROW_EXCEPTION(RESTORATION_USER_STOP, "User requested stop during restoration phase");
    }
    else {
      Jnlst().Printf(J_ERROR, J_MAIN, "Sorry, things failed ?!?!\n");
      retval = 1;
    }

    if (retval == 0) {
      // Copy the results into the trial fields;. They will be
      // accepted later in the full algorithm
      SmartPtr<const CompoundVector> cx =
        dynamic_cast<const CompoundVector*>(GetRawPtr(resto_ip_data->curr()->x()));
      DBG_ASSERT(IsValid(cx));
      SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer();
      trial->Set_primal(*cx->GetComp(0), *resto_ip_data->curr()->s());
      IpData().set_trial(trial);

      // If this is a square problem, we are done because a
      // sufficiently feasible point has been found
      if (square_problem) {
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "Recursive restoration phase algorithm termined successfully for square problem.\n");
        IpData().AcceptTrialPoint();
        THROW_EXCEPTION(FEASIBILITY_PROBLEM_SOLVED, "Restoration phase converged to sufficiently feasible point of original square problem.");
      }

      // Update the bound multiplers, pretending that the entire
      // progress in x and s in the restoration phase has been one
      // [rimal-dual Newton step (and therefore the result of solving
      // an augmented system)
      SmartPtr<IteratesVector> delta = IpData().curr()->MakeNewIteratesVector(true);
      delta->Set(0.0);
      ComputeBoundMultiplierStep(*delta->z_L_NonConst(), *IpData().curr()->z_L(),
                                 *IpCq().curr_slack_x_L(),
                                 *IpCq().trial_slack_x_L());
      ComputeBoundMultiplierStep(*delta->z_U_NonConst(), *IpData().curr()->z_U(),
                                 *IpCq().curr_slack_x_U(),
                                 *IpCq().trial_slack_x_U());
      ComputeBoundMultiplierStep(*delta->v_L_NonConst(), *IpData().curr()->v_L(),
                                 *IpCq().curr_slack_s_L(),
                                 *IpCq().trial_slack_s_L());
      ComputeBoundMultiplierStep(*delta->v_U_NonConst(), *IpData().curr()->v_U(),
                                 *IpCq().curr_slack_s_U(),
                                 *IpCq().trial_slack_s_U());

      DBG_PRINT_VECTOR(1, "delta_z_L", *delta->z_L());
      DBG_PRINT_VECTOR(1, "delta_z_U", *delta->z_U());
      DBG_PRINT_VECTOR(1, "delta_v_L", *delta->v_L());
      DBG_PRINT_VECTOR(1, "delta_v_U", *delta->v_U());

      Number alpha_dual = IpCq().dual_frac_to_the_bound(IpData().curr_tau(),
                          *delta->z_L_NonConst(),
                          *delta->z_U_NonConst(),
                          *delta->v_L_NonConst(),
                          *delta->v_U_NonConst());
      Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                     "Step size for bound multipliers: %8.2e\n", alpha_dual);

      IpData().SetTrialBoundMultipliersFromStep(alpha_dual, *delta->z_L(), *delta->z_U(), *delta->v_L(), *delta->v_U() );

      // ToDo: Check what to do here:
      Number bound_mult_max = Max(IpData().trial()->z_L()->Amax(),
                                  IpData().trial()->z_U()->Amax(),
                                  IpData().trial()->v_L()->Amax(),
                                  IpData().trial()->v_U()->Amax());
      if (bound_mult_max > bound_mult_reset_threshold_) {
        trial = IpData().trial()->MakeNewContainer();
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "Bound multipliers after restoration phase too large (max=%8.2e). Set all to 1.\n",
                       bound_mult_max);
        trial->create_new_z_L();
        trial->create_new_z_U();
        trial->create_new_v_L();
        trial->create_new_v_U();
        trial->z_L_NonConst()->Set(1.0);
        trial->z_U_NonConst()->Set(1.0);
        trial->v_L_NonConst()->Set(1.0);
        trial->v_U_NonConst()->Set(1.0);
        IpData().set_trial(trial);

      }

      DefaultIterateInitializer::least_square_mults(
        Jnlst(), IpNLP(), IpData(), IpCq(),
        eq_mult_calculator_, constr_mult_reset_threshold_);

      DBG_PRINT_VECTOR(2, "y_c", *IpData().curr()->y_c());
      DBG_PRINT_VECTOR(2, "y_d", *IpData().curr()->y_d());

      IpData().Set_iter_count(resto_ip_data->iter_count()-1);
      // Skip the next line, because it would just replicate the first
      // on during the restoration phase.
      IpData().Set_info_skip_output(true);
    }

    return (retval == 0);
  }
  bool WarmStartIterateInitializer::SetInitialIterates()
  {
    DBG_START_METH("WarmStartIterateInitializer::SetInitialIterates",
                   dbg_verbosity);

    // Get the starting values provided by the NLP and store them
    // in the ip_data current fields.

    SmartPtr<IteratesVector> init_vec;
    bool have_iterate = false;

    if (warm_start_entire_iterate_) {
      if (!IpData().InitializeDataStructures(IpNLP(), false, false, false,
                                             false, false)) {
        return false;
      }

      init_vec = IpData().curr()->MakeNewIteratesVector(true);

      have_iterate = IpNLP().GetWarmStartIterate(*init_vec);

      if (!have_iterate) {
        Jnlst().Printf(J_DETAILED, J_LINE_SEARCH,
                       "Tried to obtain entire warm start iterate from NLP, but it returned false.\n");
        IpData().Append_info_string("NW");
      }

      // Make sure given bounds are respected
      if (have_iterate && warm_start_mult_init_max_>0.) {
        SmartPtr<Vector> y_c = init_vec->create_new_y_c_copy();
        SmartPtr<Vector> tmp = y_c->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        y_c->ElementWiseMin(*tmp);
        tmp->Set(-warm_start_mult_init_max_);
        y_c->ElementWiseMax(*tmp);

        SmartPtr<Vector> y_d = init_vec->create_new_y_d_copy();
        tmp = y_d->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        y_d->ElementWiseMin(*tmp);
        tmp->Set(-warm_start_mult_init_max_);
        y_d->ElementWiseMax(*tmp);

        SmartPtr<Vector> z_L = init_vec->create_new_z_L_copy();
        tmp = z_L->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        z_L->ElementWiseMin(*tmp);

        SmartPtr<Vector> z_U = init_vec->create_new_z_U_copy();
        tmp = z_U->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        z_U->ElementWiseMin(*tmp);

        SmartPtr<Vector> v_L = init_vec->create_new_v_L_copy();
        tmp = v_L->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        v_L->ElementWiseMin(*tmp);

        SmartPtr<Vector> v_U = init_vec->create_new_v_U_copy();
        tmp = v_U->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        v_U->ElementWiseMin(*tmp);
      }
    }

    if (!have_iterate) {

      /////////////////////////////////////////////////////////////////////
      //                   Initialize primal variables                   //
      /////////////////////////////////////////////////////////////////////

      // Get the intial values for x, y_c, y_d, z_L, z_U,
      if (!IpData().InitializeDataStructures(IpNLP(), true, true, true, true, true)) {
        return false;
      }

      IpData().curr()->x()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "user-provided x");
      IpData().curr()->y_c()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                    "user-provided y_c");
      IpData().curr()->y_d()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                    "user-provided y_d");
      IpData().curr()->z_L()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                    "user-provided z_L");
      IpData().curr()->z_U()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                    "user-provided z_U");
      if (Jnlst().ProduceOutput(J_MOREVECTOR, J_INITIALIZATION)) {
        IpCq().curr_d()->Print(Jnlst(), J_MOREVECTOR, J_INITIALIZATION,
                               "d at user-provided x");
      }

      SmartPtr<Vector> tmp;

      init_vec = IpData().curr()->MakeNewContainer();

      // If requested, make sure that the multipliers are not too large
      if (warm_start_mult_init_max_>0.) {
        SmartPtr<Vector> y_c = init_vec->create_new_y_c_copy();
        tmp = y_c->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        y_c->ElementWiseMin(*tmp);
        tmp->Set(-warm_start_mult_init_max_);
        y_c->ElementWiseMax(*tmp);

        SmartPtr<Vector> y_d = init_vec->create_new_y_d_copy();
        tmp = y_d->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        y_d->ElementWiseMin(*tmp);
        tmp->Set(-warm_start_mult_init_max_);
        y_d->ElementWiseMax(*tmp);

        SmartPtr<Vector> z_L = init_vec->create_new_z_L_copy();
        tmp = z_L->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        z_L->ElementWiseMin(*tmp);

        SmartPtr<Vector> z_U = init_vec->create_new_z_U_copy();
        tmp = z_U->MakeNew();
        tmp->Set(warm_start_mult_init_max_);
        z_U->ElementWiseMin(*tmp);
      }

      // Get the initial values for v_L and v_U out of y_d
      SmartPtr<Vector> v_L = init_vec->create_new_v_L();
      IpNLP().Pd_L()->TransMultVector(-1., *init_vec->y_d(), 0., *v_L);
      tmp = v_L->MakeNew();
      tmp->Set(warm_start_mult_bound_push_);
      v_L->ElementWiseMax(*tmp);

      SmartPtr<Vector> v_U = init_vec->create_new_v_U();
      IpNLP().Pd_U()->TransMultVector(1., *init_vec->y_d(), 0., *v_U);
      tmp = v_U->MakeNew();
      tmp->Set(warm_start_mult_bound_push_);
      v_U->ElementWiseMax(*tmp);

      // Initialize slack variables
      init_vec->Set_s(*IpCq().curr_d());
    }

    // Make the corrected values current (and initialize s)
    IpData().set_trial(init_vec);
    IpData().AcceptTrialPoint();

    // Now apply the target mu heuristic if required
    if (warm_start_target_mu_>0.) {
      SmartPtr<const Vector> new_x;
      SmartPtr<const Vector> new_z_L;

      SmartPtr<const IteratesVector> curr = IpData().curr();
      process_target_mu(1., *curr->x(), *IpCq().curr_slack_x_L(),
                        *curr->z_L(), *IpNLP().Px_L(),
                        new_x, new_z_L);
      SmartPtr<const Vector> new_s;
      SmartPtr<const Vector> new_v_L;
      process_target_mu(1., *curr->s(), *IpCq().curr_slack_s_L(),
                        *curr->v_L(), *IpNLP().Pd_L(),
                        new_s, new_v_L);

      // Set the trial pointers to new_x and new_s. The process_target_mu
      // methods below create new vectors in new_x and new_s and do not alter
      // the existing ones.
      init_vec->Set_x(*new_x);
      init_vec->Set_s(*new_s);
      IpData().set_trial(init_vec);

      SmartPtr<const Vector> new_z_U;
      process_target_mu(-1., *IpData().trial()->x(), *IpCq().trial_slack_x_U(),
                        *IpData().curr()->z_U(), *IpNLP().Px_U(),
                        new_x, new_z_U);
      SmartPtr<const Vector> new_v_U;
      process_target_mu(-1., *IpData().trial()->s(), *IpCq().trial_slack_s_U(),
                        *IpData().curr()->v_U(), *IpNLP().Pd_U(),
                        new_s, new_v_U);

      // Now submit the full modified point
      init_vec->Set_x(*new_x);
      init_vec->Set_s(*new_s);
      // y_c and y_d currently contain a copy of curr()->y_c...
      // we set them back to the actual pointer to reuse the tags
      init_vec->Set_y_c(*IpData().curr()->y_c());
      init_vec->Set_y_d(*IpData().curr()->y_d());
      init_vec->Set_z_L(*new_z_L);
      init_vec->Set_z_U(*new_z_U);
      init_vec->Set_v_L(*new_v_L);
      init_vec->Set_v_U(*new_v_U);
      IpData().set_trial(init_vec);
      IpData().AcceptTrialPoint();

      // We need to call this to make sure that we don't get an error
      // message because at some point a slack became too small
      IpCq().ResetAdjustedTrialSlacks();
    }

    SmartPtr<const Vector> new_x;
    SmartPtr<const Vector> new_s;
    // Push the primal x variables
    DefaultIterateInitializer::push_variables(Jnlst(),
        warm_start_bound_push_,
        warm_start_bound_frac_,
        "x",
        *IpData().curr()->x(),
        new_x,
        *IpNLP().x_L(),
        *IpNLP().x_U(),
        *IpNLP().Px_L(),
        *IpNLP().Px_U());

    // Push the primal s variables
    DefaultIterateInitializer::push_variables(Jnlst(),
        warm_start_slack_bound_push_,
        warm_start_slack_bound_frac_,
        "s",
        *IpData().curr()->s(),
        new_s,
        *IpNLP().d_L(),
        *IpNLP().d_U(),
        *IpNLP().Pd_L(),
        *IpNLP().Pd_U());

    // Push the multipliers
    SmartPtr<Vector> new_z_L = IpData().curr()->z_L()->MakeNewCopy();
    SmartPtr<Vector> tmp = IpData().curr()->z_L()->MakeNew();
    tmp->Set(warm_start_mult_bound_push_);
    new_z_L->ElementWiseMax(*tmp);

    SmartPtr<Vector> new_z_U = IpData().curr()->z_U()->MakeNewCopy();
    tmp = IpData().curr()->z_U()->MakeNew();
    tmp->Set(warm_start_mult_bound_push_);
    new_z_U->ElementWiseMax(*tmp);

    SmartPtr<Vector> new_v_L = IpData().curr()->v_L()->MakeNewCopy();
    tmp = IpData().curr()->v_L()->MakeNew();
    tmp->Set(warm_start_mult_bound_push_);
    new_v_L->ElementWiseMax(*tmp);

    SmartPtr<Vector> new_v_U = IpData().curr()->v_U()->MakeNewCopy();
    tmp = IpData().curr()->v_U()->MakeNew();
    tmp->Set(warm_start_mult_bound_push_);
    new_v_U->ElementWiseMax(*tmp);

    // Make sure the new variables are current
    init_vec = IpData().curr()->MakeNewContainer();
    init_vec->Set_x(*new_x);
    init_vec->Set_s(*new_s);
    init_vec->Set_z_L(*new_z_L);
    init_vec->Set_z_U(*new_z_U);
    init_vec->Set_v_L(*new_v_L);
    init_vec->Set_v_U(*new_v_U);
    IpData().set_trial(init_vec);
    IpData().AcceptTrialPoint();

    IpData().curr()->x()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                "initial x");
    IpData().curr()->s()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                "initial s");
    IpData().curr()->y_c()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial y_c");
    IpData().curr()->y_d()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial y_d");
    IpData().curr()->z_L()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial z_L");
    IpData().curr()->z_U()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial z_U");
    IpData().curr()->v_L()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial v_L");
    IpData().curr()->v_U()->Print(Jnlst(), J_VECTOR, J_INITIALIZATION,
                                  "initial v_U");
    if (Jnlst().ProduceOutput(J_MOREVECTOR, J_INITIALIZATION)) {
      IpCq().curr_slack_x_L()->Print(Jnlst(), J_MOREVECTOR, J_INITIALIZATION,
                                     "initial slack_x_L");
      IpCq().curr_slack_x_U()->Print(Jnlst(), J_MOREVECTOR, J_INITIALIZATION,
                                     "initial slack_x_U");
      IpCq().curr_slack_s_L()->Print(Jnlst(), J_MOREVECTOR, J_INITIALIZATION,
                                     "initial slack_s_L");
      IpCq().curr_slack_s_U()->Print(Jnlst(), J_MOREVECTOR, J_INITIALIZATION,
                                     "initial slack_s_U");
    }

    return true;
  }
Ejemplo n.º 29
0
  bool
  RestoRestorationPhase::PerformRestoration()
  {
    DBG_START_METH("RestoRestorationPhase::PerformRestoration",
                   dbg_verbosity);
    Jnlst().Printf(J_DETAILED, J_MAIN,
                   "Performing second level restoration phase for current constriant violation %8.2e\n", IpCq().curr_constraint_violation());

    DBG_ASSERT(IpCq().curr_constraint_violation()>0.);

    // Get a grip on the restoration phase NLP and obtain the pointers
    // to the original NLP data
    SmartPtr<RestoIpoptNLP> resto_ip_nlp =
      static_cast<RestoIpoptNLP*> (&IpNLP());
    DBG_ASSERT(dynamic_cast<RestoIpoptNLP*> (&IpNLP()));
    SmartPtr<IpoptNLP> orig_ip_nlp =
      static_cast<IpoptNLP*> (&resto_ip_nlp->OrigIpNLP());
    DBG_ASSERT(dynamic_cast<IpoptNLP*> (&resto_ip_nlp->OrigIpNLP()));

    // Get the current point and create a new vector for the result
    SmartPtr<const CompoundVector> Ccurr_x =
      static_cast<const CompoundVector*> (GetRawPtr(IpData().curr()->x()));
    SmartPtr<Vector> new_x = IpData().curr()->x()->MakeNew();
    SmartPtr<CompoundVector> Cnew_x =
      static_cast<CompoundVector*> (GetRawPtr(new_x));

    // The x values remain unchanged
    SmartPtr<Vector> x = Cnew_x->GetCompNonConst(0);
    x->Copy(*Ccurr_x->GetComp(0));

    // ToDo in free mu mode - what to do here?
    Number mu = IpData().curr_mu();

    // Compute the initial values for the n and p variables for the
    // equality constraints
    Number rho = resto_ip_nlp->Rho();
    SmartPtr<Vector> nc = Cnew_x->GetCompNonConst(1);
    SmartPtr<Vector> pc = Cnew_x->GetCompNonConst(2);
    SmartPtr<const Vector> cvec = orig_ip_nlp->c(*Ccurr_x->GetComp(0));
    SmartPtr<Vector> a = nc->MakeNew();
    SmartPtr<Vector> b = nc->MakeNew();
    a->Set(mu/(2.*rho));
    a->Axpy(-0.5, *cvec);
    b->Copy(*cvec);
    b->Scal(mu/(2.*rho));
    solve_quadratic(*a, *b, *nc);
    pc->Copy(*cvec);
    pc->Axpy(1., *nc);
    DBG_PRINT_VECTOR(2, "nc", *nc);
    DBG_PRINT_VECTOR(2, "pc", *pc);

    // initial values for the n and p variables for the inequality
    // constraints
    SmartPtr<Vector> nd = Cnew_x->GetCompNonConst(3);
    SmartPtr<Vector> pd = Cnew_x->GetCompNonConst(4);
    SmartPtr<Vector> dvec = pd->MakeNew();
    dvec->Copy(*orig_ip_nlp->d(*Ccurr_x->GetComp(0)));
    dvec->Axpy(-1., *IpData().curr()->s());
    a = nd->MakeNew();
    b = nd->MakeNew();
    a->Set(mu/(2.*rho));
    a->Axpy(-0.5, *dvec);
    b->Copy(*dvec);
    b->Scal(mu/(2.*rho));
    solve_quadratic(*a, *b, *nd);
    pd->Copy(*dvec);
    pd->Axpy(1., *nd);
    DBG_PRINT_VECTOR(2, "nd", *nd);
    DBG_PRINT_VECTOR(2, "pd", *pd);

    // Now set the trial point to the solution of the restoration phase
    // s and all multipliers remain unchanged
    SmartPtr<IteratesVector> new_trial = IpData().curr()->MakeNewContainer();
    new_trial->Set_x(*new_x);
    IpData().set_trial(new_trial);

    IpData().Append_info_string("R");

    return true;
  }
Ejemplo n.º 30
0
  void IpoptAlgorithm::PrintProblemStatistics()
  {
    if (!Jnlst().ProduceOutput(J_SUMMARY, J_STATISTICS)) {
      // nothing to print
      return;
    }

    SmartPtr<const Vector> x = IpData().curr()->x();
    SmartPtr<const Vector> x_L = IpNLP().x_L();
    SmartPtr<const Vector> x_U = IpNLP().x_U();
    SmartPtr<const Matrix> Px_L = IpNLP().Px_L();
    SmartPtr<const Matrix> Px_U = IpNLP().Px_U();

    Index nx_tot, nx_only_lower, nx_both, nx_only_upper;
    calc_number_of_bounds(*IpData().curr()->x(), *IpNLP().x_L(), *IpNLP().x_U(),
                          *IpNLP().Px_L(), *IpNLP().Px_U(),
                          nx_tot, nx_only_lower, nx_both, nx_only_upper);

    Index ns_tot, ns_only_lower, ns_both, ns_only_upper;
    calc_number_of_bounds(*IpData().curr()->s(), *IpNLP().d_L(), *IpNLP().d_U(),
                          *IpNLP().Pd_L(), *IpNLP().Pd_U(),
                          ns_tot, ns_only_lower, ns_both, ns_only_upper);

    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "Total number of variables............................: %8d\n",nx_tot);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "                     variables with only lower bounds: %8d\n",
                   nx_only_lower);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "                variables with lower and upper bounds: %8d\n",nx_both);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "                     variables with only upper bounds: %8d\n",
                   nx_only_upper);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "Total number of equality constraints.................: %8d\n",
                   IpData().curr()->y_c()->Dim());
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "Total number of inequality constraints...............: %8d\n",ns_tot);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "        inequality constraints with only lower bounds: %8d\n",
                   ns_only_lower);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "   inequality constraints with lower and upper bounds: %8d\n",ns_both);
    Jnlst().Printf(J_SUMMARY, J_STATISTICS,
                   "        inequality constraints with only upper bounds: %8d\n\n",
                   ns_only_upper);
  }