// Copyright (C) 2018  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#include "opaque_types.h"
#include <dlib/python.h>
#include "dlib/pixel.h"
#include <dlib/image_transforms.h>
#include <dlib/image_processing.h>

using namespace dlib;
using namespace std;

namespace py = pybind11;

// ----------------------------------------------------------------------------------------

template <typename T>
line ht_get_line (
    const hough_transform& ht,
    const dlib::vector<T,2>& p
)
{
    DLIB_CASSERT(get_rect(ht).contains(p));
    auto temp = ht.get_line(p);
    return line(temp.first, temp.second);
}

template <typename T>
double ht_get_line_angle_in_degrees (
    const hough_transform& ht,
    const dlib::vector<T,2>& p
)
{
    DLIB_CASSERT(get_rect(ht).contains(p));
    return ht.get_line_angle_in_degrees(p);
}

template <typename T>
py::tuple ht_get_line_properties (
    const hough_transform& ht,
    const dlib::vector<T,2>& p
)
{
    DLIB_CASSERT(get_rect(ht).contains(p));
    double angle_in_degrees;
    double radius;
    ht.get_line_properties(p, angle_in_degrees, radius);
    return py::make_tuple(angle_in_degrees, radius);
}

point ht_get_best_hough_point (
    hough_transform& ht,
    const point& p,
    const numpy_image<float>& himg
)
{
    DLIB_CASSERT(num_rows(himg) == ht.size() && num_columns(himg) == ht.size() &&
        get_rect(ht).contains(p) == true,
        "\t point hough_transform::get_best_hough_point()"
        << "\n\t Invalid arguments given to this function."
        << "\n\t num_rows(himg): " << num_rows(himg)
        << "\n\t num_columns(himg): " << num_columns(himg)
        << "\n\t size():    " << ht.size()
        << "\n\t p:         " << p
    );
    return ht.get_best_hough_point(p,himg);
}

template <
    typename T
    >
numpy_image<float> compute_ht (
    const hough_transform& ht,
    const numpy_image<T>& img,
    const rectangle& box
)
{
    numpy_image<float> out;
    ht(img, box, out);
    return out;
}

template <
    typename T
    >
numpy_image<float> compute_ht2 (
    const hough_transform& ht,
    const numpy_image<T>& img
)
{
    numpy_image<float> out;
    ht(img, out);
    return out;
}

template <
    typename T
    >
py::list ht_find_pixels_voting_for_lines (
    const hough_transform& ht,
    const numpy_image<T>& img,
    const rectangle& box,
    const std::vector<point>& hough_points,
    const unsigned long angle_window_size = 1,
    const unsigned long radius_window_size = 1
)
{
    return vector_to_python_list(ht.find_pixels_voting_for_lines(img, box, hough_points, angle_window_size, radius_window_size));
}

template <
    typename T
    >
py::list ht_find_pixels_voting_for_lines2 (
    const hough_transform& ht,
    const numpy_image<T>& img,
    const std::vector<point>& hough_points,
    const unsigned long angle_window_size = 1,
    const unsigned long radius_window_size = 1
)
{
    return vector_to_python_list(ht.find_pixels_voting_for_lines(img, hough_points, angle_window_size, radius_window_size));
}

std::vector<point> ht_find_strong_hough_points(
    hough_transform& ht,
    const numpy_image<float>& himg,
    const float hough_count_thresh,
    const double angle_nms_thresh,
    const double radius_nms_thresh
)
{
    return ht.find_strong_hough_points(himg, hough_count_thresh, angle_nms_thresh, radius_nms_thresh);
}

// ----------------------------------------------------------------------------------------

void register_hough_transform(py::module& m)
{
    const char* class_docs =
"This object is a tool for computing the line finding version of the Hough transform \n\
given some kind of edge detection image as input.  It also allows the edge pixels \n\
to be weighted such that higher weighted edge pixels contribute correspondingly \n\
more to the output of the Hough transform, allowing stronger edges to create \n\
correspondingly stronger line detections in the final Hough transform.";

    const char* doc_constr =
"requires \n\
    - size_ > 0 \n\
ensures \n\
    - This object will compute Hough transforms that are size_ by size_ pixels.   \n\
      This is in terms of both the Hough accumulator array size as well as the \n\
      input image size. \n\
    - size() == size_";
        /*!
            requires
                - size_ > 0
            ensures
                - This object will compute Hough transforms that are size_ by size_ pixels.
                  This is in terms of both the Hough accumulator array size as well as the
                  input image size.
                - size() == size_
        !*/

    py::class_<hough_transform>(m, "hough_transform", class_docs)
        .def(py::init<unsigned long>(), doc_constr, py::arg("size_"))
        .def_property_readonly("size", &hough_transform::size,
            "returns the size of the Hough transforms generated by this object.  In particular, this object creates Hough transform images that are size by size pixels in size.")
        .def("get_line", &ht_get_line<long>, py::arg("p"))
        .def("get_line", &ht_get_line<double>, py::arg("p"),
"requires \n\
    - rectangle(0,0,size-1,size-1).contains(p) == true \n\
      (i.e. p must be a point inside the Hough accumulator array) \n\
ensures \n\
    - returns the line segment in the original image space corresponding \n\
      to Hough transform point p.  \n\
    - The returned points are inside rectangle(0,0,size-1,size-1).")
    /*!
        requires
            - rectangle(0,0,size-1,size-1).contains(p) == true
              (i.e. p must be a point inside the Hough accumulator array)
        ensures
            - returns the line segment in the original image space corresponding
              to Hough transform point p.
            - The returned points are inside rectangle(0,0,size-1,size-1).
    !*/

        .def("get_line_angle_in_degrees", &ht_get_line_angle_in_degrees<long>, py::arg("p"))
        .def("get_line_angle_in_degrees", &ht_get_line_angle_in_degrees<double>, py::arg("p"),
"requires \n\
    - rectangle(0,0,size-1,size-1).contains(p) == true \n\
      (i.e. p must be a point inside the Hough accumulator array) \n\
ensures \n\
    - returns the angle, in degrees, of the line corresponding to the Hough \n\
      transform point p.")
    /*!
        requires
            - rectangle(0,0,size-1,size-1).contains(p) == true
              (i.e. p must be a point inside the Hough accumulator array)
        ensures
            - returns the angle, in degrees, of the line corresponding to the Hough
              transform point p.
    !*/

        .def("get_line_properties", &ht_get_line_properties<long>, py::arg("p"))
        .def("get_line_properties", &ht_get_line_properties<double>, py::arg("p"),
"requires \n\
    - rectangle(0,0,size-1,size-1).contains(p) == true \n\
      (i.e. p must be a point inside the Hough accumulator array) \n\
ensures \n\
    - Converts a point in the Hough transform space into an angle, in degrees, \n\
      and a radius, measured in pixels from the center of the input image. \n\
    - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough \n\
      transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90. \n\
    - RADIUS == the distance from the center of the input image, measured in \n\
      pixels, and the line corresponding to the Hough transform point p. \n\
      Moreover: -sqrt(size*size/2) <= RADIUS <= sqrt(size*size/2) \n\
    - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)" )
    /*!
        requires
            - rectangle(0,0,size-1,size-1).contains(p) == true
              (i.e. p must be a point inside the Hough accumulator array)
        ensures
            - Converts a point in the Hough transform space into an angle, in degrees,
              and a radius, measured in pixels from the center of the input image.
            - let ANGLE_IN_DEGREES == the angle of the line corresponding to the Hough
              transform point p.  Moreover: -90 <= ANGLE_IN_DEGREES < 90.
            - RADIUS == the distance from the center of the input image, measured in
              pixels, and the line corresponding to the Hough transform point p.
              Moreover: -sqrt(size*size/2) <= RADIUS <= sqrt(size*size/2)
            - returns a tuple of (ANGLE_IN_DEGREES, RADIUS)
    !*/

        .def("get_best_hough_point", &ht_get_best_hough_point, py::arg("p"), py::arg("himg"),
"requires \n\
    - himg has size rows and columns. \n\
    - rectangle(0,0,size-1,size-1).contains(p) == true \n\
ensures \n\
    - This function interprets himg as a Hough image and p as a point in the \n\
      original image space.  Given this, it finds the maximum scoring line that \n\
      passes though p.  That is, it checks all the Hough accumulator bins in \n\
      himg corresponding to lines though p and returns the location with the \n\
      largest score.   \n\
    - returns a point X such that get_rect(himg).contains(X) == true")
    /*!
        requires
            - himg has size rows and columns.
            - rectangle(0,0,size-1,size-1).contains(p) == true
        ensures
            - This function interprets himg as a Hough image and p as a point in the
              original image space.  Given this, it finds the maximum scoring line that
              passes though p.  That is, it checks all the Hough accumulator bins in
              himg corresponding to lines though p and returns the location with the
              largest score.
            - returns a point X such that get_rect(himg).contains(X) == true
    !*/

        .def("__call__", &compute_ht<uint8_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<uint16_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<uint32_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<uint64_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<int8_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<int16_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<int32_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<int64_t>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<float>, py::arg("img"), py::arg("box"))
        .def("__call__", &compute_ht<double>, py::arg("img"), py::arg("box"),
"requires \n\
    - box.width() == size \n\
    - box.height() == size \n\
ensures \n\
    - Computes the Hough transform of the part of img contained within box. \n\
      In particular, we do a grayscale version of the Hough transform where any \n\
      non-zero pixel in img is treated as a potential component of a line and \n\
      accumulated into the returned Hough accumulator image.  However, rather than \n\
      adding 1 to each relevant accumulator bin we add the value of the pixel \n\
      in img to each Hough accumulator bin.  This means that, if all the \n\
      pixels in img are 0 or 1 then this routine performs a normal Hough \n\
      transform.  However, if some pixels have larger values then they will be \n\
      weighted correspondingly more in the resulting Hough transform. \n\
    - The returned hough transform image will be size rows by size columns. \n\
    - The returned image is the Hough transform of the part of img contained in \n\
      box.  Each point in the Hough image corresponds to a line in the input box. \n\
      In particular, the line for hough_image[y][x] is given by get_line(point(x,y)).  \n\
      Also, when viewing the Hough image, the x-axis gives the angle of the line \n\
      and the y-axis the distance of the line from the center of the box.  The \n\
      conversion between Hough coordinates and angle and pixel distance can be \n\
      obtained by calling get_line_properties()." )
    /*!
        requires
            - box.width() == size
            - box.height() == size
        ensures
            - Computes the Hough transform of the part of img contained within box.
              In particular, we do a grayscale version of the Hough transform where any
              non-zero pixel in img is treated as a potential component of a line and
              accumulated into the returned Hough accumulator image.  However, rather than
              adding 1 to each relevant accumulator bin we add the value of the pixel
              in img to each Hough accumulator bin.  This means that, if all the
              pixels in img are 0 or 1 then this routine performs a normal Hough
              transform.  However, if some pixels have larger values then they will be
              weighted correspondingly more in the resulting Hough transform.
            - The returned hough transform image will be size rows by size columns.
            - The returned image is the Hough transform of the part of img contained in
              box.  Each point in the Hough image corresponds to a line in the input box.
              In particular, the line for hough_image[y][x] is given by get_line(point(x,y)).
              Also, when viewing the Hough image, the x-axis gives the angle of the line
              and the y-axis the distance of the line from the center of the box.  The
              conversion between Hough coordinates and angle and pixel distance can be
              obtained by calling get_line_properties().
    !*/

        .def("__call__", &compute_ht2<uint8_t>, py::arg("img"))
        .def("__call__", &compute_ht2<uint16_t>, py::arg("img"))
        .def("__call__", &compute_ht2<uint32_t>, py::arg("img"))
        .def("__call__", &compute_ht2<uint64_t>, py::arg("img"))
        .def("__call__", &compute_ht2<int8_t>, py::arg("img"))
        .def("__call__", &compute_ht2<int16_t>, py::arg("img"))
        .def("__call__", &compute_ht2<int32_t>, py::arg("img"))
        .def("__call__", &compute_ht2<int64_t>, py::arg("img"))
        .def("__call__", &compute_ht2<float>, py::arg("img"))
        .def("__call__", &compute_ht2<double>, py::arg("img"),
            "    simply performs: return self(img, get_rect(img)).  That is, just runs the hough transform on the whole input image.")

        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<uint8_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<uint16_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<uint32_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<uint64_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<int8_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<int16_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<int32_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<int64_t>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<float>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines<double>, py::arg("img"), py::arg("box"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1,
"requires \n\
    - box.width() == size \n\
    - box.height() == size \n\
    - for all valid i: \n\
        - rectangle(0,0,size-1,size-1).contains(hough_points[i]) == true \n\
          (i.e. hough_points must contain points in the output Hough transform \n\
          space generated by this object.) \n\
    - angle_window_size >= 1 \n\
    - radius_window_size >= 1 \n\
ensures \n\
    - This function computes the Hough transform of the part of img contained \n\
      within box.  It does the same computation as __call__() defined above, \n\
      except instead of accumulating into an image we create an explicit list \n\
      of all the points in img that contributed to each line (i.e each point in \n\
      the Hough image). To do this we take a list of Hough points as input and \n\
      only record hits on these specifically identified Hough points.  A \n\
      typical use of find_pixels_voting_for_lines() is to first run the normal \n\
      Hough transform using __call__(), then find the lines you are interested \n\
      in, and then call find_pixels_voting_for_lines() to determine which \n\
      pixels in the input image belong to those lines. \n\
    - This routine returns a vector, CONSTITUENT_POINTS, with the following \n\
      properties: \n\
        - CONSTITUENT_POINTS.size == hough_points.size \n\
        - for all valid i: \n\
            - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size) \n\
            - Any point in img with a non-zero value that lies on a line \n\
              corresponding to one of the Hough points in HP[i] is added to \n\
              CONSTITUENT_POINTS[i].  Therefore, when this routine finishes, \n\
              #CONSTITUENT_POINTS[i] will contain all the points in img that \n\
              voted for the lines associated with the Hough accumulator bins in \n\
              HP[i]. \n\
            - #CONSTITUENT_POINTS[i].size == the number of points in img that \n\
              voted for any of the lines HP[i] in Hough space.  Note, however, \n\
              that if angle_window_size or radius_window_size are made so large \n\
              that HP[i] overlaps HP[j] for i!=j then the overlapping regions \n\
              of Hough space are assigned to HP[i] or HP[j] arbitrarily. \n\
              That is, we treat HP[i] and HP[j] as disjoint even if their boxes \n\
              overlap.  In this case, the overlapping region is assigned to \n\
              either HP[i] or HP[j] in an arbitrary manner." )
    /*!
        requires
            - box.width() == size
            - box.height() == size
            - for all valid i:
                - rectangle(0,0,size-1,size-1).contains(hough_points[i]) == true
                  (i.e. hough_points must contain points in the output Hough transform
                  space generated by this object.)
            - angle_window_size >= 1
            - radius_window_size >= 1
        ensures
            - This function computes the Hough transform of the part of img contained
              within box.  It does the same computation as __call__() defined above,
              except instead of accumulating into an image we create an explicit list
              of all the points in img that contributed to each line (i.e each point in
              the Hough image). To do this we take a list of Hough points as input and
              only record hits on these specifically identified Hough points.  A
              typical use of find_pixels_voting_for_lines() is to first run the normal
              Hough transform using __call__(), then find the lines you are interested
              in, and then call find_pixels_voting_for_lines() to determine which
              pixels in the input image belong to those lines.
            - This routine returns a vector, CONSTITUENT_POINTS, with the following
              properties:
                - CONSTITUENT_POINTS.size == hough_points.size
                - for all valid i:
                    - Let HP[i] = centered_rect(hough_points[i], angle_window_size, radius_window_size)
                    - Any point in img with a non-zero value that lies on a line
                      corresponding to one of the Hough points in HP[i] is added to
                      CONSTITUENT_POINTS[i].  Therefore, when this routine finishes,
                      #CONSTITUENT_POINTS[i] will contain all the points in img that
                      voted for the lines associated with the Hough accumulator bins in
                      HP[i].
                    - #CONSTITUENT_POINTS[i].size == the number of points in img that
                      voted for any of the lines HP[i] in Hough space.  Note, however,
                      that if angle_window_size or radius_window_size are made so large
                      that HP[i] overlaps HP[j] for i!=j then the overlapping regions
                      of Hough space are assigned to HP[i] or HP[j] arbitrarily.
                      That is, we treat HP[i] and HP[j] as disjoint even if their boxes
                      overlap.  In this case, the overlapping region is assigned to
                      either HP[i] or HP[j] in an arbitrary manner.
    !*/
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<uint8_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<uint16_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<uint32_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<uint64_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<int8_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<int16_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<int32_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<int64_t>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<float>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1)
        .def("find_pixels_voting_for_lines", &ht_find_pixels_voting_for_lines2<double>, py::arg("img"), py::arg("hough_points"), py::arg("angle_window_size")=1, py::arg("radius_window_size")=1,
"    performs: return find_pixels_voting_for_lines(img, get_rect(img), hough_points, angle_window_size, radius_window_size); \n\
That is, just runs the routine on the whole input image." )

        .def("find_strong_hough_points", &ht_find_strong_hough_points, py::arg("himg"), py::arg("hough_count_thresh"), py::arg("angle_nms_thresh"), py::arg("radius_nms_thresh"),
"requires \n\
    - himg has size() rows and columns. \n\
    - angle_nms_thresh >= 0 \n\
    - radius_nms_thresh >= 0 \n\
ensures \n\
    - This routine finds strong lines in a Hough transform and performs \n\
      non-maximum suppression on the detected lines.  Recall that each point in \n\
      Hough space is associated with a line. Therefore, this routine finds all \n\
      the pixels in himg (a Hough transform image) with values >= \n\
      hough_count_thresh and performs non-maximum suppression on the \n\
      identified list of pixels.  It does this by discarding lines that are \n\
      within angle_nms_thresh degrees of a stronger line or within \n\
      radius_nms_thresh distance (in terms of radius as defined by \n\
      get_line_properties()) to a stronger Hough point. \n\
    - The identified lines are returned as a list of coordinates in himg. \n\
    - The returned points are sorted so that points with larger Hough transform \n\
      values come first."
    /*!
        requires
            - himg has size() rows and columns.
            - angle_nms_thresh >= 0
            - radius_nms_thresh >= 0
        ensures
            - This routine finds strong lines in a Hough transform and performs
              non-maximum suppression on the detected lines.  Recall that each point in
              Hough space is associated with a line. Therefore, this routine finds all
              the pixels in himg (a Hough transform image) with values >=
              hough_count_thresh and performs non-maximum suppression on the
              identified list of pixels.  It does this by discarding lines that are
              within angle_nms_thresh degrees of a stronger line or within
              radius_nms_thresh distance (in terms of radius as defined by
              get_line_properties()) to a stronger Hough point.
            - The identified lines are returned as a list of coordinates in himg.
            - The returned points are sorted so that points with larger Hough transform
              values come first.
    !*/
        );

    m.def("get_rect", [](const hough_transform& ht){ return get_rect(ht); },
        "returns a rectangle(0,0,ht.size()-1,ht.size()-1).  Therefore, it is the rectangle that bounds the Hough transform image.",
        py::arg("ht")  );
}

// ----------------------------------------------------------------------------------------

template <typename T>
numpy_image<T> py_transform_image (
    const numpy_image<T>& img,
    const point_transform_projective& map_point,
    long rows,
    long columns
)
{
    DLIB_CASSERT(rows > 0 && columns > 0, "The requested output image dimensions are invalid.");
    numpy_image<T> out(rows, columns);

    transform_image(img, out, interpolate_bilinear(), map_point);

    return out;
}
// ----------------------------------------------------------------------------------------

template <typename T>
numpy_image<T> py_extract_image_chip (
    const numpy_image<T>& img,
    const chip_details& chip_location
)
{
    numpy_image<T> out;
    extract_image_chip(img, chip_location, out);
    return out;
}

template <typename T>
py::list py_extract_image_chips (
    const numpy_image<T>& img,
    const py::list& chip_locations
)
{
    dlib::array<numpy_image<T>> out;
    extract_image_chips(img, python_list_to_vector<chip_details>(chip_locations), out);
    py::list ret;
    for (const auto& i : out)
        ret.append(i);
    return ret;
}

// ----------------------------------------------------------------------------------------

template <typename T>
dpoint py_max_point(const numpy_image<T>& img)
{
    DLIB_CASSERT(img.size() != 0);
    return max_point(mat(img));
}

template <typename T>
dpoint py_max_point_interpolated(const numpy_image<T>& img)
{
    DLIB_CASSERT(img.size() != 0);
    return max_point_interpolated(mat(img));
}

// ----------------------------------------------------------------------------------------

template <typename T>
void py_zero_border_pixels (
    numpy_image<T>& img,
    long x_border_size,
    long y_border_size
)
{
    zero_border_pixels(img, x_border_size, y_border_size);
}

template <typename T>
void py_zero_border_pixels2 (
    numpy_image<T>& img,
    const rectangle& inside
)
{
    zero_border_pixels(img, inside);
}

// ----------------------------------------------------------------------------------------

template <typename T>
py::tuple py_spatially_filter_image (
    const numpy_image<T>& img,
    const numpy_image<T>& filter
)
{
    DLIB_CASSERT(filter.size() != 0);
    numpy_image<T> out;
    auto rect = spatially_filter_image(img, out, mat(filter));
    return py::make_tuple(out, rect);
}

template <typename T>
bool is_vector(
    const py::array_t<T>& m
)
{
    const size_t dims = m.ndim();
    const size_t size = m.size();
    if (dims == 1)
        return true;

    for (size_t i = 0; i < dims; ++i)
    {
        if (m.shape(i) != 1 && m.shape(i) != size)
            return false;
    }

    return true;
}

template <typename T>
py::tuple py_spatially_filter_image_separable (
    const numpy_image<T>& img,
    const py::array_t<T>& row_filter,
    const py::array_t<T>& col_filter
)
{
    DLIB_CASSERT(row_filter.size() != 0);
    DLIB_CASSERT(col_filter.size() != 0);
    DLIB_CASSERT(is_vector(row_filter), "The row filter must be either a row or column vector.");
    DLIB_CASSERT(is_vector(col_filter), "The column filter must be either a row or column vector.");

    numpy_image<T> out;
    auto rect = spatially_filter_image_separable(img, out, mat(row_filter.data(),row_filter.size()), mat(col_filter.data(),col_filter.size()));
    return py::make_tuple(out, rect);
}

// ----------------------------------------------------------------------------------------

void bind_image_classes4(py::module& m)
{

    const char* docs = "";

    register_hough_transform(m);

    m.def("transform_image", &py_transform_image<uint8_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<uint16_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<uint32_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<uint64_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<int8_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<int16_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<int32_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<int64_t>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<float>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<double>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"));
    m.def("transform_image", &py_transform_image<rgb_pixel>, py::arg("img"), py::arg("map_point"), py::arg("rows"), py::arg("columns"),
"requires \n\
    - rows > 0 \n\
    - columns > 0 \n\
ensures \n\
    - Returns an image that is the given rows by columns in size and contains a \n\
      transformed part of img.  To do this, we interpret map_point as a mapping \n\
      from pixels in the returned image to pixels in the input img.  transform_image()  \n\
      uses this mapping and bilinear interpolation to fill the output image with an \n\
      interpolated copy of img.   \n\
    - Any locations in the output image that map to pixels outside img are set to 0."
    /*!
        requires
            - rows > 0
            - columns > 0
        ensures
            - Returns an image that is the given rows by columns in size and contains a
              transformed part of img.  To do this, we interpret map_point as a mapping
              from pixels in the returned image to pixels in the input img.  transform_image()
              uses this mapping and bilinear interpolation to fill the output image with an
              interpolated copy of img.
            - Any locations in the output image that map to pixels outside img are set to 0.
    !*/
        );

    m.def("max_point", &py_max_point<uint8_t>, py::arg("img"));
    m.def("max_point", &py_max_point<uint16_t>, py::arg("img"));
    m.def("max_point", &py_max_point<uint32_t>, py::arg("img"));
    m.def("max_point", &py_max_point<uint64_t>, py::arg("img"));
    m.def("max_point", &py_max_point<int8_t>, py::arg("img"));
    m.def("max_point", &py_max_point<int16_t>, py::arg("img"));
    m.def("max_point", &py_max_point<int32_t>, py::arg("img"));
    m.def("max_point", &py_max_point<int64_t>, py::arg("img"));
    m.def("max_point", &py_max_point<float>, py::arg("img"));
    m.def("max_point", &py_max_point<double>, py::arg("img"),
"requires \n\
    - m.size > 0 \n\
ensures \n\
    - returns the location of the maximum element of the array, that is, if the \n\
      returned point is P then it will be the case that: img[P.y,P.x] == img.max()."
    /*!
        requires
            - m.size > 0
        ensures
            - returns the location of the maximum element of the array, that is, if the
              returned point is P then it will be the case that: img[P.y,P.x] == img.max().
    !*/
        );

    m.def("max_point_interpolated", &py_max_point_interpolated<uint8_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<uint16_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<uint32_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<uint64_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<int8_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<int16_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<int32_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<int64_t>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<float>, py::arg("img"));
    m.def("max_point_interpolated", &py_max_point_interpolated<double>, py::arg("img"),
"requires \n\
    - m.size > 0 \n\
ensures \n\
    - Like max_point(), this function finds the location in m with the largest \n\
      value.  However, we additionally use some quadratic interpolation to find the \n\
      location of the maximum point with sub-pixel accuracy.  Therefore, the \n\
      returned point is equal to max_point(m) + some small sub-pixel delta."
    /*!
        requires
            - m.size > 0
        ensures
            - Like max_point(), this function finds the location in m with the largest
              value.  However, we additionally use some quadratic interpolation to find the
              location of the maximum point with sub-pixel accuracy.  Therefore, the
              returned point is equal to max_point(m) + some small sub-pixel delta.
    !*/
        );

    m.def("zero_border_pixels", &py_zero_border_pixels<uint8_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<uint16_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<uint32_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<uint64_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<int8_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<int16_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<int32_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<int64_t>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<float>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<double>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"));
    m.def("zero_border_pixels", &py_zero_border_pixels<rgb_pixel>, py::arg("img"), py::arg("x_border_size"), py::arg("y_border_size"),
"requires \n\
    - x_border_size >= 0 \n\
    - y_border_size >= 0 \n\
ensures \n\
    - The size and shape of img isn't changed by this function. \n\
    - for all valid r such that r+y_border_size or r-y_border_size gives an invalid row \n\
        - for all valid c such that c+x_border_size or c-x_border_size gives an invalid column  \n\
            - assigns the pixel img[r][c] to 0.  \n\
              (i.e. assigns 0 to every pixel in the border of img)"
    /*!
        requires
            - x_border_size >= 0
            - y_border_size >= 0
        ensures
            - The size and shape of img isn't changed by this function.
            - for all valid r such that r+y_border_size or r-y_border_size gives an invalid row
                - for all valid c such that c+x_border_size or c-x_border_size gives an invalid column
                    - assigns the pixel img[r][c] to 0.
                      (i.e. assigns 0 to every pixel in the border of img)
    !*/
        );

    m.def("zero_border_pixels", &py_zero_border_pixels2<uint8_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<uint16_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<uint32_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<uint64_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<int8_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<int16_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<int32_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<int64_t>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<float>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<double>, py::arg("img"), py::arg("inside"));
    m.def("zero_border_pixels", &py_zero_border_pixels2<rgb_pixel>, py::arg("img"), py::arg("inside"),
"ensures \n\
    - The size and shape of img isn't changed by this function. \n\
    - All the pixels in img that are not contained inside the inside rectangle \n\
      given to this function are set to 0.  That is, anything not \"inside\" is on \n\
      the border and set to 0."
    /*!
        ensures
            - The size and shape of img isn't changed by this function.
            - All the pixels in img that are not contained inside the inside rectangle
              given to this function are set to 0.  That is, anything not "inside" is on
              the border and set to 0.
    !*/
        );

    m.def("spatially_filter_image", &py_spatially_filter_image<uint8_t>, py::arg("img"), py::arg("filter"));
    m.def("spatially_filter_image", &py_spatially_filter_image<float>,   py::arg("img"), py::arg("filter"));
    m.def("spatially_filter_image", &py_spatially_filter_image<double>,  py::arg("img"), py::arg("filter"),
"requires \n\
    - filter.size != 0 \n\
ensures \n\
    - Applies the given spatial filter to img and returns the result (i.e. we  \n\
      cross-correlate img with filter).  We also return a rectangle which \n\
      indicates what pixels in the returned image are considered non-border pixels \n\
      and therefore contain output from the filter.  E.g. \n\
        - filtered_img,rect = spatially_filter_image(img, filter) \n\
      would give you the filtered image and the rectangle in question.  Since the \n\
      returned image has the same shape as img we fill the border pixels by setting \n\
      them to 0. \n\
 \n\
    - The filter is applied such that it's centered over the pixel it writes its \n\
      output into.  For centering purposes, we consider the center element of the \n\
      filter to be filter[filter.shape[0]/2,filter.shape[1]/2].  This means that \n\
      the filter that writes its output to a pixel at location point(c,r) and is W \n\
      by H (width by height) pixels in size operates on exactly the pixels in the \n\
      rectangle centered_rect(point(c,r),W,H) within img."
    /*!
        requires
            - filter.size != 0
        ensures
            - Applies the given spatial filter to img and returns the result (i.e. we
              cross-correlate img with filter).  We also return a rectangle which
              indicates what pixels in the returned image are considered non-border pixels
              and therefore contain output from the filter.  E.g.
                - filtered_img,rect = spatially_filter_image(img, filter)
              would give you the filtered image and the rectangle in question.  Since the
              returned image has the same shape as img we fill the border pixels by setting
              them to 0.

            - The filter is applied such that it's centered over the pixel it writes its
              output into.  For centering purposes, we consider the center element of the
              filter to be filter[filter.shape[0]/2,filter.shape[1]/2].  This means that
              the filter that writes its output to a pixel at location point(c,r) and is W
              by H (width by height) pixels in size operates on exactly the pixels in the
              rectangle centered_rect(point(c,r),W,H) within img.
    !*/
        );

    m.def("spatially_filter_image_separable", &py_spatially_filter_image_separable<uint8_t>, py::arg("img"), py::arg("row_filter"), py::arg("col_filter"));
    m.def("spatially_filter_image_separable", &py_spatially_filter_image_separable<float>,   py::arg("img"), py::arg("row_filter"), py::arg("col_filter"));
    m.def("spatially_filter_image_separable", &py_spatially_filter_image_separable<double>,  py::arg("img"), py::arg("row_filter"), py::arg("col_filter"),
"requires \n\
    - row_filter.size != 0 \n\
    - col_filter.size != 0 \n\
    - row_filter and col_filter are both either row or column vectors.  \n\
ensures \n\
    - Applies the given separable spatial filter to img and returns the result \n\
      (i.e. we cross-correlate img with the filters).  In particular, calling this \n\
      function has the same effect as calling the regular spatially_filter_image() \n\
      routine with a filter, FILT, defined as follows:  \n\
        - FILT(r,c) == col_filter(r)*row_filter(c) \n\
      Therefore, the return value of this routine is the same as if it were \n\
      implemented as:    \n\
        return spatially_filter_image(img, FILT) \n\
      Except that this version should be faster for separable filters."
    /*!
        requires
            - row_filter.size != 0
            - col_filter.size != 0
            - row_filter and col_filter are both either row or column vectors.
        ensures
            - Applies the given separable spatial filter to img and returns the result
              (i.e. we cross-correlate img with the filters).  In particular, calling this
              function has the same effect as calling the regular spatially_filter_image()
              routine with a filter, FILT, defined as follows:
                - FILT(r,c) == col_filter(r)*row_filter(c)
              Therefore, the return value of this routine is the same as if it were
              implemented as:
                return spatially_filter_image(img, FILT)
              Except that this version should be faster for separable filters.
    !*/
        );
}


// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef MTL_STD_CONCEPT_INCLUDE
#define MTL_STD_CONCEPT_INCLUDE

#ifdef __GXX_CONCEPTS__
#  include <concepts>
#else
// Use Joel de Guzman's return type deduction
#  include <boost/numeric/ublas/detail/returntype_deduction.hpp>
#  include <boost/mpl/at.hpp>
#  include <boost/numeric/linear_algebra/pseudo_concept.hpp>
#endif

// #include <boost/numeric/mtl/utility/is_what.hpp>         -> leads to cyclic inclusions
// #include <boost/numeric/mtl/operation/mult_result.hpp>

namespace mtl {

/**
 * \defgroup Concepts Concepts
 */
/*@{*/

    // Use Joel de Guzman's return type deduction
    // Adapted from uBLAS
    // Differences:
    //   - Separate types for all operations
    //   - result_type like in concept

    /// Concept Addable: Binary operation
    /** In concept-free compilations also used for return type deduction.
        If available use decltype instead of meta-programming. */
    template<class X, class Y>
    struct Addable
    {
#    ifdef MTL_WITH_AUTO
	/// Result of addition
	typedef decltype(X() + Y())   result_type;
#    else
      private:
        typedef boost::numeric::ublas::type_deduction_detail::base_result_of<X, Y> base_type;
        static typename base_type::x_type x;
        static typename base_type::y_type y;
        static const std::size_t size = sizeof (
                   boost::numeric::ublas::type_deduction_detail::test<
                        typename base_type::x_type
                      , typename base_type::y_type
		   >(x + y)
                );

        static const std::size_t index = (size / sizeof (char)) - 1;
        typedef typename boost::mpl::at_c<
    	typename base_type::types, index>::type id;
      public:
	/// Result of addition
        typedef typename id::type result_type;
#    endif
    };

    /// Concept Subtractable: Binary operation
    /** In concept-free compilations also used for return type deduction.
        If available use decltype instead of meta-programming. */
    template<class X, class Y>
    struct Subtractable
    {
#    ifdef MTL_WITH_AUTO
	/// Result of addition
	typedef decltype(X() - Y())   result_type;
#    else
      private:
        typedef boost::numeric::ublas::type_deduction_detail::base_result_of<X, Y> base_type;
        static typename base_type::x_type x;
        static typename base_type::y_type y;
        static const std::size_t size = sizeof (
                   boost::numeric::ublas::type_deduction_detail::test<
                        typename base_type::x_type
                      , typename base_type::y_type
		   >(x - y)
                );

        static const std::size_t index = (size / sizeof (char)) - 1;
        typedef typename boost::mpl::at_c<
    	typename base_type::types, index>::type id;
      public:
	/// Result of subtraction
        typedef typename id::type result_type;
#    endif
    };

    /// Concept Multiplicable: Binary operation
    /** In concept-free compilations also used for return type deduction.
        If available use decltype instead of meta-programming.  */
    template<class X, class Y>
    struct Multiplicable
    {
#    ifdef MTL_WITH_AUTO
	/// Result of multiplication
	typedef decltype(X() * Y())   result_type;
#    else
      private:
        typedef boost::numeric::ublas::type_deduction_detail::base_result_of<X, Y> base_type;
        static typename base_type::x_type x;
        static typename base_type::y_type y;
        static const std::size_t size = sizeof (
                   boost::numeric::ublas::type_deduction_detail::test<
                        typename base_type::x_type
                      , typename base_type::y_type
                    >(x * y)
                );

        static const std::size_t index = (size / sizeof (char)) - 1;
        typedef typename boost::mpl::at_c<
    	typename base_type::types, index>::type id;
      public:
	/// Result of multiplication
        typedef typename id::type result_type;
#    endif
    };

    /// Concept Divisible: Binary operation
    /** In concept-free compilations also used for return type deduction.
        If available use decltype instead of meta-programming.  */
    template<class X, class Y>
    struct Divisible
    {
#    ifdef MTL_WITH_AUTO
	/// Result of division
	typedef decltype(X() / Y())   result_type;
#    else
      private:
        typedef boost::numeric::ublas::type_deduction_detail::base_result_of<X, Y> base_type;
        static typename base_type::x_type x;
        static typename base_type::y_type y;
        static const std::size_t size = sizeof (
                   boost::numeric::ublas::type_deduction_detail::test<
                        typename base_type::x_type
                      , typename base_type::y_type
                    >(x / y)
                );

        static const std::size_t index = (size / sizeof (char)) - 1;
        typedef typename boost::mpl::at_c<
    	typename base_type::types, index>::type id;
      public:
	/// Result of division
        typedef typename id::type result_type;
#    endif
    };

    /// Concept UnaryFunctor
    /** With concept corresponds to std::Callable1 */
    template <typename T>
    struct UnaryFunctor
    {
	/// Result type of operator()
	typedef associated_type result_type;

	/// The unary  function
	result_type operator()(T);
    };

    /// Concept UnaryStaticFunctor
    /**
       \par Refinement of:
       - std::Callable1 < T >
    */
    template <typename T>
    struct UnaryStaticFunctor
      : public UnaryFunctor<T>
    {
	/// Result type of apply
	typedef associated_type result_type;

	/// The unary static function
	static result_type apply(T);

	/// The application operator behaves like apply. Exists for compatibility with UnaryFunctor
	result_type operator()(T);
    };

    /// Concept BinaryFunctor
    /** With concept corresponds to std::Callable2 */
    template <typename T, typename U>
    struct BinaryFunctor
    {
	/// Result type of operator()
	typedef associated_type result_type;

	/// The unary  function
	result_type operator()(T, U);
    };

    /// Concept BinaryStaticFunctor
    /**
       \par Refinement of:
       - BinaryFunctor <T, U>
    */
    template <typename T, typename U>
    struct BinaryStaticFunctor
	: public BinaryFunctor <T, U>
    {
	/// Result type of apply
	typedef associated_type result_type;

	/// The unary static function
	static result_type apply(T, U);

	/// The application operator behaves like apply. Exists for compatibility with BinaryFunctor
	result_type operator()(T, U);
    };

/*@}*/ // end of group Concepts

} // namespace mtl

#endif // MTL_STD_CONCEPT_INCLUDE


//
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
//

#ifndef BOOST_GRAPH_STRONG_COMPONENTS_HPP
#define BOOST_GRAPH_STRONG_COMPONENTS_HPP

#include <stack>
#include <boost/config.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/type_traits/conversion_traits.hpp>
#include <boost/static_assert.hpp>
#include <boost/graph/overloading.hpp>
#include <boost/concept/assert.hpp>

namespace boost {

  //==========================================================================
  // This is Tarjan's algorithm for strongly connected components
  // from his paper "Depth first search and linear graph algorithms".
  // It calculates the components in a single application of DFS.
  // We implement the algorithm as a dfs-visitor.

  namespace detail {

    template <typename ComponentMap, typename RootMap, typename DiscoverTime,
              typename Stack>
    class tarjan_scc_visitor : public dfs_visitor<>
    {
      typedef typename property_traits<ComponentMap>::value_type comp_type;
      typedef typename property_traits<DiscoverTime>::value_type time_type;
    public:
      tarjan_scc_visitor(ComponentMap comp_map, RootMap r, DiscoverTime d,
                         comp_type& c_, Stack& s_)
        : c(c_), comp(comp_map), root(r), discover_time(d),
          dfs_time(time_type()), s(s_) { }

      template <typename Graph>
      void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,
                           const Graph&) {
        put(root, v, v);
        put(comp, v, (std::numeric_limits<comp_type>::max)());
        put(discover_time, v, dfs_time++);
        s.push(v);
      }
      template <typename Graph>
      void finish_vertex(typename graph_traits<Graph>::vertex_descriptor v,
                         const Graph& g) {
        typename graph_traits<Graph>::vertex_descriptor w;
        typename graph_traits<Graph>::out_edge_iterator ei, ei_end;
        for (boost::tie(ei, ei_end) = out_edges(v, g); ei != ei_end; ++ei) {
          w = target(*ei, g);
          if (get(comp, w) == (std::numeric_limits<comp_type>::max)())
            put(root, v, this->min_discover_time(get(root,v), get(root,w)));
        }
        if (get(root, v) == v) {
          do {
            w = s.top(); s.pop();
            put(comp, w, c);
          } while (w != v);
          ++c;
        }
      }
    private:
      template <typename Vertex>
      Vertex min_discover_time(Vertex u, Vertex v) {
        return get(discover_time, u) < get(discover_time,v) ? u : v;
      }

      comp_type& c;
      ComponentMap comp;
      RootMap root;
      DiscoverTime discover_time;
      time_type dfs_time;
      Stack& s;
    };

    template <class Graph, class ComponentMap, class RootMap,
              class DiscoverTime, class P, class T, class R>
    typename property_traits<ComponentMap>::value_type
    strong_components_impl
      (const Graph& g,    // Input
       ComponentMap comp, // Output
       // Internal record keeping
       RootMap root,
       DiscoverTime discover_time,
       const bgl_named_params<P, T, R>& params)
    {
      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ComponentMap, Vertex> ));
      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<RootMap, Vertex> ));
      typedef typename property_traits<RootMap>::value_type RootV;
      BOOST_CONCEPT_ASSERT(( ConvertibleConcept<RootV, Vertex> ));
      BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<DiscoverTime, Vertex> ));

      typename property_traits<ComponentMap>::value_type total = 0;

      std::stack<Vertex> s;
      detail::tarjan_scc_visitor<ComponentMap, RootMap, DiscoverTime,
        std::stack<Vertex> >
        vis(comp, root, discover_time, total, s);
      depth_first_search(g, params.visitor(vis));
      return total;
    }

    //-------------------------------------------------------------------------
    // The dispatch functions handle the defaults for the rank and discover
    // time property maps.
    // dispatch with class specialization to avoid VC++ bug

    template <class DiscoverTimeMap>
    struct strong_comp_dispatch2 {
      template <class Graph, class ComponentMap, class RootMap, class P, class T, class R>
      inline static typename property_traits<ComponentMap>::value_type
      apply(const Graph& g,
            ComponentMap comp,
            RootMap r_map,
            const bgl_named_params<P, T, R>& params,
            DiscoverTimeMap time_map)
      {
        return strong_components_impl(g, comp, r_map, time_map, params);
      }
    };

    template <>
    struct strong_comp_dispatch2<param_not_found> {
      template <class Graph, class ComponentMap, class RootMap,
                class P, class T, class R>
      inline static typename property_traits<ComponentMap>::value_type
      apply(const Graph& g,
            ComponentMap comp,
            RootMap r_map,
            const bgl_named_params<P, T, R>& params,
            param_not_found)
      {
        typedef typename graph_traits<Graph>::vertices_size_type size_type;
        size_type       n = num_vertices(g) > 0 ? num_vertices(g) : 1;
        std::vector<size_type> time_vec(n);
        return strong_components_impl
          (g, comp, r_map,
           make_iterator_property_map(time_vec.begin(), choose_const_pmap
                                      (get_param(params, vertex_index),
                                       g, vertex_index), time_vec[0]),
           params);
      }
    };

    template <class Graph, class ComponentMap, class RootMap,
              class P, class T, class R, class DiscoverTimeMap>
    inline typename property_traits<ComponentMap>::value_type
    scc_helper2(const Graph& g,
                ComponentMap comp,
                RootMap r_map,
                const bgl_named_params<P, T, R>& params,
                DiscoverTimeMap time_map)
    {
      return strong_comp_dispatch2<DiscoverTimeMap>::apply(g, comp, r_map, params, time_map);
    }

    template <class RootMap>
    struct strong_comp_dispatch1 {

      template <class Graph, class ComponentMap, class P, class T, class R>
      inline static typename property_traits<ComponentMap>::value_type
      apply(const Graph& g,
            ComponentMap comp,
            const bgl_named_params<P, T, R>& params,
            RootMap r_map)
      {
        return scc_helper2(g, comp, r_map, params, get_param(params, vertex_discover_time));
      }
    };
    template <>
    struct strong_comp_dispatch1<param_not_found> {

      template <class Graph, class ComponentMap,
                class P, class T, class R>
      inline static typename property_traits<ComponentMap>::value_type
      apply(const Graph& g,
            ComponentMap comp,
            const bgl_named_params<P, T, R>& params,
            param_not_found)
      {
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
        typename std::vector<Vertex>::size_type
          n = num_vertices(g) > 0 ? num_vertices(g) : 1;
        std::vector<Vertex> root_vec(n);
        return scc_helper2
          (g, comp,
           make_iterator_property_map(root_vec.begin(), choose_const_pmap
                                      (get_param(params, vertex_index),
                                       g, vertex_index), root_vec[0]),
           params,
           get_param(params, vertex_discover_time));
      }
    };

    template <class Graph, class ComponentMap, class RootMap,
              class P, class T, class R>
    inline typename property_traits<ComponentMap>::value_type
    scc_helper1(const Graph& g,
               ComponentMap comp,
               const bgl_named_params<P, T, R>& params,
               RootMap r_map)
    {
      return detail::strong_comp_dispatch1<RootMap>::apply(g, comp, params,
                                                           r_map);
    }

  } // namespace detail

  template <class Graph, class ComponentMap,
            class P, class T, class R>
  inline typename property_traits<ComponentMap>::value_type
  strong_components(const Graph& g, ComponentMap comp,
                    const bgl_named_params<P, T, R>& params
                    BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))
  {
    typedef typename graph_traits<Graph>::directed_category DirCat;
    BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));
    return detail::scc_helper1(g, comp, params,
                               get_param(params, vertex_root_t()));
  }

  template <class Graph, class ComponentMap>
  inline typename property_traits<ComponentMap>::value_type
  strong_components(const Graph& g, ComponentMap comp
                    BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))
  {
    typedef typename graph_traits<Graph>::directed_category DirCat;
    BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));
    bgl_named_params<int, int> params(0);
    return strong_components(g, comp, params);
  }

  template <typename Graph, typename ComponentMap, typename ComponentLists>
  void build_component_lists
    (const Graph& g,
     typename graph_traits<Graph>::vertices_size_type num_scc,
     ComponentMap component_number,
     ComponentLists& components)
  {
    components.resize(num_scc);
    typename graph_traits<Graph>::vertex_iterator vi, vi_end;
    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
      components[component_number[*vi]].push_back(*vi);
  }

} // namespace boost

#include <queue>
#include <vector>
#include <boost/graph/transpose_graph.hpp>
#include <boost/pending/indirect_cmp.hpp>
#include <boost/graph/connected_components.hpp> // for components_recorder

namespace boost {

  //==========================================================================
  // This is the version of strongly connected components from
  // "Intro. to Algorithms" by Cormen, Leiserson, Rivest, which was
  // adapted from "Data Structure and Algorithms" by Aho, Hopcroft,
  // and Ullman, who credit the algorithm to S.R. Kosaraju and M. Sharir.
  // The algorithm is based on computing DFS forests the graph
  // and its transpose.

  // This algorithm is slower than Tarjan's by a constant factor, uses
  // more memory, and puts more requirements on the graph type.

  template <class Graph, class DFSVisitor, class ComponentsMap,
            class DiscoverTime, class FinishTime,
            class ColorMap>
  typename property_traits<ComponentsMap>::value_type
  kosaraju_strong_components(Graph& G, ComponentsMap c,
                             FinishTime finish_time, ColorMap color)
  {
    BOOST_CONCEPT_ASSERT(( MutableGraphConcept<Graph> ));
    // ...

    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
    typedef typename property_traits<ColorMap>::value_type ColorValue;
    typedef color_traits<ColorValue> Color;
    typename property_traits<FinishTime>::value_type time = 0;
    depth_first_search
     (G, make_dfs_visitor(stamp_times(finish_time, time, on_finish_vertex())),
      color);

    Graph G_T(num_vertices(G));
    transpose_graph(G, G_T);

    typedef typename property_traits<ComponentsMap>::value_type count_type;

    count_type c_count(0);
    detail::components_recorder<ComponentsMap>
      vis(c, c_count);

    // initialize G_T
    typename graph_traits<Graph>::vertex_iterator ui, ui_end;
    for (boost::tie(ui, ui_end) = vertices(G_T); ui != ui_end; ++ui)
      put(color, *ui, Color::white());

    typedef typename property_traits<FinishTime>::value_type D;
    typedef indirect_cmp< FinishTime, std::less<D> > Compare;

    Compare fl(finish_time);
    std::priority_queue<Vertex, std::vector<Vertex>, Compare > Q(fl);

    typename graph_traits<Graph>::vertex_iterator i, j, iend, jend;
    boost::tie(i, iend) = vertices(G_T);
    boost::tie(j, jend) = vertices(G);
    for ( ; i != iend; ++i, ++j) {
      put(finish_time, *i, get(finish_time, *j));
       Q.push(*i);
    }

    while ( !Q.empty() ) {
      Vertex u = Q.top();
      Q.pop();
      if  (get(color, u) == Color::white()) {
        depth_first_visit(G_T, u, vis, color);
        ++c_count;
      }
    }
    return c_count;
  }

} // namespace boost

