Coder Social home page Coder Social logo

gyanz / pydsstools Goto Github PK

View Code? Open in Web Editor NEW
76.0 18.0 34.0 189.86 MB

Python library for simple HEC-DSS functions

License: MIT License

Python 64.72% Dockerfile 0.12% Cython 35.11% Shell 0.05%
python ctypes cython hec-dss database engineering windows10 linux

pydsstools's Introduction

About pydsstools

pydsstools is an experimental Cython based Python library to manipulate HEC-DSS database file. It supports regular/irregular time-series, paired data series and spatial grid records. It is compatible with 64-bit Python on Windows 10 and Ubuntu like linux distributions. For the later, zlib, math, quadmath, and gfortran libraries must be installed. dssvue python library provides graphical user interface for HEC-DSS. There is also a Rust binding hecdss for HEC-DSS.

About HEC-DSS [1]

HEC-DSS is designed to be optimal for storing and retrieving large sets, or series, of data. HEC-DSS is not a relational database, but a database that is designed to retrieve and store large amounts of data quickly that are not necessarily interlinked to other sets of data, like relational databases are. Additionally, HEC-DSS provides a flexible set of utility programs and is easy to add to a user's application program. These are the features that distinguish HEC-DSS from most commercial relational database programs and make it optimal for scientific applications.

HEC-DSS uses a block of sequential data as the basic unit of storage. Each block contains a series of values of a single variable over a time span appropriate for most applications. The basic concept underlying HEC-DSS is the organization of data into records of continuous, applications-related elements as opposed to individually addressable data items. This approach is more efficient for scientific applications than a relational database system because it avoids the processing and storage overhead required to assemble an equivalent record from a relational database.

Data is stored in blocks, or records, within a file and each record is identified by a unique name called a "pathname." Each time data is stored or retrieved from the file, its pathname is used to access its data. Information about the record (e.g., units) is stored in a "header array." This includes the name of the program writing the data, the number of times the data has been written to, and the last written date and time. HEC-DSS documents stored data completely via information contained in the pathname and stored in the header so no additional information is required to identify it. One data set is not directly related to another so there is no need to update other areas of the database when a new data set is stored. The self-documenting nature of the database allows information to be recognized and understood months or years after it was stored.

Because of the self-documenting nature of the pathname and the conventions adopted, there is no need for a data dictionary or data definition file as required with other database systems. In fact, there are no database creation tasks or any database setup. Both HEC-DSS utility programs and applications that use HEC-DSS will generate and configure HEC-DSS database files automatically. There is also no pre-allocation of space; the software automatically expands the file size as needed.

HEC-DSS references data sets, or records, by their pathnames. A pathname may consist of up to 391 characters and is, by convention, separated into six parts, which may be up to 64 characters each. Each part is delimited by a slashe "/", and is labeled "A" through "F", as follows: /A/B/C/D/E/F/.

A list of the pathnames in a DSS file is called a "catalog." In version 6, the catalog was a separate file; in version 7, the catalog is constructed directly from pathnames in the file.

Multi-user access mode is handled automatically by HEC-DSS. The user does not need to do anything to turn it on. Multi-user access allows multiple users, multiple processes, to read and write to the same HEC-DSS file at the same time. This is true for a network drive as well as a local drive. You can have a shared network HEC-DSS file that has several processes reading and writing to it at the same time. The only drawback is that file access may be slower, depending on the operating system.

  1. USACE, Hydrologic Engineering Center (July, 2019). HEC Data Storage System Guide (Draft).

Changes

changelog

Usage

Sample dss file available in examples folder.

Example 1

Write regular time-series data to example.dss

Notes: The interval must be [any] integer greater than 0 for regular time-series. Actual time-series interval implied from E-Part of pathname The values attribute can be list, array or numpy array

from datetime import datetime
from pydsstools.heclib.dss import HecDss
from pydsstools.core import TimeSeriesContainer,UNDEFINED

dss_file = "example.dss"
pathname = "/REGULAR/TIMESERIES/FLOW//1HOUR/Ex1/"
tsc = TimeSeriesContainer()
tsc.pathname = pathname
tsc.startDateTime = "15JUL2019 19:00:00"
tsc.numberValues = 7
tsc.units = "cfs"
tsc.type = "INST"
tsc.interval = 1
tsc.values = [100,UNDEFINED,500,5000,10000,24.1,25]

fid = HecDss.Open(dss_file)
fid.deletePathname(tsc.pathname)
fid.put_ts(tsc)
ts = fid.read_ts(pathname)
fid.close()

Example 2

Read and plot regular time-series

from pydsstools.heclib.dss import HecDss
import matplotlib.pyplot as plt
import numpy as np

dss_file = "example.dss"
pathname = "/REGULAR/TIMESERIES/FLOW//1HOUR/Ex1/"
startDate = "15JUL2019 19:00:00"
endDate = "15AUG2019 19:00:00"

fid = HecDss.Open(dss_file)
ts = fid.read_ts(pathname,window=(startDate,endDate),trim_missing=True)

times = np.array(ts.pytimes)
values = ts.values
plt.plot(times[~ts.nodata],values[~ts.nodata],"o")
plt.show()
fid.close()

Example 3

Write irregular time-series data

Notes: The interval must be [any] integer <= 0 for irregular time-series. DParts: IR-MONTH, IR-YEAR, IR-DECADE, IR-CENTURY

from datetime import datetime
from pydsstools.heclib.dss import HecDss
from pydsstools.core import TimeSeriesContainer, UNDEFINED

dss_file = "example.dss"
pathname = "/IRREGULAR/TIMESERIES/FLOW//IR-DECADE/Ex3/"

tsc = TimeSeriesContainer()
tsc.numberValues = 5
tsc.pathname = pathname
tsc.units ="cfs"
tsc.type = "INST"
tsc.interval = -1
tsc.values = [100,UNDEFINED,500,5000,10000]


tsc.times = [datetime(1900,1,12),datetime(1950,6,2,12),
             datetime(1999,12,31,23,0,0),datetime(2009,1,20),
             datetime(2019,7,15,5,0)]

with HecDss.Open(dss_file) as fid:
    status = fid.put_ts(tsc)

Example 4

Read irregular time-series data

from pydsstools.heclib.dss import HecDss

dss_file = "example.dss"
pathname = "/IRREGULAR/TIMESERIES/FLOW//IR-DECADE/Ex3/"

with HecDss.Open(dss_file) as fid:
    ts = fid.read_ts(pathname,regular=False,window_flag=0)
    print(ts.pytimes)
    print(ts.values)
    print(ts.nodata)
    print(ts.empty)

Example 5

Write paired data series

import numpy as np
from pydsstools.heclib.dss import HecDss
from pydsstools.core import PairedDataContainer

dss_file = "example.dss"
pathname ="/PAIRED/DATA/FREQ-FLOW///Ex5/"

