Repository: yt-project/yt

Issue:
Surface calculation is not unit safe
When calculating a surface, there is no check that the surface value is in the same units as the surface field.  The script below shows this:
http://paste.yt-project.org/show/7152/

This will give a surface of size zero when the units are not the same and a non-zero sized surface when they are the same.  I'm listing this as a bug because it's simple to fix.
Surface calculation with radius field produces zero-sized surfaces
I'm listing this as a separate issue from Issue #1406 because I think they are unrelated.  To be honest, I cannot tell if this is a real issue or not.

### Bug report

When making surfaces using the radius field, I find that the surfaces almost always have zero size even for rather large data containers.  When constructing surfaces with other fields, like "density", "x", etc, this does not seem to be the case.

**Code for reproduction**

In this script, we make a sphere with size 0.5 and 0.4 using the IsolatedGalaxy dataset.  Both spheres have about 3.6 million cells.  The sphere 
http://paste.yt-project.org/show/7153/


```python
import yt

ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")

sp = ds.sphere(ds.domain_center, 0.5)
print ("sphere size:", sp["density"].size)
units = sp["radius"].units
surf = ds.surface(sp, "radius", sp.radius.to(units))
print ("surface size:", surf["density"].size)

sp = ds.sphere(ds.domain_center, 0.4)
print ("sphere size:", sp["density"].size)
units = sp["radius"].units
surf = ds.surface(sp, "radius", sp.radius.to(units))
print ("surface size:", surf["density"].size)
surf = ds.surface(sp, "radius", sp["radius"].max())
print ("surface size:", surf["density"].size)
```

**Actual outcome**

```
yt : [INFO     ] 2017-05-19 07:43:52,125 Parameters: current_time              = 0.0060000200028298
yt : [INFO     ] 2017-05-19 07:43:52,125 Parameters: domain_dimensions         = [32 32 32]
yt : [INFO     ] 2017-05-19 07:43:52,125 Parameters: domain_left_edge          = [ 0.  0.  0.]
yt : [INFO     ] 2017-05-19 07:43:52,126 Parameters: domain_right_edge         = [ 1.  1.  1.]
yt : [INFO     ] 2017-05-19 07:43:52,126 Parameters: cosmological_simulation   = 0.0
Parsing Hierarchy : 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 173/173 [00:00<00:00, 37610.25it/s]
yt : [INFO     ] 2017-05-19 07:43:52,145 Gathering a field list (this may take a moment.)
sphere size: 3628948
yt : [INFO     ] 2017-05-19 07:43:54,153 Extracting (sampling: ('gas', 'density'))
surface size: 917
sphere size: 3620292
yt : [INFO     ] 2017-05-19 07:44:00,449 Extracting (sampling: ('gas', 'density'))
surface size: 0
yt : [INFO     ] 2017-05-19 07:44:05,949 Extracting (sampling: ('gas', 'density'))
surface size: 0
```

Even when using the maximum value of the radius field, the surface is empty.  This seems wrong, but that's all I can say.


Discussion:

I think a better way to demonstrate this to set the surface value to be half of the radius, or some other value between the minimum and maximum.  When I do that, I always get an empty surface.

Resolving patch:
diff --git a/yt/data_objects/construction_data_containers.py b/yt/data_objects/construction_data_containers.py
--- a/yt/data_objects/construction_data_containers.py
+++ b/yt/data_objects/construction_data_containers.py
@@ -1092,7 +1092,7 @@ class YTSurface(YTSelectionContainer3D):
     surface_field : string
         Any field that can be obtained in a data object.  This is the field
         which will be isocontoured.
-    field_value : float
+    field_value : float, YTQuantity, or unit tuple
         The value at which the isocontour should be calculated.
 
     Examples
@@ -1117,14 +1117,21 @@ class YTSurface(YTSelectionContainer3D):
                          ("index", "x"),
                          ("index", "y"),
                          ("index", "z"))
-    vertices = None
     def __init__(self, data_source, surface_field, field_value, ds=None):
         self.data_source = data_source
-        self.surface_field = surface_field
-        self.field_value = field_value
+        self.surface_field = data_source._determine_fields(surface_field)[0]
+        finfo = data_source.ds.field_info[self.surface_field]
+        try:
+            self.field_value = field_value.to(finfo.units)
+        except AttributeError:
+            if isinstance(field_value, tuple):
+                self.field_value = data_source.ds.quan(*field_value)
+                self.field_value = self.field_value.to(finfo.units)
+            else:
+                self.field_value = data_source.ds.quan(field_value, finfo.units)
         self.vertex_samples = YTFieldData()
         center = data_source.get_field_parameter("center")
-        super(YTSurface, self).__init__(center = center, ds=ds)
+        super(YTSurface, self).__init__(center=center, ds=ds)
 
     def _generate_container_field(self, field):
         self.get_data(field)