#ifdef BOOST_GRAPH_USE_MPI
#  include <boost/graph/distributed/strong_components.hpp>
#endif

#endif // BOOST_GRAPH_STRONG_COMPONENTS_HPP


// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/list/for_each.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/tuple/enum.hpp>
#include <boost/preprocessor/tuple/to_list.hpp>

#include "DataStructures/Tensor/TypeAliases.hpp"
#include "Parallel/CharmPupable.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TypeTraits.hpp"

/// \cond
class DataVector;
namespace EquationsOfState {
template <bool IsRelativistic>
class DarkEnergyFluid;
template <bool IsRelativistic>
class IdealFluid;
template <bool IsRelativistic>
class PolytropicFluid;
class Spectral;
}  // namespace EquationsOfState
/// \endcond

/// Contains all equations of state, including base class
namespace EquationsOfState {

namespace detail {
template <bool IsRelativistic, size_t ThermodynamicDim>
struct DerivedClasses {};

template <>
struct DerivedClasses<true, 1> {
  using type = tmpl::list<Spectral, PolytropicFluid<true>>;
};

template <>
struct DerivedClasses<false, 1> {
  using type = tmpl::list<PolytropicFluid<false>>;
};

template <>
struct DerivedClasses<true, 2> {
  using type = tmpl::list<DarkEnergyFluid<true>, IdealFluid<true>>;
};

template <>
struct DerivedClasses<false, 2> {
  using type = tmpl::list<IdealFluid<false>>;
};

}  // namespace detail

/*!
 * \ingroup EquationsOfStateGroup
 * \brief Base class for equations of state depending on whether or not the
 * system is relativistic, and the number of independent thermodynamic variables
 * (`ThermodynamicDim`) needed to determine the pressure.
 *
 * The template parameter `IsRelativistic` is `true` for relativistic equations
 * of state and `false` for non-relativistic equations of state.
 */
template <bool IsRelativistic, size_t ThermodynamicDim>
class EquationOfState;

/*!
 * \ingroup EquationsOfStateGroup
 * \brief Base class for equations of state which need one thermodynamic
 * variable in order to determine the pressure.
 *
 * The template parameter `IsRelativistic` is `true` for relativistic equations
 * of state and `false` for non-relativistic equations of state.
 */
template <bool IsRelativistic>
class EquationOfState<IsRelativistic, 1>
    : public PUP::able {
 public:
  static constexpr bool is_relativistic = IsRelativistic;
  static constexpr size_t thermodynamic_dim = 1;
  using creatable_classes =
      typename detail::DerivedClasses<IsRelativistic, 1>::type;

  EquationOfState() = default;
  EquationOfState(const EquationOfState&) = default;
  EquationOfState& operator=(const EquationOfState&) = default;
  EquationOfState(EquationOfState&&) = default;
  EquationOfState& operator=(EquationOfState&&) = default;
  ~EquationOfState() override = default;

  WRAPPED_PUPable_abstract(EquationOfState);  // NOLINT

  /// @{
  /*!
   * Computes the pressure \f$p\f$ from the rest mass density \f$\rho\f$.
   */
  virtual Scalar<double> pressure_from_density(
      const Scalar<double>& /*rest_mass_density*/) const = 0;
  virtual Scalar<DataVector> pressure_from_density(
      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the rest mass density \f$\rho\f$ from the specific enthalpy
   * \f$h\f$.
   */
  virtual Scalar<double> rest_mass_density_from_enthalpy(
      const Scalar<double>& /*specific_enthalpy*/) const = 0;
  virtual Scalar<DataVector> rest_mass_density_from_enthalpy(
      const Scalar<DataVector>& /*specific_enthalpy*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the specific enthalpy \f$h\f$ from the rest mass density
   * \f$\rho\f$.
   */
  virtual Scalar<double> specific_enthalpy_from_density(
      const Scalar<double>& /*rest_mass_density*/) const = 0;
  virtual Scalar<DataVector> specific_enthalpy_from_density(
      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the specific internal energy \f$\epsilon\f$ from the rest mass
   * density \f$\rho\f$.
   */
  virtual Scalar<double> specific_internal_energy_from_density(
      const Scalar<double>& /*rest_mass_density*/) const = 0;
  virtual Scalar<DataVector> specific_internal_energy_from_density(
      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes \f$\chi=\partial p / \partial \rho\f$ from \f$\rho\f$, where
   * \f$p\f$ is the pressure and \f$\rho\f$ is the rest mass density.
   */
  virtual Scalar<double> chi_from_density(
      const Scalar<double>& /*rest_mass_density*/) const = 0;
  virtual Scalar<DataVector> chi_from_density(
      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes \f$\kappa p/\rho^2=(p/\rho^2)\partial p / \partial \epsilon\f$
   * from \f$\rho\f$, where \f$p\f$ is the pressure, \f$\rho\f$ is the rest mass
   * density, and \f$\epsilon\f$ is the specific internal energy.
   *
   * The reason for not returning just
   * \f$\kappa=\partial p / \partial \epsilon\f$ is to avoid division by zero
   * for small values of \f$\rho\f$ when assembling the speed of sound with
   * some equations of state.
   */
  virtual Scalar<double> kappa_times_p_over_rho_squared_from_density(
      const Scalar<double>& /*rest_mass_density*/) const = 0;
  virtual Scalar<DataVector> kappa_times_p_over_rho_squared_from_density(
      const Scalar<DataVector>& /*rest_mass_density*/) const = 0;

  /// The lower bound of the rest mass density that is valid for this EOS
  virtual double rest_mass_density_lower_bound() const = 0;

  /// The upper bound of the rest mass density that is valid for this EOS
  virtual double rest_mass_density_upper_bound() const = 0;

  /// The lower bound of the specific internal energy that is valid for this EOS
  /// at the given rest mass density \f$\rho\f$
  virtual double specific_internal_energy_lower_bound(
      const double rest_mass_density) const = 0;

  /// The upper bound of the specific internal energy that is valid for this EOS
  /// at the given rest mass density \f$\rho\f$
  virtual double specific_internal_energy_upper_bound(
      const double rest_mass_density) const = 0;

  /// The lower bound of the specific enthalpy that is valid for this EOS
  virtual double specific_enthalpy_lower_bound() const = 0;
};

/*!
 * \ingroup EquationsOfStateGroup
 * \brief Base class for equations of state which need two independent
 * thermodynamic variables in order to determine the pressure.
 *
 * The template parameter `IsRelativistic` is `true` for relativistic equations
 * of state and `false` for non-relativistic equations of state.
 */
template <bool IsRelativistic>
class EquationOfState<IsRelativistic, 2>
    : public PUP::able {
 public:
  static constexpr bool is_relativistic = IsRelativistic;
  static constexpr size_t thermodynamic_dim = 2;
  using creatable_classes =
      typename detail::DerivedClasses<IsRelativistic, 2>::type;

  EquationOfState() = default;
  EquationOfState(const EquationOfState&) = default;
  EquationOfState& operator=(const EquationOfState&) = default;
  EquationOfState(EquationOfState&&) = default;
  EquationOfState& operator=(EquationOfState&&) = default;
  ~EquationOfState() override = default;

  WRAPPED_PUPable_abstract(EquationOfState);  // NOLINT

  /// @{
  /*!
   * Computes the pressure \f$p\f$ from the rest mass density \f$\rho\f$ and the
   * specific internal energy \f$\epsilon\f$.
   */
  virtual Scalar<double> pressure_from_density_and_energy(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*specific_internal_energy*/) const = 0;
  virtual Scalar<DataVector> pressure_from_density_and_energy(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the pressure \f$p\f$ from the rest mass density \f$\rho\f$ and the
   * specific enthalpy \f$h\f$.
   */
  virtual Scalar<double> pressure_from_density_and_enthalpy(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*specific_enthalpy*/) const = 0;
  virtual Scalar<DataVector> pressure_from_density_and_enthalpy(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*specific_enthalpy*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the specific enthalpy \f$h\f$ from the rest mass density
   * \f$\rho\f$ and the specific internal energy \f$\epsilon\f$.
   */
  virtual Scalar<double> specific_enthalpy_from_density_and_energy(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*specific_internal_energy*/) const = 0;
  virtual Scalar<DataVector> specific_enthalpy_from_density_and_energy(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes the specific internal energy \f$\epsilon\f$ from the rest mass
   * density \f$\rho\f$ and the pressure \f$p\f$.
   */
  virtual Scalar<double> specific_internal_energy_from_density_and_pressure(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*pressure*/) const = 0;
  virtual Scalar<DataVector> specific_internal_energy_from_density_and_pressure(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*pressure*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes \f$\chi=\partial p / \partial \rho\f$ from the \f$\rho\f$ and
   * \f$\epsilon\f$, where \f$p\f$ is the pressure, \f$\rho\f$ is the rest mass
   * density, and \f$\epsilon\f$ is the specific internal energy.
   */
  virtual Scalar<double> chi_from_density_and_energy(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*specific_internal_energy*/) const = 0;
  virtual Scalar<DataVector> chi_from_density_and_energy(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;
  /// @}

  /// @{
  /*!
   * Computes \f$\kappa p/\rho^2=(p/\rho^2)\partial p / \partial \epsilon\f$
   * from \f$\rho\f$ and \f$\epsilon\f$, where \f$p\f$ is the pressure,
   * \f$\rho\f$ is the rest mass density, and \f$\epsilon\f$ is the specific
   * internal energy.
   *
   * The reason for not returning just
   * \f$\kappa=\partial p / \partial \epsilon\f$ is to avoid division by zero
   * for small values of \f$\rho\f$ when assembling the speed of sound with
   * some equations of state.
   */
  virtual Scalar<double> kappa_times_p_over_rho_squared_from_density_and_energy(
      const Scalar<double>& /*rest_mass_density*/,
      const Scalar<double>& /*specific_internal_energy*/) const = 0;
  virtual Scalar<DataVector>
  kappa_times_p_over_rho_squared_from_density_and_energy(
      const Scalar<DataVector>& /*rest_mass_density*/,
      const Scalar<DataVector>& /*specific_internal_energy*/) const = 0;
  /// @}

  /// The lower bound of the rest mass density that is valid for this EOS
  virtual double rest_mass_density_lower_bound() const = 0;

  /// The upper bound of the rest mass density that is valid for this EOS
  virtual double rest_mass_density_upper_bound() const = 0;

  /// The lower bound of the specific internal energy that is valid for this EOS
  /// at the given rest mass density \f$\rho\f$
  virtual double specific_internal_energy_lower_bound(
      const double rest_mass_density) const = 0;

  /// The upper bound of the specific internal energy that is valid for this EOS
  /// at the given rest mass density \f$\rho\f$
  virtual double specific_internal_energy_upper_bound(
      const double rest_mass_density) const = 0;

  /// The lower bound of the specific enthalpy that is valid for this EOS
  virtual double specific_enthalpy_lower_bound() const = 0;
};
}  // namespace EquationsOfState

/// \cond
#define EQUATION_OF_STATE_FUNCTIONS_1D                                    \
  (pressure_from_density, rest_mass_density_from_enthalpy,                \
   specific_enthalpy_from_density, specific_internal_energy_from_density, \
   chi_from_density, kappa_times_p_over_rho_squared_from_density)

#define EQUATION_OF_STATE_FUNCTIONS_2D                                   \
  (pressure_from_density_and_energy, pressure_from_density_and_enthalpy, \
   specific_enthalpy_from_density_and_energy,                            \
   specific_internal_energy_from_density_and_pressure,                   \
   chi_from_density_and_energy,                                          \
   kappa_times_p_over_rho_squared_from_density_and_energy)

#define EQUATION_OF_STATE_ARGUMENTS_EXPAND(z, n, type) \
  BOOST_PP_COMMA_IF(n) const Scalar<type>&

#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS_HELPER(r, DIM,        \
                                                         FUNCTION_NAME) \
  Scalar<double> FUNCTION_NAME(BOOST_PP_REPEAT(                         \
      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, double)) const override; \
  Scalar<DataVector> FUNCTION_NAME(BOOST_PP_REPEAT(                     \
      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, DataVector)) const override;

/// \endcond

/*!
 * \ingroup EquationsOfStateGroup
 * \brief Macro used to generate forward declarations of member functions in
 * derived classes
 */
#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS(DERIVED, DIM)               \
  BOOST_PP_LIST_FOR_EACH(                                                     \
      EQUATION_OF_STATE_FORWARD_DECLARE_MEMBERS_HELPER, DIM,                  \
      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                             \
          BOOST_PP_SUB(DIM, 1),                                               \
          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D)))) \
                                                                              \
  /* clang-tidy: do not use non-const references */                           \
  void pup(PUP::er& p) override; /* NOLINT */                                 \
                                                                              \
  explicit DERIVED(CkMigrateMessage* /*unused*/);

/// \cond
#define EQUATION_OF_STATE_FORWARD_ARGUMENTS(z, n, unused) \
  BOOST_PP_COMMA_IF(n) arg##n

#define EQUATION_OF_STATE_ARGUMENTS_EXPAND_NAMED(z, n, type) \
  BOOST_PP_COMMA_IF(n) const Scalar<type>& arg##n

#define EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER(                        \
    TEMPLATE, DERIVED, DATA_TYPE, DIM, FUNCTION_NAME)                       \
  TEMPLATE                                                                  \
  Scalar<DATA_TYPE> DERIVED::FUNCTION_NAME(BOOST_PP_REPEAT(                 \
      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND_NAMED, DATA_TYPE)) const {    \
    return FUNCTION_NAME##_impl(                                            \
        BOOST_PP_REPEAT(DIM, EQUATION_OF_STATE_FORWARD_ARGUMENTS, UNUSED)); \
  }

#define EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER_2(r, ARGS, FUNCTION_NAME) \
  EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER(                                \
      BOOST_PP_TUPLE_ELEM(0, ARGS), BOOST_PP_TUPLE_ELEM(1, ARGS),             \
      BOOST_PP_TUPLE_ELEM(2, ARGS), BOOST_PP_TUPLE_ELEM(3, ARGS),             \
      FUNCTION_NAME)
/// \endcond

#define EQUATION_OF_STATE_MEMBER_DEFINITIONS(TEMPLATE, DERIVED, DATA_TYPE, \
                                             DIM)                          \
  BOOST_PP_LIST_FOR_EACH(                                                  \
      EQUATION_OF_STATE_MEMBER_DEFINITIONS_HELPER_2,                       \
      (TEMPLATE, DERIVED, DATA_TYPE, DIM),                                 \
      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                          \
          BOOST_PP_SUB(DIM, 1),                                            \
          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D))))