pdc = PairedDataContainer()
pdc.pathname = pathname
pdc.curve_no = 2
pdc.independent_axis = list(range(1,10))
pdc.data_no = 9
pdc.curves = np.array([[5,50,500,5000,50000,10,100,1000,10000],
                       [11,11,11,11,11,11,11,11,11]],dtype=np.float32)
pdc.labels_list = ['Column 1','Elevens']
pdc.independent_units = 'Number'
pdc.dependent_units = 'Feet'

fid = HecDss.Open(dss_file)
fid.put_pd(pdc)
fid.close()

Example 6

Read paired data-series

Notes: Row and column/curve indices start at 1 (not zero)

from pydsstools.heclib.dss import HecDss

dss_file = "example.dss"
pathname ="/PAIRED/DATA/FREQ-FLOW///Ex5/"

#labels_list = ['Column 1','Elevens']

with HecDss.Open(dss_file) as fid:
    read_all = fid.read_pd(pathname)

    row1,row2 = (2,4)
    col1,col2 = (1,2)
    read_partial = fid.read_pd(pathname,window=(row1,row2,col1,col2))

Example 7

Pre-allocate paired data-series

from pydsstools.heclib.dss import HecDss

dss_file = "example.dss"
pathname ="/PAIRED/PREALLOCATED DATA/FREQ-FLOW///Ex7/"

with HecDss.Open(dss_file) as fid:
    rows = 10
    curves = 15
    fid.preallocate_pd((rows,curves),pathname=pathname)

Example 8

Write individual curve data in pre-allocated paired data-series

from pydsstools.heclib.dss import HecDss

dss_file = "example.dss"
pathname ="/PAIRED/PREALLOCATED DATA/FREQ-FLOW///Ex7/"

with HecDss.Open(dss_file) as fid:
    curve_index = 5
    curve_label = 'Column 5'
    curve_data = [10,20,30,40,50,60,70,80,90,100]
    fid.put_pd(curve_data,curve_index,pathname=pathname,labels_list=[curve_label])

    curve_index = 2
    curve_label = 'Column 2'
    curve_data = [41,56,60]
    row1,row2 = (5,7)
    fid.put_pd(curve_data,curve_index,window = (row1,row2),
            pathname=pathname,labels_list=[curve_label])

Example 9

Read Spatial Grid

from pydsstools.heclib.dss.HecDss import Open

dss_file = "example.dss"

pathname = "/GRID/RECORD/DATA/01jan2001:1200/01jan2001:1300/Ex9/"

with Open(dss_file) as fid:
    dataset = fid.read_grid(pathname)
    grid_array = dataset.read()
    profile = dataset.profile
    # if rasterio library is installed
    # raster attribute is available for dataset object
    # save grid as geotiff with epsg 2868 for coordinate reference system
    try:
        dataset.raster.save_tiff(r'grid_dataset.tif', {'crs': 2868})
    except:
        pass
    else:
        print('grid data saved as grid_dataset.tif')

Example 10

Write Spatial Grid record

import numpy as np
import numpy.ma as ma
from affine import Affine
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import gridInfo

dss_file = "example.dss"

pathname_out1 = "/GRID/RECORD/DATA/01jan2019:1200/01jan2019:1300/Ex10a/"
pathname_out2 = "/GRID/RECORD/DATA/01jan2019:1200/01jan2019:1300/Ex10b/"

with Open(dss_file) as fid:
    # Type 1: data is numpy array
    # np.nan is considered as nodata
    data = np.reshape(np.array(range(100),dtype=np.float32),(10,10))
    data[0] = np.nan # assign nodata to first row
    grid_info = gridInfo()
    cellsize = 100 # feet
    xmin,ymax = (1000,5000) # grid top-left corner coordinates
    affine_transform = Affine(cellsize,0,xmin,0,-cellsize,ymax)
    grid_info.update([('grid_type','specified'),
                      ('grid_crs','unknown'),
                      ('grid_transform',affine_transform),
                      ('data_type','per-aver'),
                      ('data_units','mm'),
                      ('opt_time_stamped',False)])
    fid.put_grid(pathname_out1,data,grid_info)
            
    # Type 2: data is numpy masked array, where masked values are considered nodata
    data = np.reshape(np.array(range(100),dtype=np.float32),(10,10))
    data = ma.masked_where((data >= 10) & (data <30),data) # mask second and third rows
    fid.put_grid(pathname_out2,data,grid_info)

Example 11

Read DSS-6 Spatial Grid record Copy DSS-6 Grid to DSS-7 file

from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import dss_logging
dss_logging.config(level='Diagnostic')

dss6_file = "example_dss6.dss"
dss7_file = "example.dss"

pathname_in = "/SHG/MAXTEMP/DAILY/08FEB1982:0000/08FEB1982:2400/PRISM/"
pathname_out = "/SHG/MAXTEMP/DAILY/08FEB1982:0000/08FEB1982:2400/Ex11/"

with Open(dss6_file) as fid:
    dataset = fid.read_grid(pathname_in)
    data = dataset.read()
    profile = dataset.profile

with Open(dss6_file) as fidin, Open(dss7_file) as fidout:
    dataset = fidin.read_grid(pathname_in)
    fidout.put_grid(pathname_out,dataset,compute_range = True) # recomputing range limit table

Example 12

Read pathname catalog

from pydsstools.heclib.dss.HecDss import Open

dss_file = "example.dss"

pathname_pattern ="/PAIRED/*/*/*/*/*/"

with Open(dss_file) as fid:
    path_list = fid.getPathnameList(pathname_pattern,sort=1)
    print('list = %r' % path_list)

Example 13

Copy dss record

from pydsstools.heclib.dss.HecDss import Open

dss_file = "example.dss"

pathname_in ="/PAIRED/DATA/FREQ-FLOW///Ex5/"
pathname_out ="/PAIRED/DATA/FREQ-FLOW///Ex12/"

with Open(dss_file) as fid:
    fid.copy(pathname_in,pathname_out)

Example 14

Delete dss record

from pydsstools.heclib.dss.HecDss import Open

dss_file = "example.dss"

pathname ="/PAIRED/DATA/FREQ-FLOW///Ex12/"

with Open(dss_file) as fid:
    fid.deletePathname(pathname)

Example 15

Spatial Analysis on grid

# Notes
# Experimental geospatial methods for grid
# Not 100% sure about gridinfo that is computed for the cropped grid esp. for SHG and HRAP
# Will apreciate user feedbacks on this
# This example code was tested using the following libraries
# gdal 3.2.2
# matplotlib 3.4.4
# rasterio 1.2.1
# Potential rasterio issue with CRS
# https://github.com/mapbox/rasterio/blob/master/docs/faq.rst#why-cant-rasterio-find-projdb
# Unset PROJ_LIB environmental variable (i.e., SET PROJ_LIB= )

from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import BoundingBox

dss_file = "example.dss"

pathname = r"/SHG/LCOLORADO/PRECIP/02JAN2020:1500/02JAN2020:1600/Ex15/"
pathname_out = r"/SHG/LCOLORADO/PRECIP/02JAN2020:1500/02JAN2020:1600/Ex15 OUT/"

fid = Open(dss_file)
ds0 = fid.read_grid(pathname)

if not getattr(ds0,'raster',None) is None:
    ds0.raster.plot(mask_zeros = True, title = 'Original Spatial Grid')
    bbox = BoundingBox(-50000,6*10**5,50000,7*10**5)
    ds1 = ds0.raster.mask(bbox,crop = False)
    ds1.raster.plot(mask_zeros = True, title = 'Clipped Spatial Grid')
    ds2 = ds1.raster.mask(bbox,crop = True)
    ds2.raster.plot(mask_zeros = True, title = 'Cropped Spatial Grid')
    fid.put_grid(pathname_out,ds2)

Dependencies

Build from source

Download the source files, open the command prompt in the root directory, and enter the following command. Note that the command prompt must be setup with build tools and python environment.

python -m build 

Installation from PyPI

pip install pydsstools

Contributing

All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome. Feel free to ask questions on my email.

License

This program is a free software: you can modify and/or redistribute it under MIT license.

pydsstools's People

Contributors

brettpalmberg avatar gyanz avatar jeffsuperglide avatar ktarbet avatar kushalmbi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pydsstools's Issues

Incorrect dates returned with Monthly Time series

Hello, when I read in monthly time series, I am not getting my actual dates returned. Instead, I am getting dates that are exactly 30 days apart. Attached is the tabulated values of my monthly timeseries in DSSVue
2023-10-13_9-38-00

I am reading in the values in python using the following calls

fid = HecDss.Open(dss_path)
ts = fid.read_ts(line_path, window=(start_time, end_time), regular=True, trim_missing=False)

where my start_time is DateTime(2020, 1, 1, 0, 0, 0) and my end_time is DateTime(2020, 12, 31, 0, 0 ,0). When I use ts.pytimes, these are the values I get back
[datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 31, 0, 0), datetime.datetime(2020, 3, 1, 0, 0), datetime.datetime(2020, 3, 31, 0, 0), datetime.datetime(2020, 4, 30, 0, 0), datetime.datetime(2020, 5, 30, 0, 0), datetime.datetime(2020, 6, 29, 0, 0), datetime.datetime(2020, 7, 29, 0, 0), datetime.datetime(2020, 8, 28, 0, 0), datetime.datetime(2020, 9, 27, 0, 0), datetime.datetime(2020, 10, 27, 0, 0), datetime.datetime(2020, 11, 26, 0, 0), datetime.datetime(2020, 12, 26, 0, 0)]

I get similar results even when changing my start and end times, and changing the record to a different monthly record also gets me the same results. When I convert the values to daily, and then read them in, the correct values are at the correct times. This also happens reading from a DSS6 vs DSS7 file.

Additional info:
python version: 3.9.13
DSSVue version: 3.3.25
pydsstools version: 2.3.1

ImportError: DLL load failed

I am having an having an ImportError after I updated the pydsstools package from an earlier version using Python 3.7. Do you have any ideas what the cause might be?

MicrosoftTeams-image (2)

Best,
Sercan

Support Python 3.6.11 ?

pip install https://github.com/gyanz/pydsstools/zipball/master
Collecting https://github.com/gyanz/pydsstools/zipball/master
Using cached https://github.com/gyanz/pydsstools/zipball/master
Requirement already satisfied: numpy>=1.16.4 in ./env/lib/python3.6/site-packages (from pydsstools==1.6) (1.18.5)
Requirement already satisfied: pandas in ./env/lib/python3.6/site-packages (from pydsstools==1.6) (1.0.4)
Collecting affine
Downloading affine-2.3.0-py2.py3-none-any.whl (15 kB)
ERROR: Package 'pydsstools' requires a different Python: 3.6.11 not in '~=3.8'

Install for 3.6?

Is it possible to have this compatible with 3.6 as well? trying to use this with ESRI which only uses up to 3.6.

Thanks

print statements

Most of the library uses logging calls, but there are some lingering print statements that produce a lot of output with no way to suppress them without changing core code in a fork. Notably this one that executes for every grid record written.

print('stats=',stats)

Example - writing a GIS Tiff file to DSS.

Hello, I have struggled to write a valid GIS tiff, to a dss file.

I had to leave disabled the 'raise_profile_error', because the values calculated by the pydsstools, appear to be calculated using the top left of the grid, instead of the bottom left.

The comment on the 25th of november here mentions this as well:
#31

The end result is that the raster, ends up shifted up, by the distance of the height of the raster If i provide values that pass your validation.

Problems with the installation of the library

Dear,

Firstly, thank you very much for the so useful library that allows the automation of HMS softwares.

We are trying to install the library in Windows OS, following the procedure (installing firstly the dependent libraries and the MS Visual C++ Redistributable for VS 2015 - 2019) you are describing. Unfortunately, it was not possible to install the library (neither via githab directly nor via "wheel_file"). You can see below the error that is returned by the system. Our IT guys consulting me that perhaps a tool that support the building of the library is not included in MS Visual C++ Redistributable for VS 2015 - 2019. Due to this we downloaded and installed the entire MS Visual C++ libraries with .NET Frameworks as well as the Visual studio code but the error insists.

We tried the above procedure with different python versions and using the DSS tool you propose.

This is really strange to us because we had managed to instal the library previous September, and it was a straightforward procedure (it was taken just a couple of minutes).

Capture
8-11eb-84f0-6ea29df8249a.png)

Could you please provide any advice on the above? It whould be much appreciated.

Best regards,

Panagiotis Kossieris

--
Dr. Panagiotis Kossieris
Civil Engineer NTUA, M.Sc. NTUA, Ph.D. NTUA

Research associate
National Technical University of Athens
School of Civil Engineering, Department of Water Resources and Environmental Engineering
Heroon Polytechneiou 5, GR 157 80 Zographou, Greece
Tel: +30 210 772 2842
e-mail: [email protected]| [email protected]

Installation problem

Hi, I try to install the repository using pip install https://github.com/gyanz/pydsstools/zipball/master command on my PC but I get the below error.
Could you please provide any advice on the above? It would be much appreciated.
Thanks,

pip install https://github.com/gyanz/pydsstools/zipball/master

