Repository: esheldon/pymangle (language: python)

Issue:
Question about `genrand_range`
Hi,

I have a question about the intended usage of the function `genrand_range`. From the docs I understood that, for small masks, one would want to choose a box small enough to speed the calculation up but large enough to contain the full mask.

However, when I call the function in this way I get a `ValueError: no corners are contained within mask`. This is because the code requires that at least one of the corners of the box is contained in the mask: https://github.com/esheldon/pymangle/blob/0aeec8ca7a406a9c0f6f5500a28a2f9226bd4f96/pymangle/_mangle.c#L1589-L1595

However, if one of the corners is inside the mask, I understand that it is no longer possible to generate random points from the full mask (only from the part of the mask that overlaps with the box). So, is this a bug or am I misunderstanding the intended usage of the function?

Thanks,
Pablo.



Discussion / hints:
Good point, I think this is a bug.

Fix patch:
diff --git a/pymangle/_mangle.c b/pymangle/_mangle.c
index c21863b..4d0168f 100644
--- a/pymangle/_mangle.c
+++ b/pymangle/_mangle.c
@@ -1563,36 +1563,9 @@ PyMangleMask_genrand_range(struct PyMangleMask* self, PyObject* args)
     }
 
     point_set_from_radec(&pt, ramin, decmin);
-    status=MANGLE_POLYID_AND_WEIGHT(self->mask, &pt, &poly_id, &weight);
-    if (poly_id >= 0) {
-        num_contained += 1;
-    }
-
     point_set_from_radec(&pt, ramin, decmax);
-    status=MANGLE_POLYID_AND_WEIGHT(self->mask, &pt, &poly_id, &weight);
-    if (poly_id >= 0) {
-        num_contained += 1;
-    }
-
     point_set_from_radec(&pt, ramax, decmin);
-    status=MANGLE_POLYID_AND_WEIGHT(self->mask, &pt, &poly_id, &weight);
-    if (poly_id >= 0) {
-        num_contained += 1;
-    }
-
     point_set_from_radec(&pt, ramax, decmax);
-    status=MANGLE_POLYID_AND_WEIGHT(self->mask, &pt, &poly_id, &weight);
-    if (poly_id >= 0) {
-        num_contained += 1;
-    }
-
-    if (num_contained==0) {
-        PyErr_Format(PyExc_ValueError,
-                "no corners are contained within mask");
-        status=0;
-        goto _genrand_range_cleanup;
-    }
-
 
     if (!(ra_obj=make_longdouble_array(nrand, "ra", &ra_ptr))) {
         status=0;


Test patch:
diff --git a/pymangle/test.py b/pymangle/test.py
index 7045a26..07d4f6a 100644
--- a/pymangle/test.py
+++ b/pymangle/test.py
@@ -114,7 +114,17 @@ def testNopixel(self):
             fobj.write(text)
 
         m = Mangle(fname)
-        ra,dec = m.genrand(3)
+
+        n = 100
+        ra, dec = m.genrand(n)
+        assert np.all(m.contains(ra, dec))
+
+        ra, dec = m.genrand_range(n, 180, 190, -3.5, -3.2)
+        assert np.all(m.contains(ra, dec))
+
+        ra, dec = m.genrand_range(n, 100, 250, -4, 0)
+        assert np.all(m.contains(ra, dec))
+
         if os.path.exists(fname):
             os.remove(fname)