Repository: metric-space-ai/metric (language: python)

Issue:
python wrapper for EMD random required
Hello @victor1234, 

I work with Michael at PANDA. I am trying to use the emd-random distance with python but it is not wrapped yet. May you please help me in having it in python? thanks for your help in advance


Discussion / hints:

Fix patch:
diff --git a/python/src/distance/RandomEMD.cpp b/python/src/distance/RandomEMD.cpp
new file mode 100644
index 000000000..f90b2b611
--- /dev/null
+++ b/python/src/distance/RandomEMD.cpp
@@ -0,0 +1,38 @@
+/*
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+  Copyright (c) 2020 Panda Team
+*/
+
+#include "modules/distance/k-random/RandomEMD.hpp"
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+#include <pybind11/numpy.h>
+#include <vector>
+#include <string>
+#include <typeinfo>
+
+namespace py = pybind11;
+
+
+template<typename Sample, typename D = double>
+void wrap_metric_RandomEMD(py::module& m) {
+
+	using Class = metric::RandomEMD<Sample, D>;
+    auto emd = py::class_<Class>(m, "RandomEMD", "Random Earth mover's distance");
+    emd.def(py::init<>(), "Default constructor");
+	emd.def(py::init<double>(),
+			py::arg("precision")
+	);
+	D (Class::*call)(const Sample&, const Sample&) const = &Class::operator();
+    emd.def("__call__", call);
+}
+
+void export_metric_RandomEMD(py::module& m) {
+    wrap_metric_RandomEMD<std::vector<double>, double>(m);
+}
+
+
+
diff --git a/python/src/distance/init.cpp b/python/src/distance/init.cpp
index 32daa4e08..b4cf6db90 100644
--- a/python/src/distance/init.cpp
+++ b/python/src/distance/init.cpp
@@ -10,6 +10,7 @@
 namespace py = pybind11;
 
 void export_metric_EMD(py::module& m);
+void export_metric_RandomEMD(py::module& m);
 void export_metric_kohonen(py::module& m);
 void export_metric_sorensen(py::module& m);
 void export_metric_SSIM(py::module& m);
@@ -18,6 +19,7 @@ void export_metric_Edit(py::module& m);
 
 PYBIND11_MODULE(distance, m) {
     export_metric_EMD(m);
+    export_metric_RandomEMD(m);
     export_metric_kohonen(m);
     export_metric_sorensen(m);
     export_metric_SSIM(m);


Test patch:
diff --git a/python/tests/distance/test_random_emd.py b/python/tests/distance/test_random_emd.py
new file mode 100644
index 000000000..0d517fe6f
--- /dev/null
+++ b/python/tests/distance/test_random_emd.py
@@ -0,0 +1,12 @@
+from metric.distance import RandomEMD
+import numpy as np 
+import math
+
+
+def test__constructor():
+    d1 = np.array(range(11))
+    d2 = np.array(range(1, 12))
+    remd = RandomEMD()
+
+    print(remd(d1, d2))
+    assert(math.isclose(remd(d1, d2), 1, rel_tol=0.01))