/// \cond
#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS_HELPER(r, DIM,        \
                                                              FUNCTION_NAME) \
  template <class DataType>                                                  \
  Scalar<DataType> FUNCTION_NAME##_impl(BOOST_PP_REPEAT(                     \
      DIM, EQUATION_OF_STATE_ARGUMENTS_EXPAND, DataType)) const;
/// \endcond

#define EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS(DIM)       \
  BOOST_PP_LIST_FOR_EACH(                                         \
      EQUATION_OF_STATE_FORWARD_DECLARE_MEMBER_IMPLS_HELPER, DIM, \
      BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_ELEM(                 \
          BOOST_PP_SUB(DIM, 1),                                   \
          (EQUATION_OF_STATE_FUNCTIONS_1D, EQUATION_OF_STATE_FUNCTIONS_2D))))


// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <array>
#include <boost/optional.hpp>
#include <cstddef>
#include <limits>

#include "DataStructures/Tensor/TypeAliases.hpp"
#include "Domain/OrientationMap.hpp"
#include "Utilities/TypeTraits.hpp"

/// \cond
namespace PUP {
class er;
}  // namespace PUP
/// \endcond

namespace CoordinateMaps {

/// \ingroup CoordinateMapsGroup
///
/// Frustum map from the cube to a rectangular frustum where the bases of the
/// frustum are perpendicular to the z-axis. The `lower_bound` and
/// `upper_bound` values correspond to the locations of the bases along this
/// axis. The `face_vertices` values determine the size of the two rectangular
/// bases along the other two axes. For example, for a frustum along the z-axis,
/// with the lower base starting at (x,y) = (-2.0,3.0) and extending to
/// (2.0,5.0), and with the upper base extending from (0.0,1.0) to (1.0,3.0),
/// the corresponding value for `face_vertices` is `{{{{-2.0,3.0}}, {{2.0,5.0}},
/// {{0.0,1.0}}, {{1.0,3.0}}}}`. The user may reorient the frustum by passing
/// an `OrientationMap` to the constructor. If `with_equiangular_map` is true,
/// then this coordinate map applies a tangent function mapping to the logical
/// xi and eta coordinates.
class Frustum {
 public:
  static constexpr size_t dim = 3;
  Frustum(const std::array<std::array<double, 2>, 4>& face_vertices,
          double lower_bound, double upper_bound,
          OrientationMap<3> orientation_of_frustum,
          bool with_equiangular_map = false) noexcept;
  Frustum() = default;
  ~Frustum() = default;
  Frustum(Frustum&&) = default;
  Frustum(const Frustum&) = default;
  Frustum& operator=(const Frustum&) = default;
  Frustum& operator=(Frustum&&) = default;

