Due to the current gap in continued funding from the U.S. National Science Foundation (NSF), the NSF Unidata Program Center has temporarily paused most operations. See NSF Unidata Pause in Most Operations for details.

[python-users] How to make scale_factor work with python-netcdf4 + np.ushort

  • To: python-users@xxxxxxxxxxxxxxxx
  • Subject: [python-users] How to make scale_factor work with python-netcdf4 + np.ushort
  • From: daryl herzmann <akrherz@xxxxxxxxxxx>
  • Date: Sat, 17 Jun 2017 06:54:49 -0500 (CDT)
  • Authentication-results: unidata.ucar.edu; dkim=none (message not signed) header.d=none;unidata.ucar.edu; dmarc=none action=none header.from=iastate.edu;
  • Spamdiagnosticmetadata: NSPM
  • Spamdiagnosticoutput: 1:99
Howdy,

Would some kind python user hit me with the clue-by-four here as to how to make scale_factor work with python-netcdf4 and the ushort type? I am using current conda-forge on python2.7. Here's my minimal example:

"""scale_factor.py"""
from __future__ import print_function
import netCDF4
import numpy as np


def create_file():
    """Create"""
    nc = netCDF4.Dataset('test.nc', 'w')
    nc.createDimension('x', 10)
    ncvar = nc.createVariable('ncvar', np.ushort, ('x', ))
    ncvar.scale_factor = 100.
    ncvar.add_offset = 0.
    nc.close()


def write_data():
    """Write"""
    nc = netCDF4.Dataset('test.nc', 'a')
    nc.set_auto_maskandscale(True)
    nc.variables['ncvar'][5] = 1.5
    nc.close()

    nc = netCDF4.Dataset('test.nc', 'a')
    nc.set_auto_maskandscale(False)
    nc.variables['ncvar'][6] = 150.5
    nc.close()


def read_file():
    """Read"""
    nc = netCDF4.Dataset('test.nc', 'r')
    nc.set_auto_maskandscale(True)
    print("read[5] resulted in %s" % (nc.variables['ncvar'][5],))
    print("read[6] resulted in %s" % (nc.variables['ncvar'][6],))
    nc.close()

    nc = netCDF4.Dataset('test.nc', 'r')
    nc.set_auto_maskandscale(False)
    print("readv2[5] resulted in %s" % (nc.variables['ncvar'][5],))
    print("readv2[6] resulted in %s" % (nc.variables['ncvar'][6],))
    nc.close()


def main():
    """Go Main"""
    create_file()
    write_data()
    read_file()


if __name__ == '__main__':
    main()

This results in

$ python scale_factor.py
read[5] resulted in 0.0
read[6] resulted in 15000.0
readv2[5] resulted in 0
readv2[6] resulted in 150

if I switch to np.float32 as the netcdf variable type, I get proper results

$ python scale_factor.py
read[5] resulted in 1.49999996647
read[6] resulted in 15050.0
readv2[5] resulted in 0.015
readv2[6] resulted in 150.5


thanks!
daryl



  • 2017 messages navigation, sorted by:
    1. Thread
    2. Subject
    3. Author
    4. Date
    5. ↑ Table Of Contents
  • Search the python-users archives: