2016年2月9日火曜日

LocalSolver(4) : 計算結果の再取得から最適化、データ格納

LocalSolver(3) : データベースの連携と結果格納で得られたデータを再度取り出し、最適化を実施します。

 [knapsack03.java]

********** Knapsack03.java **********/
import java.sql.*;
import java.util.*;
import java.io.*;
import localsolver.*;

public class Knapsack03 {
    /* Number of items. */
    int nbItems;
    int facility_id[];

    /* Items properties. */
    double[] weights;
    double[] values;

    //public int[] getValues(){ return this.values;}
    //public int[] getWeights(){ return this.weights;}

    /* Knapsack bound */
    int knapsackBound;

    /* Solver. */
    LocalSolver localsolver;

    /* LS Program variables. */
    LSExpression[] x;

    /* Solutions (classes at each position). */
    List solutions;

    public Knapsack03(int n, int knapsackBound, int facility_id[], double r[], double throughput[]){
        nbItems = n;
        weights = r;
        values = throughput;
        this.knapsackBound = knapsackBound;
        this.facility_id = facility_id;
    }

    void solve(int limit) {
        try {
            /* Declares the optimization model. */
            localsolver = new LocalSolver();
            LSModel model = localsolver.getModel();
            x = new LSExpression[nbItems];

            System.out.println("nbItems="+nbItems);
            System.out.println("knapsackBound="+knapsackBound);

            // boolean variables x[i]
            for (int i = 0; i < nbItems; i++) {
                x[i] = model.boolVar();
                x[i].setName("x[" + i + "]");
            }

            // weight constraint
            LSExpression weightSum = model.sum();
            for (int i = 0; i < nbItems; i++) {
                LSExpression itemWeight = model.prod(x[i],weights[i]);
                weightSum.addOperand(itemWeight);
            }
            model.constraint(model.leq(weightSum,knapsackBound));

            // maximize value
            LSExpression valueSum = model.sum();
            for (int i = 0; i < nbItems; i++) {
                LSExpression itemValue = model.prod(x[i],values[i]);
                valueSum.addOperand(itemValue);
            }

            model.maximize(valueSum);
            model.close();

            /* Parameterizes the solver. */
            LSPhase phase = localsolver.createPhase();
            phase.setTimeLimit(limit);

            localsolver.solve();

            solutions = new ArrayList();
            for (int i = 0; i < nbItems; i++)
                if (x[i].getValue() == 1)
            solutions.add(i);

        } catch (LSException e) {
            System.out.println("LSException:" + e.getMessage());
            System.exit(1);
        }
    }

    /* Writes the solution in a file */
    void writeSolution(String fileName, MySQL mysql) {
        try {
            BufferedWriter output = new BufferedWriter(new FileWriter(fileName));

            int idx[] = new int[solutions.size()];
            double obj = 0;
            for (int i = 0; i < solutions.size(); ++i){
                output.write(solutions.get(i) + " ");
                idx[i] = facility_id[solutions.get(i)]-1;
                obj += values[solutions.get(i)];
            }
            mysql.insertKnapsack(solutions.size(),obj);
            mysql.insertElement(idx);
            output.write("\n");

            output.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

     public static void main(String[] args) {

        int combination_id = 15, n = 0;;
        String outputFile = "result.txt";
        MySQL mysql = new MySQL(combination_id);

        ResultSet rs = mysql.selectCombinations();
        try {
                while(rs.next()){
                        n = rs.getInt("n");
                }
        }catch (SQLException e) {
                        e.printStackTrace();
        }

        int facility_id[] = new int[n];
        double l[] = new double[n];
        double r[] = new double[n];
        double throughput[] = new double[n];
        int index = 0;
        rs = mysql.selectPoints();
        try {
                while(rs.next()){
                        facility_id[index] = rs.getInt("facility_id");
                        l[index] = rs.getDouble("l");
                        r[index] = rs.getDouble("r");
                        throughput[index] = rs.getDouble("throughput");
                        index++;
                }
        }catch (SQLException e) {
                        e.printStackTrace();
        }

        Knapsack03 model = new Knapsack03(n, 2000, facility_id, r, throughput);
        String strTimeLimit = "10";
        model.solve(Integer.parseInt(strTimeLimit));
        if(outputFile != null) {
            model.writeSolution(outputFile, mysql);
        }
    }
}

class MySQL {

        String driver;
        String server, dbname, url, user, password;
        Connection con;
        Statement stmt;
        ResultSet rs;
        int combination_id,n;
        int id = -1;

        public MySQL(int combination_id) {
                this.combination_id = combination_id;
                this.driver = "org.gjt.mm.mysql.Driver";
                this.server = "xxxx.yyyy.com";
                this.dbname = "xxxx";
                this.url = "jdbc:mysql://" + server + "/" + dbname + "?useUnicode=true&characterEncoding=UTF-8";
                this.user = "xxxx";
                this.password = "zzzzzzzzzzzzzzzz";
                try {
                        this.con = DriverManager.getConnection(url, user, password);
                        this.stmt = con.createStatement ();
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        Class.forName (driver);
                } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        public void close(){
                try {
                        rs.close();
                        stmt.close();
                        con.close();
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        public ResultSet selectPoints(){

                String sql = "SELECT * FROM points where combination_id ="+this.combination_id;
                ResultSet rs = null;
                try {
                        rs = stmt.executeQuery (sql);
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return rs;
        }

        public ResultSet selectCombinations(){

                String sql = "SELECT * FROM combinations where id ="+this.combination_id;
                ResultSet rs = null;
                try {
                        rs = stmt.executeQuery (sql);
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return rs;
        }

        public void insertKnapsack(int n,double obj){
                String sql = "INSERT INTO knapsacks(n,obj) VALUES ("+n+","+obj+")";
                try {
                        stmt.execute (sql);
                        ResultSet rs1 = stmt.executeQuery("SELECT LAST_INSERT_ID() AS LAST");
                        if (rs1 != null && rs1.next()){
                                id = rs1.getInt("LAST");
                        }
                        System.out.println("Knapsack_ID="+id);
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }  //try catchで囲む
        }

        public void insertElement(int idx[]){
                int idex = 0;
                StringBuffer buf = new StringBuffer();
                buf.append("INSERT INTO elements(facility_id, knapsack_id) VALUES");
                for(int i = 0; i < idx.length; i++){//対象のDMUの係数を使い、全部のDMUのDEAを計算
                                idex = idx[i] +1;
                        if(i == idx.length -1)
                                buf.append("("+idex+","+this.id+")");
                        else
                                buf.append("("+idex+","+this.id+"),");

                }
                String sql4 = buf.toString();
                try {
                        stmt.execute (sql4);
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

}


0 件のコメント:

コメントを投稿