  template <typename T>
  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(
      const std::array<T, 3>& source_coords) const noexcept;

  /// Returns boost::none if \f$z\f$ is at or beyond the \f$z\f$-coordinate of
  /// the apex of the pyramid, tetrahedron, or triangular prism that is
  /// formed by extending the `Frustum` (for a
  /// \f$z\f$-oriented `Frustum`).
  boost::optional<std::array<double, 3>> inverse(
      const std::array<double, 3>& target_coords) const noexcept;

  template <typename T>
  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(
      const std::array<T, 3>& source_coords) const noexcept;

  template <typename T>
  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(
      const std::array<T, 3>& source_coords) const noexcept;

  // clang-tidy: google runtime references
  void pup(PUP::er& p) noexcept;  // NOLINT

 private:
  friend bool operator==(const Frustum& lhs, const Frustum& rhs) noexcept;

  OrientationMap<3> orientation_of_frustum_{};
  double sum_midpoint_x_{std::numeric_limits<double>::signaling_NaN()};
  double dif_midpoint_x_{std::numeric_limits<double>::signaling_NaN()};
  double sum_half_length_x_{std::numeric_limits<double>::signaling_NaN()};
  double dif_half_length_x_{std::numeric_limits<double>::signaling_NaN()};
  double sum_midpoint_y_{std::numeric_limits<double>::signaling_NaN()};
  double dif_midpoint_y_{std::numeric_limits<double>::signaling_NaN()};
  double sum_half_length_y_{std::numeric_limits<double>::signaling_NaN()};
  double dif_half_length_y_{std::numeric_limits<double>::signaling_NaN()};
  double midpoint_z_{std::numeric_limits<double>::signaling_NaN()};
  double half_length_z_{std::numeric_limits<double>::signaling_NaN()};
  bool with_equiangular_map_{false};
};

bool operator!=(const Frustum& lhs, const Frustum& rhs) noexcept;
}  // namespace CoordinateMaps