int OsiVolSolverInterface::readMps(const char *filename, const char *extension) { CoinMpsIO reader; reader.setInfinity(getInfinity()); int retVal = reader.readMps(filename, extension); loadProblem(*reader.getMatrixByCol(), reader.getColLower(), reader.getColUpper(), reader.getObjCoefficients(), reader.getRowLower(), reader.getRowUpper()); int nc = getNumCols(); assert (continuous_); CoinFillN(continuous_, nc, true); return retVal; }
void OsiVolSolverInterface::writeMps(const char *filename, const char *extension, double /*objSense*/) const { CoinMpsIO writer; writer.setMpsData(*getMatrixByCol(), getInfinity(), getColLower(), getColUpper(), getObjCoefficients(), reinterpret_cast<const char *> (NULL) /*integrality*/, getRowLower(), getRowUpper(), reinterpret_cast<const char **> (NULL) /*colnam*/, reinterpret_cast<const char **> (NULL) /*rownam*/); std::string fname = filename; if (extension) { if (extension[0] != '\0' && extension[0] != '.') fname += "." ; } fname += extension; writer.writeMps(fname.c_str()); }
/* Install the name information from a CoinMpsIO object. */ void OsiSolverInterface::setRowColNames (const CoinMpsIO &mps) { int nameDiscipline,m,n ; /* Determine how we're handling names. It's possible that the underlying solver has overridden getIntParam, but doesn't recognise OsiNameDiscipline. In that case, we want to default to auto names */ bool recognisesOsiNames = getIntParam(OsiNameDiscipline,nameDiscipline) ; if (recognisesOsiNames == false) { nameDiscipline = 0 ; } /* Whatever happens, we're about to clean out the current name vectors. Decide on an appropriate size and call reallocRowColNames to adjust capacity. */ if (nameDiscipline == 0) { m = 0 ; n = 0 ; } else { m = mps.getNumRows() ; n = mps.getNumCols() ; } reallocRowColNames(rowNames_,m,colNames_,n) ; /* If name discipline is auto, we're done already. Otherwise, load 'em up. If I understand MPS correctly, names are required. */ if (nameDiscipline != 0) { rowNames_.resize(m) ; for (int i = 0 ; i < m ; i++) { rowNames_[i] = mps.rowName(i) ; } objName_ = mps.getObjectiveName() ; colNames_.resize(n) ; for (int j = 0 ; j < n ; j++) { colNames_[j] = mps.columnName(j) ; } } return ; }
int main(int argc, const char *argv[]) { #if COIN_BIG_INDEX<2 ClpSimplex model; int status; int maxIts = 0; int maxFactor = 100; if (argc < 2) { #if defined(SAMPLEDIR) status = model.readMps(SAMPLEDIR "/p0033.mps", true); #else fprintf(stderr, "Do not know where to find sample MPS files.\n"); exit(1); #endif } else status = model.readMps(argv[1]); if (status) { printf("errors on input\n"); exit(77); } if (argc > 2) { maxFactor = atoi(argv[2]); printf("max factor %d\n", maxFactor); } if (argc > 3) { maxIts = atoi(argv[3]); printf("max its %d\n", maxIts); } // For now scaling off model.scaling(0); if (maxIts) { // Do partial dantzig ClpPrimalColumnSteepest dantzig(5); model.setPrimalColumnPivotAlgorithm(dantzig); //model.messageHandler()->setLogLevel(63); model.setFactorizationFrequency(maxFactor); model.setMaximumIterations(maxIts); model.primal(); if (!model.status()) exit(1); } // find gub int numberRows = model.numberRows(); int * gubStart = new int[numberRows+1]; int * gubEnd = new int[numberRows]; int * which = new int[numberRows]; int * whichGub = new int[numberRows]; int numberColumns = model.numberColumns(); int * mark = new int[numberColumns]; int iRow, iColumn; // delete variables fixed to zero const double * columnLower = model.columnLower(); const double * columnUpper = model.columnUpper(); int numberDelete = 0; for (iColumn = 0; iColumn < numberColumns; iColumn++) { if (columnUpper[iColumn] == 0.0 && columnLower[iColumn] == 0.0) mark[numberDelete++] = iColumn; } if (numberDelete) { model.deleteColumns(numberDelete, mark); numberColumns -= numberDelete; columnLower = model.columnLower(); columnUpper = model.columnUpper(); #if 0 CoinMpsIO writer; writer.setMpsData(*model.matrix(), COIN_DBL_MAX, model.getColLower(), model.getColUpper(), model.getObjCoefficients(), (const char*) 0 /*integrality*/, model.getRowLower(), model.getRowUpper(), NULL, NULL); writer.writeMps("cza.mps", 0, 0, 1); #endif } double * lower = new double[numberRows]; double * upper = new double[numberRows]; const double * rowLower = model.rowLower(); const double * rowUpper = model.rowUpper(); for (iColumn = 0; iColumn < numberColumns; iColumn++) mark[iColumn] = -1; CoinPackedMatrix * matrix = model.matrix(); // get row copy CoinPackedMatrix rowCopy = *matrix; rowCopy.reverseOrdering(); const int * column = rowCopy.getIndices(); const int * rowLength = rowCopy.getVectorLengths(); const CoinBigIndex * rowStart = rowCopy.getVectorStarts(); const double * element = rowCopy.getElements(); int putGub = numberRows; int putNonGub = numberRows; int * rowIsGub = new int [numberRows]; for (iRow = numberRows - 1; iRow >= 0; iRow--) { bool gubRow = true; int first = numberColumns + 1; int last = -1; for (int j = rowStart[iRow]; j < rowStart[iRow] + rowLength[iRow]; j++) { if (element[j] != 1.0) { gubRow = false; break; } else { int iColumn = column[j]; if (mark[iColumn] >= 0) { gubRow = false; break; } else { last = CoinMax(last, iColumn); first = CoinMin(first, iColumn); } } } if (last - first + 1 != rowLength[iRow] || !gubRow) { which[--putNonGub] = iRow; rowIsGub[iRow] = 0; } else { for (int j = rowStart[iRow]; j < rowStart[iRow] + rowLength[iRow]; j++) { int iColumn = column[j]; mark[iColumn] = iRow; } rowIsGub[iRow] = -1; putGub--; gubStart[putGub] = first; gubEnd[putGub] = last + 1; lower[putGub] = rowLower[iRow]; upper[putGub] = rowUpper[iRow]; whichGub[putGub] = iRow; } } int numberNonGub = numberRows - putNonGub; int numberGub = numberRows - putGub; if (numberGub > 0) { printf("** %d gub rows\n", numberGub); int numberNormal = 0; const int * row = matrix->getIndices(); const int * columnLength = matrix->getVectorLengths(); const CoinBigIndex * columnStart = matrix->getVectorStarts(); const double * elementByColumn = matrix->getElements(); int numberElements = 0; bool doLower = false; bool doUpper = false; for (iColumn = 0; iColumn < numberColumns; iColumn++) { if (mark[iColumn] < 0) { mark[numberNormal++] = iColumn; } else { numberElements += columnLength[iColumn]; if (columnLower[iColumn] != 0.0) doLower = true; if (columnUpper[iColumn] < 1.0e20) doUpper = true; } } if (!numberNormal) { printf("Putting back one gub row to make non-empty\n"); for (iColumn = gubStart[putGub]; iColumn < gubEnd[putGub]; iColumn++) mark[numberNormal++] = iColumn; putGub++; numberGub--; } ClpSimplex model2(&model, numberNonGub, which + putNonGub, numberNormal, mark); int numberGubColumns = numberColumns - numberNormal; // sort gubs so monotonic int * which = new int[numberGub]; int i; for (i = 0; i < numberGub; i++) which[i] = i; CoinSort_2(gubStart + putGub, gubStart + putGub + numberGub, which); int * temp1 = new int [numberGub]; for (i = 0; i < numberGub; i++) { int k = which[i]; temp1[i] = gubEnd[putGub+k]; } memcpy(gubEnd + putGub, temp1, numberGub * sizeof(int)); delete [] temp1; double * temp2 = new double [numberGub]; for (i = 0; i < numberGub; i++) { int k = which[i]; temp2[i] = lower[putGub+k]; } memcpy(lower + putGub, temp2, numberGub * sizeof(double)); for (i = 0; i < numberGub; i++) { int k = which[i]; temp2[i] = upper[putGub+k]; } memcpy(upper + putGub, temp2, numberGub * sizeof(double)); delete [] temp2; delete [] which; numberElements -= numberGubColumns; int * start2 = new int[numberGubColumns+1]; int * row2 = new int[numberElements]; double * element2 = new double[numberElements]; double * cost2 = new double [numberGubColumns]; double * lowerColumn2 = NULL; if (doLower) { lowerColumn2 = new double [numberGubColumns]; CoinFillN(lowerColumn2, numberGubColumns, 0.0); } double * upperColumn2 = NULL; if (doUpper) { upperColumn2 = new double [numberGubColumns]; CoinFillN(upperColumn2, numberGubColumns, COIN_DBL_MAX); } numberElements = 0; int numberNonGubRows = 0; for (iRow = 0; iRow < numberRows; iRow++) { if (!rowIsGub[iRow]) rowIsGub[iRow] = numberNonGubRows++; } numberColumns = 0; gubStart[0] = 0; start2[0] = 0; const double * cost = model.objective(); for (int iSet = 0; iSet < numberGub; iSet++) { int iStart = gubStart[iSet+putGub]; int iEnd = gubEnd[iSet+putGub]; for (int k = iStart; k < iEnd; k++) { cost2[numberColumns] = cost[k]; if (columnLower[k]) lowerColumn2[numberColumns] = columnLower[k]; if (columnUpper[k] < 1.0e20) upperColumn2[numberColumns] = columnUpper[k]; for (int j = columnStart[k]; j < columnStart[k] + columnLength[k]; j++) { int iRow = rowIsGub[row[j]]; if (iRow >= 0) { row2[numberElements] = iRow; element2[numberElements++] = elementByColumn[j]; } } start2[++numberColumns] = numberElements; } gubStart[iSet+1] = numberColumns; } model2.replaceMatrix(new ClpGubDynamicMatrix(&model2, numberGub, numberColumns, gubStart, lower + putGub, upper + putGub, start2, row2, element2, cost2, lowerColumn2, upperColumn2)); delete [] rowIsGub; delete [] start2; delete [] row2; delete [] element2; delete [] cost2; delete [] lowerColumn2; delete [] upperColumn2; // For now scaling off model2.scaling(0); // Do partial dantzig ClpPrimalColumnSteepest dantzig(5); model2.setPrimalColumnPivotAlgorithm(dantzig); //model2.messageHandler()->setLogLevel(63); model2.setFactorizationFrequency(maxFactor); model2.setMaximumIterations(4000000); double time1 = CoinCpuTime(); model2.primal(); { ClpGubDynamicMatrix * gubMatrix = dynamic_cast< ClpGubDynamicMatrix*>(model2.clpMatrix()); assert(gubMatrix); const double * solution = model2.primalColumnSolution(); int numberGubColumns = gubMatrix->numberGubColumns(); int firstOdd = gubMatrix->firstDynamic(); int lastOdd = gubMatrix->firstAvailable(); int numberTotalColumns = firstOdd + numberGubColumns; int numberRows = model2.numberRows(); char * status = new char [numberTotalColumns]; double * gubSolution = new double [numberTotalColumns]; int numberSets = gubMatrix->numberSets(); const int * id = gubMatrix->id(); int i; const double * lowerColumn = gubMatrix->lowerColumn(); const double * upperColumn = gubMatrix->upperColumn(); for (i = 0; i < numberGubColumns; i++) { if (gubMatrix->getDynamicStatus(i) == ClpGubDynamicMatrix::atUpperBound) { gubSolution[i+firstOdd] = upperColumn[i]; status[i+firstOdd] = 2; } else if (gubMatrix->getDynamicStatus(i) == ClpGubDynamicMatrix::atLowerBound && lowerColumn) { gubSolution[i+firstOdd] = lowerColumn[i]; status[i+firstOdd] = 1; } else { gubSolution[i+firstOdd] = 0.0; status[i+firstOdd] = 1; } } for (i = 0; i < firstOdd; i++) { ClpSimplex::Status thisStatus = model2.getStatus(i); if (thisStatus == ClpSimplex::basic) status[i] = 0; else if (thisStatus == ClpSimplex::atLowerBound) status[i] = 1; else if (thisStatus == ClpSimplex::atUpperBound) status[i] = 2; else if (thisStatus == ClpSimplex::isFixed) status[i] = 3; else abort(); gubSolution[i] = solution[i]; } for (i = firstOdd; i < lastOdd; i++) { int iBig = id[i-firstOdd] + firstOdd; ClpSimplex::Status thisStatus = model2.getStatus(i); if (thisStatus == ClpSimplex::basic) status[iBig] = 0; else if (thisStatus == ClpSimplex::atLowerBound) status[iBig] = 1; else if (thisStatus == ClpSimplex::atUpperBound) status[iBig] = 2; else if (thisStatus == ClpSimplex::isFixed) status[iBig] = 3; else abort(); gubSolution[iBig] = solution[i]; } char * rowStatus = new char[numberRows]; for (i = 0; i < numberRows; i++) { ClpSimplex::Status thisStatus = model2.getRowStatus(i); if (thisStatus == ClpSimplex::basic) rowStatus[i] = 0; else if (thisStatus == ClpSimplex::atLowerBound) rowStatus[i] = 1; else if (thisStatus == ClpSimplex::atUpperBound) rowStatus[i] = 2; else if (thisStatus == ClpSimplex::isFixed) rowStatus[i] = 3; else abort(); } char * setStatus = new char[numberSets]; int * keyVariable = new int[numberSets]; memcpy(keyVariable, gubMatrix->keyVariable(), numberSets * sizeof(int)); for (i = 0; i < numberSets; i++) { int iKey = keyVariable[i]; if (iKey > lastOdd) iKey = numberTotalColumns + i; else iKey = id[iKey-firstOdd] + firstOdd; keyVariable[i] = iKey; ClpSimplex::Status thisStatus = gubMatrix->getStatus(i); if (thisStatus == ClpSimplex::basic) setStatus[i] = 0; else if (thisStatus == ClpSimplex::atLowerBound) setStatus[i] = 1; else if (thisStatus == ClpSimplex::atUpperBound) setStatus[i] = 2; else if (thisStatus == ClpSimplex::isFixed) setStatus[i] = 3; else abort(); } FILE * fp = fopen("xx.sol", "w"); fwrite(gubSolution, sizeof(double), numberTotalColumns, fp); fwrite(status, sizeof(char), numberTotalColumns, fp); const double * rowsol = model2.primalRowSolution(); int originalNumberRows = model.numberRows(); double * rowsol2 = new double[originalNumberRows]; memset(rowsol2, 0, originalNumberRows * sizeof(double)); model.times(1.0, gubSolution, rowsol2); for (i = 0; i < numberRows; i++) assert(fabs(rowsol[i] - rowsol2[i]) < 1.0e-3); //for (;i<originalNumberRows;i++) //printf("%d %g\n",i,rowsol2[i]); delete [] rowsol2; fwrite(rowsol, sizeof(double), numberRows, fp); fwrite(rowStatus, sizeof(char), numberRows, fp); fwrite(setStatus, sizeof(char), numberSets, fp); fwrite(keyVariable, sizeof(int), numberSets, fp); fclose(fp); delete [] status; delete [] gubSolution; delete [] setStatus; delete [] keyVariable; // ** if going to rstart as dynamic need id_ // also copy coding in useEf.. from ClpGubMatrix (i.e. test for basis) } printf("obj offset is %g\n", model2.objectiveOffset()); printf("Primal took %g seconds\n", CoinCpuTime() - time1); //model2.primal(1); } delete [] mark; delete [] gubStart; delete [] gubEnd; delete [] which; delete [] whichGub; delete [] lower; delete [] upper; #else printf("testGub2 not available with COIN_BIG_INDEX=2\n"); #endif return 0; }
int main(int argc, const char *argv[]) { int status; CoinMpsIO m; if (argc < 2) status = m.readMps("model1.mps", ""); else status = m.readMps(argv[1], ""); if (status) { fprintf(stdout, "Bad readMps %s\n", argv[1]); exit(1); } // Load up model1 - so we can use known good solution ClpSimplex model1; model1.loadProblem(*m.getMatrixByCol(), m.getColLower(), m.getColUpper(), m.getObjCoefficients(), m.getRowLower(), m.getRowUpper()); model1.dual(); // Get data arrays const CoinPackedMatrix * matrix1 = m.getMatrixByCol(); const int * start1 = matrix1->getVectorStarts(); const int * length1 = matrix1->getVectorLengths(); const int * row1 = matrix1->getIndices(); const double * element1 = matrix1->getElements(); const double * columnLower1 = m.getColLower(); const double * columnUpper1 = m.getColUpper(); const double * rowLower1 = m.getRowLower(); const double * rowUpper1 = m.getRowUpper(); const double * objective1 = m.getObjCoefficients(); int numberColumns = m.getNumCols(); int numberRows = m.getNumRows(); int numberElements = m.getNumElements(); // Get new arrays int numberColumns2 = (numberColumns + 1); int * start2 = new int[numberColumns2+1]; int * row2 = new int[numberElements]; double * element2 = new double[numberElements]; int * segstart = new int[numberColumns+1]; double * breakpt = new double[2*numberColumns]; double * slope = new double[2*numberColumns]; double * objective2 = new double[numberColumns2]; double * columnLower2 = new double[numberColumns2]; double * columnUpper2 = new double[numberColumns2]; double * rowLower2 = new double[numberRows]; double * rowUpper2 = new double[numberRows]; // We need to modify rhs memcpy(rowLower2, rowLower1, numberRows * sizeof(double)); memcpy(rowUpper2, rowUpper1, numberRows * sizeof(double)); double objectiveOffset = 0.0; // For new solution double * newSolution = new double [numberColumns]; const double * oldSolution = model1.primalColumnSolution(); int iColumn; for (iColumn = 0; iColumn < numberColumns; iColumn++) printf("%g ", oldSolution[iColumn]); printf("\n"); numberColumns2 = 0; numberElements = 0; start2[0] = 0; int segptr = 0; segstart[0] = 0; // Now check for duplicates for (iColumn = 0; iColumn < numberColumns; iColumn++) { // test if column identical to next column bool ifcopy = 1; if (iColumn < numberColumns - 1) { int joff = length1[iColumn]; for (int j = start1[iColumn]; j < start1[iColumn] + length1[iColumn]; j++) { if (row1[j] != row1[j+joff]) { ifcopy = 0; break; } if (element1[j] != element1[j+joff]) { ifcopy = 0; break; } } } else { ifcopy = 0; } //if (iColumn>47||iColumn<45) //ifcopy=0; if (ifcopy) { double lo1 = columnLower1[iColumn]; double up1 = columnUpper1[iColumn]; double obj1 = objective1[iColumn]; double sol1 = oldSolution[iColumn]; double lo2 = columnLower1[iColumn+1]; double up2 = columnUpper1[iColumn+1]; double obj2 = objective1[iColumn+1]; double sol2 = oldSolution[iColumn+1]; if (fabs(up1 - lo2) > 1.0e-8) { // try other way double temp; temp = lo1; lo1 = lo2; lo2 = temp; temp = up1; up1 = up2; up2 = temp; temp = obj1; obj1 = obj2; obj2 = temp; temp = sol1; sol1 = sol2; sol2 = temp; assert(fabs(up1 - lo2) < 1.0e-8); } // subtract out from rhs double fixed = up1; // do offset objectiveOffset += fixed * obj2; for (int j = start1[iColumn]; j < start1[iColumn] + length1[iColumn]; j++) { int iRow = row1[j]; double value = element1[j]; if (rowLower2[iRow] > -1.0e30) rowLower2[iRow] -= value * fixed; if (rowUpper2[iRow] < 1.0e30) rowUpper2[iRow] -= value * fixed; } newSolution[numberColumns2] = fixed; if (fabs(sol1 - fixed) > 1.0e-8) newSolution[numberColumns2] = sol1; if (fabs(sol2 - fixed) > 1.0e-8) newSolution[numberColumns2] = sol2; columnLower2[numberColumns2] = lo1; columnUpper2[numberColumns2] = up2; objective2[numberColumns2] = 0.0; breakpt[segptr] = lo1; slope[segptr++] = obj1; breakpt[segptr] = lo2; slope[segptr++] = obj2; for (int j = start1[iColumn]; j < start1[iColumn] + length1[iColumn]; j++) { row2[numberElements] = row1[j]; element2[numberElements++] = element1[j]; } start2[++numberColumns2] = numberElements; breakpt[segptr] = up2; slope[segptr++] = COIN_DBL_MAX; segstart[numberColumns2] = segptr; iColumn++; // skip next column } else { // normal column columnLower2[numberColumns2] = columnLower1[iColumn]; columnUpper2[numberColumns2] = columnUpper1[iColumn]; objective2[numberColumns2] = objective1[iColumn]; breakpt[segptr] = columnLower1[iColumn]; slope[segptr++] = objective1[iColumn]; for (int j = start1[iColumn]; j < start1[iColumn] + length1[iColumn]; j++) { row2[numberElements] = row1[j]; element2[numberElements++] = element1[j]; } newSolution[numberColumns2] = oldSolution[iColumn]; start2[++numberColumns2] = numberElements; breakpt[segptr] = columnUpper1[iColumn]; slope[segptr++] = COIN_DBL_MAX; segstart[numberColumns2] = segptr; } } // print new number of columns, elements printf("New number of columns = %d\n", numberColumns2); printf("New number of elements = %d\n", numberElements); printf("Objective offset is %g\n", objectiveOffset); ClpSimplex model; // load up model.loadProblem(numberColumns2, numberRows, start2, row2, element2, columnLower2, columnUpper2, objective2, rowLower2, rowUpper2); model.scaling(0); model.setDblParam(ClpObjOffset, -objectiveOffset); // Create nonlinear objective int returnCode = model.createPiecewiseLinearCosts(segstart, breakpt, slope); assert(!returnCode); // delete delete [] segstart; delete [] breakpt; delete [] slope; delete [] start2; delete [] row2 ; delete [] element2; delete [] objective2; delete [] columnLower2; delete [] columnUpper2; delete [] rowLower2; delete [] rowUpper2; // copy in solution - (should be optimal) model.allSlackBasis(); memcpy(model.primalColumnSolution(), newSolution, numberColumns2 * sizeof(double)); //memcpy(model.columnLower(),newSolution,numberColumns2*sizeof(double)); //memcpy(model.columnUpper(),newSolution,numberColumns2*sizeof(double)); delete [] newSolution; //model.setLogLevel(63); const double * solution = model.primalColumnSolution(); double * saveSol = new double[numberColumns2]; memcpy(saveSol, solution, numberColumns2 * sizeof(double)); for (iColumn = 0; iColumn < numberColumns2; iColumn++) printf("%g ", solution[iColumn]); printf("\n"); // solve model.primal(1); for (iColumn = 0; iColumn < numberColumns2; iColumn++) { if (fabs(solution[iColumn] - saveSol[iColumn]) > 1.0e-3) printf(" ** was %g ", saveSol[iColumn]); printf("%g ", solution[iColumn]); } printf("\n"); model.primal(1); for (iColumn = 0; iColumn < numberColumns2; iColumn++) { if (fabs(solution[iColumn] - saveSol[iColumn]) > 1.0e-3) printf(" ** was %g ", saveSol[iColumn]); printf("%g ", solution[iColumn]); } printf("\n"); model.primal(); for (iColumn = 0; iColumn < numberColumns2; iColumn++) { if (fabs(solution[iColumn] - saveSol[iColumn]) > 1.0e-3) printf(" ** was %g ", saveSol[iColumn]); printf("%g ", solution[iColumn]); } printf("\n"); model.allSlackBasis(); for (iColumn = 0; iColumn < numberColumns2; iColumn++) { if (fabs(solution[iColumn] - saveSol[iColumn]) > 1.0e-3) printf(" ** was %g ", saveSol[iColumn]); printf("%g ", solution[iColumn]); } printf("\n"); model.setLogLevel(63); model.primal(); for (iColumn = 0; iColumn < numberColumns2; iColumn++) { if (fabs(solution[iColumn] - saveSol[iColumn]) > 1.0e-3) printf(" ** was %g ", saveSol[iColumn]); printf("%g ", solution[iColumn]); } printf("\n"); return 0; }
//-------------------------------------------------------------------------- // Test building a model void CoinModelUnitTest(const std::string & mpsDir, const std::string & netlibDir, const std::string & testModel) { // Get a model CoinMpsIO m; std::string fn = mpsDir+"exmip1"; int numErr = m.readMps(fn.c_str(),"mps"); assert( numErr== 0 ); int numberRows = m.getNumRows(); int numberColumns = m.getNumCols(); // Build by row from scratch { CoinPackedMatrix matrixByRow = * m.getMatrixByRow(); const double * element = matrixByRow.getElements(); const int * column = matrixByRow.getIndices(); const CoinBigIndex * rowStart = matrixByRow.getVectorStarts(); const int * rowLength = matrixByRow.getVectorLengths(); const double * rowLower = m.getRowLower(); const double * rowUpper = m.getRowUpper(); const double * columnLower = m.getColLower(); const double * columnUpper = m.getColUpper(); const double * objective = m.getObjCoefficients(); int i; CoinModel temp; for (i=0; i<numberRows; i++) { temp.addRow(rowLength[i],column+rowStart[i], element+rowStart[i],rowLower[i],rowUpper[i],m.rowName(i)); } // Now do column part for (i=0; i<numberColumns; i++) { temp.setColumnBounds(i,columnLower[i],columnUpper[i]); temp.setColumnObjective(i,objective[i]); if (m.isInteger(i)) temp.setColumnIsInteger(i,true);; } // write out temp.writeMps("byRow.mps"); } // Build by column from scratch and save CoinModel model; { CoinPackedMatrix matrixByColumn = * m.getMatrixByCol(); const double * element = matrixByColumn.getElements(); const int * row = matrixByColumn.getIndices(); const CoinBigIndex * columnStart = matrixByColumn.getVectorStarts(); const int * columnLength = matrixByColumn.getVectorLengths(); const double * rowLower = m.getRowLower(); const double * rowUpper = m.getRowUpper(); const double * columnLower = m.getColLower(); const double * columnUpper = m.getColUpper(); const double * objective = m.getObjCoefficients(); int i; for (i=0; i<numberColumns; i++) { model.addColumn(columnLength[i],row+columnStart[i], element+columnStart[i],columnLower[i],columnUpper[i], objective[i],m.columnName(i),m.isInteger(i)); } // Now do row part for (i=0; i<numberRows; i++) { model.setRowBounds(i,rowLower[i],rowUpper[i]); } // write out model.writeMps("byColumn.mps"); } // model was created by column - play around { CoinModel temp; int i; for (i=numberRows-1; i>=0; i--) temp.setRowLower(i,model.getRowLower(i)); for (i=0; i<numberColumns; i++) { temp.setColumnUpper(i,model.getColumnUpper(i)); temp.setColumnName(i,model.getColumnName(i)); } for (i=numberColumns-1; i>=0; i--) { temp.setColumnLower(i,model.getColumnLower(i)); temp.setColumnObjective(i,model.getColumnObjective(i)); temp.setColumnIsInteger(i,model.getColumnIsInteger(i)); } for (i=0; i<numberRows; i++) { temp.setRowUpper(i,model.getRowUpper(i)); temp.setRowName(i,model.getRowName(i)); } // Now elements for (i=0; i<numberRows; i++) { CoinModelLink triple=model.firstInRow(i); while (triple.column()>=0) { temp(i,triple.column(),triple.value()); triple=model.next(triple); } } // and by column for (i=numberColumns-1; i>=0; i--) { CoinModelLink triple=model.lastInColumn(i); while (triple.row()>=0) { assert (triple.value()==temp(triple.row(),i)); temp(triple.row(),i,triple.value()); triple=model.previous(triple); } } // check equal model.setLogLevel(1); assert (!model.differentModel(temp,false)); } // Try creating model with strings { CoinModel temp; int i; for (i=numberRows-1; i>=0; i--) { double value = model.getRowLower(i); if (value==-1.0) temp.setRowLower(i,"minusOne"); else if (value==1.0) temp.setRowLower(i,"sqrt(plusOne)"); else if (value==4.0) temp.setRowLower(i,"abs(4*plusOne)"); else temp.setRowLower(i,value); } for (i=0; i<numberColumns; i++) { double value; value = model.getColumnUpper(i); if (value==-1.0) temp.setColumnUpper(i,"minusOne"); else if (value==1.0) temp.setColumnUpper(i,"plusOne"); else temp.setColumnUpper(i,value); temp.setColumnName(i,model.getColumnName(i)); } for (i=numberColumns-1; i>=0; i--) { temp.setColumnLower(i,model.getColumnLower(i)); temp.setColumnObjective(i,model.getColumnObjective(i)); temp.setColumnIsInteger(i,model.getColumnIsInteger(i)); } for (i=0; i<numberRows; i++) { double value = model.getRowUpper(i); if (value==-1.0) temp.setRowUpper(i,"minusOne"); else if (value==1.0) temp.setRowUpper(i,"plusOne"); else temp.setRowUpper(i,value); temp.setRowName(i,model.getRowName(i)); } // Now elements for (i=0; i<numberRows; i++) { CoinModelLink triple=model.firstInRow(i); while (triple.column()>=0) { double value = triple.value(); if (value==-1.0) temp(i,triple.column(),"minusOne"); else if (value==1.0) temp(i,triple.column(),"plusOne"); else if (value==-2.0) temp(i,triple.column(),"minusOne-1.0"); else if (value==2.0) temp(i,triple.column(),"plusOne+1.0+minusOne+(2.0-plusOne)"); else temp(i,triple.column(),value); triple=model.next(triple); } } temp.associateElement("minusOne",-1.0); temp.associateElement("plusOne",1.0); temp.setProblemName("fromStrings"); temp.writeMps("string.mps"); // check equal model.setLogLevel(1); assert (!model.differentModel(temp,false)); } // Test with various ways of generating { /* Get a model. Try first with netlibDir, fall back to mpsDir (sampleDir) if that fails. */ CoinMpsIO m; std::string fn = netlibDir+testModel; double time1 = CoinCpuTime(); int numErr = m.readMps(fn.c_str(),""); if (numErr != 0) { std::cout << "Could not read " << testModel << " in " << netlibDir << "; falling back to " << mpsDir << "." << std::endl ; fn = mpsDir+testModel ; numErr = m.readMps(fn.c_str(),"") ; if (numErr != 0) { std::cout << "Could not read " << testModel << "; skipping test." << std::endl ; } } if (numErr == 0) { std::cout << "Time for readMps is " << (CoinCpuTime()-time1) << " seconds." << std::endl ; int numberRows = m.getNumRows(); int numberColumns = m.getNumCols(); // Build model CoinModel model; CoinPackedMatrix matrixByRow = * m.getMatrixByRow(); const double * element = matrixByRow.getElements(); const int * column = matrixByRow.getIndices(); const CoinBigIndex * rowStart = matrixByRow.getVectorStarts(); const int * rowLength = matrixByRow.getVectorLengths(); const double * rowLower = m.getRowLower(); const double * rowUpper = m.getRowUpper(); const double * columnLower = m.getColLower(); const double * columnUpper = m.getColUpper(); const double * objective = m.getObjCoefficients(); int i; for (i=0; i<numberRows; i++) { model.addRow(rowLength[i],column+rowStart[i], element+rowStart[i],rowLower[i],rowUpper[i],m.rowName(i)); } // Now do column part for (i=0; i<numberColumns; i++) { model.setColumnBounds(i,columnLower[i],columnUpper[i]); model.setColumnObjective(i,objective[i]); model.setColumnName(i,m.columnName(i)); if (m.isInteger(i)) model.setColumnIsInteger(i,true);; } // Test CoinSeedRandom(11111); time1 = 0.0; int nPass=50; for (i=0; i<nPass; i++) { double random = CoinDrand48(); int iSeed = (int) (random*1000000); //iSeed = 776151; CoinSeedRandom(iSeed); std::cout << "before pass " << i << " with seed of " << iSeed << std::endl ; buildRandom(model,CoinDrand48(),time1,i); model.validateLinks(); } std::cout << "Time for " << nPass << " CoinModel passes is " << time1 << " seconds\n" << std::endl ; } } }
// status = write_mps_file(c,a,lhs,rhs,ub,lb,btype,vartype,filename); // btype is not yet used. But I keep this parameter for the future extern "C" int write_mps_file(char * fname) { int m_c, n_c; int m_a, n_a; int m_lhs, n_lhs; int m_rhs, n_rhs; int m_ub, n_ub; int m_lb, n_lb; int m_col_name, n_col_name; int m_row_name, n_row_name; vector<string> RowNames, ColNames; stringstream tmpstring; CoinMpsIO mpsWriter; DerivedHandler * printer = NULL; CoinPackedMatrix A_matrix; SciSparse S_A; char ** pColNames = NULL; char ** pRowNames = NULL; int i, j, status; int nrows, ncols, count, type; int * c_addr = NULL, * lhs_addr = NULL, * rhs_addr = NULL, * ub_addr = NULL, * lb_addr = NULL; int * btype_addr = NULL, * vartype_addr = NULL, * pb_name_addr = NULL, * a_addr = NULL; int * col_name_addr = NULL, * row_name_addr = NULL, * filename_addr = NULL, * verbose_addr = NULL; double * c = NULL, * lhs = NULL, * rhs = NULL, * ub = NULL, * lb = NULL, * a = NULL; double verbose = 0; char * btype = NULL, * vartype = NULL, * pb_name = NULL, * filename = NULL; SciErr _SciErr; _SciErr = getVarAddressFromPosition(pvApiCtx, C_IN, &c_addr); SCICOINOR_ERROR; _SciErr = getMatrixOfDouble(pvApiCtx, c_addr, &n_c, &m_c, &c); SCICOINOR_ERROR; _SciErr = getVarAddressFromPosition(pvApiCtx, LHS_IN, &lhs_addr); SCICOINOR_ERROR; _SciErr = getMatrixOfDouble(pvApiCtx, lhs_addr, &n_lhs, &m_lhs, &lhs); SCICOINOR_ERROR; _SciErr = getVarAddressFromPosition(pvApiCtx, RHS_IN, &rhs_addr); SCICOINOR_ERROR; _SciErr = getMatrixOfDouble(pvApiCtx, rhs_addr, &n_rhs, &m_rhs, &rhs); SCICOINOR_ERROR; _SciErr = getVarAddressFromPosition(pvApiCtx, UB_IN, &ub_addr); SCICOINOR_ERROR; _SciErr = getMatrixOfDouble(pvApiCtx, ub_addr, &n_ub, &m_ub, &ub); SCICOINOR_ERROR; _SciErr = getVarAddressFromPosition(pvApiCtx, LB_IN, &lb_addr); SCICOINOR_ERROR; _SciErr = getMatrixOfDouble(pvApiCtx, lb_addr, &n_lb, &m_lb, &lb); SCICOINOR_ERROR; _SciErr = getVarAddressFromPosition(pvApiCtx, BTYPE_IN, &btype_addr); SCICOINOR_ERROR; getAllocatedSingleString(pvApiCtx, btype_addr, &btype); _SciErr = getVarAddressFromPosition(pvApiCtx, VARTYPE_IN, &vartype_addr); SCICOINOR_ERROR; getAllocatedSingleString(pvApiCtx, vartype_addr, &vartype); _SciErr = getVarAddressFromPosition(pvApiCtx, PB_NAME_IN, &pb_name_addr); SCICOINOR_ERROR; getAllocatedSingleString(pvApiCtx, pb_name_addr, &pb_name); _SciErr = getVarAddressFromPosition(pvApiCtx, COL_NAME_IN, &col_name_addr); SCICOINOR_ERROR; getAllocatedMatrixOfString(pvApiCtx, col_name_addr, &n_col_name, &m_col_name, &pColNames); _SciErr = getVarAddressFromPosition(pvApiCtx, ROW_NAME_IN, &row_name_addr); SCICOINOR_ERROR; getAllocatedMatrixOfString(pvApiCtx, row_name_addr, &n_row_name, &m_row_name, &pRowNames); _SciErr = getVarAddressFromPosition(pvApiCtx, FILENAME_IN, &filename_addr); SCICOINOR_ERROR; getAllocatedSingleString(pvApiCtx, filename_addr, &filename); _SciErr = getVarAddressFromPosition(pvApiCtx, VERBOSE_IN, &verbose_addr); SCICOINOR_ERROR; getScalarDouble(pvApiCtx, verbose_addr, &verbose); nrows = n_lhs * m_lhs; if (nrows==0) nrows = n_rhs*m_rhs; ncols = n_c * m_c; #ifdef DEBUG DBGPRINTF("rowname n = %d m = %d\n", n_row_name, m_row_name); #endif if (n_row_name * m_row_name==0) { RowNames.resize(nrows); for(i=0;i<nrows;i++) { tmpstring.str(""); tmpstring << "R" << i; RowNames[i] = tmpstring.str(); } } else { RowNames.resize(nrows); for(i=0;i<nrows;i++) { RowNames[i] = string(pRowNames[i]); } } #ifdef DEBUG DBGPRINTF("colname n = %d m = %d\n", n_col_name, m_col_name); #endif if (n_col_name * m_col_name==0) { ColNames.resize(ncols); for(i=0;i<ncols;i++) { tmpstring.str(""); tmpstring << "R" << i; ColNames[i] = tmpstring.str(); } } else { ColNames.resize(ncols); for(i=0;i<ncols;i++) { ColNames[i] = string(pColNames[i]); } } ////////////////// // The A matrix // ////////////////// _SciErr = getVarAddressFromPosition(pvApiCtx, A_IN, &a_addr); SCICOINOR_ERROR; _SciErr = getVarType(pvApiCtx, a_addr, &type); SCICOINOR_ERROR; if(type!=sci_sparse) { _SciErr = getMatrixOfDouble(pvApiCtx, a_addr, &n_a, &m_a, &a); SCICOINOR_ERROR; A_matrix.setDimensions(nrows,ncols); if (a==NULL) { Scierror(999,"%s: invalid value of matrix a\n",fname); freeAllocatedSingleString(btype); freeAllocatedSingleString(vartype); freeAllocatedSingleString(pb_name); freeAllocatedSingleString(filename); if (pRowNames) freeAllocatedMatrixOfString(m_row_name, n_row_name, pRowNames); if (pColNames) freeAllocatedMatrixOfString(m_col_name, n_col_name, pColNames); return 0; } for(i=0; i<m_a; i++) { for(j=0; j<n_a; j++) { if (*(a+i+j*m_a) != 0) A_matrix.modifyCoefficient(i,j,*(a+i+j*m_a)); } } } else { getAllocatedSparseMatrix(pvApiCtx, a_addr, &S_A.m, &S_A.n, &S_A.nel, &S_A.mnel, &S_A.icol, &S_A.R); A_matrix.setDimensions(nrows,ncols); count = 0; for(i=0;i<S_A.m;i++) { if (S_A.mnel[i]!=0) { for(j=0;j<S_A.mnel[i];j++) { count++; A_matrix.modifyCoefficient(i,S_A.icol[count-1]-1,S_A.R[count-1]); } } } freeAllocatedSparseMatrix(S_A.mnel, S_A.icol, S_A.R); } if (verbose) { printer = new DerivedHandler(); printer->setLogLevel((int)verbose); mpsWriter.passInMessageHandler(printer); } // void setMpsData (const CoinPackedMatrix &m, const double infinity, // const double *collb, const double *colub, // const double *obj, const char *integrality, // const double *rowlb, const double *rowub, // const std::vector< std::string > &colnames, const std::vector< std::string > &rownames) mpsWriter.setMpsData(A_matrix, mpsWriter.getInfinity(), lb, ub, c, vartype, lhs, rhs, ColNames, RowNames); mpsWriter.setProblemName(pb_name); status = mpsWriter.writeMps(filename); createScalarDouble(pvApiCtx, STATUS_OUT, (double)status); LhsVar(1) = STATUS_OUT; freeAllocatedSingleString(btype); freeAllocatedSingleString(vartype); freeAllocatedSingleString(pb_name); freeAllocatedSingleString(filename); if (pRowNames) freeAllocatedMatrixOfString(m_row_name, n_row_name, pRowNames); if (pColNames) freeAllocatedMatrixOfString(m_col_name, n_col_name, pColNames); return 0; }
int main(int argc, const char *argv[]) { /* Read quadratic model in two stages to test loadQuadraticObjective. And is also possible to just read into ClpSimplex/Interior which sets it all up in one go. But this is only if it is in QUADOBJ format. If no arguments does share2qp using ClpInterior (also creates quad.mps which is in QUADOBJ format) If one argument uses simplex e.g. testit quad.mps If > one uses barrier via ClpSimplex input and then ClpInterior borrow */ if (argc < 2) { CoinMpsIO m; #if defined(SAMPLEDIR) int status = m.readMps(SAMPLEDIR "/share2qp", "mps"); #else fprintf(stderr, "Do not know where to find sample MPS files.\n"); exit(1); #endif if (status) { printf("errors on input\n"); exit(77); } ClpInterior model; model.loadProblem(*m.getMatrixByCol(), m.getColLower(), m.getColUpper(), m.getObjCoefficients(), m.getRowLower(), m.getRowUpper()); // get quadratic part int * start = NULL; int * column = NULL; double * element = NULL; m.readQuadraticMps(NULL, start, column, element, 2); int j; for (j = 0; j < 79; j++) { if (start[j] < start[j+1]) { int i; printf("Column %d ", j); for (i = start[j]; i < start[j+1]; i++) { printf("( %d, %g) ", column[i], element[i]); } printf("\n"); } } model.loadQuadraticObjective(model.numberColumns(), start, column, element); // share2qp is in old style qp format - convert to new so other options can use model.writeMps("quad.mps"); ClpCholeskyBase * cholesky = new ClpCholeskyBase(); cholesky->setKKT(true); model.setCholesky(cholesky); model.primalDual(); double *primal; double *dual; primal = model.primalColumnSolution(); dual = model.dualRowSolution(); int i; int numberColumns = model.numberColumns(); int numberRows = model.numberRows(); for (i = 0; i < numberColumns; i++) { if (fabs(primal[i]) > 1.0e-8) printf("%d primal %g\n", i, primal[i]); } for (i = 0; i < numberRows; i++) { if (fabs(dual[i]) > 1.0e-8) printf("%d dual %g\n", i, dual[i]); } } else { // Could read into ClpInterior ClpSimplex model; if (model.readMps(argv[1])) { printf("errors on input\n"); exit(77); } model.writeMps("quad"); if (argc < 3) { // simplex - just primal as dual does not work // also I need to fix scaling of duals on output // (Was okay in first place - can't mix and match scaling techniques) // model.scaling(0); model.primal(); } else { // barrier ClpInterior barrier; barrier.borrowModel(model); ClpCholeskyBase * cholesky = new ClpCholeskyBase(); cholesky->setKKT(true); barrier.setCholesky(cholesky); barrier.primalDual(); barrier.returnModel(model); } // Just check if share2qp (quad.mps here) // this is because I am not checking if variables at ub if (model.numberColumns() == 79) { double *primal; double *dual; primal = model.primalColumnSolution(); dual = model.dualRowSolution(); // Check duals by hand const ClpQuadraticObjective * quadraticObj = (dynamic_cast<const ClpQuadraticObjective*>(model.objectiveAsObject())); assert(quadraticObj); CoinPackedMatrix * quad = quadraticObj->quadraticObjective(); const int * columnQuadratic = quad->getIndices(); const CoinBigIndex * columnQuadraticStart = quad->getVectorStarts(); const int * columnQuadraticLength = quad->getVectorLengths(); const double * quadraticElement = quad->getElements(); int numberColumns = model.numberColumns(); int numberRows = model.numberRows(); double * gradient = new double [numberColumns]; // move linear objective memcpy(gradient, quadraticObj->linearObjective(), numberColumns * sizeof(double)); int iColumn; for (iColumn = 0; iColumn < numberColumns; iColumn++) { double valueI = primal[iColumn]; CoinBigIndex j; for (j = columnQuadraticStart[iColumn]; j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) { int jColumn = columnQuadratic[j]; double valueJ = primal[jColumn]; double elementValue = quadraticElement[j]; if (iColumn != jColumn) { double gradientI = valueJ * elementValue; double gradientJ = valueI * elementValue; gradient[iColumn] += gradientI; gradient[jColumn] += gradientJ; } else { double gradientI = valueI * elementValue; gradient[iColumn] += gradientI; } } if (fabs(primal[iColumn]) > 1.0e-8) printf("%d primal %g\n", iColumn, primal[iColumn]); } for (int i = 0; i < numberRows; i++) { if (fabs(dual[i]) > 1.0e-8) printf("%d dual %g\n", i, dual[i]); } // Now use duals to get reduced costs // Can't use this as will try and use scaling // model.transposeTimes(-1.0,dual,gradient); // So ... CoinPackedMatrix * matrix = model.matrix(); const int * row = matrix->getIndices(); const CoinBigIndex * columnStart = matrix->getVectorStarts(); const int * columnLength = matrix->getVectorLengths(); const double * element = matrix->getElements(); for (iColumn = 0; iColumn < numberColumns; iColumn++) { double dj = gradient[iColumn]; CoinBigIndex j; for (j = columnStart[iColumn]; j < columnStart[iColumn] + columnLength[iColumn]; j++) { int jRow = row[j]; dj -= element[j] * dual[jRow]; } if (model.getColumnStatus(iColumn) == ClpSimplex::basic) { assert(fabs(dj) < 1.0e-5); } else { assert(dj > -1.0e-5); } } delete [] gradient; } } return 0; }