Collecting https://github.com/gyanz/pydsstools/zipball/master
Using cached https://github.com/gyanz/pydsstools/zipball/master
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing wheel metadata ... done
Collecting affine
Using cached affine-2.3.0-py2.py3-none-any.whl (15 kB)
Requirement already satisfied: numpy>=1.16.4 in c:\programdata\anaconda3\lib\site-packages (from pydsstools==2.2) (1.20.1)
Requirement already satisfied: pandas in c:\programdata\anaconda3\lib\site-packages (from pydsstools==2.2) (1.2.4)
Requirement already satisfied: pytz>=2017.3 in c:\programdata\anaconda3\lib\site-packages (from pandas->pydsstools==2.2) (2021.1)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\programdata\anaconda3\lib\site-packages (from pandas->pydsstools==2.2) (2.8.1)
Requirement already satisfied: six>=1.5 in c:\programdata\anaconda3\lib\site-packages (from python-dateutil>=2.7.3->pandas->pydsstools==2.2) (1.15.0)
Building wheels for collected packages: pydsstools
Building wheel for pydsstools (PEP 517) ... error
ERROR: Command errored out with exit status 1:
command: 'C:\ProgramData\Anaconda3\python.exe' 'C:\ProgramData\Anaconda3\lib\site-packages\pip_vendor\pep517_in_process.py' build_wheel 'C:\Users\axj0964\AppData\Local\Temp\tmp8vyau6sc'
cwd: C:\Users\axj0964\AppData\Local\Temp\pip-req-build-0n0uifjx

Suppress Output

Anyone know a way to suppress this output every time I am reading a variable with read_ts? Thanks!
image

Issue with installation of pydsstools

I am unable to run the command

python setup.py install.

Here is the exception. Could you please help here?

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.43
x64\release\grid.lib
1 File(s) copied
building 'pydsstools._lib.x64.core_heclib' extension
core_heclib.c
C:\Users\chand\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(14) : Warning Msg: Using deprecated NumPy API, disable it with #define NPY_NO_D
EPRECATED_API NPY_1_7_API_VERSION
pydsstools/src/core_heclib.c(6554): warning C4244: '=': conversion from 'double' to 'float', possible loss of data
pydsstools/src/core_heclib.c(16429): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(16707): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(17001): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(48057): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(48154): warning C4090: '=': different 'const' qualifiers
LINK : fatal error LNK1104: cannot open file 'ifconsol.lib'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1104

cannot import name 'core_heclib' from 'pydsstools._lib.x64'

I am hitting an import error

>>> from pydsstools.heclib.dss import HecDss
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\dhah\Documents\pydsstools\pydsstools\heclib\dss\HecDss.py", line 15, in <module>
    from ...core import Open as _Open
  File "C:\Users\dhah\Documents\pydsstools\pydsstools\core\__init__.py", line 28, in <module>
    from .._lib import *
  File "C:\Users\dhah\Documents\pydsstools\pydsstools\_lib\__init__.py", line 1, in <module>
    from .x64 import core_heclib
ImportError: cannot import name 'core_heclib' from 'pydsstools._lib.x64' (C:\Users\dhah\Documents\pydsstools\pydsstools\_lib\x64\__init__.py)

Using Python 3.7 pydsstools installed using .whl file.
Thank you

Cant view grids after opening file.

After running Example 10:

import numpy as np
import numpy.ma as ma
from affine import Affine
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import gridInfo

dss_file = "example.dss"

pathname_out1 = "/GRID/RECORD/DATA/01jan2019:1200/01jan2019:1300/Ex10a/"
pathname_out2 = "/GRID/RECORD/DATA/01jan2019:1200/01jan2019:1300/Ex10b/"

with Open(dss_file) as fid:
    # Type 1: data is numpy array
    # np.nan is considered as nodata
    data = np.reshape(np.array(range(100),dtype=np.float32),(10,10))
    data[0] = np.nan # assign nodata to first row
    grid_info = gridInfo()
    cellsize = 100 # feet
    xmin,ymax = (1000,5000) # grid top-left corner coordinates
    affine_transform = Affine(cellsize,0,xmin,0,-cellsize,ymax)
    grid_info.update([('grid_type','specified'),
                      ('grid_crs','unknown'),
                      ('grid_transform',affine_transform),
                      ('data_type','per-aver'),
                      ('data_units','mm'),
                      ('opt_time_stamped',False)])
    fid.put_grid(pathname_out1,data,grid_info)
            
    # Type 2: data is numpy masked array, where masked values are considered nodata
    data = np.reshape(np.array(range(100),dtype=np.float32),(10,10))
    data = ma.masked_where((data >= 10) & (data <30),data) # mask second and third rows
    fid.put_grid(pathname_out2,data,grid_info)

I cant seem to view the grids in DSS. I have tried DSSvue version 3.0.00.212. I see the traceback from DSSvue of:

Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: hec.heclib.util.Heclib.Hec_zgridRetrieve([ILhec/heclib/grid/GridContainer;Z)I
        at hec.heclib.util.Heclib.Hec_zgridRetrieve(Native Method)
        at hec.heclib.util.Heclib.zgridRetrieve(Heclib.java:790)
        at hec.heclib.dss.HecDssGrid.read(HecDssGrid.java:41)
        at hec.heclib.grid.GriddedData.retrieveGriddedContainer(GriddedData.java:182)
        at hec.heclib.grid.GriddedData.retrieveGriddedData(GriddedData.java:210)
        at hec.dssgui.CombinedDataManager.getGriddedDataLocal(CombinedDataManager.java:1673)
        at hec.dssgui.CombinedDataManager.readGriddedData(CombinedDataManager.java:1606)
        at hec.dssgui.CombinedDataManager.readData(CombinedDataManager.java:1487)
        at hec.dssgui.ListSelection.readData(ListSelection.java:3212)
        at hec.dssgui.ListSelection.readData(ListSelection.java:3001)
        at hec.dssgui.ListSelection.getSelectedDataContainers(ListSelection.java:2846)
        at hec.dssgui.ListSelection.plot(ListSelection.java:3595)
        at hec.dssgui.ListSelection$VueActionListener.actionPerformed(ListSelection.java:13340)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
        at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
        at java.awt.Component.processMouseEvent(Component.java:6525)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6290)
        at java.awt.Container.processEvent(Container.java:2234)
        at java.awt.Component.dispatchEventImpl(Component.java:4881)
        at java.awt.Container.dispatchEventImpl(Container.java:2292)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
        at java.awt.Container.dispatchEventImpl(Container.java:2278)
        at java.awt.Window.dispatchEventImpl(Window.java:2750)
        at java.awt.Component.dispatchEvent(Component.java:4703)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:709)
        at java.awt.EventQueue$3.run(EventQueue.java:703)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.awt.EventQueue$4.run(EventQueue.java:731)
        at java.awt.EventQueue$4.run(EventQueue.java:729)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Any ideas on what is going on here?

ERRO WARNING:root:-----DSS--- ztsRetrieveReg Warning: Invalid date or time given, after trying to open a DSS file

Dear Support team,

