Brute force optimization code, buggy yet

wip


wip


wip refactor
This commit is contained in:
tamasmeszaros 2020-08-27 23:13:05 +02:00
parent b4e30cc8ad
commit c193d7c930
7 changed files with 427 additions and 227 deletions

View file

@ -4,6 +4,7 @@
#include <tbb/spin_mutex.h>
#include <tbb/mutex.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>
#include <algorithm>
#include <libslic3r/libslic3r.h>
@ -21,28 +22,43 @@ template<> struct _ccr<true>
using SpinningMutex = tbb::spin_mutex;
using BlockingMutex = tbb::mutex;
template<class Fn, class It>
static IteratorOnly<It, void> loop_(const tbb::blocked_range<It> &range, Fn &&fn)
{
for (auto &el : range) fn(el);
}
template<class Fn, class I>
static IntegerOnly<I, void> loop_(const tbb::blocked_range<I> &range, Fn &&fn)
{
for (I i = range.begin(); i < range.end(); ++i) fn(i);
}
template<class It, class Fn>
static IteratorOnly<It, void> for_each(It from,
It to,
Fn && fn,
size_t granularity = 1)
static void for_each(It from, It to, Fn &&fn, size_t granularity = 1)
{
tbb::parallel_for(tbb::blocked_range{from, to, granularity},
[&fn, from](const auto &range) {
for (auto &el : range) fn(el);
loop_(range, std::forward<Fn>(fn));
});
}
template<class I, class Fn>
static IntegerOnly<I, void> for_each(I from,
I to,
Fn && fn,
size_t granularity = 1)
template<class I, class Fn, class MergeFn, class T>
static T reduce(I from,
I to,
const T & init,
Fn && fn,
MergeFn &&mergefn,
size_t granularity = 1)
{
tbb::parallel_for(tbb::blocked_range{from, to, granularity},
[&fn](const auto &range) {
for (I i = range.begin(); i < range.end(); ++i) fn(i);
});
return tbb::parallel_reduce(
tbb::blocked_range{from, to, granularity}, init,
[&](const auto &range, T subinit) {
T acc = subinit;
loop_(range, [&](auto &i) { acc = mergefn(acc, fn(i, acc)); });
return acc;
},
std::forward<MergeFn>(mergefn));
}
};
@ -55,23 +71,39 @@ public:
using SpinningMutex = _Mtx;
using BlockingMutex = _Mtx;
template<class It, class Fn>
static IteratorOnly<It, void> for_each(It from,
It to,
Fn &&fn,
size_t /* ignore granularity */ = 1)
template<class Fn, class It>
static IteratorOnly<It, void> loop_(It from, It to, Fn &&fn)
{
for (auto it = from; it != to; ++it) fn(*it);
}
template<class I, class Fn>
static IntegerOnly<I, void> for_each(I from,
I to,
Fn &&fn,
size_t /* ignore granularity */ = 1)
template<class Fn, class I>
static IntegerOnly<I, void> loop_(I from, I to, Fn &&fn)
{
for (I i = from; i < to; ++i) fn(i);
}
template<class It, class Fn>
static void for_each(It from,
It to,
Fn &&fn,
size_t /* ignore granularity */ = 1)
{
loop_(from, to, std::forward<Fn>(fn));
}
template<class I, class Fn, class MergeFn, class T>
static IntegerOnly<I, T> reduce(I from,
I to,
const T & init,
Fn && fn,
MergeFn &&mergefn,
size_t /*granularity*/ = 1)
{
T acc = init;
loop_(from, to, [&](auto &i) { acc = mergefn(acc, fn(i, acc)); });
return acc;
}
};
using ccr = _ccr<USE_FULL_CONCURRENCY>;

View file

@ -2,23 +2,19 @@
#include <exception>
//#include <libnest2d/optimizers/nlopt/genetic.hpp>
#include <libslic3r/Optimizer.hpp>
#include <libslic3r/Optimize/BruteforceOptimizer.hpp>
#include <libslic3r/SLA/Rotfinder.hpp>
#include <libslic3r/SLA/Concurrency.hpp>
#include <libslic3r/SLA/SupportTree.hpp>
#include <libslic3r/SLA/SupportPointGenerator.hpp>
#include <libslic3r/SimplifyMesh.hpp>
#include "Model.hpp"
#include <thread>
namespace Slic3r {
namespace sla {
double area(const Vec3d &p1, const Vec3d &p2, const Vec3d &p3) {
Vec3d a = p2 - p1;
Vec3d b = p3 - p1;
Vec3d c = a.cross(b);
return 0.5 * c.norm();
}
using VertexFaceMap = std::vector<std::vector<size_t>>;
VertexFaceMap create_vertex_face_map(const TriangleMesh &mesh) {
@ -35,61 +31,75 @@ VertexFaceMap create_vertex_face_map(const TriangleMesh &mesh) {
return vmap;
}
// Find transformed mesh ground level without copy and with parallell reduce.
double find_ground_level(const TriangleMesh &mesh,
const Transform3d & tr,
size_t threads)
{
size_t vsize = mesh.its.vertices.size();
auto minfn = [](double a, double b) { return std::min(a, b); };
auto findminz = [&mesh, &tr] (size_t vi, double submin) {
Vec3d v = tr * mesh.its.vertices[vi].template cast<double>();
return std::min(submin, v.z());
};
double zmin = mesh.its.vertices.front().z();
return ccr_par::reduce(size_t(0), vsize, zmin, findminz, minfn,
vsize / threads);
}
// Try to guess the number of support points needed to support a mesh
double calculate_model_supportedness(const TriangleMesh & mesh,
const VertexFaceMap &vmap,
// const VertexFaceMap &vmap,
const Transform3d & tr)
{
static const double POINTS_PER_UNIT_AREA = 1.;
static const Vec3d DOWN = {0., 0., -1.};
static constexpr double POINTS_PER_UNIT_AREA = 1.;
double score = 0.;
if (mesh.its.vertices.empty()) return std::nan("");
// double zmin = mesh.bounding_box().min.z();
size_t Nthr = std::thread::hardware_concurrency();
size_t facesize = mesh.its.indices.size();
// std::vector<Vec3d> normals(mesh.its.indices.size(), Vec3d::Zero());
double zmin = find_ground_level(mesh, tr, Nthr);
double zmin = 0;
for (auto & v : mesh.its.vertices)
zmin = std::min(zmin, double((tr * v.cast<double>()).z()));
auto score_mergefn = [&mesh, &tr, zmin](size_t fi, double subscore) {
static const Vec3d DOWN = {0., 0., -1.};
for (size_t fi = 0; fi < mesh.its.indices.size(); ++fi) {
const auto &face = mesh.its.indices[fi];
Vec3d p1 = tr * mesh.its.vertices[face(0)].cast<double>();
Vec3d p2 = tr * mesh.its.vertices[face(1)].cast<double>();
Vec3d p3 = tr * mesh.its.vertices[face(2)].cast<double>();
Vec3d p1 = tr * mesh.its.vertices[face(0)].template cast<double>();
Vec3d p2 = tr * mesh.its.vertices[face(1)].template cast<double>();
Vec3d p3 = tr * mesh.its.vertices[face(2)].template cast<double>();
// auto triang = std::array<Vec3d, 3> {p1, p2, p3};
// double a = area(triang.begin(), triang.end());
double a = area(p1, p2, p3);
Vec3d U = p2 - p1;
Vec3d V = p3 - p1;
Vec3d C = U.cross(V);
Vec3d N = C.normalized();
double area = 0.5 * C.norm();
double zlvl = zmin + 0.1;
if (p1.z() <= zlvl && p2.z() <= zlvl && p3.z() <= zlvl) {
score += a * POINTS_PER_UNIT_AREA;
continue;
// score += area * POINTS_PER_UNIT_AREA;
return subscore;
}
double phi = 1. - std::acos(N.dot(DOWN)) / PI;
phi = phi * (phi > 0.5);
Eigen::Vector3d U = p2 - p1;
Eigen::Vector3d V = p3 - p1;
Vec3d N = U.cross(V).normalized();
// std::cout << "area: " << area << std::endl;
double phi = std::acos(N.dot(DOWN)) / PI;
subscore += area * POINTS_PER_UNIT_AREA * phi;
std::cout << "area: " << a << std::endl;
return subscore;
};
score += a * POINTS_PER_UNIT_AREA * phi;
// normals[fi] = N;
}
double score = ccr_seq::reduce(size_t(0), facesize, 0., score_mergefn,
std::plus<double>{}, facesize / Nthr);
// for (size_t vi = 0; vi < mesh.its.vertices.size(); ++vi) {
// const std::vector<size_t> &neighbors = vmap[vi];
// const auto &v = mesh.its.vertices[vi];
// Vec3d vt = tr * v.cast<double>();
// }
return score;
return score / mesh.its.indices.size();
}
std::array<double, 2> find_best_rotation(const ModelObject& modelobj,
@ -97,7 +107,7 @@ std::array<double, 2> find_best_rotation(const ModelObject& modelobj,
std::function<void(unsigned)> statuscb,
std::function<bool()> stopcond)
{
static const unsigned MAX_TRIES = 1000000;
static const unsigned MAX_TRIES = 100;
// return value
std::array<double, 2> rot;
@ -126,12 +136,14 @@ std::array<double, 2> find_best_rotation(const ModelObject& modelobj,
auto objfunc = [&mesh, &status, &statuscb, &stopcond, max_tries]
(const opt::Input<2> &in)
{
std::cout << "in: " << in[0] << " " << in[1] << std::endl;
// prepare the rotation transformation
Transform3d rt = Transform3d::Identity();
rt.rotate(Eigen::AngleAxisd(in[1], Vec3d::UnitY()));
rt.rotate(Eigen::AngleAxisd(in[0], Vec3d::UnitX()));
double score = sla::calculate_model_supportedness(mesh, {}, rt);
double score = sla::calculate_model_supportedness(mesh, rt);
std::cout << score << std::endl;
// report status
@ -142,10 +154,11 @@ std::array<double, 2> find_best_rotation(const ModelObject& modelobj,
// Firing up the genetic optimizer. For now it uses the nlopt library.
opt::Optimizer<opt::AlgNLoptDIRECT> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.rel_score_diff(1e-3)
.stop_condition(stopcond));
opt::Optimizer<opt::AlgBruteForce> solver(opt::StopCriteria{}
.max_iterations(max_tries)
.rel_score_diff(1e-6)
.stop_condition(stopcond),
10 /*grid size*/);
// We are searching rotations around the three axes x, y, z. Thus the
// problem becomes a 3 dimensional optimization task.
@ -153,7 +166,7 @@ std::array<double, 2> find_best_rotation(const ModelObject& modelobj,
auto b = opt::Bound{-PI, PI};
// Now we start the optimization process with initial angles (0, 0, 0)
auto result = solver.to_max().optimize(objfunc, opt::initvals({0.0, 0.0}),
auto result = solver.to_min().optimize(objfunc, opt::initvals({0.0, 0.0}),
opt::bounds({b, b}));
// Save the result and fck off

View file

@ -1,7 +1,7 @@
#include <libslic3r/SLA/SupportTreeBuildsteps.hpp>
#include <libslic3r/SLA/SpatIndex.hpp>
#include <libslic3r/Optimizer.hpp>
#include <libslic3r/Optimize/NLoptOptimizer.hpp>
#include <boost/log/trivial.hpp>
namespace Slic3r {