Esempio n. 1
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64('2006-06-10 12:30:00.0',
                                   '2006-06-10 12:33:00.0', 16)
    tL = viscid.as_datetime64('2006-06-10 12:31:00.0')
    tR = viscid.as_datetime64('2006-06-10 12:32:00.0')
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("datetime64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("timedelta64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    return 0
Esempio n. 2
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64('2006-06-10 12:30:00.0',
                                   '2006-06-10 12:33:00.0', 16)
    tL = viscid.as_datetime64('2006-06-10 12:31:00.0')
    tR = viscid.as_datetime64('2006-06-10 12:32:00.0')
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("datetime64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("timedelta64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    return 0
Esempio n. 3
0
def main():
    parser = argparse.ArgumentParser(description="Test divergence")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64("2006-06-10 12:30:00.0", "2006-06-10 12:33:00.0", 16)
    tL = viscid.as_datetime64("2006-06-10 12:31:00.0")
    tR = viscid.as_datetime64("2006-06-10 12:32:00.0")
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names="ty", center="node")
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = mpl.plt.figure(figsize=(10, 5))
    # 1D plot
    mpl.subplot(121)
    mpl.plot(f0[tL:tR]["y=0"], marker="^")
    mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    mpl.subplot(122)
    mpl.plot(f0, x=(t[0], t[-1]))

    mpl.plt.suptitle("datetime64")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))
    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    mpl.plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names="ty", center="node")
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = mpl.plt.figure(figsize=(10, 5))
    # 1D plot
    mpl.subplot(121)
    mpl.plot(f0[tL:tR]["y=0"], marker="^")
    mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    mpl.subplot(122)
    mpl.plot(f0, x=(t[0], t[-1]), y=(y[0], y[-1]))

    mpl.plt.suptitle("timedelta64")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))
    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    mpl.plt.close(fig)

    return 0
Esempio n. 4
0
 def time_as_datetime(self):
     return viscid.as_datetime(self.time_as_datetime64())
Esempio n. 5
0
    def save_fields(cls, fname, flds, complevel=0, compression='gzip',
                    compression_opts=None, **kwargs):
        """ save some fields using the format given by the class """
        # FIXME: this is only good for writing cartesian rectilnear flds
        # FIXME: axes are renamed if flds[0] is 1D or 2D
        assert len(flds) > 0
        fname = os.path.expanduser(os.path.expandvars(fname))

        if complevel and compression == 'gzip' and compression_opts is None:
            compression_opts = complevel
        # TODO: what if compression != 'gzip'
        do_compression = compression_opts is not None

        if isinstance(flds, list):
            if isinstance(flds[0], (list, tuple)):
                flds = OrderedDict(flds)
            else:
                flds = OrderedDict([(fld.name, fld) for fld in flds])

        # FIXME: all coordinates are saved as non-uniform, the proper
        #        way to do this is to have let coordinate format its own
        #        hdf5 / xdmf / numpy binary output
        fld0 = next(iter(flds.values()))
        clist = fld0.crds.get_clist(full_arrays=True)
        crd_arrs = [np.array([0.0])] * 3
        crd_names = ["x", "y", "z"]
        for i, c in enumerate(clist):
            crd_arrs[i] = c[1]
        crd_shape = [len(arr) for arr in crd_arrs]
        time = fld0.time

        # write arrays to the hdf5 file
        with h5py.File(fname, 'w') as f:
            for axis_name, arr in zip(crd_names, crd_arrs):
                loc = cls._CRDS_GROUP + '/' + axis_name
                if do_compression:
                    f.create_dataset(loc, data=arr, compression=compression,
                                     compression_opts=compression_opts)
                else:
                    f[loc] = arr

            for name, fld in flds.items():
                loc = cls._FLD_GROUPS[fld.center.lower()] + '/' + name
                # xdmf files use kji ordering
                if do_compression:
                    f.create_dataset(loc, data=fld.data.T, compression=compression,
                                     compression_opts=compression_opts)
                else:
                    f[loc] = fld.data.T

            # big bad openggcm time_str hack to put basetime into hdf5 file
            for fld in flds.values():
                try:
                    tfmt = "%Y:%m:%d:%H:%M:%S.%f"
                    sec_td = viscid.as_timedelta64(fld.time, 's')
                    dtime = viscid.as_datetime(fld.basetime + sec_td).strftime(tfmt)
                    epoch = viscid.readers.openggcm.GGCM_EPOCH
                    ts = viscid.as_timedelta(fld.basetime - epoch).total_seconds()
                    ts += fld.time
                    timestr = "time= {0} {1:.16e} {2} 300c".format(fld.time, ts, dtime)
                    f.create_group('openggcm')
                    f['openggcm'].attrs['time_str'] = np.string_(timestr)
                    break
                except viscid.NoBasetimeError:
                    pass

        # now write an xdmf file
        xdmf_fname = os.path.splitext(fname)[0] + ".xdmf"
        relh5fname = "./" + os.path.basename(fname)
        with open(xdmf_fname, 'w') as f:
            xloc = cls._CRDS_GROUP + '/' + crd_names[0]
            yloc = cls._CRDS_GROUP + '/' + crd_names[1]
            zloc = cls._CRDS_GROUP + '/' + crd_names[2]
            dim_str = " ".join([str(l) for l in crd_shape][::-1])
            f.write(cls._XDMF_TEMPLATE_BEGIN.format(time=time))
            s = cls._XDMF_TEMPLATE_RECTILINEAR_GRID_BEGIN.format(
                grid_name="vgrid", crd_dims=dim_str, h5fname=relh5fname,
                xdim=crd_shape[0], ydim=crd_shape[1], zdim=crd_shape[2],
                xloc=xloc, yloc=yloc, zloc=zloc)
            f.write(s)

            for fld in flds.values():
                _crd_system = viscid.as_crd_system(fld, None)
                if _crd_system:
                    f.write(cls._XDMF_INFO_TEMPLATE.format(name="crd_system",
                                                           value=_crd_system))
                    break

            for name, fld in flds.items():
                fld = fld.as_flat().T
                dt = fld.dtype.name.rstrip("0123456789").title()
                precision = fld.dtype.itemsize
                fld_dim_str = " ".join([str(l) for l in fld.shape])
                loc = cls._FLD_GROUPS[fld.center.lower()] + '/' + name
                s = cls._XDMF_TEMPLATE_ATTRIBUTE.format(
                    fld_name=name,
                    fld_type=fld.fldtype, center=fld.center.title(),
                    dtype=dt, precision=precision, fld_dims=fld_dim_str,
                    h5fname=relh5fname, fld_loc=loc)
                f.write(s)

            f.write(cls._XDMF_TEMPLATE_GRID_END)
            f.write(cls._XDMF_TEMPLATE_END)
Esempio n. 6
0
    def save_fields(cls, fname, flds, **kwargs):
        """ save some fields using the format given by the class """
        # FIXME: this is only good for writing cartesian rectilnear flds
        # FIXME: axes are renamed if flds[0] is 1D or 2D
        assert len(flds) > 0
        fname = os.path.expanduser(os.path.expandvars(fname))

        # FIXME: all coordinates are saved as non-uniform, the proper
        #        way to do this is to have let coordinate format its own
        #        hdf5 / xdmf / numpy binary output
        clist = flds[0].crds.get_clist(full_arrays=True)
        crd_arrs = [np.array([0.0])] * 3
        crd_names = ["x", "y", "z"]
        for i, c in enumerate(clist):
            crd_arrs[i] = c[1]
        crd_shape = [len(arr) for arr in crd_arrs]
        time = flds[0].time

        # write arrays to the hdf5 file
        with h5py.File(fname, 'w') as f:
            for axis_name, arr in zip(crd_names, crd_arrs):
                loc = cls._CRDS_GROUP + '/' + axis_name
                f[loc] = arr

            for fld in flds:
                loc = cls._FLD_GROUPS[fld.center.lower()] + '/' + fld.name
                # xdmf files use kji ordering
                f[loc] = fld.data.T

            # big bad openggcm time_str hack to put basetime into hdf5 file
            for fld in flds:
                try:
                    tfmt = "%Y:%m:%d:%H:%M:%S.%f"
                    sec_td = viscid.as_timedelta64(fld.time, 's')
                    dtime = viscid.as_datetime(fld.basetime + sec_td).strftime(tfmt)
                    epoch = viscid.readers.openggcm.GGCM_EPOCH
                    ts = viscid.as_timedelta(fld.basetime - epoch).total_seconds()
                    ts += fld.time
                    timestr = "time= {0} {1:.16e} {2} 300c".format(fld.time, ts, dtime)
                    f.create_group('openggcm')
                    f['openggcm'].attrs['time_str'] = np.string_(timestr)
                    break
                except viscid.NoBasetimeError:
                    pass

        # now write an xdmf file
        xdmf_fname = os.path.splitext(fname)[0] + ".xdmf"
        relh5fname = "./" + os.path.basename(fname)
        with open(xdmf_fname, 'w') as f:
            xloc = cls._CRDS_GROUP + '/' + crd_names[0]
            yloc = cls._CRDS_GROUP + '/' + crd_names[1]
            zloc = cls._CRDS_GROUP + '/' + crd_names[2]
            dim_str = " ".join([str(l) for l in crd_shape][::-1])
            f.write(cls._XDMF_TEMPLATE_BEGIN.format(time=time))
            s = cls._XDMF_TEMPLATE_RECTILINEAR_GRID_BEGIN.format(
                grid_name="vgrid", crd_dims=dim_str, h5fname=relh5fname,
                xdim=crd_shape[0], ydim=crd_shape[1], zdim=crd_shape[2],
                xloc=xloc, yloc=yloc, zloc=zloc)
            f.write(s)

            for fld in flds:
                _crd_system = viscid.get_crd_system(fld, None)
                if _crd_system:
                    f.write(cls._XDMF_INFO_TEMPLATE.format(name="crd_system",
                                                           value=_crd_system))
                    break

            for fld in flds:
                fld = fld.as_flat().T
                dt = fld.dtype.name.rstrip("0123456789").title()
                precision = fld.dtype.itemsize
                fld_dim_str = " ".join([str(l) for l in fld.shape])
                loc = cls._FLD_GROUPS[fld.center.lower()] + '/' + fld.name
                s = cls._XDMF_TEMPLATE_ATTRIBUTE.format(
                    fld_name=fld.name,
                    fld_type=fld.fldtype, center=fld.center.title(),
                    dtype=dt, precision=precision, fld_dims=fld_dim_str,
                    h5fname=relh5fname, fld_loc=loc)
                f.write(s)

            f.write(cls._XDMF_TEMPLATE_GRID_END)
            f.write(cls._XDMF_TEMPLATE_END)
Esempio n. 7
0
 def time_as_datetime(self):
     return viscid.as_datetime(self.time_as_datetime64())