Description:
I encountered an error while using pydsstools library in Python when running the following command:

fid = HecDss.Open(dss_file)

The error message I received is:

WARNING:root:-----DSS--- ztsRetrieveReg Warning: Invalid date or time given.

This error seems to be related to retrieving data from the time series in the DSS file. It indicates that the provided date or time value is invalid.

Steps to Reproduce:

To reproduce the issue, you can follow these steps:
Install pydsstools library (version X.X.X) in your Python environment.

Import the necessary modules and classes:

from hec.heclib.dss import HecDss

Open a DSS file using the HecDss.Open method:

fid = HecDss.Open(dss_file)

Replace dss_file with the path to your specific DSS file.

Expected Behavior:
I expected the DSS file to be successfully opened without any warning or error related to invalid date or time values.

Actual Behavior:

The warning message "WARNING:root:-----DSS--- ztsRetrieveReg Warning: Invalid date or time given" is displayed, indicating an issue with the provided date or time.

Additional Information:

I have verified that the date and time values used are valid and correctly formatted according to the requirements of the pydsstools library.

I have checked the documentation for pydsstools but couldn't find any specific guidance related to this warning.

I am running Python 3.9 on Windows 11.

Please let me know if any further information is needed to investigate and resolve this issue. Thank you for your assistance!

Writing to a new DSS file

Hello,

I can successfully write to an existing DSS file. When I try to write to a new DSS file, the file is created successfully and it seems like some data is populated. When I try to open the DSS file with DSSVue, I get the "cannot access file" error.

Thanks for the package!
Sercan

Time Series reading dates incorrectly

I'm having an issue reading the dates when I am reading a large file. I have a dss file with data at daily time step. I am using the read_ts function in the Open class. Whenever I try to read a window larger than 24,854 days long is when the issue occurs. The first 24,854 days are read with the correct time stamp. However, the next entry reverts to 1860-09-11 17:31:44. It doesn't matter where the start date and end date are in the record. As soon as the dataset being read is longer than 24,854 days, the timestamps will revert to 1860, and continue to progress daily from there. I am able to get around the issue by making my own datetime array manually, but I'm curious if anyone else has encountered this issue. I think it may have something to do with the HecTime or perhaps pytime?

Feature Request: Squeeze

I would be very nice to have the squeeze functionality added to this package.

Do you have any insight into how complicated this might be?

pytimes error, hour must be in 0..23

I've been having trouble with the library when trying to plot a time series with the midnight hour in it, since HEC-RAS uses 24:00 for it and python doesn't recognize it. With a startDate, endDate of:

["29JAN2019 21:30:00", "30JAN2019 05:30:00"]

I get this error when running times = np.array(ts.pytimes)

dateutil.parser._parser.ParserError: hour must be in 0..23: 29 Jan2019 24:00:00

I was wondering if the code takes that into account or maybe I'm making a mistake. If the time series spans in a single day before 00:00 there's no problem. I'm using version 1.3 with python 3.6
Thanks!

Cannot Access File

Every time I try to run Example 10 and after generating the example.dss, my HEC-DSSVue is not able to open it and I get the following message:

Cannot Access File: filepath

Can we please get a conda-forge feedstock?

Have you considered putting this package on a language-agnostic package manager like conda? I'm a big fan of this package but I've only gotten it working by copying the whole project over, or using the wheel file. The wheel works well, but it doesn't seem as repeatable as spinning up an env with conda create -n myEnv -c conda-forge python=3.8 pydsstools.

This is as far as I was able to get in the setup from source. I tried uninstalling visual studio 2022 and moving back to 2019, still no luck:

(raz) C:\Py\pydsstools>python setup.py install 
setup directory: 'C:\\Py\\pydsstools'
running install
C:\Users\openSourcerer9000\Anaconda3\envs\raz\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
C:\Users\openSourcerer9000\Anaconda3\envs\raz\lib\site-packages\setuptools\command\easy_install.py:156: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
running bdist_egg
running egg_info
writing pydsstools.egg-info\PKG-INFO
writing dependency_links to pydsstools.egg-info\dependency_links.txt
writing requirements to pydsstools.egg-info\requires.txt
writing top-level names to pydsstools.egg-info\top_level.txt        
reading manifest file 'pydsstools.egg-info\SOURCES.txt'
adding license file 'LICENSE'
writing manifest file 'pydsstools.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg   
running install_lib
running build_py
running build_ext
Building external library: grid.lib
Using "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\msbuild.exe" (found in the Visual Studio installation)
Microsoft (R) Build Engine version 16.11.2+f32259642 for .NET Framework
Copyright (C) Microsoft Corporation. All rights reserved.

Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
Build started 12/14/2021 2:14:45 PM.
Project "C:\Py\pydsstools\pydsstools\src\external\gridv6\grid.sln" on node 1 (default targets).
ValidateSolutionConfiguration:
  Building solution configuration "Release|x64".
Project "C:\Py\pydsstools\pydsstools\src\external\gridv6\grid.sln" (1) is building "C:\Py\pydsstools\pydsstools\src\external\gridv6\grid.vcxproj" (2) on node 1 (default targets).
InitializeBuildStatus:
  Creating "x64\Release\intermediate\grid.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
ClCompile:
  All outputs are up-to-date.
  All outputs are up-to-date.
Lib:
  All outputs are up-to-date.
  grid.vcxproj -> C:\Py\pydsstools\pydsstools\src\external\gridv6\x64\Release\grid.lib
FinalizeBuildStatus:
  Deleting file "x64\Release\intermediate\grid.tlog\unsuccessfulbuild".
  Touching "x64\Release\intermediate\grid.tlog\grid.lastbuildstate".
Done Building Project "C:\Py\pydsstools\pydsstools\src\external\gridv6\grid.vcxproj" (default targets).

