Skip to content

The current data read-in will make the FillValue=nan instead of -1 #189

Closed

Description

@hongyuchen1030

Our current implementation to construct Grid from

xr_tgrid1 = xr.open_dataset(str(ug_filename1))
tgrid1 = ux.Grid(xr_tgrid1)

According to our API documentation, the uxarray.Grid.Mesh2_face_nodes should have the following properties

uxarray.Grid.Mesh2_face_nodes: integer DataArray of size (nMesh2_face, MaxNumNodesPerFace)
A DataArray of indices for each face node, corresponding to coordinates in uxarray.Grid.node_*. Faces can have arbitrary length, with _FillValue=-1 used when faces have fewer nodes than MaxNumNodesPerFace. Nodes are in counter-clockwise order.

However, the current Grid construction will make the _FillValue=nan instead of -1. This already caused a malfunction in my implemented build_edge_face_connectivity which I will take care of later. But such inconsistency might bring more problems in the following code developments

Activity

  1. added
    bug
    on Dec 13, 2022
  2. erogluorhan commented on Dec 14, 2022

    @erogluorhan
    Member

    Thanks! I think defaulting to NaN is better than to -1, so we need to change the draft API doc. Is it also what you meant to fix the inconsistency?

  3. paullric commented on Dec 14, 2022

    @paullric
    Contributor
  4. erogluorhan commented on Dec 14, 2022

    @erogluorhan
    Member

    I'd say,

    • NaN is consistently used for missing data representation in Python,
    • np.nan could enable vectorized execution and hence I'd expect improved performance
    • isnan is convenient and also said to have better performance but didn't read or experience further about
    • I also personally like the fact that -1 == -1 is true but NaN == NaN is false, which would be useful for cases such as comparing indices, etc.
    • Despite not applicable to the case here (i.e. -1 can never be an index), using particular values for missing data might lead to not-breaking but wrong-executing codes.

    Though, NaN might be converting the data arrays it resides in to floating point even if they are integer (which is this case since we are working on index numbers). I don't know if this'd be an issue.

  5. hongyuchen1030 commented on Dec 15, 2022

    @hongyuchen1030
    ContributorAuthor

    Thanks! I think defaulting to NaN is better than to -1, so we need to change the draft API doc. Is it also what you meant to fix the inconsistency?

    Yes. I was just saying no matter what kind of FillValue we choose finally, it's better to have a clear description in the documentation so that we can base the following development on that.

    Currently, I have considered FillValue = -1 and nan in my following implementation to eliminate possible marginal cases.

  6. rljacob commented on Dec 15, 2022

    @rljacob
    Member

    What happens when a Netcdf data set we read has missing values? Are they converted to NaN?

  7. erogluorhan commented on Dec 15, 2022

    @erogluorhan
    Member

    Great question that helped me think twice on the issue! Re Xarray Issue #2742, netCDF files, most of the time if not always, should be coming with the _FillValue information, which Xarray should be consistently handling through dataset.variable.encoding. I think, we should implement something like:

    • If netCDF file provided us with a _FillValue for the variable (e.g. Mesh2_face_nodes in this case), use it
    • Otherwise, determine our default _FillValue, which can be either -1 or NaN, depending on our discussion
    • To decide between the above two, write an internal convenience function so that we would avoid checking against magic fill value numbers throughout our code (e.g. PR DRAFT: Add Grid.build_face_edges_connectivity #191 Line Nearest Neighbor Regridding #397 )

    Would that make sense?

  8. philipc2 commented on Dec 16, 2022

    @philipc2
    Member

    Another issue with using -1 is that it corresponds to the last value in an array if used as an index. For example, if a row in Mesh2_face_nodes consists of indices $[1, 2, 3, -1, -1, -1]$, attempting to use this as an index into Mesh2_node_x would return a total of six values, with the final 3 being the last value in Mesh2_node_x. I can see similar issues occurring if our _FillValue is in the range [-nMesh2_node, nMesh2_node), since any value here would be considered a valid index in Python.

    Using NaN would prevent this from happening and would raise IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices.

  9. rljacob commented on Dec 17, 2022

    @rljacob
    Member

    Seems like xarray would already have a solution for this.

  10. philipc2 commented on Dec 17, 2022

    @philipc2
    Member

    Seems like xarray would already have a solution for this.

    Appears that they use NaN's when handling missing values.

    https://xarray.pydata.org/en/v0.10.4/computation.html#missing-values

  11. dcherian commented on Dec 20, 2022

    @dcherian
    Contributor

    Seems like xarray would already have a solution for this.

    Unfortunately not :(

    1. Xarray doesn't support masked arrays
    2. You can't disable the "masking by NaN" behaviour on file read for specific variables. You can disable converting _FillValue and missing_value to np.nan for all variables with mask_and_scale=False. So that's the downside of the following pattern:
    ds = xr.open_dataset(...)
    tgrid1 = ux.Grid(ds)

    A pragmatic, but ugly, solution would be to convert these variables back to ints with -1 fill value (da.fillna(-1).astype(int)) and explicitly treat -1 as the fill value.

    @philipc2 if this variable had NaNs how would you address the indexing use-case? It seems like you'd have to handle it explictlly, which isn't too different from handling the -1 fill value explicitly.

  12. rljacob commented on Dec 20, 2022

    @rljacob
    Member

    After reading masked arrays it appears that "NaN instead of -1" is a symptom of a different problem: if you try to create an integer array and there are masked values, the array gets promoted to float and the missing values to NaN.

  13. philipc2 commented on Dec 22, 2022

    @philipc2
    Member

    To clarify what I stated above, using an integer _FillValue in the range [-nMesh2_node, nMesh2_node) in a mixed-topology scenario could lead to indexing/slicing issues, since the _FillValue would be a valid index into Mesh2_node_x for a lower-dimension geometry (triangle vs polygon) with negative indexing and slicing in arrays.

    In theory, having NaN values would prevent users from indexing using the full slice for a lower dimension geometry, however this would require us to convert our array into floats, which isn't ideal for Mesh2_face_nodes since they should be represented as integers.

    #162 also set our default datatype for Mesh2_face_nodes to uint32, restricting us to natural integers. Behind the hood, we could represent our _FillValue as the largest possible maximum integer for whichever data type we chose, since it is VERY unlikely we will every have more than the max int number of nodes. This would allow us to keep Mesh2_face_nodes as unsigned integers and prevent improper indexing for users that attempt to slice using a mixed-topology grid.

    Much of the indexing issues could be resolved by knowing the dimension of each face, however this discussion merits its own issue.

  14. rljacob commented on Dec 23, 2022

    @rljacob
    Member

    Are you sure UGRID allows negative numbers to be used for indexing nodes?

  15. philipc2 commented on Dec 23, 2022

    @philipc2
    Member

    Are you sure UGRID allows negative numbers to be used for indexing nodes?

    I'm certain UGRID doesn't, however when not handled properly in Python, negative numbers index from the end of the array.

    Edit: For indexing nodes, I believe it should only be positive integers, but the _FillValue can be negative

  16. paullric commented on Dec 23, 2022

    @paullric
    Contributor
  17. rljacob commented on Dec 24, 2022

    @rljacob
    Member

    Technically allowed but is there any practical reason to index nodes in a mesh with negative numbers?

  18. hongyuchen1030 commented on Dec 27, 2022

    @hongyuchen1030
    ContributorAuthor

    To clarify what I stated above, using an integer _FillValue in the range [-nMesh2_node, nMesh2_node) in a mixed-topology scenario could lead to indexing/slicing issues, since the _FillValue would be a valid index into Mesh2_node_x for a lower-dimension geometry (triangle vs polygon) with negative indexing and slicing in arrays.

    In theory, having NaN values would prevent users from indexing using the full slice for a lower dimension geometry, however this would require us to convert our array into floats, which isn't ideal for Mesh2_face_nodes since they should be represented as integers.

    #162 also set our default datatype for Mesh2_face_nodes to uint32, restricting us to natural integers. Behind the hood, we could represent our _FillValue as the largest possible maximum integer for whichever data type we chose, since it is VERY unlikely we will every have more than the max int number of nodes. This would allow us to keep Mesh2_face_nodes as unsigned integers and prevent improper indexing for users that attempt to slice using a mixed-topology grid.

    Much of the indexing issues could be resolved by knowing the dimension of each face, however, this discussion merits its own issue.

    I think the concern about the _FillValue_=-1 might cause indexing errors can be solved by checking whether the index is positive every time we need to find the node index.

    Because in the end, although the possibility is low, the node number might still reach the MAX number (This is also a marginal case we need to consider about in the future). In another word, either using the _FillValue_=-1 or _FillValue_=MAX, it's always ideal to do a precheck when we call the indexing.

  19. hongyuchen1030 commented on Feb 8, 2023

    @hongyuchen1030
    ContributorAuthor

    In the

    def _read_exodus(ext_ds, ds_var_names):

    We are defining "_FillValue" -1, while the actually _FillValue read-in now is np.nan, also the actual ds["Mesh2_face_nodes"] is a float array instead of the integer array

    # outside the k,v for loop
    # set the face nodes data compiled in "connect" section
    ds["Mesh2_face_nodes"] = xr.DataArray(
        data=(conn[:] - 1),
        dims=["nMesh2_face", "nMaxMesh2_face_nodes"],
        attrs={
            "cf_role":
                "face_node_connectivity",
            "_FillValue":
                -1,
            "start_index":
                int_dtype(
                    0)  # NOTE: This might cause an error if numbering has holes
        })
    
  20. erogluorhan commented on Feb 10, 2023

    @erogluorhan
    Member

    To clarify what I stated above, using an integer _FillValue in the range [-nMesh2_node, nMesh2_node) in a mixed-topology scenario could lead to indexing/slicing issues, since the _FillValue would be a valid index into Mesh2_node_x for a lower-dimension geometry (triangle vs polygon) with negative indexing and slicing in arrays.
    In theory, having NaN values would prevent users from indexing using the full slice for a lower dimension geometry, however this would require us to convert our array into floats, which isn't ideal for Mesh2_face_nodes since they should be represented as integers.
    #162 also set our default datatype for Mesh2_face_nodes to uint32, restricting us to natural integers. Behind the hood, we could represent our _FillValue as the largest possible maximum integer for whichever data type we chose, since it is VERY unlikely we will every have more than the max int number of nodes. This would allow us to keep Mesh2_face_nodes as unsigned integers and prevent improper indexing for users that attempt to slice using a mixed-topology grid.
    Much of the indexing issues could be resolved by knowing the dimension of each face, however, this discussion merits its own issue.

    I think the concern about the _FillValue_=-1 might cause indexing errors can be solved by checking whether the index is positive every time we need to find the node index.

    Because in the end, although the possibility is low, the node number might still reach the MAX number (This is also a marginal case we need to consider about in the future). In another word, either using the _FillValue_=-1 or _FillValue_=MAX, it's always ideal to do a precheck when we call the indexing.

    Well, I am not sure about this when it is Python as this language natively supports negative indexing and it could be useful in ways that @philipc2 described in a prior review comment. I'd agree with fixing with negative index checking if it was C, C++, etc., but in Python I feel that shouldn't be the way to go. Using dtype's MAX sounds reasonable to me as we used that approach in a prior implementation somewhere else, but we should explore other viable implementations, too.

  21. hongyuchen1030 commented on Feb 12, 2023

    @hongyuchen1030
    ContributorAuthor

    To clarify what I stated above, using an integer _FillValue in the range [-nMesh2_node, nMesh2_node) in a mixed-topology scenario could lead to indexing/slicing issues, since the _FillValue would be a valid index into Mesh2_node_x for a lower-dimension geometry (triangle vs polygon) with negative indexing and slicing in arrays.
    In theory, having NaN values would prevent users from indexing using the full slice for a lower dimension geometry, however this would require us to convert our array into floats, which isn't ideal for Mesh2_face_nodes since they should be represented as integers.
    #162 also set our default datatype for Mesh2_face_nodes to uint32, restricting us to natural integers. Behind the hood, we could represent our _FillValue as the largest possible maximum integer for whichever data type we chose, since it is VERY unlikely we will every have more than the max int number of nodes. This would allow us to keep Mesh2_face_nodes as unsigned integers and prevent improper indexing for users that attempt to slice using a mixed-topology grid.
    Much of the indexing issues could be resolved by knowing the dimension of each face, however, this discussion merits its own issue.

    I think the concern about the _FillValue_=-1 might cause indexing errors can be solved by checking whether the index is positive every time we need to find the node index.
    Because in the end, although the possibility is low, the node number might still reach the MAX number (This is also a marginal case we need to consider about in the future). In another word, either using the _FillValue_=-1 or _FillValue_=MAX, it's always ideal to do a precheck when we call the indexing.

    Well, I am not sure about this when it is Python as this language natively supports negative indexing and it could be useful in ways that @philipc2 described in a prior review comment. I'd agree with fixing with negative index checking if it was C, C++, etc., but in Python I feel that shouldn't be the way to go. Using dtype's MAX sounds reasonable to me as we used that approach in a prior implementation somewhere else, but we should explore other viable implementations, too.

    My point is, the _Fill_Value should be a value we will never use for indexing. And we cannot eliminate the possibility about the index might reach to dtype's MAX so far. So even if we use dtype's MAX, a pre-check function is also recommended for robustness.

  22. erogluorhan commented on Feb 13, 2023

    @erogluorhan
    Member

    Well, I am not sure about this when it is Python as this language natively supports negative indexing and it could be useful in ways that @philipc2 described in a prior review comment. I'd agree with fixing with negative index checking if it was C, C++, etc., but in Python I feel that shouldn't be the way to go. Using dtype's MAX sounds reasonable to me as we used that approach in a prior implementation somewhere else, but we should explore other viable implementations, too.

    My point is, the _Fill_Value should be a value we will never use for indexing. And we cannot eliminate the possibility about the index might reach to dtype's MAX so far. So even if we use dtype's MAX, a pre-check function is also recommended for robustness.

    That's also reasonable, but I'd think, in practice, it should be almost impossible for index to reach the MAX even though it is technically possible. Because of the technical possibility though, I suggest we look into other good implementations about FillValue. Do we know any such implementations in Python as a reference?

  23. philipc2 commented on Feb 13, 2023

    @philipc2
    Member

    @erogluorhan

    I agree that in practice, we will rarely (if ever) reach the limits of uint32 or uint64 when working with Mesh2_face_nodes. If we need more precision that uint32, we can use uint64

    We need to have a standardized dtype for Mesh2_face_nodes (and other variables) that is defined at the data loading step. Using a consistent datatype throughout our code would allow us to assign a _FillValue that ensures no conflicts.

    This would avoid the need for users to run the following and accidently clobber any negative fill values:

    # typically fine 
    face_nodes = ugrid.Mesh2_face_nodes.astype(int)
    # if we use a negative fill value, it would be clobbered
    face_nodes = ugrid.Mesh2_face_nodes.astype(np.uint32)

    There is also the option to use np.intp which is described here. xugrid uses this as their default integer datatype and @hongyuchen1030 has worked with this in one of her recent PR's. There is also np.uintp which is the unsigned equivalent. The downside of this route is that it takes on the largest integer defined by the system, which may not be necessary for datasets that fit into a 32bit integer array.

    My Take

    • Create a constants.py or equivalent file to maintain default datatypes for variables
    • Set the default dtype as uint32, with uint64 used for extra precision for variables that are used for integer indexing (Mesh2_face_nodes, etc.)
    • Other default types can be discussed in a separate issue
    • Define _FillValue32 as the max value of uint32 and Define _FillValue64 as the max value of uint64
    • At the data loading step, use the appropriate integer data type (uint32 or uint64) and their corresponding _FillValue. This would handle loading in either 32-bit or 64-bit datasets.
    • Replace the instances of the original _FillValue if one is provided by the one we selected
    • Set the _FillValue as an attribute within the Grid object
    • Define helper functions or additional variables (such as the one is described in Face Geometry Variable for Mixed-Topology Grids  #193) to assist with indexing and bookkeeping

    Are there any objections to this? This should eliminate the case of the index reaching the max of our dtype, unless we are reading in an obscenely large dataset. This would be the case where we have use all 0xFFFFFFFFFFFFFFFF unique values in uint64 as indices in Mesh2_face_nodes, in which case we would be working with datasets on the scale of exabytes if my calculations are correct.

  24. moved this from 📝 To Do to ✅ Done in UXarray Developmenton Mar 28, 2023
  25. added this to the Grid Topology milestone on Mar 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions