diff options
Diffstat (limited to 'sci_gateway/cpp')
22 files changed, 3306 insertions, 0 deletions
diff --git a/sci_gateway/cpp/QuadTMINLP.hpp b/sci_gateway/cpp/QuadTMINLP.hpp new file mode 100644 index 0000000..84704be --- /dev/null +++ b/sci_gateway/cpp/QuadTMINLP.hpp @@ -0,0 +1,134 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#ifndef QuadTMINLP_HPP +#define QuadTMINLP_HPP + +#include "BonTMINLP.hpp" +#include "IpTNLP.hpp" + +using namespace Ipopt; +using namespace Bonmin; + +class QuadTMINLP : public TMINLP +{ + private: + Index numVars_; // Number of variables. + + Index numCons_; // Number of constraints. + + Index intconSize_; // Number of integer constraints + + const Number *qMatrix_ = NULL; //qMatrix_ is a pointer to matrix of size numVars X numVars_ + // with coefficents of quadratic terms in objective function. + + const Number *lMatrix_ = NULL;//lMatrix_ is a pointer to matrix of size 1*numVars_ + // with coefficents of linear terms in objective function. + + const Number *intcon_ = NULL; // The matrix containing the integer constraints + + const Number *conMatrix_ = NULL;//conMatrix_ is a pointer to matrix of size numCons X numVars + // with coefficients of terms in a each objective in each row. + + const Number *conUB_= NULL; //conUB_ is a pointer to a matrix of size of 1*numCons_ + // with upper bounds of all constraints. + + const Number *conLB_ = NULL; //conLB_ is a pointer to a matrix of size of 1*numConsn_ + // with lower bounds of all constraints. + + const Number *varUB_= NULL; //varUB_ is a pointer to a matrix of size of 1*numVar_ + // with upper bounds of all variables. + + const Number *varLB_= NULL; //varLB_ is a pointer to a matrix of size of 1*numVar_ + // with lower bounds of all variables. + + const Number *varGuess_= NULL; //varGuess_ is a pointer to a matrix of size of 1*numVar_ + // with initial guess of all variables. + + Number *finalX_= NULL; //finalX_ is a pointer to a matrix of size of 1*numVar_ + // with final value for the primal variables. + + Number *finalZl_= NULL; //finalZl_ is a pointer to a matrix of size of 1*numVar_ + // with final values for the lower bound multipliers + + Number *finalZu_= NULL; //finalZu_ is a pointer to a matrix of size of 1*numVar_ + // with final values for the upper bound multipliers + + Number *finalLambda_= NULL; //finalLambda_ is a pointer to a matrix of size of 1*numConstr_ + // with final values for the upper bound multipliers + + Number finalObjVal_; //finalObjVal_ is a scalar with the final value of the objective. + + int status_; //Solver return status + +public: + // Constructor + QuadTMINLP(Index nV, Index nC, Index intconSize,Number *qM, Number *lM, Number *intcon,Number *cM, Number *cLB, Number *cUB, Number *vLB, Number *vUB,Number *vG): + numVars_(nV),numCons_(nC),intconSize_(intconSize),qMatrix_(qM),lMatrix_(lM),intcon_(intcon),conMatrix_(cM),conLB_(cLB),conUB_(cUB),varLB_(vLB),varUB_(vUB),varGuess_(vG), finalObjVal_(0){ } + + // virtual destructor. + virtual ~QuadTMINLP(){} + + /* Copy constructor.*/ + QuadTMINLP(const QuadTMINLP &other){} + + // Go to http://coin-or.org/Bonmin for the details of the below methods + + virtual bool get_variables_types(Index n, VariableType* var_types); + + virtual bool get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types); + + virtual bool get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types); + + + virtual bool get_nlp_info(Index& n, Index&m, Index& nnz_jac_g, + Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style); + + virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, + Index m, Number* g_l, Number* g_u); + + virtual bool get_starting_point(Index n, bool init_x, Number* x, + bool init_z, Number* z_L, Number* z_U, + Index m, bool init_lambda, + Number* lambda); + + virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); + + virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); + + virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); + + virtual bool eval_jac_g(Index n, const Number* x, bool new_x, + Index m, Index nele_jac, Index* iRow, Index *jCol, + Number* values); + + virtual bool eval_h(Index n, const Number* x, bool new_x, + Number obj_factor, Index m, const Number* lambda, + bool new_lambda, Index nele_hess, Index* iRow, + Index* jCol, Number* values); + + virtual void QuadTMINLP::finalize_solution(TMINLP::SolverReturn status, + Index n, const Number* x,Number obj_value); + + virtual const SosInfo * sosConstraints() const{return NULL;} + virtual const BranchingInfo* branchingInfo() const{return NULL;} + + // Bonmin methods end here + + virtual const double * getX(); //Returns a pointer to a matrix of size of 1*numVar + // with final value for the primal variables. + + virtual double getObjVal(); //Returns the output of the final value of the objective. + + virtual int returnStatus(); //Returns the status count +}; + +#endif diff --git a/sci_gateway/cpp/bonmin.opt b/sci_gateway/cpp/bonmin.opt new file mode 100644 index 0000000..72fc254 --- /dev/null +++ b/sci_gateway/cpp/bonmin.opt @@ -0,0 +1,156 @@ + +# registering category: Algorithm choice + +bonmin.algorithm B-BB #Choice of the algorithm. + +# registering category: Branch-and-bound options + +bonmin.allowable_fraction_gap 0 #Specify the value of relative gap under which the algorithm stops. +bonmin.allowable_gap 0 #Specify the value of absolute gap under which the algorithm stops. +bonmin.cutoff 1e+100 #Specify cutoff value. +bonmin.cutoff_decr 1e-05 #Specify cutoff decrement. +bonmin.enable_dynamic_nlp no #Enable dynamic linear and quadratic rows addition in nlp +bonmin.integer_tolerance 1e-06 #Set integer tolerance. +bonmin.iteration_limit 2147483647 #Set the cumulative maximum number of iteration in the algorithm used to process nodes continuous relaxations in the branch-and-bound. +bonmin.nlp_failure_behavior stop #Set the behavior when an NLP or a series of NLP are unsolved by Ipopt (we call unsolved an NLP for which Ipopt is not able to guarantee optimality within the specified tolerances). +bonmin.node_comparison best-bound #Choose the node selection strategy. +bonmin.node_limit 2147483647 #Set the maximum number of nodes explored in the branch-and-bound search. +bonmin.num_cut_passes 1 #Set the maximum number of cut passes at regular nodes of the branch-and-cut. +bonmin.num_cut_passes_at_root 20 #Set the maximum number of cut passes at regular nodes of the branch-and-cut. +bonmin.number_before_trust 8 #Set the number of branches on a variable before its pseudo costs are to be believed in dynamic strong branching. +bonmin.number_strong_branch 20 #Choose the maximum number of variables considered for strong branching. +bonmin.random_generator_seed 0 #Set seed for random number generator (a value of -1 sets seeds to time since Epoch). +bonmin.read_solution_file no #Read a file with the optimal solution to test if algorithms cuts it. +bonmin.solution_limit 2147483647 #Abort after that much integer feasible solution have been found by algorithm +bonmin.sos_constraints enable #Whether or not to activate SOS constraints. +bonmin.time_limit 1e+10 #Set the global maximum computation time (in secs) for the algorithm. +bonmin.tree_search_strategy probed-dive #Pick a strategy for traversing the tree +bonmin.variable_selection strong-branching #Chooses variable selection strategy + +# registering category: ECP cuts generation + +bonmin.ecp_abs_tol 1e-06 #Set the absolute termination tolerance for ECP rounds. +bonmin.ecp_max_rounds 5 #Set the maximal number of rounds of ECP cuts. +bonmin.ecp_probability_factor 10 #Factor appearing in formula for skipping ECP cuts. +bonmin.ecp_rel_tol 0 #Set the relative termination tolerance for ECP rounds. +bonmin.filmint_ecp_cuts 0 #Specify the frequency (in terms of nodes) at which some a la filmint ecp cuts are generated. + +# registering category: Feasibility checker using OA cuts + +bonmin.feas_check_cut_types outer-approx #Choose the type of cuts generated when an integer feasible solution is found +bonmin.feas_check_discard_policy detect-cycles #How cuts from feasibility checker are discarded +bonmin.generate_benders_after_so_many_oa 5000 #Specify that after so many oa cuts have been generated Benders cuts should be generated instead. + +# registering category: MILP Solver + +bonmin.cpx_parallel_strategy 0 #Strategy of parallel search mode in CPLEX. +bonmin.milp_solver Cbc_D #Choose the subsolver to solve MILP sub-problems in OA decompositions. +bonmin.milp_strategy solve_to_optimality #Choose a strategy for MILPs. +bonmin.number_cpx_threads 0 #Set number of threads to use with cplex. + +# registering category: MILP cutting planes in hybrid algorithm + +bonmin.2mir_cuts 0 #Frequency (in terms of nodes) for generating 2-MIR cuts in branch-and-cut +bonmin.Gomory_cuts -5 #Frequency (in terms of nodes) for generating Gomory cuts in branch-and-cut. +bonmin.clique_cuts -5 #Frequency (in terms of nodes) for generating clique cuts in branch-and-cut +bonmin.cover_cuts 0 #Frequency (in terms of nodes) for generating cover cuts in branch-and-cut +bonmin.flow_cover_cuts -5 #Frequency (in terms of nodes) for generating flow cover cuts in branch-and-cut +bonmin.lift_and_project_cuts 0 #Frequency (in terms of nodes) for generating lift-and-project cuts in branch-and-cut +bonmin.mir_cuts -5 #Frequency (in terms of nodes) for generating MIR cuts in branch-and-cut +bonmin.reduce_and_split_cuts 0 #Frequency (in terms of nodes) for generating reduce-and-split cuts in branch-and-cut + +# registering category: NLP interface + +bonmin.nlp_solver Ipopt #Choice of the solver for local optima of continuous NLP's +bonmin.warm_start none #Select the warm start method + +# registering category: NLP solution robustness + +bonmin.max_consecutive_failures 10 #(temporarily removed) Number $n$ of consecutive unsolved problems before aborting a branch of the tree. +bonmin.max_random_point_radius 100000 #Set max value r for coordinate of a random point. +bonmin.num_iterations_suspect -1 #Number of iterations over which a node is considered "suspect" (for debugging purposes only, see detailed documentation). +bonmin.num_retry_unsolved_random_point 0 #Number $k$ of times that the algorithm will try to resolve an unsolved NLP with a random starting point (we call unsolved an NLP for which Ipopt is not able to guarantee optimality within the specified tolerances). +bonmin.random_point_perturbation_interval 1 #Amount by which starting point is perturbed when choosing to pick random point by perturbing starting point +bonmin.random_point_type Jon #method to choose a random starting point +bonmin.resolve_on_small_infeasibility 0 #If a locally infeasible problem is infeasible by less than this, resolve it with initial starting point. + +# registering category: NLP solves in hybrid algorithm (B-Hyb) + +bonmin.nlp_solve_frequency 10 #Specify the frequency (in terms of nodes) at which NLP relaxations are solved in B-Hyb. +bonmin.nlp_solve_max_depth 10 #Set maximum depth in the tree at which NLP relaxations are solved in B-Hyb. +bonmin.nlp_solves_per_depth 1e+100 #Set average number of nodes in the tree at which NLP relaxations are solved in B-Hyb for each depth. + +# registering category: Nonconvex problems + +bonmin.coeff_var_threshold 0.1 #Coefficient of variation threshold (for dynamic definition of cutoff_decr). +bonmin.dynamic_def_cutoff_decr no #Do you want to define the parameter cutoff_decr dynamically? +bonmin.first_perc_for_cutoff_decr -0.02 #The percentage used when, the coeff of variance is smaller than the threshold, to compute the cutoff_decr dynamically. +bonmin.max_consecutive_infeasible 0 #Number of consecutive infeasible subproblems before aborting a branch. +bonmin.num_resolve_at_infeasibles 0 #Number $k$ of tries to resolve an infeasible node (other than the root) of the tree with different starting point. +bonmin.num_resolve_at_node 0 #Number $k$ of tries to resolve a node (other than the root) of the tree with different starting point. +bonmin.num_resolve_at_root 0 #Number $k$ of tries to resolve the root node with different starting points. +bonmin.second_perc_for_cutoff_decr -0.05 #The percentage used when, the coeff of variance is greater than the threshold, to compute the cutoff_decr dynamically. + +# registering category: Outer Approximation Decomposition (B-OA) + +bonmin.oa_decomposition no #If yes do initial OA decomposition + +# registering category: Outer Approximation cuts generation + +bonmin.add_only_violated_oa no #Do we add all OA cuts or only the ones violated by current point? +bonmin.oa_cuts_scope global #Specify if OA cuts added are to be set globally or locally valid +bonmin.oa_rhs_relax 1e-08 #Value by which to relax OA cut +bonmin.tiny_element 1e-08 #Value for tiny element in OA cut +bonmin.very_tiny_element 1e-17 #Value for very tiny element in OA cut + +# registering category: Output + +bonmin.bb_log_interval 100 #Interval at which node level output is printed. +bonmin.bb_log_level 1 #specify main branch-and-bound log level. +bonmin.file_print_level 5 #Verbosity level for output file. +bonmin.file_solution no #Write a file bonmin.sol with the solution +bonmin.fp_log_frequency 100 #display an update on lower and upper bounds in FP every n seconds +bonmin.fp_log_level 1 #specify FP iterations log level. +bonmin.inf_pr_output original #Determines what value is printed in the "inf_pr" output column. +bonmin.lp_log_level 0 #specify LP log level. +bonmin.milp_log_level 0 #specify MILP solver log level. +bonmin.nlp_log_at_root 0 # Specify a different log level for root relaxation. +bonmin.nlp_log_level 1 #specify NLP solver interface log level (independent from ipopt print_level). +bonmin.oa_cuts_log_level 0 #level of log when generating OA cuts. +bonmin.oa_log_frequency 100 #display an update on lower and upper bounds in OA every n seconds +bonmin.oa_log_level 1 #specify OA iterations log level. +bonmin.option_file_name #File name of options file (to overwrite default). +bonmin.output_file #File name of desired output file (leave unset for no file output). +bonmin.print_frequency_iter 1 #Determines at which iteration frequency the summarizing iteration output line should be printed. +bonmin.print_frequency_time 0 #Determines at which time frequency the summarizing iteration output line should be printed. +bonmin.print_info_string no #Enables printing of additional info string at end of iteration output. +bonmin.print_level 5 #Output verbosity level. +bonmin.print_options_documentation no #Switch to print all algorithmic options. +bonmin.print_timing_statistics no #Switch to print timing statistics. +bonmin.print_user_options no #Print all options set by the user. +bonmin.replace_bounds no #Indicates if all variable bounds should be replaced by inequality constraints +bonmin.skip_finalize_solution_call no #Indicates if call to NLP::FinalizeSolution after optimization should be suppressed + +# registering category: Primal Heuristics + +bonmin.feasibility_pump_objective_norm 1 #Norm of feasibility pump objective function +bonmin.fp_pass_infeasible no #Say whether feasibility pump should claim to converge or not +bonmin.heuristic_RINS no #if yes runs the RINS heuristic +bonmin.heuristic_dive_MIP_fractional no #if yes runs the Dive MIP Fractional heuristic +bonmin.heuristic_dive_MIP_vectorLength no #if yes runs the Dive MIP VectorLength heuristic +bonmin.heuristic_dive_fractional no #if yes runs the Dive Fractional heuristic +bonmin.heuristic_dive_vectorLength no #if yes runs the Dive VectorLength heuristic +bonmin.heuristic_feasibility_pump no #whether the heuristic feasibility pump should be used +bonmin.pump_for_minlp no #whether to run the feasibility pump heuristic for MINLP + +# registering category: Strong branching setup + +bonmin.candidate_sort_criterion best-ps-cost #Choice of the criterion to choose candidates in strong-branching +bonmin.maxmin_crit_have_sol 0.1 #Weight towards minimum in of lower and upper branching estimates when a solution has been found. +bonmin.maxmin_crit_no_sol 0.7 #Weight towards minimum in of lower and upper branching estimates when no solution has been found yet. +bonmin.min_number_strong_branch 0 #Sets minimum number of variables for strong branching (overriding trust) +bonmin.number_before_trust_list 0 #Set the number of branches on a variable before its pseudo costs are to be believed during setup of strong branching candidate list. +bonmin.number_look_ahead 0 #Sets limit of look-ahead strong-branching trials +bonmin.number_strong_branch_root 2147483647 #Maximum number of variables considered for strong branching in root node. +bonmin.setup_pseudo_frac 0.5 #Proportion of strong branching list that has to be taken from most-integer-infeasible list. +bonmin.trust_strong_branching_for_pseudo_cost yes #Whether or not to trust strong branching results for updating pseudo costs. diff --git a/sci_gateway/cpp/builder_gateway_cpp.sce b/sci_gateway/cpp/builder_gateway_cpp.sce new file mode 100755 index 0000000..1359db8 --- /dev/null +++ b/sci_gateway/cpp/builder_gateway_cpp.sce @@ -0,0 +1,68 @@ +// Copyright (C) 2015 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +mode(-1) +lines(0) + +toolbox_title = "FOSSEE_Optimization_Toolbox"; + +Build_64Bits = %t; + +path_builder = get_absolute_file_path('builder_gateway_cpp.sce'); + +//Name of All the Functions +Function_Names = [ + 'inter_fminunc', 'cpp_intfminunc'; + 'inter_fminbnd', 'cpp_intfminbnd'; + 'inter_fmincon', 'cpp_intfmincon'; + 'sci_intqpipopt', 'cpp_intqpipopt'; + 'sci_matrix_intlinprog', 'matrix_cppintlinprog'; + 'sci_mps_intlinprog','mps_cppintlinprog'; + ]; + +//Name of all the files to be compiled +Files = [ + 'sci_iofunc.cpp', + 'sci_minuncTMINLP.cpp', + 'cpp_intfminunc.cpp', + 'sci_minbndTMINLP.cpp', + 'cpp_intfminbnd.cpp', + 'sci_minconTMINLP.cpp', + 'cpp_intfmincon.cpp', + 'cbcintlinprog_matrixcpp.cpp', + 'sci_QuadTMINLP.cpp', + 'cpp_intqpipopt.cpp', + 'cbcintlinprog_mpscpp.cpp' + ] + +[a, opt] = getversion(); +Version = opt(2); + +if getos()=="Windows" then + third_dir = path_builder+filesep()+'..'+filesep()+'..'+filesep()+'thirdparty'; + lib_base_dir = third_dir + filesep() + 'windows' + filesep() + 'lib' + filesep() + Version + filesep(); + inc_base_dir = third_dir + filesep() + 'windows' + filesep() + 'include' + filesep() + 'coin'; +// C_Flags=['-D__USE_DEPRECATED_STACK_FUNCTIONS__ -w -I '+path_builder+' '+ '-I '+inc_base_dir+' '] +// Linker_Flag = [lib_base_dir+"libClp.lib "+lib_base_dir+"libCgl.lib "+lib_base_dir+"libOsi.lib "+lib_base_dir+"libOsiClp.lib "+lib_base_dir+"libCoinUtils.lib "+lib_base_dir+"libSymphony.lib "+lib_base_dir+"IpOptFSS.lib "+lib_base_dir+"IpOpt-vc10.lib "] + +else + third_dir = path_builder+filesep()+'..'+filesep()+'..'+filesep()+'thirdparty'; + lib_base_dir = third_dir + filesep() + 'linux' + filesep() + 'lib' + filesep() + Version + filesep(); + inc_base_dir = third_dir + filesep() + 'linux' + filesep() + 'include' + filesep() + 'coin'; + + C_Flags=["-D__USE_DEPRECATED_STACK_FUNCTIONS__ -w -fpermissive -I"+path_builder+" -I"+inc_base_dir+" -Wl,-rpath="+lib_base_dir+" "] + + Linker_Flag = ["-L"+lib_base_dir+"libCoinUtils.so "+"-L"+lib_base_dir+"libClp.so "+"-L"+lib_base_dir+"libClpSolver.so "+"-L"+lib_base_dir+"libOsi.so "+"-L"+lib_base_dir+"libOsiClp.so "+"-L"+lib_base_dir+"libCgl.so "+"-L"+lib_base_dir+"libCbc.so "+"-L"+lib_base_dir+"libCbcSolver.so "+"-L"+lib_base_dir+"libOsiCbc.so "+"-L"+lib_base_dir+"libipopt.so "+"-L"+lib_base_dir+"libbonmin.so " ] +end + +tbx_build_gateway(toolbox_title,Function_Names,Files,get_absolute_file_path("builder_gateway_cpp.sce"), [], Linker_Flag, C_Flags); + +clear toolbox_title Function_Names Files Linker_Flag C_Flags; diff --git a/sci_gateway/cpp/cbcintlinprog_matrixcpp.cpp b/sci_gateway/cpp/cbcintlinprog_matrixcpp.cpp new file mode 100644 index 0000000..d4e6f41 --- /dev/null +++ b/sci_gateway/cpp/cbcintlinprog_matrixcpp.cpp @@ -0,0 +1,226 @@ +// MILP with CBC library, Matrix +// Code Authors: Akshay Miterani and Pranav Deshpande + +#include <sci_iofunc.hpp> + +// For Branch and bound +#include "OsiSolverInterface.hpp" +#include "CbcModel.hpp" +#include "CbcCutGenerator.hpp" +#include "CbcHeuristicLocal.hpp" +#include "OsiClpSolverInterface.hpp" +extern "C"{ +#include <api_scilab.h> +#include "sciprint.h" + +int matrix_cppintlinprog(){ + + //Objective function + double* obj; + //Constraint matrix coefficients + double* conMatrix; + //intcon Matrix + double* intcon; + //Constraints upper bound + double* conlb; + //Constraints lower bound + double* conub; + //Lower bounds for variables + double* lb; + //Upper bounds for variables + double* ub; + //options for maximum iterations and writing mps + double* options; + //Flag for Mps + double flagMps; + //mps file path + char * mpsFile; + //Error structure in Scilab + SciErr sciErr; + //Number of rows and columns in objective function + int nVars=0, nCons=0,temp1=0,temp2=0; + int numintcons=0; + double valobjsense; + + CheckInputArgument(pvApiCtx , 11 , 11); //Checking the input arguments + CheckOutputArgument(pvApiCtx , 8, 8); //Checking the output arguments + + ////////// Manage the input argument ////////// + + //Number of Variables + if(getIntFromScilab(1,&nVars)) + { + return 1; + } + + //Number of Constraints + if (getIntFromScilab(2,&nCons)) + { + return 1; + } + + //Objective function from Scilab + temp1 = nVars; + temp2 = nCons; + if (getFixedSizeDoubleMatrixFromScilab(3,1,temp1,&obj)) + { + return 1; + } + + //intcon matrix + if (getDoubleMatrixFromScilab(4,&numintcons,&temp2,&intcon)) + { + return 1; + } + + if (nCons!=0) + { + //conMatrix matrix from scilab + temp1 = nCons; + temp2 = nVars; + + if (getFixedSizeDoubleMatrixFromScilab(5,temp1,temp2,&conMatrix)) + { + return 1; + } + + //conLB matrix from scilab + temp1 = nCons; + temp2 = 1; + if (getFixedSizeDoubleMatrixFromScilab(6,temp1,temp2,&conlb)) + { + return 1; + } + + //conUB matrix from scilab + if (getFixedSizeDoubleMatrixFromScilab(7,temp1,temp2,&conub)) + { + return 1; + } + + } + + //lb matrix from scilab + temp1 = 1; + temp2 = nVars; + if (getFixedSizeDoubleMatrixFromScilab(8,temp1,temp2,&lb)) + { + return 1; + } + + + //ub matrix from scilab + if (getFixedSizeDoubleMatrixFromScilab(9,temp1,temp2,&ub)) + { + return 1; + } + + //Object Sense + if(getDoubleFromScilab(10,&valobjsense)) + { + return 1; + } + + //get options from scilab + if(getFixedSizeDoubleMatrixFromScilab(11 , 1 , 4 , &options)) + { + return 1; + } + + //------------Temporary Version to make coin packed matrix------ + OsiClpSolverInterface solver1; + + CoinPackedMatrix *matrix = new CoinPackedMatrix(false , 0 , 0); + matrix->setDimensions(0 , nVars); + for(int i=0 ; i<nCons ; i++) + { + CoinPackedVector row; + for(int j=0 ; j<nVars ; j++) + { + row.insert(j, conMatrix[i+j*nCons]); + } + matrix->appendRow(row); + } + + + solver1.loadProblem(*matrix, lb, ub, obj, conlb, conub); + + for(int i=0;i<numintcons;i++) + solver1.setInteger(intcon[i]-1); + + solver1.setObjSense(valobjsense); + + //------------------------------------------------------------- + + CbcModel model(solver1); + + model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry); + + if((int)options[0]!=0) + model.setIntegerTolerance(options[0]); + if((int)options[1]!=0) + model.setMaximumNodes((int)options[1]); + if((int)options[2]!=0) + model.setMaximumSeconds(options[2]); + if((int)options[3]!=0) + model.setAllowableGap(options[3]); + + model.branchAndBound(); + + const double *val = model.getColSolution(); + + //Output the solution to Scilab + + //get solution for x + double* xValue = model.getColSolution(); + + //get objective value + double objValue = model.getObjValue(); + + //Output status + double status_=-1; + if(model.isProvenOptimal()){ + status_=0; + } + else if(model.isProvenInfeasible()){ + status_=1; + } + else if(model.isSolutionLimitReached()){ + status_=2; + } + else if(model. isNodeLimitReached()){ + status_=3; + } + else if(model.isAbandoned()){ + status_=4; + } + else if(model.isSecondsLimitReached()){ + status_=5; + } + else if(model.isContinuousUnbounded()){ + status_=6; + } + else if(model.isProvenDualInfeasible()){ + status_=7; + } + + double nodeCount=model.getNodeCount(); + double nfps=model.numberIntegers(); + double U=model.getObjValue(); + double L=model.getBestPossibleObjValue(); + double iterCount=model.getIterationCount(); + + returnDoubleMatrixToScilab(1 , nVars, 1 , xValue); + returnDoubleMatrixToScilab(2 , 1 , 1 , &objValue); + returnDoubleMatrixToScilab(3 , 1 , 1 , &status_); + returnDoubleMatrixToScilab(4 , 1 , 1 , &nodeCount); + returnDoubleMatrixToScilab(5 , 1 , 1 , &nfps); + returnDoubleMatrixToScilab(6 , 1 , 1 , &L); + returnDoubleMatrixToScilab(7 , 1 , 1 , &U); + returnDoubleMatrixToScilab(8 , 1 , 1 , &iterCount); + + //------------------------------------------------------------- + + return 0; +} +} diff --git a/sci_gateway/cpp/cbcintlinprog_mpscpp.cpp b/sci_gateway/cpp/cbcintlinprog_mpscpp.cpp new file mode 100644 index 0000000..8292ab1 --- /dev/null +++ b/sci_gateway/cpp/cbcintlinprog_mpscpp.cpp @@ -0,0 +1,115 @@ +// MILP with CBC library, mps +// Finds the solution by using CBC Library +// Code Authors: Akshay Miterani and Pranav Deshpande + +#include <sci_iofunc.hpp> + +// For Branch and bound +#include "OsiSolverInterface.hpp" +#include "CbcModel.hpp"= +#include "CbcCutGenerator.hpp" +#include "CbcHeuristicLocal.hpp" +#include "OsiClpSolverInterface.hpp" +extern "C" { +#include <api_scilab.h> + +int mps_cppintlinprog() +{ + OsiClpSolverInterface solver; + + // Path to the MPS file + char *mpsFilePath; + + // Options to set maximum iterations + double *options; + + // Input - 1 or 2 arguments allowed. + CheckInputArgument(pvApiCtx, 2, 2); + + // Get the MPS File Path from Scilab + getStringFromScilab(1, &mpsFilePath); + + // Receive the options for setting the maximum number of iterations etc. + if( getFixedSizeDoubleMatrixFromScilab(2, 1, 4, &options)) + { + return 1; + } + + // Read the MPS file + solver.readMps(mpsFilePath); + + // Cbc Library used from here + CbcModel model(solver); + + model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry); + + if((int)options[0]!=0) + model.setIntegerTolerance(options[0]); + if((int)options[1]!=0) + model.setMaximumNodes((int)options[1]); + if((int)options[2]!=0) + model.setMaximumSeconds(options[2]); + if((int)options[3]!=0) + model.setAllowableGap(options[3]); + + model.branchAndBound(); + + int nVars = model.getNumCols(); + int nCons = model.getNumRows(); + + const double *val = model.getColSolution(); + + //Output the solution to Scilab + + //get solution for x + double* xValue = model.getColSolution(); + + //get objective value + double objValue = model.getObjValue(); + + //Output status + double status_=-1; + if(model.isProvenOptimal()){ + status_=0; + } + else if(model.isProvenInfeasible()){ + status_=1; + } + else if(model.isSolutionLimitReached()){ + status_=2; + } + else if(model. isNodeLimitReached()){ + status_=3; + } + else if(model.isAbandoned()){ + status_=4; + } + else if(model.isSecondsLimitReached()){ + status_=5; + } + else if(model.isContinuousUnbounded()){ + status_=6; + } + else if(model.isProvenDualInfeasible()){ + status_=7; + } + + double nodeCount = model.getNodeCount(); + double nfps = model.numberIntegers(); + double U = model.getObjValue(); + double L = model.getBestPossibleObjValue(); + double iterCount = model.getIterationCount(); + + returnDoubleMatrixToScilab(1 , nVars, 1 , xValue); + returnDoubleMatrixToScilab(2 , 1 , 1 , &objValue); + returnDoubleMatrixToScilab(3 , 1 , 1 , &status_); + returnDoubleMatrixToScilab(4 , 1 , 1 , &nodeCount); + returnDoubleMatrixToScilab(5 , 1 , 1 , &nfps); + returnDoubleMatrixToScilab(6 , 1 , 1 , &L); + returnDoubleMatrixToScilab(7 , 1 , 1 , &U); + returnDoubleMatrixToScilab(8 , 1 , 1 , &iterCount); + + return 0; +} + +} diff --git a/sci_gateway/cpp/cleaner.sce b/sci_gateway/cpp/cleaner.sce new file mode 100755 index 0000000..333775c --- /dev/null +++ b/sci_gateway/cpp/cleaner.sce @@ -0,0 +1,22 @@ +// This file is released under the 3-clause BSD license. See COPYING-BSD. +// Generated by builder.sce : Please, do not edit this file +// cleaner.sce +// ------------------------------------------------------ +curdir = pwd(); +cleaner_path = get_file_path('cleaner.sce'); +chdir(cleaner_path); +// ------------------------------------------------------ +if fileinfo('loader.sce') <> [] then + mdelete('loader.sce'); +end +// ------------------------------------------------------ +if fileinfo('libFOSSEE_Optimization_Toolbox.so') <> [] then + mdelete('libFOSSEE_Optimization_Toolbox.so'); +end +// ------------------------------------------------------ +if fileinfo('libFOSSEE_Optimization_Toolbox.c') <> [] then + mdelete('libFOSSEE_Optimization_Toolbox.c'); +end +// ------------------------------------------------------ +chdir(curdir); +// ------------------------------------------------------ diff --git a/sci_gateway/cpp/cpp_intfminbnd.cpp b/sci_gateway/cpp/cpp_intfminbnd.cpp new file mode 100644 index 0000000..4914111 --- /dev/null +++ b/sci_gateway/cpp/cpp_intfminbnd.cpp @@ -0,0 +1,172 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#include "CoinPragma.hpp" +#include "CoinTime.hpp" +#include "CoinError.hpp" + +#include "BonOsiTMINLPInterface.hpp" +#include "BonIpoptSolver.hpp" +#include "minbndTMINLP.hpp" +#include "BonCbc.hpp" +#include "BonBonminSetup.hpp" + +#include "BonOACutGenerator2.hpp" +#include "BonEcpCuts.hpp" +#include "BonOaNlpOptim.hpp" + +#include "sci_iofunc.hpp" +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> + +int cpp_intfminbnd(char *fname) +{ + using namespace Ipopt; + using namespace Bonmin; + + CheckInputArgument(pvApiCtx, 8, 8); + CheckOutputArgument(pvApiCtx, 3, 3); + + // Input arguments + Number *integertolerance=NULL, *maxnodes=NULL, *allowablegap=NULL, *cputime=NULL,*max_iter=NULL, *lb = NULL, *ub = NULL; + static unsigned int nVars = 0; + unsigned int temp1 = 0,temp2 = 0, iret = 0; + int x0_rows, x0_cols,intconSize; + Number *intcon = NULL,*options=NULL, *ifval=NULL; + + // Output arguments + Number *fX = NULL, ObjVal=0,iteration=0,cpuTime=0,fobj_eval=0; + Number dual_inf, constr_viol, complementarity, kkt_error; + int rstatus = 0; + + if(getDoubleMatrixFromScilab(4, &x0_rows, &x0_cols, &lb)) + { + return 1; + } + + if(getDoubleMatrixFromScilab(5, &x0_rows, &x0_cols, &ub)) + { + return 1; + } + + // Getting intcon + if (getDoubleMatrixFromScilab(6,&intconSize,&temp2,&intcon)) + { + return 1; + } + + //Initialization of parameters + nVars=x0_rows; + temp1 = 1; + temp2 = 1; + + //Getting parameters + if (getFixedSizeDoubleMatrixInList(7,2,temp1,temp2,&integertolerance)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(7,4,temp1,temp2,&maxnodes)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(7,6,temp1,temp2,&cputime)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(7,8,temp1,temp2,&allowablegap)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(7,10,temp1,temp2,&max_iter)) + { + return 1; + } + + SmartPtr<minbndTMINLP> tminlp = new minbndTMINLP(nVars,lb,ub,intconSize,intcon); + + BonminSetup bonmin; + bonmin.initializeOptionsAndJournalist(); + + bonmin.options()->SetStringValue("mu_oracle","loqo"); + bonmin.options()->SetNumericValue("bonmin.integer_tolerance", *integertolerance); + bonmin.options()->SetIntegerValue("bonmin.node_limit", (int)*maxnodes); + bonmin.options()->SetNumericValue("bonmin.time_limit", *cputime); + bonmin.options()->SetNumericValue("bonmin.allowable_gap", *allowablegap); + bonmin.options()->SetIntegerValue("bonmin.iteration_limit", (int)*max_iter); + + //Now initialize from tminlp + bonmin.initialize(GetRawPtr(tminlp)); + + //Set up done, now let's branch and bound + try { + Bab bb; + bb(bonmin);//process parameter file using Ipopt and do branch and bound using Cbc + } + catch(TNLPSolver::UnsolvedError *E) { + Scierror(999, "\nIpopt has failed to solve the problem!\n"); + } + catch(OsiTMINLPInterface::SimpleError &E) { + Scierror(999, "\nFailed to solve a problem!\n"); + } + catch(CoinError &E) { + Scierror(999, "\nFailed to solve a problem!\n"); + } + rstatus=tminlp->returnStatus(); + + if(rstatus==0 ||rstatus== 3) + { + fX = tminlp->getX(); + ObjVal = tminlp->getObjVal(); + if (returnDoubleMatrixToScilab(1, nVars, 1, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + else + { + if (returnDoubleMatrixToScilab(1, 0, 0, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + + return 0; + } +} + diff --git a/sci_gateway/cpp/cpp_intfmincon.cpp b/sci_gateway/cpp/cpp_intfmincon.cpp new file mode 100644 index 0000000..d921128 --- /dev/null +++ b/sci_gateway/cpp/cpp_intfmincon.cpp @@ -0,0 +1,189 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#include "CoinPragma.hpp" +#include "CoinTime.hpp" +#include "CoinError.hpp" + +#include "BonOsiTMINLPInterface.hpp" +#include "BonIpoptSolver.hpp" +#include "minconTMINLP.hpp" +#include "BonCbc.hpp" +#include "BonBonminSetup.hpp" + +#include "BonOACutGenerator2.hpp" +#include "BonEcpCuts.hpp" +#include "BonOaNlpOptim.hpp" + +#include "sci_iofunc.hpp" +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> + +int cpp_intfmincon(char *fname) +{ + using namespace Ipopt; + using namespace Bonmin; + + CheckInputArgument(pvApiCtx, 13, 13); + CheckOutputArgument(pvApiCtx, 3, 3); + + // Input arguments + Number *integertolerance=NULL, *maxnodes=NULL, *allowablegap=NULL, *cputime=NULL,*max_iter=NULL; + Number *x0 = NULL, *lb = NULL, *ub = NULL,*conLb = NULL, *conUb = NULL,*LC = NULL; + static unsigned int nVars = 0,nCons = 0; + unsigned int temp1 = 0,temp2 = 0, iret = 0; + int x0_rows, x0_cols,intconSize; + Number *intcon = NULL,*options=NULL, *ifval=NULL; + + // Output arguments + Number *fX = NULL, ObjVal=0,iteration=0,cpuTime=0,fobj_eval=0; + Number dual_inf, constr_viol, complementarity, kkt_error; + int rstatus = 0; + + if(getDoubleMatrixFromScilab(6, &nVars, &x0_cols, &x0)) + { + return 1; + } + + if(getDoubleMatrixFromScilab(7, &x0_rows, &x0_cols, &lb)) + { + return 1; + } + + if(getDoubleMatrixFromScilab(8, &x0_rows, &x0_cols, &ub)) + { + return 1; + } + + if(getDoubleMatrixFromScilab(9, &nCons, &x0_cols, &conLb)) + { + return 1; + } + + if(getDoubleMatrixFromScilab(10, &x0_rows, &x0_cols, &conUb)) + { + return 1; + } + + // Getting intcon + if (getDoubleMatrixFromScilab(11,&intconSize,&temp2,&intcon)) + { + return 1; + } + + if (getDoubleMatrixFromScilab(13,&temp1,&temp2,&LC)) + { + return 1; + } + + //Initialization of parameters + temp1 = 1; + temp2 = 1; + + //Getting parameters + if (getFixedSizeDoubleMatrixInList(12,2,temp1,temp2,&integertolerance)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(12,4,temp1,temp2,&maxnodes)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(12,6,temp1,temp2,&cputime)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(12,8,temp1,temp2,&allowablegap)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(12,10,temp1,temp2,&max_iter)) + { + return 1; + } + + SmartPtr<minconTMINLP> tminlp = new minconTMINLP(nVars,x0,lb,ub,(unsigned int)LC,nCons,conLb,conUb,intconSize,intcon); + + BonminSetup bonmin; + bonmin.initializeOptionsAndJournalist(); + bonmin.options()->SetStringValue("mu_oracle","loqo"); + bonmin.options()->SetIntegerValue("bonmin.print_level",5); + bonmin.options()->SetNumericValue("bonmin.integer_tolerance", *integertolerance); + bonmin.options()->SetIntegerValue("bonmin.node_limit", (int)*maxnodes); + bonmin.options()->SetNumericValue("bonmin.time_limit", *cputime); + bonmin.options()->SetNumericValue("bonmin.allowable_gap", *allowablegap); + bonmin.options()->SetIntegerValue("bonmin.iteration_limit", (int)*max_iter); + + //Now initialize from tminlp + bonmin.initialize(GetRawPtr(tminlp)); + + //Set up done, now let's branch and bound + try { + Bab bb; + bb(bonmin);//process parameter file using Ipopt and do branch and bound using Cbc + } + catch(TNLPSolver::UnsolvedError *E) { + } + catch(OsiTMINLPInterface::SimpleError &E) { + } + catch(CoinError &E) { + } + rstatus=tminlp->returnStatus(); + + if(rstatus==0 ||rstatus== 3) + { + fX = tminlp->getX(); + ObjVal = tminlp->getObjVal(); + if (returnDoubleMatrixToScilab(1, nVars, 1, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + else + { + if (returnDoubleMatrixToScilab(1, 0, 0, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + + return 0; + } +} + diff --git a/sci_gateway/cpp/cpp_intfminunc.cpp b/sci_gateway/cpp/cpp_intfminunc.cpp new file mode 100644 index 0000000..3e1abcd --- /dev/null +++ b/sci_gateway/cpp/cpp_intfminunc.cpp @@ -0,0 +1,174 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#include "CoinPragma.hpp" +#include "CoinTime.hpp" +#include "CoinError.hpp" + +#include "BonOsiTMINLPInterface.hpp" +#include "BonIpoptSolver.hpp" +#include "minuncTMINLP.hpp" +#include "BonCbc.hpp" +#include "BonBonminSetup.hpp" + +#include "BonOACutGenerator2.hpp" +#include "BonEcpCuts.hpp" +#include "BonOaNlpOptim.hpp" + +#include "sci_iofunc.hpp" +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> + +int cpp_intfminunc(char *fname) +{ + using namespace Ipopt; + using namespace Bonmin; + + CheckInputArgument(pvApiCtx, 8, 8); + CheckOutputArgument(pvApiCtx, 3, 3); // 3 output arguments + + //Function pointers, input matrix(Starting point) pointer, flag variable + int* funptr=NULL; + double* x0ptr=NULL; + + // Input arguments + Number *integertolerance=NULL, *maxnodes=NULL, *allowablegap=NULL, *cputime=NULL,*max_iter=NULL; + static unsigned int nVars = 0,nCons = 0; + unsigned int temp1 = 0,temp2 = 0, iret = 0; + int x0_rows, x0_cols; + double *intcon = NULL,*options=NULL, *ifval=NULL; + int intconSize; + + // Output arguments + double *fX = NULL, ObjVal=0,iteration=0,cpuTime=0,fobj_eval=0; + double dual_inf, constr_viol, complementarity, kkt_error; + int rstatus = 0; + int int_fobj_eval, int_constr_eval, int_fobj_grad_eval, int_constr_jac_eval, int_hess_eval; + + //x0(starting point) matrix from scilab + if(getDoubleMatrixFromScilab(4, &x0_rows, &x0_cols, &x0ptr)) + { + return 1; + } + + nVars=x0_rows; + + // Getting intcon + if (getDoubleMatrixFromScilab(5,&intconSize,&temp2,&intcon)) + { + return 1; + } + + temp1 = 1; + temp2 = 1; + + //Getting parameters + if (getFixedSizeDoubleMatrixInList(6,2,temp1,temp2,&integertolerance)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(6,4,temp1,temp2,&maxnodes)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(6,6,temp1,temp2,&cputime)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(6,8,temp1,temp2,&allowablegap)) + { + return 1; + } + if (getFixedSizeDoubleMatrixInList(6,10,temp1,temp2,&max_iter)) + { + return 1; + } + + SmartPtr<minuncTMINLP> tminlp = new minuncTMINLP(nVars, x0ptr, intconSize, intcon); + + BonminSetup bonmin; + bonmin.initializeOptionsAndJournalist(); + + // Here we can change the default value of some Bonmin or Ipopt option + bonmin.options()->SetStringValue("mu_oracle","loqo"); + bonmin.options()->SetNumericValue("bonmin.integer_tolerance", *integertolerance); + bonmin.options()->SetIntegerValue("bonmin.node_limit", (int)*maxnodes); + bonmin.options()->SetNumericValue("bonmin.time_limit", *cputime); + bonmin.options()->SetNumericValue("bonmin.allowable_gap", *allowablegap); + bonmin.options()->SetIntegerValue("bonmin.iteration_limit", (int)*max_iter); + + //Now initialize from tminlp + bonmin.initialize(GetRawPtr(tminlp)); + + //Set up done, now let's branch and bound + try { + Bab bb; + bb(bonmin);//process parameter file using Ipopt and do branch and bound using Cbc + } + catch(TNLPSolver::UnsolvedError *E) { + //There has been a failure to solve a problem with Ipopt. + Scierror(999, "\nIpopt has failed to solve the problem!\n"); + } + catch(OsiTMINLPInterface::SimpleError &E) { + Scierror(999, "\nFailed to solve a problem!\n"); + } + catch(CoinError &E) { + Scierror(999, "\nFailed to solve a problem!\n"); + } + rstatus=tminlp->returnStatus(); + if(rstatus==0 ||rstatus== 3) + { + fX = tminlp->getX(); + ObjVal = tminlp->getObjVal(); + if (returnDoubleMatrixToScilab(1, nVars, 1, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + else + { + if (returnDoubleMatrixToScilab(1, 0, 0, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + } + + return 0; + } +} + diff --git a/sci_gateway/cpp/cpp_intqpipopt.cpp b/sci_gateway/cpp/cpp_intqpipopt.cpp new file mode 100644 index 0000000..d89d643 --- /dev/null +++ b/sci_gateway/cpp/cpp_intqpipopt.cpp @@ -0,0 +1,267 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#include <iomanip> +#include <fstream> +#include <iostream> +#include "CoinPragma.hpp" +#include "CoinTime.hpp" +#include "CoinError.hpp" + +#include "BonOsiTMINLPInterface.hpp" +#include "BonIpoptSolver.hpp" +#include "QuadTMINLP.hpp" +#include "BonCbc.hpp" +#include "BonBonminSetup.hpp" + +#include "BonOACutGenerator2.hpp" +#include "BonEcpCuts.hpp" +#include "BonOaNlpOptim.hpp" + +#include "sci_iofunc.hpp" +extern "C" +{ +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> + +int cpp_intqpipopt(char *fname) +{ + using namespace Ipopt; + using namespace Bonmin; + + CheckInputArgument(pvApiCtx, 15, 15); // We need total 15 input arguments. + CheckOutputArgument(pvApiCtx, 3, 3); // 3 output arguments + + // Error management variable + SciErr sciErr; + + // Input arguments + double *QItems=NULL,*PItems=NULL, *intcon = NULL, *ConItems=NULL,*conUB=NULL,*conLB=NULL; + double *varUB=NULL,*varLB=NULL,*init_guess=NULL,*options=NULL, *ifval=NULL; + static unsigned int nVars = 0,nCons = 0, intconSize = 0; + unsigned int temp1 = 0,temp2 = 0; + char *bonmin_options_file = NULL; + // Output arguments + double *fX = NULL, ObjVal = 0,iteration=0; + int rstatus = 0; + + //Number of Variables + if(getIntFromScilab(1,&nVars)) + { + return 1; + } + + //Number of Constraints + if (getIntFromScilab(2,&nCons)) + { + return 1; + } + + //Number of variables constrained to be integers + if (getIntFromScilab(3,&intconSize)) + { + return 1; + } + + //Q matrix from scilab + temp1 = nVars; + temp2 = nVars; + if (getFixedSizeDoubleMatrixFromScilab(4,temp1,temp1,&QItems)) + { + return 1; + } + + //P matrix from scilab + temp1 = 1; + temp2 = nVars; + if (getFixedSizeDoubleMatrixFromScilab(5,temp1,temp2,&PItems)) + { + return 1; + } + + temp1 = 1; + temp2 = intconSize; + // Getting intcon + if (getDoubleMatrixFromScilab(6,&temp1,&temp2,&intcon)) + { + return 1; + } + + if (nCons!=0) + { + //conMatrix matrix from scilab + temp1 = nCons; + temp2 = nVars; + + if (getFixedSizeDoubleMatrixFromScilab(7,temp1,temp2,&ConItems)) + { + return 1; + } + + //conLB matrix from scilab + temp1 = 1; + temp2 = nCons; + if (getFixedSizeDoubleMatrixFromScilab(8,temp1,temp2,&conLB)) + { + return 1; + } + + //conUB matrix from scilab + if (getFixedSizeDoubleMatrixFromScilab(9,temp1,temp2,&conUB)) + { + return 1; + } + } + + //varLB matrix from scilab + temp1 = 1; + temp2 = nVars; + if (getFixedSizeDoubleMatrixFromScilab(10,temp1,temp2,&varLB)) + { + return 1; + } + + //varUB matrix from scilab + if (getFixedSizeDoubleMatrixFromScilab(11,temp1,temp2,&varUB)) + { + return 1; + } + + //Initial Value of variables from scilab + if (getFixedSizeDoubleMatrixFromScilab( 12,temp1,temp2,&init_guess)) + { + return 1; + } + + temp1=1; + temp2=5; + if (getFixedSizeDoubleMatrixFromScilab(13,temp1,temp2,&options)) + { + return 1; + } + + temp1=1; + temp2=5; + if (getFixedSizeDoubleMatrixFromScilab(14,temp1,temp2,&ifval)) + { + return 1; + } + + if (getStringFromScilab(15, &bonmin_options_file)) + { + return 1; + } + + + + + SmartPtr<QuadTMINLP> tminlp = new QuadTMINLP(nVars,nCons,intconSize,QItems, PItems, intcon,ConItems,conLB,conUB,varLB,varUB,init_guess); + + BonminSetup bonmin; + bonmin.initializeOptionsAndJournalist(); + + // Here we can change the default value of some Bonmin or Ipopt option + bonmin.options()->SetStringValue("mu_oracle","loqo"); + + + //Register an additional option + if((int)ifval[0]) + bonmin.options()->SetNumericValue("bonmin.integer_tolerance", (options[0])); + if((int)ifval[1]) + bonmin.options()->SetIntegerValue("bonmin.node_limit", (int)(options[1])); + if((int)ifval[2]) + bonmin.options()->SetNumericValue("bonmin.time_limit", (options[2])); + if((int)ifval[3]) + bonmin.options()->SetNumericValue("bonmin.allowable_gap", (options[3])); + if((int)ifval[4]) + bonmin.options()->SetIntegerValue("bonmin.iteration_limit", (int)(options[4])); + + + //Here we read the option file + //if ( bonmin_options_file!=NULL ) + // bonmin.readOptionsFile(bonmin_options_file); + + //Now initialize from tminlp + bonmin.initialize(GetRawPtr(tminlp)); + + //Set up done, now let's branch and bound + try { + Bab bb; + bb(bonmin);//process parameter file using Ipopt and do branch and bound using Cbc + } + catch(TNLPSolver::UnsolvedError *E) { + //There has been a failure to solve a problem with Ipopt. + std::cerr<<"Ipopt has failed to solve a problem!"<<std::endl; + sciprint(999, "\nIpopt has failed to solve the problem!\n"); + } + catch(OsiTMINLPInterface::SimpleError &E) { + std::cerr<<E.className()<<"::"<<E.methodName() + <<std::endl + <<E.message()<<std::endl; + sciprint(999, "\nFailed to solve a problem!\n"); + } + catch(CoinError &E) { + std::cerr<<E.className()<<"::"<<E.methodName() + <<std::endl + <<E.message()<<std::endl; + sciprint(999, "\nFailed to solve a problem!\n"); + } + rstatus=tminlp->returnStatus(); + if (rstatus >= 0 | rstatus <= 5){ + fX = tminlp->getX(); + ObjVal = tminlp->getObjVal(); + if (returnDoubleMatrixToScilab(1, 1, nVars, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + } + else + { + if (returnDoubleMatrixToScilab(1, 0, 0, fX)) + { + return 1; + } + + if (returnDoubleMatrixToScilab(2, 1, 1, &ObjVal)) + { + return 1; + } + + if (returnIntegerMatrixToScilab(3, 1, 1, &rstatus)) + { + return 1; + } + + sciprint(999, "\nThe problem could not be solved!\n"); + } + + // As the SmartPtrs go out of scope, the reference count + // will be decremented and the objects will automatically + // be deleted(No memory leakage). + + return 0; +} +} + diff --git a/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.c b/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.c new file mode 100644 index 0000000..7090628 --- /dev/null +++ b/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.c @@ -0,0 +1,40 @@ +#ifdef __cplusplus +extern "C" { +#endif +#include <mex.h> +#include <sci_gateway.h> +#include <api_scilab.h> +#include <MALLOC.h> +static int direct_gateway(char *fname,void F(void)) { F();return 0;}; +extern Gatefunc cpp_intfminunc; +extern Gatefunc cpp_intfminbnd; +extern Gatefunc cpp_intfmincon; +extern Gatefunc cpp_intqpipopt; +extern Gatefunc matrix_cppintlinprog; +extern Gatefunc mps_cppintlinprog; +static GenericTable Tab[]={ + {(Myinterfun)sci_gateway,cpp_intfminunc,"inter_fminunc"}, + {(Myinterfun)sci_gateway,cpp_intfminbnd,"inter_fminbnd"}, + {(Myinterfun)sci_gateway,cpp_intfmincon,"inter_fmincon"}, + {(Myinterfun)sci_gateway,cpp_intqpipopt,"sci_intqpipopt"}, + {(Myinterfun)sci_gateway,matrix_cppintlinprog,"sci_matrix_intlinprog"}, + {(Myinterfun)sci_gateway,mps_cppintlinprog,"sci_mps_intlinprog"}, +}; + +int C2F(libFOSSEE_Optimization_Toolbox)() +{ + Rhs = Max(0, Rhs); + if (*(Tab[Fin-1].f) != NULL) + { + if(pvApiCtx == NULL) + { + pvApiCtx = (StrCtx*)MALLOC(sizeof(StrCtx)); + } + pvApiCtx->pstName = (char*)Tab[Fin-1].name; + (*(Tab[Fin-1].f))(Tab[Fin-1].name,Tab[Fin-1].F); + } + return 0; +} +#ifdef __cplusplus +} +#endif diff --git a/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.so b/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.so Binary files differnew file mode 100755 index 0000000..233098e --- /dev/null +++ b/sci_gateway/cpp/libFOSSEE_Optimization_Toolbox.so diff --git a/sci_gateway/cpp/loader.sce b/sci_gateway/cpp/loader.sce new file mode 100644 index 0000000..cad0490 --- /dev/null +++ b/sci_gateway/cpp/loader.sce @@ -0,0 +1,26 @@ +// This file is released under the 3-clause BSD license. See COPYING-BSD. +// Generated by builder.sce : Please, do not edit this file +// ---------------------------------------------------------------------------- +// +libFOSSEE_Optimizat_path = get_absolute_file_path('loader.sce'); +// +// ulink previous function with same name +[bOK, ilib] = c_link('libFOSSEE_Optimization_Toolbox'); +if bOK then + ulink(ilib); +end +// +list_functions = [ 'inter_fminunc'; + 'inter_fminbnd'; + 'inter_fmincon'; + 'sci_intqpipopt'; + 'sci_matrix_intlinprog'; + 'sci_mps_intlinprog'; +]; +addinter(libFOSSEE_Optimizat_path + filesep() + 'libFOSSEE_Optimization_Toolbox' + getdynlibext(), 'libFOSSEE_Optimization_Toolbox', list_functions); +// remove temp. variables on stack +clear libFOSSEE_Optimizat_path; +clear bOK; +clear ilib; +clear list_functions; +// ---------------------------------------------------------------------------- diff --git a/sci_gateway/cpp/minbndTMINLP.hpp b/sci_gateway/cpp/minbndTMINLP.hpp new file mode 100644 index 0000000..581d5ce --- /dev/null +++ b/sci_gateway/cpp/minbndTMINLP.hpp @@ -0,0 +1,114 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#ifndef minbndTMINLP_HPP +#define minbndTMINLP_HPP + +#include "BonTMINLP.hpp" +#include "IpTNLP.hpp" +#include "call_scilab.h" + +using namespace Ipopt; +using namespace Bonmin; + +class minbndTMINLP : public TMINLP +{ + private: + + Index numVars_; //Number of input variables + + Index intconSize_; + + Number *lb_= NULL; //lb_ is a pointer to a matrix of size of 1*numVars_ with lower bound of all variables. + + Number *ub_= NULL; //ub_ is a pointer to a matrix of size of 1*numVars_ with upper bound of all variables. + + Number *finalX_= NULL; //finalX_ is a pointer to a matrix of size of 1*numVars_ with final value for the primal variables. + + Number finalObjVal_; //finalObjVal_ is a scalar with the final value of the objective. + + Number *intcon_ = NULL; + + int status_; //Solver return status + minbndTMINLP(const minbndTMINLP&); + minbndTMINLP& operator=(const minbndTMINLP&); + +public: + // Constructor + minbndTMINLP(Index nV, Number *lb, Number *ub, Index intconSize, Number *intcon):numVars_(nV),lb_(lb),ub_(ub),intconSize_(intconSize),intcon_(intcon),finalX_(0),finalObjVal_(1e20){ } + + /** default destructor */ + virtual ~minbndTMINLP(); + + virtual bool get_variables_types(Index n, VariableType* var_types); + + virtual bool get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types); + + virtual bool get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types); + + /** Method to return some info about the nlp */ + virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, + Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style); + + /** Method to return the bounds for my problem */ + virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, + Index m, Number* g_l, Number* g_u); + + /** Method to return the starting point for the algorithm */ + virtual bool get_starting_point(Index n, bool init_x, Number* x, + bool init_z, Number* z_L, Number* z_U, + Index m, bool init_lambda, + Number* lambda); + + /** Method to return the objective value */ + virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); + + /** Method to return the gradient of the objective */ + virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); + + /** Method to return the constraint residuals */ + virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); + + /** Method to return: + * 1) The structure of the jacobian (if "values" is NULL) + * 2) The values of the jacobian (if "values" is not NULL) + */ + virtual bool eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values); + + /** Method to return: + * 1) The structure of the hessian of the lagrangian (if "values" is NULL) + * 2) The values of the hessian of the lagrangian (if "values" is not NULL) + */ + virtual bool eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values); + + /** This method is called when the algorithm is complete so the TNLP can store/write the solution */ + virtual void finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value); + + virtual const SosInfo * sosConstraints() const{return NULL;} + virtual const BranchingInfo* branchingInfo() const{return NULL;} + + const double * getX(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value for the primal variables. + + const double * getGrad(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value of gradient for the primal variables. + + const double * getHess(); //Returns a pointer to a matrix of size of numVars_*numVars_ + //with final value of hessian for the primal variables. + + double getObjVal(); //Returns the output of the final value of the objective. + + double iterCount(); //Returns the iteration count + + int returnStatus(); //Returns the status count +}; + +#endif diff --git a/sci_gateway/cpp/minconTMINLP.hpp b/sci_gateway/cpp/minconTMINLP.hpp new file mode 100644 index 0000000..5b3006a --- /dev/null +++ b/sci_gateway/cpp/minconTMINLP.hpp @@ -0,0 +1,124 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#ifndef minconTMINLP_HPP +#define minconTMINLP_HPP + +#include "BonTMINLP.hpp" +#include "IpTNLP.hpp" +#include "call_scilab.h" + +using namespace Ipopt; +using namespace Bonmin; + +class minconTMINLP : public TMINLP +{ + private: + + Index numVars_; //Number of variables + + Index numCons_; //Number of constraints + + Index numLC_; //Number of Linear constraints + + Index intconSize_; + + Number *x0_= NULL; //lb_ is a pointer to a matrix of size of 1*numVars_ with lower bound of all variables. + + Number *lb_= NULL; //lb_ is a pointer to a matrix of size of 1*numVars_ with lower bound of all variables. + + Number *ub_= NULL; //ub_ is a pointer to a matrix of size of 1*numVars_ with upper bound of all variables. + + Number *conLb_= NULL; //conLb_ is a pointer to a matrix of size of numCon_*1 with lower bound of all constraints. + + Number *conUb_= NULL; //conUb_ is a pointer to a matrix of size of numCon_*1 with upper bound of all constraints. + + Number *finalX_= NULL; //finalX_ is a pointer to a matrix of size of 1*numVars_ with final value for the primal variables. + + Number finalObjVal_; //finalObjVal_ is a scalar with the final value of the objective. + + Number *intcon_ = NULL; + + int status_; //Solver return status + minconTMINLP(const minconTMINLP&); + minconTMINLP& operator=(const minconTMINLP&); + +public: + // Constructor + minconTMINLP(Index nV, Number *x0, Number *lb, Number *ub, Index nLC, Index nCons, Number *conlb, Number *conub, Index intconSize, Number *intcon):numVars_(nV),x0_(x0),lb_(lb),ub_(ub),numLC_(nLC),numCons_(nCons),conLb_(conlb),conUb_(conub),intconSize_(intconSize),intcon_(intcon),finalX_(0),finalObjVal_(1e20){ } + + /** default destructor */ + virtual ~minconTMINLP(); + + virtual bool get_variables_types(Index n, VariableType* var_types); + + virtual bool get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types); + + virtual bool get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types); + + /** Method to return some info about the nlp */ + virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, + Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style); + + /** Method to return the bounds for my problem */ + virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, + Index m, Number* g_l, Number* g_u); + + /** Method to return the starting point for the algorithm */ + virtual bool get_starting_point(Index n, bool init_x, Number* x, + bool init_z, Number* z_L, Number* z_U, + Index m, bool init_lambda, + Number* lambda); + + /** Method to return the objective value */ + virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); + + /** Method to return the gradient of the objective */ + virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); + + /** Method to return the constraint residuals */ + virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); + + /** Method to return: + * 1) The structure of the jacobian (if "values" is NULL) + * 2) The values of the jacobian (if "values" is not NULL) + */ + virtual bool eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values); + + /** Method to return: + * 1) The structure of the hessian of the lagrangian (if "values" is NULL) + * 2) The values of the hessian of the lagrangian (if "values" is not NULL) + */ + virtual bool eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values); + + /** This method is called when the algorithm is complete so the TNLP can store/write the solution */ + virtual void finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value); + + virtual const SosInfo * sosConstraints() const{return NULL;} + virtual const BranchingInfo* branchingInfo() const{return NULL;} + + const double * getX(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value for the primal variables. + + const double * getGrad(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value of gradient for the primal variables. + + const double * getHess(); //Returns a pointer to a matrix of size of numVars_*numVars_ + //with final value of hessian for the primal variables. + + double getObjVal(); //Returns the output of the final value of the objective. + + double iterCount(); //Returns the iteration count + + int returnStatus(); //Returns the status count +}; + +#endif diff --git a/sci_gateway/cpp/minuncTMINLP.hpp b/sci_gateway/cpp/minuncTMINLP.hpp new file mode 100644 index 0000000..2b6e954 --- /dev/null +++ b/sci_gateway/cpp/minuncTMINLP.hpp @@ -0,0 +1,113 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#define __USE_DEPRECATED_STACK_FUNCTIONS__ +#ifndef minuncTMINLP_HPP +#define minuncTMINLP_HPP + +#include "BonTMINLP.hpp" +#include "IpTNLP.hpp" +#include "call_scilab.h" + +using namespace Ipopt; +using namespace Bonmin; + +class minuncTMINLP : public TMINLP +{ + private: + + Index numVars_; //Number of input variables + + Index intconSize_; + + const Number *varGuess_= NULL; //varGuess_ is a pointer to a matrix of size of 1*numVars_ with initial guess of all variables. + + Number *finalX_= NULL; //finalX_ is a pointer to a matrix of size of 1*numVars_ with final value for the primal variables. + + Number finalObjVal_; //finalObjVal_ is a scalar with the final value of the objective. + + Number *intcon_ = NULL; + + int status_; //Solver return status + minuncTMINLP(const minuncTMINLP&); + minuncTMINLP& operator=(const minuncTMINLP&); + +public: + // Constructor + minuncTMINLP(Index nV, Number *x0, Index intconSize, Number *intcon):numVars_(nV),varGuess_(x0),intconSize_(intconSize),intcon_(intcon),finalX_(0),finalObjVal_(1e20){ } + + /** default destructor */ + virtual ~minuncTMINLP(); + + virtual bool get_variables_types(Index n, VariableType* var_types); + + virtual bool get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types); + + virtual bool get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types); + + /** Method to return some info about the nlp */ + virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, + Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style); + + /** Method to return the bounds for my problem */ + virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, + Index m, Number* g_l, Number* g_u); + + /** Method to return the starting point for the algorithm */ + virtual bool get_starting_point(Index n, bool init_x, Number* x, + bool init_z, Number* z_L, Number* z_U, + Index m, bool init_lambda, + Number* lambda); + + /** Method to return the objective value */ + virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); + + /** Method to return the gradient of the objective */ + virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); + + /** Method to return the constraint residuals */ + virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); + + /** Method to return: + * 1) The structure of the jacobian (if "values" is NULL) + * 2) The values of the jacobian (if "values" is not NULL) + */ + virtual bool eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values); + + /** Method to return: + * 1) The structure of the hessian of the lagrangian (if "values" is NULL) + * 2) The values of the hessian of the lagrangian (if "values" is not NULL) + */ + virtual bool eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values); + + /** This method is called when the algorithm is complete so the TNLP can store/write the solution */ + virtual void finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value); + + virtual const SosInfo * sosConstraints() const{return NULL;} + virtual const BranchingInfo* branchingInfo() const{return NULL;} + + const double * getX(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value for the primal variables. + + const double * getGrad(); //Returns a pointer to a matrix of size of 1*numVars_ + //with final value of gradient for the primal variables. + + const double * getHess(); //Returns a pointer to a matrix of size of numVars_*numVars_ + //with final value of hessian for the primal variables. + + double getObjVal(); //Returns the output of the final value of the objective. + + double iterCount(); //Returns the iteration count + + int returnStatus(); //Returns the status count +}; + +#endif diff --git a/sci_gateway/cpp/sci_QuadTMINLP.cpp b/sci_gateway/cpp/sci_QuadTMINLP.cpp new file mode 100644 index 0000000..a424b47 --- /dev/null +++ b/sci_gateway/cpp/sci_QuadTMINLP.cpp @@ -0,0 +1,230 @@ +// Copyright (C) 2016 - IIT Bombay - FOSSEE +// +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in + +#include "QuadTMINLP.hpp" +#include "IpIpoptData.hpp" + +extern "C"{ +#include <sciprint.h> +} + +// Go to http://coin-or.org/Ipopt and http://coin-or.org/Bonmin for the details of the below methods + +// Set the type of every variable - CONTINUOUS or INTEGER +bool QuadTMINLP::get_variables_types(Index n, VariableType* var_types) +{ + n = numVars_; + for(int i=0; i < n; i++) + var_types[i] = CONTINUOUS; + for(int i=0 ; i < intconSize_ ; ++i) + var_types[(int)(intcon_[i]-1)] = INTEGER; + return true; +} + +// The linearity of the variables - LINEAR or NON_LINEAR +bool QuadTMINLP::get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types) +{ + /* + n = numVars_; + for(int i = 0; i < n; i++) + var_types[i] = Ipopt::TNLP::LINEAR; + */ + return true; +} + +// The linearity of the constraints - LINEAR or NON_LINEAR +bool QuadTMINLP::get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types) +{ + m = numCons_; + for(int i = 0; i < m; i++) + const_types[i] = Ipopt::TNLP::LINEAR; + return true; +} + +// Get MINLP info such as the number of variables,constraints,no.of elements in jacobian and hessian to allocate memory +bool QuadTMINLP::get_nlp_info(Index& n, Index&m, Index& nnz_jac_g, Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style) +{ + n=numVars_; // Number of variables + m=numCons_; // Number of constraints + nnz_jac_g = n*m; // No. of elements in Jacobian of constraints + nnz_h_lag = (n*(n+1))/2; // No. of elements in lower traingle of Hessian of the Lagrangian. + index_style=TNLP::C_STYLE; // Index style of matrices + return true; +} + +// Get the variables and constraints bound info +bool QuadTMINLP::get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u) +{ + unsigned int i; + for(i=0;i<n;i++){ + x_l[i]=varLB_[i]; + x_u[i]=varUB_[i]; + } + + for(i=0;i<m;i++){ + g_l[i]=conLB_[i]; + g_u[i]=conUB_[i]; + } + return true; +} + +// This method sets initial values for all the required vectors. We take 0 by default. +bool QuadTMINLP::get_starting_point(Index n, bool init_x, Number* x, + bool init_z, Number* z_L, Number* z_U, + Index m, bool init_lambda, + Number* lambda) +{ + if (init_x == true){ //we need to set initial values for vector x + for (Index var=0;var<n;var++) + x[var]=varGuess_[var];//initialize with 0 or we can change. + } + + if (init_z == true){ //we need to provide initial values for vector bound multipliers + for (Index var=0;var<n;++var){ + z_L[var]=0.0; //initialize with 0 or we can change. + z_U[var]=0.0;//initialize with 0 or we can change. + } + } + + if (init_lambda == true){ //we need to provide initial values for lambda values. + for (Index var=0;var<m;++var){ + lambda[var]=0.0; //initialize with 0 or we can change. + } + } + + return true; +} + +// Evaluate the objective function at a point +bool QuadTMINLP::eval_f(Index n, const Number* x, bool new_x, Number& obj_value) +{ + unsigned int i,j; + obj_value=0; + for (i=0;i<n;i++){ + for (j=0;j<n;j++){ + obj_value+=0.5*x[i]*x[j]*qMatrix_[n*i+j]; + } + obj_value+=x[i]*lMatrix_[i]; + } + return true; +} + +// Get the value of gradient of objective function at vector x. +bool QuadTMINLP::eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f) +{ + unsigned int i,j; + for(i=0;i<n;i++) + { + grad_f[i]=lMatrix_[i]; + for(j=0;j<n;j++) + { + grad_f[i]+=(qMatrix_[n*i+j])*x[j]; + } + } + return true; +} + +// Get the values of constraints at vector x. +bool QuadTMINLP::eval_g(Index n, const Number* x, bool new_x, Index m, Number* g) +{ + unsigned int i,j; + for(i=0;i<m;i++) + { + g[i]=0; + for(j=0;j<n;j++) + { + g[i]+=x[j]*conMatrix_[i+j*m]; + } + } + return true; +} + +// The Jacobian Matrix +bool QuadTMINLP::eval_jac_g(Index n, const Number* x, bool new_x, + Index m, Index nnz_jac, Index* iRow, Index *jCol, + Number* values) +{ + //It asks for the structure of the jacobian. + if (values==NULL){ //Structure of jacobian (full structure) + int index=0; + for (int var=0;var<m;++var)//no. of constraints + for (int flag=0;flag<n;++flag){//no. of variables + iRow[index]=var; + jCol[index]=flag; + index++; + } + } + //It asks for values + else { + int index=0; + for (int var=0;var<m;++var) + for (int flag=0;flag<n;++flag) + values[index++]=conMatrix_[var+flag*m]; + } + return true; +} + +/* +The structure of the Hessain matrix and the values +*/ +bool QuadTMINLP::eval_h(Index n, const Number* x, bool new_x, + Number obj_factor, Index m, const Number* lambda, + bool new_lambda, Index nele_hess, Index* iRow, + Index* jCol, Number* values) +{ + if (values==NULL){ + Index idx=0; + for (Index row = 0; row < n; row++) { + for (Index col = 0; col <= row; col++) { + iRow[idx] = row; + jCol[idx] = col; + idx++; + } + } + } + else { + Index index=0; + for (Index row=0;row < n;++row){ + for (Index col=0; col <= row; ++col){ + values[index++]=obj_factor*(qMatrix_[n*row+col]); + } + } + } + return true; +} + +void QuadTMINLP::finalize_solution(TMINLP::SolverReturn status, Index n, const Number* x,Number obj_value) +{ + + finalX_ = (double*)malloc(sizeof(double) * numVars_ * 1); + for (Index i=0; i<n; i++) + { + finalX_[i] = x[i]; + } + + finalObjVal_ = obj_value; + status_ = status; +} + +const double * QuadTMINLP::getX() +{ + return finalX_; +} + +double QuadTMINLP::getObjVal() +{ + return finalObjVal_; +} + +int QuadTMINLP::returnStatus() +{ + return status_; +} diff --git a/sci_gateway/cpp/sci_iofunc.cpp b/sci_gateway/cpp/sci_iofunc.cpp new file mode 100644 index 0000000..f05839c --- /dev/null +++ b/sci_gateway/cpp/sci_iofunc.cpp @@ -0,0 +1,333 @@ +// Symphony Toolbox for Scilab +// (Definition of) Functions for input and output from Scilab +// By Keyur Joshi + +#include "api_scilab.h" +#include "Scierror.h" +#include "sciprint.h" +#include "BOOL.h" +#include <localization.h> +#include "call_scilab.h" +#include <string.h> + + +using namespace std; + +int getDoubleFromScilab(int argNum, double *dest) +{ + //data declarations + SciErr sciErr; + int iRet,*varAddress; + const char errMsg[]="Wrong type for input argument #%d: A double is expected.\n"; + const int errNum=999; + //get variable address + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + //check that it is a non-complex double + if ( !isDoubleType(pvApiCtx,varAddress) || isVarComplex(pvApiCtx,varAddress) ) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + //retrieve and store + iRet = getScalarDouble(pvApiCtx, varAddress, dest); + if(iRet) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + return 0; +} + +int getUIntFromScilab(int argNum, int *dest) +{ + SciErr sciErr; + int iRet,*varAddress; + double inputDouble; + const char errMsg[]="Wrong type for input argument #%d: A nonnegative integer is expected.\n"; + const int errNum=999; + //same steps as above + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + if ( !isDoubleType(pvApiCtx,varAddress) || isVarComplex(pvApiCtx,varAddress) ) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + iRet = getScalarDouble(pvApiCtx, varAddress, &inputDouble); + //check that an unsigned int is stored in the double by casting and recasting + if(iRet || ((double)((unsigned int)inputDouble))!=inputDouble) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + *dest=(unsigned int)inputDouble; + return 0; +} + +int getIntFromScilab(int argNum, int *dest) +{ + SciErr sciErr; + int iRet,*varAddress; + double inputDouble; + const char errMsg[]="Wrong type for input argument #%d: An integer is expected.\n"; + const int errNum=999; + //same steps as above + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + if ( !isDoubleType(pvApiCtx,varAddress) || isVarComplex(pvApiCtx,varAddress) ) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + iRet = getScalarDouble(pvApiCtx, varAddress, &inputDouble); + //check that an int is stored in the double by casting and recasting + if(iRet || ((double)((int)inputDouble))!=inputDouble) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + *dest=(int)inputDouble; + return 0; +} + +int getFixedSizeDoubleMatrixFromScilab(int argNum, int rows, int cols, double **dest) +{ + int *varAddress,inputMatrixRows,inputMatrixCols; + SciErr sciErr; + const char errMsg[]="Wrong type for input argument #%d: A matrix of double of size %d by %d is expected.\n"; + const int errNum=999; + //same steps as above + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + if ( !isDoubleType(pvApiCtx,varAddress) || isVarComplex(pvApiCtx,varAddress) ) + { + Scierror(errNum,errMsg,argNum,rows,cols); + return 1; + } + sciErr = getMatrixOfDouble(pvApiCtx, varAddress, &inputMatrixRows, &inputMatrixCols,NULL); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + //check that the matrix has the correct number of rows and columns + if(inputMatrixRows!=rows || inputMatrixCols!=cols) + { + Scierror(errNum,errMsg,argNum,rows,cols); + return 1; + } + getMatrixOfDouble(pvApiCtx, varAddress, &inputMatrixRows, &inputMatrixCols, dest); + return 0; +} + +int getDoubleMatrixFromScilab(int argNum, int *rows, int *cols, double **dest) +{ + int *varAddress; + SciErr sciErr; + const char errMsg[]="Wrong type for input argument #%d: A matrix of double is expected.\n"; + const int errNum=999; + //same steps as above + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + if ( !isDoubleType(pvApiCtx,varAddress) || isVarComplex(pvApiCtx,varAddress) ) + { + Scierror(errNum,errMsg,argNum); + return 1; + } + getMatrixOfDouble(pvApiCtx, varAddress, rows, cols, dest); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + return 0; +} + +int getFixedSizeDoubleMatrixInList(int argNum, int itemPos, int rows, int cols, double **dest) +{ + int *varAddress,inputMatrixRows,inputMatrixCols; + SciErr sciErr; + const char errMsg[]="Wrong type for input argument #%d: A matrix of double of size %d by %d is expected.\n"; + const int errNum=999; + //same steps as above + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + + getMatrixOfDoubleInList(pvApiCtx, varAddress, itemPos, &rows, &cols, dest); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + return 0; +} + +int getStringFromScilab(int argNum,char **dest) +{ + int *varAddress,inputMatrixRows,inputMatrixCols; + SciErr sciErr; + sciErr = getVarAddressFromPosition(pvApiCtx, argNum, &varAddress); + + //check whether there is an error or not. + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + if ( !isStringType(pvApiCtx,varAddress) ) + { + Scierror(999,"Wrong type for input argument 1: A file name is expected.\n"); + return 1; + } + //read the value in that pointer pointing to file name + getAllocatedSingleString(pvApiCtx, varAddress, dest); + +} + +bool getFunctionFromScilab(int n,char name[], double *x,int posFirstElementOnStackForSF,int nOfRhsOnSF,int nOfLhsOnSF, double **dest) +{ + double check; + createMatrixOfDouble(pvApiCtx, posFirstElementOnStackForSF, 1, n, x); + C2F(scistring)(&posFirstElementOnStackForSF,name,&nOfLhsOnSF,&nOfRhsOnSF,(unsigned long)strlen(name)); + + if(getDoubleFromScilab(posFirstElementOnStackForSF+1,&check)) + { + return true; + } + if (check==1) + { + return true; + } + else + { + int x_rows, x_cols; + if(getDoubleMatrixFromScilab(posFirstElementOnStackForSF, &x_rows, &x_cols, dest)) + { + sciprint("No results "); + return true; + + } + } + return 0; +} + +bool getHessFromScilab(int n,int numConstr_,char name[], double *x,double *obj,double *lambda,int posFirstElementOnStackForSF,int nOfRhsOnSF,int nOfLhsOnSF, double **dest) +{ + double check; + createMatrixOfDouble(pvApiCtx, posFirstElementOnStackForSF, 1, n, x); + createMatrixOfDouble(pvApiCtx, posFirstElementOnStackForSF+1, 1, 1, obj); + createMatrixOfDouble(pvApiCtx, posFirstElementOnStackForSF+2, 1, numConstr_, lambda); + C2F(scistring)(&posFirstElementOnStackForSF,name,&nOfLhsOnSF,&nOfRhsOnSF,(unsigned long)strlen(name)); + + if(getDoubleFromScilab(posFirstElementOnStackForSF+1,&check)) + { + return true; + } + if (check==1) + { + return true; + } + else + { + int x_rows, x_cols; + if(getDoubleMatrixFromScilab(posFirstElementOnStackForSF, &x_rows, &x_cols, dest)) + { + sciprint("No results "); + return 1; + } + } + return 0; +} + +int return0toScilab() +{ + int iRet; + //create variable in scilab + iRet = createScalarDouble(pvApiCtx, nbInputArgument(pvApiCtx)+1,0); + if(iRet) + { + /* If error, no return variable */ + AssignOutputVariable(pvApiCtx, 1) = 0; + return 1; + } + //make it the output variable + AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx)+1; + //return it to scilab + //ReturnArguments(pvApiCtx); + return 0; +} + +int returnDoubleToScilab(double retVal) +{ + int iRet; + //same steps as above + iRet = createScalarDouble(pvApiCtx, nbInputArgument(pvApiCtx)+1,retVal); + if(iRet) + { + /* If error, no return variable */ + AssignOutputVariable(pvApiCtx, 1) = 0; + return 1; + } + AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx)+1; + //ReturnArguments(pvApiCtx); + return 0; +} + +int returnDoubleMatrixToScilab(int itemPos, int rows, int cols, double *dest) +{ + SciErr sciErr; + //same steps as above + sciErr = createMatrixOfDouble(pvApiCtx, nbInputArgument(pvApiCtx) + itemPos, rows, cols, dest); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + + AssignOutputVariable(pvApiCtx, itemPos) = nbInputArgument(pvApiCtx)+itemPos; + + return 0; +} + +int returnIntegerMatrixToScilab(int itemPos, int rows, int cols, int *dest) +{ + SciErr sciErr; + //same steps as above + sciErr = createMatrixOfInteger32(pvApiCtx, nbInputArgument(pvApiCtx) + itemPos, rows, cols, dest); + if (sciErr.iErr) + { + printError(&sciErr, 0); + return 1; + } + + AssignOutputVariable(pvApiCtx, itemPos) = nbInputArgument(pvApiCtx)+itemPos; + + return 0; +} + + diff --git a/sci_gateway/cpp/sci_iofunc.hpp b/sci_gateway/cpp/sci_iofunc.hpp new file mode 100644 index 0000000..7e18951 --- /dev/null +++ b/sci_gateway/cpp/sci_iofunc.hpp @@ -0,0 +1,25 @@ +// Symphony Toolbox for Scilab +// (Declaration of) Functions for input and output from Scilab +// By Keyur Joshi + +#ifndef SCI_IOFUNCHEADER +#define SCI_IOFUNCHEADER + +//input +int getDoubleFromScilab(int argNum, double *dest); +int getUIntFromScilab(int argNum, int *dest); +int getIntFromScilab(int argNum, int *dest); +int getFixedSizeDoubleMatrixFromScilab(int argNum, int rows, int cols, double **dest); +int getDoubleMatrixFromScilab(int argNum, int *rows, int *cols, double **dest); +int getFixedSizeDoubleMatrixInList(int argNum, int itemPos, int rows, int cols, double **dest); +int getStringFromScilab(int argNum,char** dest); +bool getFunctionFromScilab(int n,char name[], double *x,int posFirstElementOnStackForSF,int nOfRhsOnSF,int nOfLhsOnSF, double **dest); +bool getHessFromScilab(int n,int numConstr_,char name[], double *x,double *obj,double *lambda,int posFirstElementOnStackForSF,int nOfRhsOnSF,int nOfLhsOnSF, double **dest); + +//output +int return0toScilab(); +int returnDoubleToScilab(double retVal); +int returnDoubleMatrixToScilab(int itemPos, int rows, int cols, double *dest); +int returnIntegerMatrixToScilab(int itemPos, int rows, int cols, int *dest); + +#endif //SCI_IOFUNCHEADER diff --git a/sci_gateway/cpp/sci_minbndTMINLP.cpp b/sci_gateway/cpp/sci_minbndTMINLP.cpp new file mode 100644 index 0000000..f26c089 --- /dev/null +++ b/sci_gateway/cpp/sci_minbndTMINLP.cpp @@ -0,0 +1,218 @@ +// Copyright (C) 2015 - IIT Bombay - FOSSEE +// +// Author: Harpreet Singh +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt + +#include "minbndTMINLP.hpp" +#include "sci_iofunc.hpp" + +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> +#include <string.h> +#include <assert.h> +} + +using namespace Ipopt; +using namespace Bonmin; + +minbndTMINLP::~minbndTMINLP() +{ + if(finalX_) delete[] finalX_; +} + +// Set the type of every variable - CONTINUOUS or INTEGER +bool minbndTMINLP::get_variables_types(Index n, VariableType* var_types) +{ + n = numVars_; + for(int i=0; i < n; i++) + var_types[i] = CONTINUOUS; + for(int i=0 ; i < intconSize_ ; ++i) + var_types[(int)(intcon_[i]-1)] = INTEGER; + return true; +} + +// The linearity of the variables - LINEAR or NON_LINEAR +bool minbndTMINLP::get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types) +{ return true; } + +// The linearity of the constraints - LINEAR or NON_LINEAR +bool minbndTMINLP::get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types) +{ return true;} + +//get NLP info such as number of variables,constraints,no.of elements in jacobian and hessian to allocate memory +bool minbndTMINLP::get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style) +{ + n=numVars_; // Number of variables + m=0; // Number of constraints + nnz_jac_g = 0; // No. of elements in Jacobian of constraints + nnz_h_lag = n*(n+1)/2; // No. of elements in lower traingle of Hessian of the Lagrangian. + index_style=TNLP::C_STYLE; // Index style of matrices + return true; +} + +//get variable and constraint bound info +bool minbndTMINLP::get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u) +{ + unsigned int i; + for(i=0;i<n;i++) + { + x_l[i]=lb_[i]+0.0000001; + x_u[i]=ub_[i]-0.0000001; + } + + g_l=NULL; + g_u=NULL; + return true; +} + +// return the value of the constraints: g(x) +bool minbndTMINLP::eval_g(Index n, const Number* x, bool new_x, Index m, Number* g) +{ + // return the value of the constraints: g(x) + g=NULL; + return true; +} + +// return the structure or values of the jacobian +bool minbndTMINLP::eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values) +{ + if (values == NULL) + { + // return the structure of the jacobian of the constraints + iRow=NULL; + jCol=NULL; + } + else + { + values=NULL; + } + return true; +} + +//get value of objective function at vector x +bool minbndTMINLP::eval_f(Index n, const Number* x, bool new_x, Number& obj_value) +{ + char name[20]="_f"; + Number *obj; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&obj)) + { + return false; + } + obj_value = *obj; + return true; +} + +//get value of gradient of objective function at vector x. +bool minbndTMINLP::eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f) +{ + char name[20]="_gradf"; + Number *resg; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&resg)) + { + return false; + } + + Index i; + for(i=0;i<numVars_;i++) + { + grad_f[i]=resg[i]; + } + return true; +} + +// This method sets initial values for required vectors . For now we are assuming 0 to all values. +bool minbndTMINLP::get_starting_point(Index n, bool init_x, Number* x,bool init_z, Number* z_L, Number* z_U,Index m, bool init_lambda,Number* lambda) +{ + assert(init_x == true); + assert(init_z == false); + assert(init_lambda == false); + if (init_x == true) + { //we need to set initial values for vector x + for (Index var=0;var<n;var++) + {x[var]=0.0;}//initialize with 0. + } + return true; +} + +/* + * Return either the sparsity structure of the Hessian of the Lagrangian, + * or the values of the Hessian of the Lagrangian for the given values for + * x,lambda,obj_factor. +*/ + +bool minbndTMINLP::eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values) +{ + double check; + if (values==NULL) + { + Index idx=0; + for (Index row = 0; row < numVars_; row++) + { + for (Index col = 0; col <= row; col++) + { iRow[idx] = row; + jCol[idx] = col; + idx++; + } + } + } + + else + { char name[20]="_gradhess"; + Number *resh; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&resh)) + { + return false; + } + Index index=0; + for (Index row=0;row < numVars_ ;++row) + { + for (Index col=0; col <= row; ++col) + { + values[index++]=obj_factor*(resh[numVars_*row+col]); + } + } + } + return true; +} + +void minbndTMINLP::finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value) +{ + finalObjVal_ = obj_value; + status_ = status; + if(status==0 ||status== 3) + { + finalX_ = new double[n]; + for (Index i=0; i<numVars_; i++) + { + finalX_[i] = x[i]; + } + } + +} + +const double * minbndTMINLP::getX() +{ + return finalX_; +} + +double minbndTMINLP::getObjVal() +{ + return finalObjVal_; +} + +int minbndTMINLP::returnStatus() +{ + return status_; +} diff --git a/sci_gateway/cpp/sci_minconTMINLP.cpp b/sci_gateway/cpp/sci_minconTMINLP.cpp new file mode 100644 index 0000000..350594d --- /dev/null +++ b/sci_gateway/cpp/sci_minconTMINLP.cpp @@ -0,0 +1,324 @@ +// Copyright (C) 2015 - IIT Bombay - FOSSEE +// +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt + +#include "minconTMINLP.hpp" +#include "sci_iofunc.hpp" + +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> +#include <string.h> +#include <assert.h> +} + +using namespace Ipopt; +using namespace Bonmin; + +//#define DEBUG 0 + +minconTMINLP::~minconTMINLP() +{ + if(finalX_) delete[] finalX_; +} + +// Set the type of every variable - CONTINUOUS or INTEGER +bool minconTMINLP::get_variables_types(Index n, VariableType* var_types) +{ + #ifdef DEBUG + sciprint("Code is in get_variables_types\n"); + #endif + n = numVars_; + for(int i=0; i < n; i++) + var_types[i] = CONTINUOUS; + for(int i=0 ; i < intconSize_ ; ++i) + var_types[(int)(intcon_[i]-1)] = INTEGER; + return true; +} + +// The linearity of the variables - LINEAR or NON_LINEAR +bool minconTMINLP::get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types) +{ + #ifdef DEBUG + sciprint("Code is in get_variables_linearity\n"); + #endif + for(int i=0;i<n;i++) + { + var_types[i] = Ipopt::TNLP::NON_LINEAR; + } + return true; } + +// The linearity of the constraints - LINEAR or NON_LINEAR +bool minconTMINLP::get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types) +{ + + #ifdef DEBUG + sciprint("Code is in get_constraints_linearity\n"); + #endif + for(int i=0;i<numLC_;i++) + { + const_types[i] = Ipopt::TNLP::LINEAR; + } + + for(int i=numLC_;i<m;i++) + { + const_types[i] = Ipopt::TNLP::NON_LINEAR; + } + return true;} + +//get NLP info such as number of variables,constraints,no.of elements in jacobian and hessian to allocate memory +bool minconTMINLP::get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style) +{ + #ifdef DEBUG + sciprint("Code is in get_nlp_info\n"); + #endif + n=numVars_; // Number of variables + m=numCons_; // Number of constraints + nnz_jac_g = n*m; // No. of elements in Jacobian of constraints + nnz_h_lag = n*n; // No. of elements in Hessian of the Lagrangian. + index_style=TNLP::C_STYLE; // Index style of matrices + return true; +} + +//get variable and constraint bound info +bool minconTMINLP::get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u) +{ + #ifdef DEBUG + sciprint("Code is in get_bounds_info\n"); + #endif + unsigned int i; + for(i=0;i<n;i++) + { + x_l[i]=lb_[i]; + x_u[i]=ub_[i]; + } + for(i=0;i<m;i++) + { + g_l[i]=conLb_[i]; + g_u[i]=conUb_[i]; + } + return true; +} + +// This method sets initial values for required vectors . For now we are assuming 0 to all values. +bool minconTMINLP::get_starting_point(Index n, bool init_x, Number* x,bool init_z, Number* z_L, Number* z_U,Index m, bool init_lambda,Number* lambda) +{ + assert(init_x == true); + assert(init_z == false); + assert(init_lambda == false); + if (init_x == true) + { //we need to set initial values for vector x + for (Index var=0;var<n;var++) + {x[var]=x0_[var];}//initialize with 0. + } + return true; +} + +//get value of objective function at vector x +bool minconTMINLP::eval_f(Index n, const Number* x, bool new_x, Number& obj_value) +{ + #ifdef DEBUG + sciprint("Code is eval_f\n"); + #endif + char name[20]="_f"; + Number *obj; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&obj)) + { + return false; + } + obj_value = *obj; + return true; +} + +//get value of gradient of objective function at vector x. +bool minconTMINLP::eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f) +{ + #ifdef DEBUG + sciprint("Code is in eval_grad_f\n"); + #endif + char name[20]="_gradf"; + Number *resg; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&resg)) + { + return false; + } + + Index i; + for(i=0;i<numVars_;i++) + { + grad_f[i]=resg[i]; + } + return true; +} + +// return the value of the constraints: g(x) +bool minconTMINLP::eval_g(Index n, const Number* x, bool new_x, Index m, Number* g) +{ + #ifdef DEBUG + sciprint("Code is in eval_g\n"); + #endif + // return the value of the constraints: g(x) + if(m==0) + { + g=NULL; + } + else + { + char name[20]="_addnlc"; + Number *con; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&con)) + { + return false; + } + + Index i; + for(i=0;i<m;i++) + { + g[i]=con[i]; + } + } + + return true; +} + +// return the structure or values of the jacobian +bool minconTMINLP::eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values) +{ + #ifdef DEBUG + sciprint("Code is in eval_jac_g\n"); + #endif + if (values == NULL) + { + if(m==0)// return the structure of the jacobian of the constraints + { + iRow=NULL; + jCol=NULL; + } + else + { + unsigned int i,j,idx=0; + for(i=0;i<m;i++) + for(j=0;j<n;j++) + { + iRow[idx]=i; + jCol[idx]=j; + idx++; + } + } + } + else + { + if(m==0) + { + values=NULL; + } + else + { + double* resj; + char name[20]="_gradnlc"; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&resj)) + { + return false; + } + int c = 0; + for(int i=0;i<m;i++) + { + for(int j=0;j<n;j++) + { + values[c] = resj[j*(int)m+i]; + c++; + } + } + } + } + return true; +} + +/* + * Return either the sparsity structure of the Hessian of the Lagrangian, + * or the values of the Hessian of the Lagrangian for the given values for + * x,lambda,obj_factor. +*/ + +bool minconTMINLP::eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values) +{ + #ifdef DEBUG + sciprint("Code is in eval_h\n"); + #endif + double check; + if (values==NULL) + { + Index idx=0; + for (Index row = 0; row < numVars_; row++) + { + for (Index col = 0; col < numVars_; col++) + { + iRow[idx] = row; + jCol[idx] = col; + idx++; + } + } + } + else + { char name[20]="_gradhess"; + Number *resCh; + if (getHessFromScilab(n,m,name,x, &obj_factor, lambda, 7, 3,2,&resCh)) + { + return false; + } + Index index=0; + for (Index row=0;row < numVars_ ;++row) + { + for (Index col=0; col < numVars_; ++col) + { + values[index++]=resCh[numVars_*row+col]; + } + } + } + return true; +} + +void minconTMINLP::finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value) +{ + #ifdef DEBUG + sciprint("Code is in finalize_solution\n"); + sciprint("%d",status); + #endif + finalObjVal_ = obj_value; + status_ = status; + if(status==0 ||status== 3) + { + finalX_ = new double[n]; + for (Index i=0; i<numVars_; i++) + { + finalX_[i] = x[i]; + } + } +} + +const double * minconTMINLP::getX() +{ + return finalX_; +} + +double minconTMINLP::getObjVal() +{ + return finalObjVal_; +} + +int minconTMINLP::returnStatus() +{ + return status_; +} diff --git a/sci_gateway/cpp/sci_minuncTMINLP.cpp b/sci_gateway/cpp/sci_minuncTMINLP.cpp new file mode 100644 index 0000000..a3212aa --- /dev/null +++ b/sci_gateway/cpp/sci_minuncTMINLP.cpp @@ -0,0 +1,236 @@ +// Copyright (C) 2015 - IIT Bombay - FOSSEE +// +// Author: Harpreet Singh, Pranav Deshpande and Akshay Miterani +// Organization: FOSSEE, IIT Bombay +// Email: toolbox@scilab.in +// This file must be used under the terms of the CeCILL. +// This source file is licensed as described in the file COPYING, which +// you should have received as part of this distribution. The terms +// are also available at +// http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt + +#include "minuncTMINLP.hpp" +#include "sci_iofunc.hpp" + +extern "C" +{ +#include "call_scilab.h" +#include <api_scilab.h> +#include <Scierror.h> +#include <BOOL.h> +#include <localization.h> +#include <sciprint.h> +#include <string.h> +#include <assert.h> +} + +using namespace Ipopt; +using namespace Bonmin; + +minuncTMINLP::~minuncTMINLP() +{ + if(finalX_) delete[] finalX_; +} + +// Set the type of every variable - CONTINUOUS or INTEGER +bool minuncTMINLP::get_variables_types(Index n, VariableType* var_types) +{ + n = numVars_; + for(int i=0; i < n; i++) + var_types[i] = CONTINUOUS; + for(int i=0 ; i < intconSize_ ; ++i) + var_types[(int)(intcon_[i]-1)] = INTEGER; + return true; +} + +// The linearity of the variables - LINEAR or NON_LINEAR +bool minuncTMINLP::get_variables_linearity(Index n, Ipopt::TNLP::LinearityType* var_types) +{ + /* + n = numVars_; + for(int i = 0; i < n; i++) + var_types[i] = Ipopt::TNLP::LINEAR; + */ + return true; +} + +// The linearity of the constraints - LINEAR or NON_LINEAR +bool minuncTMINLP::get_constraints_linearity(Index m, Ipopt::TNLP::LinearityType* const_types) +{ + /* m = numConstr_; + for(int i = 0; i < m; i++) + const_types[i] = Ipopt::TNLP::LINEAR; + */ + return true; +} + +//get NLP info such as number of variables,constraints,no.of elements in jacobian and hessian to allocate memory +bool minuncTMINLP::get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, Index& nnz_h_lag, TNLP::IndexStyleEnum& index_style) +{ + n=numVars_; // Number of variables + m=0; // Number of constraints + nnz_jac_g = 0; // No. of elements in Jacobian of constraints + nnz_h_lag = n*(n+1)/2; // No. of elements in lower traingle of Hessian of the Lagrangian. + index_style=TNLP::C_STYLE; // Index style of matrices + return true; +} + +//get variable and constraint bound info +bool minuncTMINLP::get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u) +{ + unsigned int i; + for(i=0;i<n;i++) + { + x_l[i]=-1.0e19; + x_u[i]=1.0e19; + } + + g_l=NULL; + g_u=NULL; + return true; +} + +// return the value of the constraints: g(x) +bool minuncTMINLP::eval_g(Index n, const Number* x, bool new_x, Index m, Number* g) +{ + // return the value of the constraints: g(x) + g=NULL; + return true; +} + +// return the structure or values of the jacobian +bool minuncTMINLP::eval_jac_g(Index n, const Number* x, bool new_x,Index m, Index nele_jac, Index* iRow, Index *jCol,Number* values) +{ + if (values == NULL) + { + // return the structure of the jacobian of the constraints + iRow=NULL; + jCol=NULL; + } + else + { + values=NULL; + } + + return true; +} + +//get value of objective function at vector x +bool minuncTMINLP::eval_f(Index n, const Number* x, bool new_x, Number& obj_value) +{ + char name[20]="_f"; + Number *obj; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&obj)) + { + return false; + } + obj_value = *obj; + return true; +} + +//get value of gradient of objective function at vector x. +bool minuncTMINLP::eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f) +{ + char name[20]="_gradf"; + Number *resg; + if (getFunctionFromScilab(n,name,x, 7, 1, 2, &resg)) + { + return false; + } + + Index i; + for(i=0;i<numVars_;i++) + { + grad_f[i]=resg[i]; + } + return true; +} + +// This method sets initial values for required vectors . For now we are assuming 0 to all values. +bool minuncTMINLP::get_starting_point(Index n, bool init_x, Number* x,bool init_z, Number* z_L, Number* z_U,Index m, bool init_lambda,Number* lambda) +{ + assert(init_x == true); + assert(init_z == false); + assert(init_lambda == false); + if (init_x == true) + { //we need to set initial values for vector x + for (Index var=0;var<n;var++) + x[var]=varGuess_[var];//initialize with 0 or we can change. + } + + return true; +} + +/* + * Return either the sparsity structure of the Hessian of the Lagrangian, + * or the values of the Hessian of the Lagrangian for the given values for + * x,lambda,obj_factor. +*/ + +bool minuncTMINLP::eval_h(Index n, const Number* x, bool new_x,Number obj_factor, Index m, const Number* lambda,bool new_lambda, Index nele_hess, Index* iRow,Index* jCol, Number* values) +{ + double check; + if (values==NULL) + { + Index idx=0; + for (Index row = 0; row < numVars_; row++) + { + for (Index col = 0; col <= row; col++) + { + iRow[idx] = row; + jCol[idx] = col; + idx++; + } + } + } + + else + { + char name[20]="_gradhess"; + Number *resh; + if (getFunctionFromScilab(n,name,x, 7, 1,2,&resh)) + { + return false; + } + Index index=0; + for (Index row=0;row < numVars_ ;++row) + { + for (Index col=0; col <= row; ++col) + { + values[index++]=obj_factor*(resh[numVars_*row+col]); + } + } + return true; + } +} + + +void minuncTMINLP::finalize_solution(SolverReturn status,Index n, const Number* x, Number obj_value) +{ + finalObjVal_ = obj_value; + status_ = status; + if(status==0 ||status== 3) + { + finalX_ = new double[n]; + for (Index i=0; i<numVars_; i++) + { + finalX_[i] = x[i]; + } + } + +} + +const double * minuncTMINLP::getX() +{ + return finalX_; +} + +double minuncTMINLP::getObjVal() +{ + return finalObjVal_; +} + +int minuncTMINLP::returnStatus() +{ + return status_; +} |