Done Building Project "C:\Py\pydsstools\pydsstools\src\external\gridv6\grid.sln" (default targets).


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.11
x64\release\grid.lib
1 File(s) copied
building 'pydsstools._lib.x64.core_heclib' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ipydsstools/src/external/dss/headers -Ipydsstools/src/external/gridv6/headers -Ipydsstools/src/external/zlib -IC:\Users\openSourcerer9000\Anaconda3\envs\raz\lib\site-packages\numpy\core\include -IC:\Users\openSourcerer9000\Anaconda3\envs\raz\include -IC:\Users\openSourcerer9000\Anaconda3\envs\raz\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt /Tcpydsstools/src/core_heclib.c /Fobuild\temp.win-amd64-3.9\Release\pydsstools/src/core_heclib.obj
core_heclib.c
C:\Users\openSourcerer9000\Anaconda3\envs\raz\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(14) : Warning Msg: Using deprecated NumPy API, disable it with #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
pydsstools/src/core_heclib.c(6554): warning C4244: '=': conversion from 'double' to 'float', possible loss of data
pydsstools/src/core_heclib.c(16429): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(16707): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(17001): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(48057): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data
pydsstools/src/core_heclib.c(48154): warning C4090: '=': different 'const' qualifiers
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:pydsstools/src/external/dss/win64 /LIBPATH:pydsstools/src/external/gridv6/build /LIBPATH:pydsstools/src/external/zlib /LIBPATH:C:\Users\openSourcerer9000\Anaconda3\envs\raz\libs /LIBPATH:C:\Users\openSourcerer9000\Anaconda3\envs\raz\PCbuild\amd64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\ATLMFC\lib\x64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\lib\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\ucrt\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64 heclib_c.lib heclib_f.lib zlibstatic.lib grid.lib /EXPORT:PyInit_core_heclib build\temp.win-amd64-3.9\Release\pydsstools/src/core_heclib.obj /OUT:build\lib.win-amd64-3.9\pydsstools\_lib\x64\core_heclib.cp39-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.9\Release\pydsstools/src\core_heclib.cp39-win_amd64.lib /NODEFAULTLIB:LIBCMT
LINK : fatal error LNK1104: cannot open file 'ifconsol.lib'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1104

windows, conda env, python 3.9

example3.py ModuleNotFoundError: No module named 'pydsstools.core.core_heclib'

Hi,

Thanks for the great package.

I installed using:

pip install https://github.com/gyanz/pydsstools/zipball/master

Which seemed to work fine. After trying a few of the example scripts, I got the following error when I ran example3.py.

python example3.py
Traceback (most recent call last):
  File "example3.py", line 7, in <module>
    from pydsstools.heclib.utils import HecTime
  File "C:\Anaconda3\lib\site-packages\pydsstools\heclib\utils.py", line 1, in <module>
    from ..core.core_heclib import (HecTime, DssStatusException, GranularityException,ArgumentException)
ModuleNotFoundError: No module named 'pydsstools.core.core_heclib'

A bit about my computer:

windows 10            10.0.17134
python                    3.7.1                h33f27b4_4
pandas                    0.24.2                   pypi_0    pypi
numpy                     1.16.2                   pypi_0    pypi
cython                    0.29.6           py37ha925a31_0

I looked in _Lib and only found the .pyd file. Do you have the cython files I could look at? If so, I can submit PR.

Thanks!

Dan

Comptability on PPC64

We trying too install pydsstools, but have problem with this library:
pydsstools/_lib/x64/core_heclib.cpython-38-x86_64-linux-gnu.so

Is there any source code, for pydsstools/src/core_heclib.c, which we can compile on our system from the beginning ?

Required DSS-6 format instead of DSS-7

Hi. I want to write all the grids to DSS-6 version only instead of DSS-7. What can I do (edit) in the script so that all my files are in DSS-6 version only? Please help me out. Because, the DSS-7 version files are unable to run in HEC-HMS 4.6.1. Coule you please tell me any alternative?

Thanks

Installation From Source and Import Error

Installation From Source issues presented in #23 and #27 may be related to hecdatetime.h. The error I was getting is related to grid.a not found. Traced it down to header hecdatetime.h renamed to HecDateTime.h. Compiles and installs but get an error when importing.

>>> from pydsstools.heclib.dss.HecDss import Open
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/dist-packages/pydsstools/heclib/dss/HecDss.py", line 15, in <module>
    from ...core import Open as _Open
  File "/usr/local/lib/python3.8/dist-packages/pydsstools/core/__init__.py", line 28, in <module>
    from .._lib import *
  File "/usr/local/lib/python3.8/dist-packages/pydsstools/_lib/__init__.py", line 1, in <module>
    from .x64 import core_heclib
  File "pydsstools/src/core_heclib.pyx", line 1, in init pydsstools._lib.x64.core_heclib
ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject

Records in DSS file written to SHG/Albers is corrupt

So I'm trying to write a DSS file in SHG. The data is in EPSG:5070 with 20m cell size, snapped to the SHG grid (all x and y values are multiples of 20). This is what I'm putting into my grid info:

t =  ds.rio.transform()
# rioxarray method, returns
# Affine(20.0, 0.0, 251370.0,
#           0.0, -20.0, 903530.0)

