// Create launcher button toggleLauncherButton->setViewType("icon"); toggleLauncherButton->setObjectName("ToggleLauncherButton"); toggleLauncherButton->setIconID("icon-m-quicklaunchbar-menu-open"); connect(toggleLauncherButton, SIGNAL(clicked()), controller, SIGNAL(toggleLauncherButtonClicked())); // Put the stuff into a layout l->addStretch(); l->addItem(launcherButtonLayout); l->addStretch(); } QuickLaunchBarView::~QuickLaunchBarView() { // remove buttons from layout to avoid multi deletion (buttons are in model as QSharedPointer's) foreach (QSharedPointer<LauncherButton> button, model()->buttons().values()) { launcherButtonLayout->removeItem(button.data()); button->setParentItem(0); } } void QuickLaunchBarView::setupModel() { MWidgetView::setupModel(); QList<const char *> modifications; modifications << QuickLaunchBarModel::Buttons; updateData(modifications); } void QuickLaunchBarView::updateData(const QList<const char *>& modifications) {
const QStandardItemModel *FlagsComboBox::standardItemModel() const { return static_cast<const QStandardItemModel *>(model()); }
/*! \brief Assign a specific FX Channel for this track */ void SampleTrackView::assignFxLine(int channelIndex) { model()->effectChannelModel()->setValue(channelIndex); gui->fxMixerView()->setCurrentFxLine(channelIndex); }
void KateCompletionTree::resizeColumnsSlot() { if (model()) { resizeColumns(); } }
KateCompletionModel *KateCompletionTree::kateModel() const { return static_cast<KateCompletionModel *>(model()); }
surface::instance_t make(const description_t& description) { BOOST_LOG_TRIVIAL(debug) << "Make surface sor"; const auto& points = description.points; spline_t spline = make_spline(points.begin(), points.end()); derivations_t derivations; rtree_t rtree; for (std::size_t i = 0; i < spline.size(); ++i) { const spline_segment_t& segment = spline[i]; const polynomial5_t derivation = differentiate(std::get<2>(segment) * std::get<2>(segment)); const float delta = std::get<1>(segment) - std::get<0>(segment); float max = std::max ( evaluate(std::get<2>(segment), 0.0f), evaluate(std::get<2>(segment), delta) ); std::array<float, 5> roots; const auto end = solve(derivation, roots.begin()); for (auto root = roots.begin(); root != end; ++root) if (*root >= 0.0f && *root <= delta) max = std::max ({ max, evaluate(std::get<2>(segment), *root) }); const box_t box ( point_t(-max, std::get<0>(segment), -max), point_t(+max, std::get<1>(segment), +max) ); derivations.emplace_back(derivation); rtree.insert(value_t(box, i)); } /* const box_t box = transform ( description.transformation, box_t// TODO: puke => ( vector_t { geo::get<X>(rtree.bounds().min_corner()), geo::get<Y>(rtree.bounds().min_corner()), geo::get<Z>(rtree.bounds().min_corner()) }, vector_t { geo::get<X>(rtree.bounds().max_corner()), geo::get<Y>(rtree.bounds().max_corner()), geo::get<Z>(rtree.bounds().max_corner()) } ) ); BOOST_LOG_TRIVIAL(trace) << "Box: min = " << box.min_corner() << ", max = " << box.max_corner() << std::endl; const box_t box// TODO: puke => ( vector_t { geo::get<X>(rtree.bounds().min_corner()), geo::get<Y>(rtree.bounds().min_corner()), geo::get<Z>(rtree.bounds().min_corner()) }, vector_t { geo::get<X>(rtree.bounds().max_corner()), geo::get<Y>(rtree.bounds().max_corner()), geo::get<Z>(rtree.bounds().max_corner()) } ); BOOST_LOG_TRIVIAL(trace) << "Box: min = " << box.min_corner() << ", max = " << box.max_corner() << std::endl; */ model_t model ( std::move(spline), std::move(derivations), std::move(rtree), points.front()[X], points.back()[X], points.front()[Y], points.back()[Y] // box ); return std::make_shared<instance_impl_t<model_t>>(description.transformation, std::move(model)); // return boost::make_tuple // ( // primitive::make<model> // ( // description.transformation, // std::move(spline), // std::move(derivations), // std::move(rtree), // points.front()[X], // points.back()[X], // points.front()[Y], // points.back()[Y] // ), // box, // 3 * spline.size() + 2 // ); }
int run(const boost::mpi::communicator& comm, skylark::base::context_t& context, hilbert_options_t& options) { int rank = comm.rank(); InputType X, Xv, Xt; LabelType Y, Yv, Yt; if(!options.trainfile.empty()) { //training mode read(comm, options.fileformat, options.trainfile, X, Y); int dimensions = skylark::base::Height(X); int targets = GetNumTargets<LabelType>(comm, Y); bool shift = false; if ((options.lossfunction == LOGISTIC) && (targets == 1)) { ShiftForLogistic(Y); targets = 2; shift = true; } BlockADMMSolver<InputType>* Solver = GetSolver<InputType>(context, options, dimensions); if(!options.valfile.empty()) { comm.barrier(); if(rank == 0) std::cout << "Loading validation data." << std::endl; read(comm, options.fileformat, options.valfile, Xv, Yv, skylark::base::Height(X)); if ((options.lossfunction == LOGISTIC) && shift) { ShiftForLogistic(Yv); } } skylark::ml::model_t<InputType, LabelType>* model = Solver->train(X, Y, Xv, Yv, comm); if (comm.rank() == 0) model->save(options.modelfile, options.print()); } else { std::cout << "Testing Mode (currently loads test data in memory)" << std::endl; skylark::ml::model_t<InputType, LabelType> model(options.modelfile); read(comm, options.fileformat, options.testfile, Xt, Yt, model.get_input_size()); LabelType DecisionValues(Yt.Height(), model.get_num_outputs()); LabelType PredictedLabels(Yt.Height(), 1); El::Zero(DecisionValues); El::Zero(PredictedLabels); std::cout << "Starting predictions" << std::endl; model.predict(Xt, PredictedLabels, DecisionValues, options.numthreads); double accuracy = model.evaluate(Yt, DecisionValues, comm); if(rank == 0) std::cout << "Test Accuracy = " << accuracy << " %" << std::endl; // fix logistic case -- provide mechanism to dump predictions -- clean up evaluate } return 0; }
/** Extract the master block from <code>problem</code>. * The constructor also sets up the solver for the newly created master * block. The master block can only be extracted if all sub-blocks have * already been extracted. * @param problem The problem from which to extract the master. * @param blocks The sub blocks that have already been extracted. */ BendersOpt::Block::Block(Problem const *problem, BlockVector const &blocks) : env(), number(-1), vars(0), rows(0), cplex(0), cb(0) { IloNumVarArray problemVars = problem->getVariables(); IloRangeArray problemRanges = problem->getRows(); IloExpr masterObj(env); IloNumVarArray masterVars(env); IloRangeArray masterRows(env); // Find columns that do not intersect block variables and // copy them to the master block. IdxMap idxMap; RowSet rowSet; for (IloInt j = 0; j < problemVars.getSize(); ++j) { IloNumVar x = problemVars[j]; if ( problem->getBlock(x) < 0 ) { // Column is not in a block. Copy it to the master. IloNumVar v(env, x.getLB(), x.getUB(), x.getType(), x.getName()); varMap.insert(VarMap::value_type(v, x)); masterObj += problem->getObjCoef(x) * v; idxMap[x] = masterVars.getSize(); masterVars.add(v); } else { // Column is in a block. Collect all rows that intersect // this column. RowSet const &intersected = problem->getIntersectedRows(x); for (RowSet::const_iterator it = intersected.begin(); it != intersected.end(); ++it) rowSet.insert(*it); idxMap[x] = -1; } } // Pick up the rows that we need to copy. // These are the rows that are only intersected by master variables, // that is, the rows that are not in any block's rowset. for (IloInt i = 0; i < problemRanges.getSize(); ++i) { IloRange r = problemRanges[i]; if ( rowSet.find(r) == rowSet.end() ) { IloRange masterRow(env, r.getLB(), r.getUB(), r.getName()); IloExpr lhs(env); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) { lhs += it.getCoef() * masterVars[idxMap[it.getVar()]]; } masterRow.setExpr(lhs); masterRows.add(masterRow); } } // Adjust variable indices in blocks so that reference to variables // in the original problem become references to variables in the master. for (BlockVector::const_iterator b = blocks.begin(); b != blocks.end(); ++b) { for (std::vector<FixData>::iterator it = (*b)->fixed.begin(); it != (*b)->fixed.end(); ++it) it->col = idxMap[problemVars[it->col]]; } // Create the eta variables, one for each block. // See the comments at the top of this file for details about the // eta variables. IloInt const firsteta = masterVars.getSize(); for (BlockVector::size_type i = 0; i < blocks.size(); ++i) { std::stringstream s; s << "_eta" << i; IloNumVar eta(env, 0.0, IloInfinity, s.str().c_str()); masterObj += eta; masterVars.add(eta); } // Create model and solver instance vars = masterVars; rows = masterRows; IloModel model(env); model.add(obj = IloObjective(env, masterObj, problem->getObjSense())); model.add(vars); model.add(rows); cplex = IloCplex(model); cplex.use(cb = new (env) LazyConstraintCallback(env, this, blocks, firsteta)); for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) objMap.insert(ObjMap::value_type(it.getVar(), it.getCoef())); }
void InstrumentTrackView::activityIndicatorPressed() { model()->processInEvent( MidiEvent( MidiNoteOn, 0, DefaultKey, MidiDefaultVelocity ) ); }
void ExtractGameobjectModels() { Constants::ToWoWCoords = true; printf("Extracting GameObject models\n"); std::string baseBuildingsPath = "Buildings/"; std::string baseVmapsPath = "vmaps/"; Utils::CreateDir(baseVmapsPath); Utils::CreateDir(baseBuildingsPath); FILE* modelList = fopen((baseVmapsPath + "GameObjectModels.list").c_str(), "wb"); if (!modelList) { printf("Could not create file vmaps/GameObjectModels.list, please make sure that you have the write permissions in the folder\n"); return; } DBC* dbc = MPQHandler->GetDBC("GameObjectDisplayInfo"); for (std::vector<Record*>::iterator itr = dbc->Records.begin(); itr != dbc->Records.end(); ++itr) { std::string path = (*itr)->GetString(1); std::string fileName = Utils::GetPlainName(path.c_str()); std::string extension = Utils::GetExtension(fileName); // Convert the extension to lowercase std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); if (extension == "mdx" || extension == "m2") { fileName = Utils::FixModelPath(fileName); Model model(path); if (model.IsBad) continue; FILE* output = fopen((baseBuildingsPath + fileName).c_str(), "wb"); if (!output) { printf("Could not create file %s, please check that you have write permissions\n", (baseBuildingsPath + fileName).c_str()); continue; } // Placeholder for 0 values int Nop[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; fwrite(Constants::VMAPMagic, 8, 1, output); uint32 numVerts = model.Header.CountBoundingVertices; fwrite(&numVerts, sizeof(uint32), 1, output); uint32 numGroups = 1; fwrite(&numGroups, sizeof(uint32), 1, output); fwrite(Nop, 4 * 3 , 1, output); // rootwmoid, flags, groupid fwrite(Nop, sizeof(float), 3 * 2, output);//bbox, only needed for WMO currently fwrite(Nop, 4, 1, output);// liquidflags fwrite("GRP ", 4, 1, output); uint32 branches = 1; uint32 wsize = sizeof(branches) + sizeof(uint32) * branches; fwrite(&wsize, sizeof(uint32), 1, output); fwrite(&branches, sizeof(branches), 1, output); uint32 numTris = model.Header.CountBoundingTriangles; fwrite(&numTris, sizeof(uint32), 1, output); fwrite("INDX", 4, 1, output); wsize = sizeof(uint32) + sizeof(unsigned short) * numTris; fwrite(&wsize, sizeof(int), 1, output); fwrite(&numTris, sizeof(uint32), 1, output); uint16* indices = new uint16[numTris]; if (numTris > 0) { uint32 i = 0; for (std::vector<Triangle<uint16> >::iterator itr2 = model.Triangles.begin(); itr2 != model.Triangles.end(); ++itr2, ++i) { indices[i * 3 + 0] = itr2->V0; indices[i * 3 + 1] = itr2->V1; indices[i * 3 + 2] = itr2->V2; } fwrite(indices, sizeof(uint16), numTris, output); } fwrite("VERT", 4, 1, output); wsize = sizeof(int) + sizeof(float) * 3 * numVerts; fwrite(&wsize, sizeof(int), 1, output); fwrite(&numVerts, sizeof(int), 1, output); float* vertices = new float[numVerts*3]; if (numVerts > 0) { uint32 i = 0; for (std::vector<Vector3>::iterator itr2 = model.Vertices.begin(); itr2 != model.Vertices.end(); ++itr2, ++i) { vertices[i * 3 + 0] = itr2->x; vertices[i * 3 + 1] = itr2->y; vertices[i * 3 + 2] = itr2->z; } fwrite(vertices, sizeof(float), numVerts * 3, output); } fclose(output); delete[] indices; delete[] vertices; uint32 displayId = (*itr)->Values[0]; uint32 pathLength = fileName.size(); fwrite(&displayId, sizeof(uint32), 1, modelList); fwrite(&pathLength, sizeof(uint32), 1, modelList); fwrite(fileName.c_str(), sizeof(char), pathLength, modelList); } else if (extension == "wmo") { WorldModelRoot model(path); FILE* output = fopen((baseBuildingsPath + fileName).c_str(), "wb"); if (!output) { printf("Could not create file %s, please check that you have write permissions\n", (baseBuildingsPath + fileName).c_str()); continue; } fwrite(Constants::VMAPMagic, 1, 8, output); uint32 numVertices = 0; fwrite(&numVertices, sizeof(uint32), 1, output); // will be filled later fwrite(&model.Header.CountGroups, sizeof(uint32), 1, output); fwrite(&model.Header.WmoId, sizeof(uint32), 1, output); const char grp[] = { 'G' , 'R' , 'P', ' ' }; for (std::vector<WorldModelGroup>::iterator itr2 = model.Groups.begin(); itr2 != model.Groups.end(); ++itr2) { const WMOGroupHeader& header = itr2->Header; fwrite(&header.Flags, sizeof(uint32), 1, output); fwrite(&header.WmoId, sizeof(uint32), 1, output); fwrite(&header.BoundingBox[0], sizeof(uint32), 1, output); fwrite(&header.BoundingBox[1], sizeof(uint32), 1, output); uint32 LiquidFlags = itr2->HasLiquidData ? 1 : 0; fwrite(&LiquidFlags, sizeof(uint32), 1, output); fwrite(grp, sizeof(char), sizeof(grp), output); uint32 k = 0; uint32 mobaBatch = itr2->MOBALength / 12; uint32* MobaEx = new uint32[mobaBatch*4]; for(uint32 i = 8; i < itr2->MOBALength; i += 12) MobaEx[k++] = itr2->MOBA[i]; int mobaSizeGrp = mobaBatch * 4 + 4; fwrite(&mobaSizeGrp, 4, 1, output); fwrite(&mobaBatch, 4, 1, output); fwrite(MobaEx, 4, k, output); delete[] MobaEx; //@TODO: Finish this. } fclose(output); } } fclose(modelList); printf("GameObject models extraction finished!"); Constants::ToWoWCoords = false; }
/** Extract sub block number <code>n</code> from <code>problem</code>. * The constructor creates a representation of block number <code>n</code> * as described in <code>problem</code>. * The constructor will also connect the newly created block to a remote * object solver instance. * @param problem The problem from which the block is to be extracted. * @param n Index of the block to be extracted. * @param argc Argument for IloCplex constructor. * @param argv Argument for IloCplex constructor. * @param machines List of machines to which to connect. If the code is * compiled for the TCP/IP transport then the block will * be connected to <code>machines[n]</code>. */ BendersOpt::Block::Block(Problem const *problem, IloInt n, int argc, char const *const *argv, std::vector<char const *> const &machines) : env(), number(n), vars(0), rows(0), cplex(0), cb(0) { IloNumVarArray problemVars = problem->getVariables(); IloRangeArray problemRanges = problem->getRows(); // Create a map that maps variables in the original model to their // respective index in problemVars. std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> > origIdxMap; for (IloInt j = 0; j < problemVars.getSize(); ++j) origIdxMap.insert(std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> >::value_type(problemVars[j], j)); // Copy non-fixed variables from original problem into primal problem. IloExpr primalObj(env); IloNumVarArray primalVars(env); IloRangeArray primalRows(env); IdxMap idxMap; // Index of original variable in block's primal model RowSet rowSet; for (IloInt j = 0; j < problemVars.getSize(); ++j) { IloNumVar x = problemVars[j]; if ( problem->getBlock(x) == number ) { // Create column in block LP with exactly the same data. if ( x.getType() != IloNumVar::Float ) { std::stringstream s; s << "Cannot create non-continuous block variable " << x; std::cerr << s.str() << std::endl; throw s.str(); } IloNumVar v(env, x.getLB(), x.getUB(), x.getType(), x.getName()); // Normalize objective function to 'minimize' double coef = problem->getObjCoef(x); if ( problem->getObjSense() != IloObjective::Minimize ) coef *= -1.0; primalObj += coef * v; // Record the index that the copied variable has in the // block model. idxMap.insert(IdxMap::value_type(x, primalVars.getSize())); primalVars.add(v); // Mark the rows that are intersected by this column // so that we can collect them later. RowSet const &intersected = problem->getIntersectedRows(x); for (RowSet::const_iterator it = intersected.begin(); it != intersected.end(); ++it) rowSet.insert(*it); } else idxMap.insert(IdxMap::value_type(x, -1)); } // Now copy all rows that intersect block variables. for (IloInt i = 0; i < problemRanges.getSize(); ++i) { IloRange r = problemRanges[i]; if ( rowSet.find(r) == rowSet.end() ) continue; // Create a copy of the row, normalizing it to '<=' double factor = 1.0; if ( r.getLB() > -IloInfinity ) factor = -1.0; IloRange primalR(env, factor < 0 ? -r.getUB() : r.getLB(), factor < 0 ? -r.getLB() : r.getUB(), r.getName()); IloExpr lhs(env); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) { IloNumVar v = it.getVar(); double const val = factor * it.getCoef(); if ( problem->getBlock(v) != number ) { // This column is not explicitly in this block. This means // that it is a column that will be fixed by the master. // We collect all such columns so that we can adjust the // dual objective function according to concrete fixings. // Store information about variables in this block that // will be fixed by master solves. fixed.push_back(FixData(primalRows.getSize(), origIdxMap[v], -val)); } else { // The column is an ordinary in this block. Just copy it. lhs += primalVars[idxMap[v]] * val; } } primalR.setExpr(lhs); primalRows.add(primalR); lhs.end(); } // Create the dual of the primal model we just created. // Note that makeDual _always_ returns a 'maximize' objective. IloObjective objective(env, primalObj, IloObjective::Minimize); makeDual(objective, primalVars, primalRows, &obj, &vars, &rows); objective.end(); primalRows.endElements(); primalRows.end(); primalVars.endElements(); primalVars.end(); primalObj.end(); // Create a model. IloModel model(env); model.add(obj); model.add(vars); model.add(rows); for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) objMap.insert(ObjMap::value_type(it.getVar(), it.getCoef())); // Finally create the IloCplex instance that will solve // the problems associated with this block. char const **transargv = new char const *[argc + 3]; for (int i = 0; i < argc; ++i) transargv[i] = argv[i]; #if defined(USE_MPI) char extra[128]; sprintf (extra, "-remoterank=%d", static_cast<int>(number + 1)); transargv[argc++] = extra; (void)machines; #elif defined(USE_PROCESS) char extra[128]; sprintf (extra, "-logfile=block%04d.log", static_cast<int>(number)); transargv[argc++] = extra; (void)machines; #elif defined(USE_TCPIP) transargv[argc++] = machines[number]; #endif cplex = IloCplex(model, TRANSPORT, argc, transargv); delete[] transargv; // Suppress output from this block's solver. cplex.setOut(env.getNullStream()); cplex.setWarning(env.getNullStream()); }
QModelIndex ProposalTreeWidget::indexFromRow(int r) const { return model()->index(r, 0); }
void BBTrackContainerView::addAutomationTrack() { (void) Track::create( Track::AutomationTrack, model() ); }
MSStringEntryField::MSStringEntryField(MSWidget *owner_,MSString& model_,const char *label_,const MSSymbol& tag_): MSEntryFieldPlus(owner_,label_,tag_) { model(model_); }
int main (int argc, char **argv) { int result = 0; IloEnv env; try { static int indices[] = { 0, 1, 2, 3, 4, 5, 6 }; IloModel model(env); /* ***************************************************************** * * * * S E T U P P R O B L E M * * * * The model we setup here is * * Minimize * * obj: 3x1 - x2 + 3x3 + 2x4 + x5 + 2x6 + 4x7 * * Subject To * * c1: x1 + x2 = 4 * * c2: x1 + x3 >= 3 * * c3: x6 + x7 <= 5 * * c4: -x1 + x7 >= -2 * * q1: [ -x1^2 + x2^2 ] <= 0 * * q2: [ 4.25x3^2 -2x3*x4 + 4.25x4^2 - 2x4*x5 + 4x5^2 ] + 2 x1 <= 9.0 * q3: [ x6^2 - x7^2 ] >= 4 * * Bounds * * 0 <= x1 <= 3 * * x2 Free * * 0 <= x3 <= 0.5 * * x4 Free * * x5 Free * * x7 Free * * End * * * * ***************************************************************** */ IloNumVarArray x(env); x.add(IloNumVar(env, 0, 3, "x1")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x2")); x.add(IloNumVar(env, 0, 0.5, "x3")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x4")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x5")); x.add(IloNumVar(env, 0, IloInfinity, "x6")); x.add(IloNumVar(env, -IloInfinity, IloInfinity, "x7")); for (IloInt i = 0; i < x.getSize(); ++i) x[i].setObject(&indices[i]); IloObjective obj = IloMinimize(env, 3*x[0] - x[1] + 3*x[2] + 2*x[3] + x[4] + 2*x[5] + 4*x[6], "obj"); model.add(obj); IloRangeArray linear(env); linear.add(IloRange(env, 4.0, x[0] + x[1], 4.0, "c1")); linear.add(IloRange(env, 3.0, x[0] + x[2], IloInfinity, "c2")); linear.add(IloRange(env, -IloInfinity, x[5] + x[6], 5.0, "c3")); linear.add(IloRange(env, -2.0, -x[0] + x[6], IloInfinity, "c4")); for (IloInt i = 0; i < linear.getSize(); ++i) linear[i].setObject(&indices[i]); model.add(linear); IloRangeArray quad(env); quad.add(IloRange(env, -IloInfinity, -x[0]*x[0] + x[1] * x[1], 0, "q1")); quad.add(IloRange(env, -IloInfinity, 4.25*x[2]*x[2] - 2*x[2]*x[3] + 4.25*x[3]*x[3] + -2*x[3]*x[4] + 4*x[4]*x[4] + 2*x[0], 9.0, "q2")); quad.add(IloRange(env, 4.0, x[5]*x[5] - x[6]*x[6], IloInfinity, "q3")); for (IloInt i = 0; i < quad.getSize(); ++i) quad[i].setObject(&indices[i]); model.add(quad); /* ***************************************************************** * * * * O P T I M I Z E P R O B L E M * * * * ***************************************************************** */ IloCplex cplex(model); cplex.setParam(IloCplex::Param::Barrier::QCPConvergeTol, 1e-10); cplex.solve(); /* ***************************************************************** * * * * Q U E R Y S O L U T I O N * * * * ***************************************************************** */ IloNumArray xval(env); IloNumArray slack(env); IloNumArray qslack(env); IloNumArray cpi(env); IloNumArray rpi(env); IloNumArray qpi; cplex.getValues(x, xval); cplex.getSlacks(slack, linear); cplex.getSlacks(qslack, quad); cplex.getReducedCosts(cpi, x); cplex.getDuals(rpi, linear); qpi = getqconstrmultipliers(cplex, xval, quad); /* ***************************************************************** * * * * C H E C K K K T C O N D I T I O N S * * * * Here we verify that the optimal solution computed by CPLEX * * (and the qpi[] values computed above) satisfy the KKT * * conditions. * * * * ***************************************************************** */ // Primal feasibility: This example is about duals so we skip this test. // Dual feasibility: We must verify // - for <= constraints (linear or quadratic) the dual // multiplier is non-positive. // - for >= constraints (linear or quadratic) the dual // multiplier is non-negative. for (IloInt i = 0; i < linear.getSize(); ++i) { if ( linear[i].getLB() <= -IloInfinity ) { // <= constraint if ( rpi[i] > ZEROTOL ) { cerr << "Dual feasibility test failed for <= row " << i << ": " << rpi[i] << endl; result = -1; } } else if ( linear[i].getUB() >= IloInfinity ) { // >= constraint if ( rpi[i] < -ZEROTOL ) { cerr << "Dual feasibility test failed for >= row " << i << ":" << rpi[i] << endl; result = -1; } } else { // nothing to do for equality constraints } } for (IloInt q = 0; q < quad.getSize(); ++q) { if ( quad[q].getLB() <= -IloInfinity ) { // <= constraint if ( qpi[q] > ZEROTOL ) { cerr << "Dual feasibility test failed for <= quad " << q << ": " << qpi[q] << endl; result = -1; } } else if ( quad[q].getUB() >= IloInfinity ) { // >= constraint if ( qpi[q] < -ZEROTOL ) { cerr << "Dual feasibility test failed for >= quad " << q << ":" << qpi[q] << endl; result = -1; } } else { // nothing to do for equality constraints } } // Complementary slackness. // For any constraint the product of primal slack and dual multiplier // must be 0. for (IloInt i = 0; i < linear.getSize(); ++i) { if ( fabs (linear[i].getUB() - linear[i].getLB()) > ZEROTOL && fabs (slack[i] * rpi[i]) > ZEROTOL ) { cerr << "Complementary slackness test failed for row " << i << ": " << fabs (slack[i] * rpi[i]) << endl; result = -1; } } for (IloInt q = 0; q < quad.getSize(); ++q) { if ( fabs (quad[q].getUB() - quad[q].getLB()) > ZEROTOL && fabs (qslack[q] * qpi[q]) > ZEROTOL ) { cerr << "Complementary slackness test failed for quad " << q << ":" << fabs (qslack[q] * qpi[q]) << endl; result = -1; } } for (IloInt j = 0; j < x.getSize(); ++j) { if ( x[j].getUB() < IloInfinity ) { double const slk = x[j].getUB() - xval[j]; double const dual = cpi[j] < -ZEROTOL ? cpi[j] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { cerr << "Complementary slackness test failed for ub " << j << ": " << fabs (slk * dual) << endl; result = -1; } } if ( x[j].getLB() > -IloInfinity ) { double const slk = xval[j] - x[j].getLB(); double const dual = cpi[j] > ZEROTOL ? cpi[j] : 0.0; if ( fabs (slk * dual) > ZEROTOL ) { cerr << "Complementary slackness test failed for lb " << j << ": " << fabs (slk * dual) << endl; result = -1; } } } // Stationarity. // The difference between objective function and gradient at optimal // solution multiplied by dual multipliers must be 0, i.e., for the // optimal solution x // 0 == c // - sum(r in rows) r'(x)*rpi[r] // - sum(q in quads) q'(x)*qpi[q] // - sum(c in cols) b'(x)*cpi[c] // where r' and q' are the derivatives of a row or quadratic constraint, // x is the optimal solution and rpi[r] and qpi[q] are the dual // multipliers for row r and quadratic constraint q. // b' is the derivative of a bound constraint and cpi[c] the dual bound // multiplier for column c. IloNumArray kktsum(env, x.getSize()); // Objective function. for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] = it.getCoef(); // Linear constraints. // The derivative of a linear constraint ax - b (<)= 0 is just a. for (IloInt i = 0; i < linear.getSize(); ++i) { for (IloExpr::LinearIterator it = linear[i].getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] -= rpi[i] * it.getCoef(); } // Quadratic constraints. // The derivative of a constraint xQx + ax - b <= 0 is // Qx + Q'x + a. for (IloInt q = 0; q < quad.getSize(); ++q) { for (IloExpr::LinearIterator it = quad[q].getLinearIterator(); it.ok(); ++it) kktsum[idx(it.getVar())] -= qpi[q] * it.getCoef(); for (IloExpr::QuadIterator it = quad[q].getQuadIterator(); it.ok(); ++it) { kktsum[idx(it.getVar1())] -= qpi[q] * xval[idx(it.getVar2())] * it.getCoef(); kktsum[idx(it.getVar2())] -= qpi[q] * xval[idx(it.getVar1())] * it.getCoef(); } } // Bounds. // The derivative for lower bounds is -1 and that for upper bounds // is 1. // CPLEX already returns dj with the appropriate sign so there is // no need to distinguish between different bound types here. for (IloInt j = 0; j < x.getSize(); ++j) kktsum[j] -= cpi[j]; for (IloInt j = 0; j < kktsum.getSize(); ++j) { if ( fabs (kktsum[j]) > ZEROTOL ) { cerr << "Stationarity test failed at index " << j << ": " << kktsum[j] << endl; result = -1; } } if ( result == 0) { // KKT conditions satisfied. Dump out the optimal solutions and // the dual values. streamsize oprec = cout.precision(3); ios_base::fmtflags oflags = cout.setf(ios::fixed | ios::showpos); cout << "Optimal solution satisfies KKT conditions." << endl; cout << " x[] = " << xval << endl; cout << " cpi[] = " << cpi << endl; cout << " rpi[] = " << rpi << endl; cout << " qpi[] = " << qpi << endl; cout.precision(oprec); cout.flags(oflags); } } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; result = -1; } catch (...) { cerr << "Unknown exception caught" << endl; result = -1; } env.end(); return result; } // END main
void InstrumentTrackView::activityIndicatorReleased() { model()->processInEvent( MidiEvent( MidiNoteOff, 0, DefaultKey, 0 ) ); }
TEST(McmcHmcIntegratorsImplLeapfrog, unit_e_symplecticness) { rng_t base_rng(0); std::fstream data_stream(std::string("").c_str(), std::fstream::in); stan::io::dump data_var_context(data_stream); data_stream.close(); std::stringstream model_output; std::stringstream metric_output; stan::interface_callbacks::writer::stream_writer writer(metric_output); std::stringstream error_stream; stan::interface_callbacks::writer::stream_writer error_writer(error_stream); gauss_model_namespace::gauss_model model(data_var_context, &model_output); stan::mcmc::impl_leapfrog< stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> > integrator; stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> metric(model); // Create a circle of points const int n_points = 1000; double pi = 3.141592653589793; double r = 1.5; double q0 = 1; double p0 = 0; std::vector<stan::mcmc::unit_e_point> z; for (int i = 0; i < n_points; ++i) { z.push_back(stan::mcmc::unit_e_point(1)); double theta = 2 * pi * (double)i / (double)n_points; z.back().q(0) = r * cos(theta) + q0; z.back().p(0) = r * sin(theta) + p0; } // Evolve circle double epsilon = 1e-3; size_t L = pi / epsilon; for (int i = 0; i < n_points; ++i) metric.init(z.at(i), writer, error_writer); for (size_t n = 0; n < L; ++n) for (int i = 0; i < n_points; ++i) integrator.evolve(z.at(i), metric, epsilon, writer, error_writer); // Compute area of evolved shape using divergence theorem in 2D double area = 0; for (int i = 0; i < n_points; ++i) { double x1 = z[i].q(0); double y1 = z[i].p(0); double x2 = z[(i + 1) % n_points].q(0); double y2 = z[(i + 1) % n_points].p(0); double x_bary = 0.5 * (x1 + x2); double y_bary = 0.5 * (y1 + y2); double x_delta = x2 - x1; double y_delta = y2 - y1; double a = sqrt( x_delta * x_delta + y_delta * y_delta); double x_norm = 1; double y_norm = - x_delta / y_delta; double norm = sqrt( x_norm * x_norm + y_norm * y_norm ); a *= (x_bary * x_norm + y_bary * y_norm) / norm; a = a < 0 ? -a : a; area += a; } area *= 0.5; // Symplectic integrators preserve volume (area in 2D) EXPECT_NEAR(area, pi * r * r, 1e-2); EXPECT_EQ("", model_output.str()); EXPECT_EQ("", metric_output.str()); }
void InstrumentTrackView::midiConfigChanged() { m_midiInputAction->setChecked( model()->m_midiPort.isReadable() ); m_midiOutputAction->setChecked( model()->m_midiPort.isWritable() ); }
int main (void) { IloEnv env; try { IloModel model(env); IloCplex cplex(env); IloInt nbWhouses = 4; IloInt nbLoads = 31; IloInt w, l; IloNumVarArray capVars(env, nbWhouses, 0, 10, ILOINT); // Used capacities IloNumArray capLbs (env, nbWhouses, 2, 3, 5, 7); // Minimum usage level IloNumArray costs (env, nbWhouses, 1, 2, 4, 6); // Cost per warehouse // These variables represent the assigninment of a // load to a warehouse. IloNumVarArrayArray assignVars(env, nbWhouses); for (w = 0; w < nbWhouses; w++) { assignVars[w] = IloNumVarArray(env, nbLoads, 0, 1, ILOINT); // Links the number of loads assigned to a warehouse with // the capacity variable of the warehouse. model.add(IloSum(assignVars[w]) == capVars[w]); } // Each load must be assigned to just one warehouse. for (l = 0; l < nbLoads; l++) { IloNumVarArray aux(env); for (w = 0; w < nbWhouses; w++) aux.add(assignVars[w][l]); model.add(IloSum(aux) == 1); aux.end(); } model.add (IloMinimize(env, IloScalProd(costs, capVars))); cplex.extract(model); cplex.setParam(IloCplex::Param::MIP::Strategy::Search, IloCplex::Traditional); if ( cplex.solve(SemiContGoal(env, capVars, capLbs)) ) { cout << " --------------------------------------------------" << endl; cout << "Solution status: " << cplex.getStatus() << endl; cout << endl << "Solution found:" << endl; cout << " Objective value = " << cplex.getObjValue() << endl << endl; for (w = 0; w < nbWhouses; w++) { cout << "Warehouse " << w << ": stored " << cplex.getValue(capVars[w]) << " loads" << endl; for (l = 0; l < nbLoads; l++) { if ( cplex.getValue(assignVars[w][l]) > 1e-5 ) cout << "Load " << l << " | "; } cout << endl << endl; } cout << " --------------------------------------------------" << endl; } else { cout << " No solution found " << endl; } } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } env.end(); return 0; } // END main
void EditTreeView::removeAll() { if (!model()) return; model()->removeRows(0, model()->rowCount(rootIndex()), rootIndex()); }
void ThreadsWindow::resizeColumnsToContents() { const int columnCount = model()->columnCount(); for (int c = 0 ; c < columnCount; c++) resizeColumnToContents(c); }
void PieView::paintEvent(QPaintEvent *event) { QItemSelectionModel *selections = selectionModel(); QStyleOptionViewItem option = viewOptions(); QStyle::State state = option.state; QBrush background = option.palette.base(); QPen foreground(option.palette.color(QPalette::WindowText)); QPen textPen(option.palette.color(QPalette::Text)); QPen highlightedPen(option.palette.color(QPalette::HighlightedText)); QPainter painter(viewport()); painter.setRenderHint(QPainter::Antialiasing); painter.fillRect(event->rect(), background); painter.setPen(foreground); // Viewport rectangles QRect pieRect = QRect(margin, margin, pieSize, pieSize); QPoint keyPoint = QPoint(totalSize - horizontalScrollBar()->value(), margin - verticalScrollBar()->value()); if (validItems > 0) { painter.save(); painter.translate(pieRect.x() - horizontalScrollBar()->value(), pieRect.y() - verticalScrollBar()->value()); painter.drawEllipse(0, 0, pieSize, pieSize); double startAngle = 0.0; int row; for (row = 0; row < model()->rowCount(rootIndex()); ++row) { QModelIndex index = model()->index(row, 1, rootIndex()); double value = model()->data(index).toDouble(); if (value > 0.0) { double angle = 360*value/totalValue; QModelIndex colorIndex = model()->index(row, 0, rootIndex()); QColor color = QColor(model()->data(colorIndex, Qt::DecorationRole).toString()); if (currentIndex() == index) painter.setBrush(QBrush(color, Qt::Dense4Pattern)); else if (selections->isSelected(index)) painter.setBrush(QBrush(color, Qt::Dense3Pattern)); else painter.setBrush(QBrush(color)); painter.drawPie(0, 0, pieSize, pieSize, int(startAngle*16), int(angle*16)); startAngle += angle; } } painter.restore(); int keyNumber = 0; for (row = 0; row < model()->rowCount(rootIndex()); ++row) { QModelIndex index = model()->index(row, 1, rootIndex()); double value = model()->data(index).toDouble(); if (value > 0.0) { QModelIndex labelIndex = model()->index(row, 0, rootIndex()); QStyleOptionViewItem option = viewOptions(); option.rect = visualRect(labelIndex); if (selections->isSelected(labelIndex)) option.state |= QStyle::State_Selected; if (currentIndex() == labelIndex) option.state |= QStyle::State_HasFocus; itemDelegate()->paint(&painter, option, labelIndex); keyNumber++; } } } }
void KateCompletionTree::resizeColumns(bool firstShow, bool forceResize) { static bool preventRecursion = false; if (preventRecursion) { return; } m_resizeTimer->stop(); if (firstShow) { forceResize = true; } preventRecursion = true; widget()->setUpdatesEnabled(false); int modelIndexOfName = kateModel()->translateColumn(KTextEditor::CodeCompletionModel::Name); int oldIndentWidth = columnViewportPosition(modelIndexOfName); ///Step 1: Compute the needed column-sizes for the visible content const int numColumns = model()->columnCount(); QVarLengthArray<int, 8> columnSize(numColumns); for (int i = 0; i < numColumns; ++i) { columnSize[i] = 5; } QModelIndex current = indexAt(QPoint(1, 1)); const bool changed = current.isValid(); int currentYPos = 0; measureColumnSizes(this, current, columnSize, currentYPos, height()); int totalColumnsWidth = 0, originalViewportWidth = viewport()->width(); int maxWidth = (QApplication::desktop()->screenGeometry(widget()->view()).width() * 3) / 4; ///Step 2: Update column-sizes //This contains several hacks to reduce the amount of resizing that happens. Generally, //resizes only happen if a) More than a specific amount of space is saved by the resize, or //b) the resizing is required so the list can show all of its contents. int minimumResize = 0; int maximumResize = 0; if (changed) { for (int n = 0; n < numColumns; n++) { totalColumnsWidth += columnSize[n]; int diff = columnSize[n] - columnWidth(n); if (diff < minimumResize) { minimumResize = diff; } if (diff > maximumResize) { maximumResize = diff; } } int noReduceTotalWidth = 0; //The total width of the widget of no columns are reduced for (int n = 0; n < numColumns; n++) { if (columnSize[n] < columnWidth(n)) { noReduceTotalWidth += columnWidth(n); } else { noReduceTotalWidth += columnSize[n]; } } //Check whether we can afford to reduce none of the columns //Only reduce size if we widget would else be too wide. bool noReduce = noReduceTotalWidth < maxWidth && !forceResize; if (noReduce) { totalColumnsWidth = 0; for (int n = 0; n < numColumns; n++) { if (columnSize[n] < columnWidth(n)) { columnSize[n] = columnWidth(n); } totalColumnsWidth += columnSize[n]; } } if (minimumResize > -40 && maximumResize == 0 && !forceResize) { //No column needs to be exanded, and no column needs to be reduced by more than 40 pixels. //To prevent flashing, do not resize at all. totalColumnsWidth = 0; for (int n = 0; n < numColumns; n++) { columnSize[n] = columnWidth(n); totalColumnsWidth += columnSize[n]; } } else { // viewport()->resize( 5000, viewport()->height() ); for (int n = 0; n < numColumns; n++) { setColumnWidth(n, columnSize[n]); } // qCDebug(LOG_KTE) << "resizing viewport to" << totalColumnsWidth; viewport()->resize(totalColumnsWidth, viewport()->height()); } } ///Step 3: Update widget-size and -position int scrollBarWidth = verticalScrollBar()->width(); int newIndentWidth = columnViewportPosition(modelIndexOfName); int newWidth = qMin(maxWidth, qMax(75, totalColumnsWidth)); if (newWidth == maxWidth) { setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); } else { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } if (maximumResize > 0 || forceResize || oldIndentWidth != newIndentWidth) { // qCDebug(LOG_KTE) << geometry() << "newWidth" << newWidth << "current width" << width() << "target width" << newWidth + scrollBarWidth; if ((newWidth + scrollBarWidth) != width() && originalViewportWidth != totalColumnsWidth) { widget()->resize(newWidth + scrollBarWidth + 2, widget()->height()); resize(newWidth + scrollBarWidth, widget()->height() - (2 * widget()->frameWidth())); } // qCDebug(LOG_KTE) << "created geometry:" << widget()->geometry() << geometry() << "newWidth" << newWidth << "viewport" << viewport()->width(); if (viewport()->width() > totalColumnsWidth) { //Set the size of the last column to fill the whole rest of the widget setColumnWidth(numColumns - 1, viewport()->width() - columnViewportPosition(numColumns - 1)); } /* for(int a = 0; a < numColumns; ++a) qCDebug(LOG_KTE) << "column" << a << columnWidth(a) << "target:" << columnSize[a];*/ if (oldIndentWidth != newIndentWidth) if (widget()->updatePosition() && !forceResize) { preventRecursion = false; resizeColumns(true, true); } } widget()->setUpdatesEnabled(true); preventRecursion = false; }
int PieView::rows(const QModelIndex &index) const { return model()->rowCount(model()->parent(index)); }
QPixmap KFileItemListView::createDragPixmap(const KItemSet& indexes) const { if (!model()) { return QPixmap(); } const int itemCount = indexes.count(); Q_ASSERT(itemCount > 0); if (itemCount == 1) { return KItemListView::createDragPixmap(indexes); } // If more than one item is dragged, align the items inside a // rectangular grid. The maximum grid size is limited to 5 x 5 items. int xCount; int size; if (itemCount > 16) { xCount = 5; size = KIconLoader::SizeSmall; } else if (itemCount > 9) { xCount = 4; size = KIconLoader::SizeSmallMedium; } else { xCount = 3; size = KIconLoader::SizeMedium; } if (itemCount < xCount) { xCount = itemCount; } int yCount = itemCount / xCount; if (itemCount % xCount != 0) { ++yCount; } if (yCount > xCount) { yCount = xCount; } const qreal dpr = scene()->views()[0]->devicePixelRatio(); // Draw the selected items into the grid cells. QPixmap dragPixmap(QSize(xCount * size + xCount, yCount * size + yCount) * dpr); dragPixmap.setDevicePixelRatio(dpr); dragPixmap.fill(Qt::transparent); QPainter painter(&dragPixmap); int x = 0; int y = 0; foreach (int index, indexes) { QPixmap pixmap = model()->data(index).value("iconPixmap").value<QPixmap>(); if (pixmap.isNull()) { QIcon icon = QIcon::fromTheme(model()->data(index).value("iconName").toString()); pixmap = icon.pixmap(size, size); } else { KPixmapModifier::scale(pixmap, QSize(size, size) * dpr); } painter.drawPixmap(x, y, pixmap); x += size + 1; if (x >= dragPixmap.width()) { x = 0; y += size + 1; } if (y >= dragPixmap.height()) { break; } }
QModelIndex PieView::indexAt(const QPoint &point) const { if (validItems == 0) return QModelIndex(); // Transform the view coordinates into contents widget coordinates. int wx = point.x() + horizontalScrollBar()->value(); int wy = point.y() + verticalScrollBar()->value(); if (wx < totalSize) { double cx = wx - totalSize/2; double cy = totalSize/2 - wy; // positive cy for items above the center // Determine the distance from the center point of the pie chart. double d = pow(pow(cx, 2) + pow(cy, 2), 0.5); if (d == 0 || d > pieSize/2) return QModelIndex(); // Determine the angle of the point. double angle = (180 / M_PI) * acos(cx/d); if (cy < 0) angle = 360 - angle; // Find the relevant slice of the pie. double startAngle = 0.0; for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { QModelIndex index = model()->index(row, 1, rootIndex()); double value = model()->data(index).toDouble(); if (value > 0.0) { double sliceAngle = 360*value/totalValue; if (angle >= startAngle && angle < (startAngle + sliceAngle)) return model()->index(row, 1, rootIndex()); startAngle += sliceAngle; } } } else { double itemHeight = QFontMetrics(viewOptions().font).height(); int listItem = int((wy - margin) / itemHeight); int validRow = 0; for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { QModelIndex index = model()->index(row, 1, rootIndex()); if (model()->data(index).toDouble() > 0.0) { if (listItem == validRow) return model()->index(row, 0, rootIndex()); // Update the list index that corresponds to the next valid row. validRow++; } } } return QModelIndex(); }
QVariant QgsSymbolV2LegendNode::data( int role ) const { if ( role == Qt::DisplayRole ) { return mLabel; } else if ( role == Qt::EditRole ) { return mUserLabel.isEmpty() ? mItem.label() : mUserLabel; } else if ( role == Qt::DecorationRole ) { if ( mPixmap.isNull() || mPixmap.size() != mIconSize ) { QPixmap pix; if ( mItem.symbol() ) { QScopedPointer<QgsRenderContext> context( createTemporaryRenderContext() ); pix = QgsSymbolLayerV2Utils::symbolPreviewPixmap( mItem.symbol(), mIconSize, context.data() ); } else { pix = QPixmap( mIconSize ); pix.fill( Qt::transparent ); } if ( mItem.level() == 0 || ( model() && model()->testFlag( QgsLayerTreeModel::ShowLegendAsTree ) ) ) mPixmap = pix; else { // ident the symbol icon to make it look like a tree structure QPixmap pix2( pix.width() + mItem.level() * indentSize, pix.height() ); pix2.fill( Qt::transparent ); QPainter p( &pix2 ); p.drawPixmap( mItem.level() * indentSize, 0, pix ); p.end(); mPixmap = pix2; } } return mPixmap; } else if ( role == Qt::CheckStateRole ) { if ( !mItem.isCheckable() ) return QVariant(); QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( mLayerNode->layer() ); if ( !vlayer || !vlayer->rendererV2() ) return QVariant(); return vlayer->rendererV2()->legendSymbolItemChecked( mItem.ruleKey() ) ? Qt::Checked : Qt::Unchecked; } else if ( role == RuleKeyRole ) { return mItem.ruleKey(); } else if ( role == SymbolV2LegacyRuleKeyRole ) { return QVariant::fromValue<void*>( mItem.legacyRuleKey() ); } else if ( role == ParentRuleKeyRole ) { return mItem.parentRuleKey(); } return QVariant(); }
int KNNotificationView::heightHint() const { return (model()==nullptr || model()->rowCount()==0)? 45:model()->rowCount()*NotificationItemHeight; }
/** * The main entry of dw-lr-train, whose goal * is to takes as input in the same format as * libsvm, and train a classifier. **/ int main(int argc, char ** argv){ /** * First, parse command line input to get * (1) step size * (2) number of epoches to run * (3) regularization (l2) **/ std::string filename; int flags, opt; int nsecs, tfnd; nsecs = 0; tfnd = 0; flags = 0; while ((opt = getopt(argc, argv, "s:e:r:")) != -1) { switch (opt) { case 's': stepsize = atof(optarg); break; case 'e': epoches = atof(optarg); break; case 'r': lambda = atof(optarg); break; default: fprintf(stderr, "Usage: %s [-s stepsize] [-e epoches] [-r regularization] trainfile\n", argv[0]); exit(EXIT_FAILURE); } } if (optind >= argc) { fprintf(stderr, "Expected argument after options\n"); exit(EXIT_FAILURE); } filename = std::string(argv[optind]); printf("stepsize=%f; epoches=%f; lambda=%f\n", stepsize, epoches, lambda); printf("trainfile = %s\n", filename.c_str()); /** * Second, create corpus **/ size_t n_elements, n_examples, n_features; double * p_examples; long * p_cols; long * p_rows; get_corpus_stats(filename.c_str(), &n_elements, &n_examples); n_features = create_dw_corpus(filename.c_str(), n_elements, n_examples, p_examples, p_cols, p_rows); printf("#elements=%zu; #examples=%zu; #n_features=%zu\n", n_elements, n_examples, n_features); /** * Third, create DimmWitted object, and let it run. **/ GLMModelExample_Sparse model(n_features); for(int i=0;i<model.n;i++){ model.p[i] = 0.0; } SparseDimmWitted<double, GLMModelExample_Sparse, DW_MODELREPL_PERMACHINE, DW_DATAREPL_SHARDING, DW_ACCESS_ROW> dw(p_examples, p_rows, p_cols, n_examples, n_features+1, n_elements, &model); unsigned int f_handle_grad = dw.register_row(f_lr_grad_sparse); unsigned int f_handle_loss = dw.register_row(f_lr_loss_sparse); dw.register_model_avg(f_handle_grad, f_lr_modelavg); dw.register_model_avg(f_handle_loss, f_lr_modelavg); printf("Start training...\n"); double sum = 0.0; for(int i_epoch=0;i_epoch<epoches;i_epoch++){ double loss = dw.exec(f_handle_loss)/n_examples; std::cout << "loss=" << loss << std::endl; dw.exec(f_handle_grad); } /** * Forth, dump result. **/ printf("Dumping training result to %s.model...\n", filename.c_str()); std::ofstream fout((filename + ".model").c_str()); fout << n_features << std::endl; for(int i=0;i<model.n;i++){ fout << model.p[i] << std::endl; } fout.close(); exit(EXIT_SUCCESS); }
int main() { Leph::HumanoidFloatingModel model(Leph::SigmabanModel); model.putOnGround(); Leph::ModelViewer viewer(1200, 900); //Inverse Kinematics Leph::InverseKinematics inv(model); //Declare model degrees of freedom inv.addDOF("right_hip_pitch"); inv.addDOF("right_hip_roll"); inv.addDOF("right_knee"); inv.addDOF("right_ankle_pitch"); inv.addDOF("right_ankle_roll"); inv.addDOF("left_hip_pitch"); inv.addDOF("left_hip_roll"); inv.addDOF("left_knee"); inv.addDOF("left_ankle_pitch"); inv.addDOF("left_ankle_roll"); inv.addDOF("base_x"); inv.addDOF("base_y"); inv.addDOF("base_z"); //Declare degree of freefom box bounds //XXX Not fully implemented inv.setLowerBound("left_knee", 0.0); inv.setLowerBound("right_knee", 0.0); //Declare target position inv.addTargetPosition("flying_foot", "right_foot_tip"); inv.addTargetPosition("support_foot", "left_foot_tip"); //target of center of mass inv.addTargetCOM(); inv.targetCOM().z() -= 0.05; //Target orientation inv.addTargetOrientation("flying_foot", "right_foot_tip"); inv.addTargetOrientation("support_foot", "left_foot_tip"); Leph::Chrono chrono; double t = 0.0; while (viewer.update()) { t += 0.01; //Update targets inv.targetPosition("flying_foot").z() = 0.05+0.02*sin(t); inv.targetPosition("flying_foot").x() = 0.05+0.02*sin(2.0*t); inv.targetCOM().y() = 0.01*sin(t); inv.targetCOM().x() = 0.01*sin(2.0*t); chrono.start("InverseKinematics"); //Compute Inverse Kinematics inv.run(0.0001, 100); chrono.stop("InverseKinematics"); chrono.print(); std::cout << "ERRORS" << std::endl; std::cout << "COM pos: " << inv.errorCOM() << std::endl; std::cout << "Flying foot pos: " << inv.errorPosition("flying_foot") << std::endl; std::cout << "Support foot pos: " << inv.errorPosition("support_foot") << std::endl; std::cout << "Flying foot orientation: " << inv.errorOrientation("flying_foot") << std::endl; std::cout << "Support foot orientation: " << inv.errorOrientation("support_foot") << std::endl; //Display Eigen::Vector3d pt = model.centerOfMass("origin"); viewer.addTrackedPoint(pt); Leph::ModelDraw(model, viewer); } return 0; }