Skip to content

Consistent way to specify numpy dtype across the PyGMT codebase #3547

Closed

Description

@seisman

There are many different ways to specify the dtype argument in NumPy arrays, for example:

  1. Using NumPy types (e.g., dtype=np.int32, dtype=np.float64)
  2. Using strings (e.g., dtype="int32", dtype="float64")
  3. Using Python builtin types (e.g, dtype=int, dtype=float)
  4. Using NumPy Array-protocol type strings (e.g., dtype='i4')
  5. maybe more

Currently, we're using both 1 and 2 (i.e., np.int32 and "int32") across the PyGMT codebase. It would be better if we could consistently use only one way, which can improve code maintainability and also reduce confusion for new contributors/maintainers.

I think "NumPy dtypes" like np.int32 is better:

  1. Makes the code more readable by clearly indicating that the type is a NumPy-specific data type
  2. NumPy official documentation uses NumPy types (e.g., np.float64) mostly (e.g., https://numpy.org/doc/stable/user/basics.creation.html)
  3. Using NumPy types is also slightly faster than "strings"
In [1]: import numpy as np

In [2]: %timeit np.array([1, 2, 3], dtype=np.float64)
576 ns ± 1.29 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

In [3]: %timeit np.array([1, 2, 3], dtype="float64")
763 ns ± 5.46 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

Another related issue is to standardize the use of NumPy dtype names. Most NumPy dtypes have a canonical name and one or multiple alias names. For example, np.single/np.float32 is the same numpy dtype (xref: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.single). I think we should use dtypes like np.float32, which is more readable, and can ensure consistency across different platforms.

See https://numpy.org/doc/stable/reference/arrays.scalars.html for the upstream docuem

Activity

  1. added
    discussions
    on Oct 23, 2024
  2. added this to the 0.14.0 milestone on Nov 4, 2024
  3. added
    maintenance
    and removed
    discussions
    on Nov 4, 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

    maintenance

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions