Lagrange
sortrows.h
1/*
2 * Copyright 2022 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include <Eigen/Dense>
15
16// clang-format off
17#include <lagrange/utils/warnoff.h>
18#include <tbb/parallel_sort.h>
19#include <lagrange/utils/warnon.h>
20// clang-format on
21
22#include <algorithm>
23#include <numeric>
24
25namespace lagrange::internal {
26
27template <typename DerivedX, typename DerivedIX>
28void sortrows(
29 const Eigen::DenseBase<DerivedX>& X,
30 const bool ascending,
31 Eigen::PlainObjectBase<DerivedX>& Y,
32 Eigen::PlainObjectBase<DerivedIX>& IX)
33{
34 using Index = typename DerivedIX::Scalar;
35
36 // Resize output
37 Y.resizeLike(X);
38 IX.resize(X.rows(), 1);
39 std::iota(IX.begin(), IX.end(), Index(0));
40
41 auto run_sort = [&](auto cmp) {
42 tbb::parallel_sort(IX.begin(), IX.end(), [&](Index i, Index j) {
43 return std::lexicographical_compare(
44 X.row(i).begin(),
45 X.row(i).end(),
46 X.row(j).begin(),
47 X.row(j).end(),
48 cmp);
49 });
50 };
51
52 if (ascending) {
53 run_sort(std::less<>());
54 } else {
55 run_sort(std::greater<>());
56 }
57
58 for (Eigen::Index i = 0; i < X.rows(); ++i) {
59 Y.row(i) = X.row(IX(i));
60 }
61}
62
63template <typename DerivedX>
64void sortrows(
65 const Eigen::DenseBase<DerivedX>& X,
66 const bool ascending,
67 Eigen::PlainObjectBase<DerivedX>& Y)
68{
69 Eigen::Matrix<int, DerivedX::RowsAtCompileTime, 1> I;
70 return lagrange::internal::sortrows(X, ascending, Y, I);
71}
72
73} // namespace lagrange::internal
nullptr_t, size_t, ptrdiff_t basic_ostream bad_weak_ptr extent, remove_extent, is_array,...
Definition: attribute_string_utils.h:21