grid_info.update([('grid_type','albers'),
                ('grid_crs',ds.spatial_ref.crs_wkt),
                ('grid_transform',t,
                ('data_type','inst-val'),
                ('data_units','in'),
                ('opt_time_stamped',False),
                ('opt_lower_left_x',int( t[2]/np.abs(t[0]) ) ),
                ('opt_lower_left_y',int( t[5]/np.abs(t[4]) ) )
                ])

When I use 'grid_type':'specified', it produces a valid DSS, but HMS complains that my gridded deficit and constant loss params are bad, which I am assuming is due to the projection. When I try to specify 'albers' or 'shg', I can view the record names in DSSVue, but when I try to plot or tabulate nothing comes up. In the HMS DSS viewer it pops up an error 'there is no record' when I try to select the visible pathnames.

I'm thinking it may be something to do with this operation in grid_accessors.py, I'm not sure:

            if gridinfo['grid_type'].lower() in ('albers','albers-time','shg','shg-time'):
                gridinfo = correct_shg_gridinfo(gridinfo,out_data[0].shape)

I was able to add the same grids through vortex (and run the HMS method successfully), so I read those into pydsstools and their grid_type was actually 'albers-time'. Trying 'albers-time' in my own results in this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\Anaconda3\envs\raz\lib\site-packages\pydsstools\heclib\dss\HecDss.py in put_grid(self, pathname, data, profile, flipud, compute_range, inplace, raise_profile_error)
    435                     # TODO: Found out HecTime('1') passes this test
--> 436                     HecTime(dpart)
    437                     HecTime(epart)

~\Anaconda3\envs\raz\lib\site-packages\pydsstools\src\hectime.pyx in pydsstools._lib.x64.core_heclib.HecTime.__init__()

~\Anaconda3\envs\raz\lib\site-packages\pydsstools\src\hectime.pyx in pydsstools._lib.x64.core_heclib.HecTime.parse_datetime_string()

AttributeError: 'NoneType' object has no attribute 'year'

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19644/125238972.py in <module>
      1 get_ipython().run_line_magic('run', '-n C:\\Users\\seanm\\Docs\\LWI\\DefCon\\gssurgo_to_defcon_grids')
----> 2 dss.rioxdsToDSS(ds,outDSS,parts)

~\Docs\LWI\DefCon\gssurgo_to_defcon_grids.py in rioxdsToDSS(ds, outDSSpth, parts)
     90                 print(pathname)
     91                 if 'band' in ds.coords and 'band' in ds.dims:
---> 92                     fid.put_grid(pathname,ds.sel(band=ds['band'].values[0]).drop('band')[varr].values,grid_info)
     93                 else:
     94                     fid.put_grid(pathname,ds[varr].values,grid_info)

~\Anaconda3\envs\raz\lib\site-packages\pydsstools\heclib\dss\HecDss.py in put_grid(self, pathname, data, profile, flipud, compute_range, inplace, raise_profile_error)
    437                     HecTime(epart)
    438                 except:
--> 439                     raise Exception('For %s grid type, DPart and EPart of pathname must be datetime string')
    440                 else:
    441                     grid_info['opt_time_stamped'] = 1

Exception: For %s grid type, DPart and EPart of pathname must be datetime string

py 3.9
pydsstools 2.2

Can write time series with only one data point

When trying to write a regular time series with only one item you get the following error after you call the put method.

TypeError: len() of unsized object

Exception ignored in: 'core_heclib.TimeSeriesContainer.setValues'
TypeError: len() of unsized object

Data:

me = pd.DataFrame(index = [0], data = {'date':'1987-10-10', 'depth':0.5})
me.date = pd.to_datetime(me.date)
me = me.set_index('date')

Write to dss file:

pname = f"/basin/site/PRECIP//1DAY/data_source/"
start_date =me.index.min().strftime('%d%b%Y %H:%M:%S')
tsc = TimeSeriesContainer()
tsc.granularity = 60 #seconds i.e. minute granularity
tsc.numberValues = me.size
tsc.startDateTime=start_date
tsc.pathname = pname
tsc.units = "mm"
tsc.type = "INST-VAL"
tsc.interval = 1
#must a +ve integer for regular time-series
#actual interval implied from E part of pathname
tsc.values =me.values.squeeze()
#values may be list,array, numpy array

#Write DSS time sereis to file
fid = HecDss.Open(dss_file)

#Optional
fid.deletePathname(tsc.pathname)
status = fid.put(tsc)

#Close the file
fid.close()

Note on DSS Version 6 versus DSS Version 7 grid records.

The DSS C/Fortran library hec-dss does not support writing DSS6 Grids. However, hec-dss has some support for Reading DSS6 grids. That same limitation is passed onto pydsstools, or any Non-Java tool or application. The intent is for hec-dss to focus on DSS Version 7 and retire the DSS 6 Java/Fortran based file format.

Tools such as HMS, DSSVue, and Vortex use underlying Java libraries that support both DSS6 and DSS7 files. The feature of Writing DSS6 girds is performed with both Java and hec-dss . For DSS6 grids Java defines the byte order of data and hec-dss performs the disk IO. For DSS7 grids hec-dss performs all the steps.

Developers seeking a pure C, or non-Java stack have used a pattern of working with DSS 7 files, and converting to DSS 6 only as needed. For example Cumulus uses DSS7 for cloud based processing of grids, and relies on Windows client side apps to convert to DSS6 when needed.

Support for python 3.11

Will there be any planned updates for python 3.11? The new update has some great speed increases I'd like to use this library with.

thank you!

Problem in projection of Grid DSS file

I am trying to create Spatial Grid DSS and the put_grid function works just fine when I use "specified" as grid type. But if want to create the dss grid in SHG CRS, I get the following error:
grid_info['grid_crs'] = SHG_WKT
NameError: name 'SHG_WKT' is not defined

This error is related to from related to utils.py (line 192-195). It seems the SHG_WKT is variable but no where is defined. Does anyone know who should I resolve the issue?

Thank you!

Regular Interval Time Series Data - Missing Values

If data is missing in a DSS record, DSS returns the max negative float value = -3.4028235e+38

This is by design, so the user must handle any values equal to the max negative float. Otherwise, any missing values will be erroneously displayed in the user's tables and plots as -3.4028235e+38. Example shown below.

image

image

Bizarre "OverflowError: Python int too large to convert to C long" when using put_grid()

So I'm trying put_grid on this ndarray, reproducible example below:
array.zip

import _pickle as cPickle
from affine import Affine
from pathlib import Path
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import gridInfo

YOURPATH = Path(r'your path here')
pklpth = YOURPATH/'array.pkl'
outDSS = YOURPATH/'newDSS.dss'

with open(pklpth, "rb") as input_file:
    aray = cPickle.load(input_file)

with Open(str(outDSS)) as fid:
    from affine import Affine
    crs_wkt = 'PROJCS["NAD_1983_Contiguous_USA_Albers",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101004,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["latitude_of_center",23],PARAMETER["longitude_of_center",-96],PARAMETER["standard_parallel_1",29.5],PARAMETER["standard_parallel_2",45.5],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","5070"]]'
    grid_info = gridInfo()
    grid_info.update([('grid_type','specified'),
                ('grid_crs',crs_wkt),
                ('grid_transform',Affine(29.99999999971379, 0.0, -39765.000000203516,
        0.0, -29.99999999971379, 1146914.9999751365)),
                ('data_type','inst-val'),
                ('data_units','percent'),
                ('opt_time_stamped',False)])
    fid.put_grid(r'/Impervious Area/WC/IMPERVIOUS AREA////',aray,grid_info)

And getting this weird error:

ERROR:root:opt_lower_left_x, opt_lower_left_y has issue or both are incorrect
Given = (0, 0), computed = (-1326, 38230)
stats= {'min': 0, 'max': 255, 'mean': 187.08584783937707, 'range_values': [-3.4028234663852886e+38, 0, 63.75, 127.5, 191.25], 'range_counts': [174749232, 174749232, 128327655, 127638397, 127638397]}

---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_30284/1847009270.py in <module>
     18                 ('data_units','percent'),
     19                 ('opt_time_stamped',False)])
---> 20     fid.put_grid(r'/Impervious Area/WC/IMPERVIOUS AREA////',aray,grid_info)

~\Anaconda3\envs\raz\lib\site-packages\pydsstools\heclib\dss\HecDss.py in put_grid(self, pathname, data, profile, flipud, compute_range, inplace, raise_profile_error)
    458             else:
    459                 _data = _data.copy()
--> 460                 _data[mask] = nodata
    461 
    462             if flipud:

OverflowError: Python int too large to convert to C long

There's definitely no -3.4e38 value in the array (range is 0-255). Trying to trace it back in the code, it seems to be something to do with a self._data['data'].fill_value in grid.py creating this giant phantom int. Any quick fixes for this?

Thanks

Windows
Python 3.9
conda env
pydsstools v 2.2
numpy v 1.21.4

Problem with merging different HEC-DSS file

Hello,
I am trying to append multiple time series of HEC-DSS data into one file, but there were always empty raws between the data set. I would be pleased if anyone could give me some tips on how to solve this issue using some pydsstools script. The attached picture is taken from the merged HEC-DSS data using DSSVue GUI interface.
HEC-DSS2023-01-17 152921
Or is there any method to append HEC-DSS files into a single one?

Parallel I/O call failure

When I attempt to run multiple models in parallel making simultaneous DSS calls to pydsstools, my models fail due to I/O errors. It appears that either the calls do not block for the read/write or time out and fail to complete. When I do the same set of runs in separate environments, each with their own pydsstools package, I do not receive the issue. Since the DSS libraries are the same on my machine, the only difference is how the runs are using pydsstools, which isolates the issue to the package.

This happens regardless as to whether I'm using the python multiprocessing module or the same environment running multiple models simultaneously.

Time Series types

I have a question about how TimeSeriesContainer containers interpret time series types. In the examples you have:

dss_file = "example.dss"
pathname = "/REGULAR/TIMESERIES/FLOW//1HOUR/Ex1/"
tsc = TimeSeriesContainer()
tsc.pathname = pathname
tsc.startDateTime = "15JUL2019 19:00:00"
tsc.numberValues = 5
tsc.units = "cfs"
tsc.type = "INST"
tsc.interval = 1
tsc.values = [100,UNDEFINED,500,5000,10000]

When I run this code, I get dss time series of the type `INST-VAL'. Specific questions:

  1. Why wasn't this iterpreted as INST-CUM?

Is there a docstring that explains this logic?

Thanks,

Dan

How to suppress prints?

Hello, thank you for building this tool! I'm wondering how can I suppress the printed statements/warnings that it generates as I use it? I'm trying to read thousands of time series' to a pd dataframe, from the examples it seems I have to do them one at a time. Especially with all of this stuff printing out it runs very very slow.

In JupyterLab, they show up as warnings and print for miles down the notebook, but with warnings.catch_warnings():
warnings.simplefilter("ignore") doesn't get rid of them. Any help would be appreciated, thanks!

This is the warning I'm getting, it doesn't see mto affect the results:
WARNING:root:-----DSS--- ztsRetrieveReg Warning: Incompatible DSS version
This function is only compatible with version 7 DSS files
This file is version 0

cannot import core heclib

Hi gyanz,
I am trying to import HecDss by using the following command:

from pydsstools.heclib.dss import HecDss

and this is the error that I am getting:

Traceback (most recent call last):

  File "C:\Smart Detention Storage\Simple_model\Simple_1\test1.py", line 2, in <module>
    from pydsstools.heclib.dss import HecDss

  File "C:\Smart Detention Storage\Simple_model\Simple_1\pydsstools\heclib\dss\HecDss.py", line 15, in <module>
    from ...core import Open as _Open

  File "C:\Smart Detention Storage\Simple_model\Simple_1\pydsstools\core\__init__.py", line 28, in <module>
    from .._lib import *

  File "C:\Smart Detention Storage\Simple_model\Simple_1\pydsstools\_lib\__init__.py", line 1, in <module>
    from .x64 import core_heclib

ImportError: cannot import name 'core_heclib' from 'pydsstools._lib.x64' (C:\Smart Detention Storage\Simple_model\Simple_1\pydsstools\_lib\x64\__init__.py)

Would you please help me with that? I think a file is missing from x64.

Python 3.8?

Are there any plans to make pydsstools compatible with Python 3.8 (for Windows)?

Thanks for creating this awesome library.

Written dss file not valid in HEC HMS

Hey Gyan,

I am currently working on a project with HEC HMS and HEC RAS and your package has been a big help getting all the data into dss files. Unfortunately I am getting an error if I try to use the dss file of gridded precipitation in HEC HMS. I can open and view the dss file containing my grids in dssvue and it says the record has no issues.

dssvue

But when I try to use them in HEC HMS (4.8) I get the following error mesage:

HEC_HMS_ERROR_3

As the beta version of HEC HMS (4.9) has a grid validation check tool I tried opening the file with that version to get some more information. What I did get is those two additional error messages:

HEC_HMS_ERROR_1

HEC_HMS_ERROR_2

I was wondering if this is a known Issue (I could not find anything listed) and if there is a way to fix it.

This is a shortened version of the code I am using to write my precipitation data from a geotiff stack into the dss file:

`

from os import path
import pandas as pd
import rasterio
from affine import Affine
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.heclib.utils import gridInfo

radolan_file_path = r'C:\FILEPATH\Sachsen_Kemnitz_200107.tif'

dss_file = r"C:\FILEPATH\RADOLAN_example.dss"


#load monthly RADOLAN raster stack
raster_stack = rasterio.open(radolan_file_path)

#loop over raster layers
#for j in range(1, (raster_stack.count)+1):
for i in range(0, 3):
  
    layers = [63, 64, 65]
    layer = layers[i]
    
    #get single raster layer
    raster = raster_stack.read(layer, masked=False)
    
    pathnames = ["/UTM33N/SACHSEN_KEMNITZ/PRECIP/02JUL2017:0505/01JUL2017:0510/RADOLAN/",
    "/UTM33N/SACHSEN_KEMNITZ/PRECIP/02JUL2017:0510/01JUL2017:0515/RADOLAN/",
    "/UTM33N/SACHSEN_KEMNITZ/PRECIP/02JUL2017:0515/01JUL2017:0520/RADOLAN/"]
    
    pathname_out = pathnames[i]
    
    #open dss file
    with Open(dss_file) as dss_con:
        
        #prepare data to be put into dss file
        data = raster
        grid_info = gridInfo()
        cellsize = 1000
        xmin = raster_stack.bounds.left
        ymin= raster_stack.bounds.bottom
        ymax = raster_stack.bounds.top
        affine_transform = Affine(cellsize,0,xmin,0,-cellsize,ymax)
        grid_info.update([('grid_type', 'specified'),
                          ('grid_crs', 'EPSG:25833'),
                          ('grid_transform', affine_transform),
                          ('data_type', 'per-cum'),
                          ('data_units', 'mm'),
                          ('opt_crs_name', 'UTM33N'),
                          ('opt_crs_type', 0)])
        
        #put data in dss file
        dss_con.put_grid(pathname_out, data, grid_info)

`

I also want to mention, that I have the same issue using your example code to write grid data into a dss file, however the example files you provide seem to work.

This is the virtual environment I am using:

affine 2.3.0
attrs 21.2.0
certifi 2021.10.8
click 8.0.3
click-plugins 1.1.1
cligj 0.7.2
colorama 0.4.4
cycler 0.11.0
Cython 0.29.24
GDAL 3.3.2
kiwisolver 1.3.2
matplotlib 3.4.3
numpy 1.21.3
pandas 1.3.4
Pillow 8.4.0
pip 20.2.3
pydsstools 2.1
pyparsing 3.0.4
python-dateutil 2.8.2
pytz 2021.3
rasterio 1.2.10
regex 2021.11.2
setuptools 49.2.1
six 1.16.0
snuggs 1.4.7

I testet this on two different computers under Windows 10 and independent installations.

I am thankfull for any help.

Best Regards
Siggi

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.