@@ -1137,7 +1144,8 @@ def get_data(self, fields = None, sample_type = "face", no_ghost = False):
         elif isinstance(fields, list):
             fields = fields[0]
         # Now we have a "fields" value that is either a string or None
-        mylog.info("Extracting (sampling: %s)" % (fields,))
+        if fields is not None:
+            mylog.info("Extracting (sampling: %s)" % (fields,))
         verts = []
         samples = []
         for io_chunk in parallel_objects(self.data_source.chunks([], "io")):
@@ -1153,7 +1161,7 @@ def get_data(self, fields = None, sample_type = "face", no_ghost = False):
         verts = self.comm.par_combine_object(verts, op='cat', datatype='array')
         # verts is an ndarray here and will always be in code units, so we
         # expose it in the public API as a YTArray
-        self.vertices = self.ds.arr(verts, 'code_length')
+        self._vertices = self.ds.arr(verts, 'code_length')
         if fields is not None:
             samples = uconcatenate(samples)
             samples = self.comm.par_combine_object(samples, op='cat',
@@ -1270,16 +1278,37 @@ def _calculate_flux_in_grid(self, grid, mask,
         ret.convert_to_units(self.ds.unit_system[ret_units.dimensions])
         return ret
 
+    _vertices = None
     @property
-    def triangles(self):
-        if self.vertices is None:
+    def vertices(self):
+        if self._vertices is None:
             self.get_data()
+        return self._vertices
+
+    @property
+    def triangles(self):
         vv = np.empty((self.vertices.shape[1]//3, 3, 3), dtype="float64")
+        vv = self.ds.arr(vv, self.vertices.units)
         for i in range(3):
             for j in range(3):
                 vv[:,i,j] = self.vertices[j,i::3]
         return vv
 
+    _surface_area = None
+    @property
+    def surface_area(self):
+        if self._surface_area is not None:
+            return self._surface_area
+        tris = self.triangles
+        x = tris[:, 1, :] - tris[:, 0, :]
+        y = tris[:, 2, :] - tris[:, 0, :]
+        areas = (x[:, 1]*y[:, 2] - x[:, 2]*y[:, 1])**2
+        np.add(areas, (x[:, 2]*y[:, 0] - x[:, 0]*y[:, 2])**2, out=areas)
+        np.add(areas, (x[:, 0]*y[:, 1] - x[:, 1]*y[:, 0])**2, out=areas)
+        np.sqrt(areas, out=areas)
+        self._surface_area = 0.5*areas.sum()
+        return self._surface_area
+
     def export_obj(self, filename, transparency = 1.0, dist_fac = None,
                    color_field = None, emit_field = None, color_map = None,
                    color_log = True, emit_log = True, plot_index = None,
diff --git a/yt/data_objects/data_containers.py b/yt/data_objects/data_containers.py
--- a/yt/data_objects/data_containers.py
+++ b/yt/data_objects/data_containers.py
@@ -1166,9 +1166,12 @@ def blocks(self):
                 # For grids this will be a grid object, and for octrees it will
                 # be an OctreeSubset.  Note that we delegate to the sub-object.
                 o = self._current_chunk.objs[0]
+                cache_fp = o.field_parameters.copy()
+                o.field_parameters.update(self.field_parameters)
                 for b, m in o.select_blocks(self.selector):
                     if m is None: continue
                     yield b, m
+                o.field_parameters = cache_fp
 
 class GenerationInProgress(Exception):
     def __init__(self, fields):


Test patch:
diff --git a/yt/data_objects/tests/test_fluxes.py b/yt/data_objects/tests/test_fluxes.py
--- a/yt/data_objects/tests/test_fluxes.py
+++ b/yt/data_objects/tests/test_fluxes.py
@@ -111,3 +111,21 @@ def test_correct_output_unit():
     Nmax = sp1.max('HI_Density')
     sur = ds.surface(sp1,"HI_Density", .5*Nmax)
     sur['x'][0]
+
+@requires_file(ISOGAL)
+def test_radius_surface():
+    # see #1407
+    ds = load(ISOGAL)
+    reg = ds.all_data()
+    sp = ds.sphere(ds.domain_center, (0.5, 'code_length'))
+    for obj in [reg, sp]:
+        for rad in [0.05, .1, .4]:
+            surface = ds.surface(obj, 'radius', (rad, 'code_length'))
+            assert_almost_equal(
+                surface.surface_area.v, 4*np.pi*rad**2, decimal=2)
+            verts = surface.vertices
+            for i in range(3):
+                assert_almost_equal(
+                    verts[i, :].min().v, 0.5-rad, decimal=2)
+                assert_almost_equal(
+                    verts[i, :].max().v, 0.5+rad, decimal=2)