#!/usr/bin/python3
# -*- coding: utf-8 -*-
########################################################################
#
# This file is part of python module <pyspc>.
# Copyright (C) 2013-2021 R. Marty
# (renaud.marty@developpement-durable.gouv.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (see COPYING.txt).
# If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
"""
Modélisations hydrologiques - GRP version 2018 - Evenement
"""
from datetime import datetime as dt
from functools import partial
import numpy as np
import os.path
import pandas as pnd
import pyspc.core.exception as _exception
from pyspc.core.timeutil import dtfmt, dtheader, lenstr2dtfmt
def date_parser(fmt, txt):
""""Convertisseur de date"""
return dt.strptime(txt, fmt)
[docs]
class GRP_Event():
"""
Structure du fichier Evenement de GRP *Calage*
Attributes
----------
filename : str
Nom du fichier Evenement de GRP *Calage*
station : str
Nom de la station
event : str
Identifiant de l'événement
"""
[docs]
def __init__(self, filename=None):
"""
Initialisation de l'instance de la classe GRP_Event
Parameters
----------
filename : str
Nom du fichier Bassin de GRP *Calage*
"""
super().__init__()
self.filename = filename
self.station, self.event = self.split_basename(self.filename)
def __str__(self):
"""
Afficher les méta-données de l'instance GRP_Event
"""
text = """
*************************************
*********** GRP 2018 - Event ********
*************************************
* NOM FICHIER = {filename}
* CODE STATION = {station}
* CODE EVENEMENT = {event}
*************************************
"""
return text.format(**vars(self))
[docs]
def read(self):
"""
Lecture du fichier Evenement de GRP *Calage*
Returns
-------
pandas.DataFrame
Tableau des données Evenement de GRP 2018
Examples
--------
>>> from pyspc.model.grp18 import GRP_Event
Cas de données horaires
>>> f = 'data/model/grp18/cal/RH10585x-EVhor1.DAT'
>>> reader = GRP_Event(filename=f)
>>> df = reader.read()
>>> df
Date Pluie(mm/h) Debit(m3/s)
0 2007-01-18 18:00:00 8.48 3.537
1 2007-01-18 19:00:00 3.72 5.150
2 2007-01-18 20:00:00 7.60 7.864
3 2007-01-18 21:00:00 6.32 10.192
4 2007-01-18 22:00:00 9.44 12.464
5 2007-01-18 23:00:00 6.64 14.695
6 2007-01-19 00:00:00 7.88 16.625
7 2007-01-19 01:00:00 8.44 18.250
8 2007-01-19 02:00:00 5.32 19.710
9 2007-01-19 03:00:00 6.64 20.432
10 2007-01-19 04:00:00 5.96 21.912
11 2007-01-19 05:00:00 6.72 23.425
12 2007-01-19 06:00:00 7.24 23.550
13 2007-01-19 07:00:00 7.44 24.913
14 2007-01-19 08:00:00 6.60 29.306
15 2007-01-19 09:00:00 6.48 33.850
16 2007-01-19 10:00:00 5.36 36.100
17 2007-01-19 11:00:00 2.96 36.367
18 2007-01-19 12:00:00 1.32 34.750
19 2007-01-19 13:00:00 1.08 30.500
20 2007-01-19 14:00:00 0.48 26.928
21 2007-01-19 15:00:00 1.60 24.993
22 2007-01-19 16:00:00 1.00 23.685
23 2007-01-19 17:00:00 0.72 22.642
24 2007-01-19 18:00:00 0.80 21.467
Cas de données journalières
>>> f = 'data/model/grp18/cal/RH10585x-EVhor1.DAT'
>>> reader = GRP_Event(filename=f)
>>> df = reader.read()
>>> df
Date Pluie(mm/h) Debit(m3/s)
0 2007-01-14 1.60 NaN
1 2007-01-15 6.88 3.568
2 2007-01-16 0.00 2.922
3 2007-01-17 0.40 NaN
4 2007-01-18 7.84 2.183
5 2007-01-19 70.08 4.886
6 2007-01-20 82.96 24.449
7 2007-01-21 10.48 11.924
8 2007-01-22 9.00 8.095
9 2007-01-23 2.04 5.140
10 2007-01-24 1.12 3.819
11 2007-01-25 2.96 2.969
12 2007-01-26 0.04 2.272
"""
with open(self.filename, 'r', encoding='utf-8') as f:
f.readline()
txt = f.readline().split(' ')[0]
fmt = lenstr2dtfmt(txt)
n = len(txt)
return pnd.read_fwf(
self.filename,
colspecs=[(0, n), (n+1, n+13), (n+14, n+26)],
converters={'Date': partial(date_parser, fmt)},
na_values=[-99.9]
)
[docs]
def write(self, data=None, tdelta=None):
"""
Ecriture du fichier Evenement de GRP *Calage*
"""
_exception.check_td(tdelta)
data['Debit(m3/s)'] = data['Debit(m3/s)'].map(
lambda x: f'{x:12.4f}'
if not np.isnan(x) else ' -99.9000')
data['Pluie(mm/h)'] = data['Pluie(mm/h)'].map(
lambda x: f'{x:12.4f}'
if not np.isnan(x) else ' -99.9000')
header_dt = ' ' * (len(dtheader(tdelta)) - 4) + 'Date'
data[header_dt] = data['Date'].map(lambda x: x.strftime(dtfmt(tdelta)))
data = data.drop(columns='Date')
data = data.reindex(columns=[header_dt, 'Pluie(mm/h)', 'Debit(m3/s)'])
with open(self.filename, 'w', encoding='utf-8', newline='\r\n') as f:
x = '\n'.join([y.rstrip()
for y in data.to_string(
header=True, index=False).split('\n')])
f.write(x)
f.write('\n')
[docs]
@staticmethod
def split_basename(filename=None):
"""
Extraire les informations depuis le nom du fichier
Evenement de GRP *Calage*
Parameters
----------
filename : str
Fichier Evenement de GRP *Calage*
Returns
-------
station : str
Identifiant de la station
event : str
Identifiant de l'événement
Examples
--------
>>> from pyspc.model.grp18 import GRP_Event
>>> f = 'data/model/grp18/cal/RH10585x-EVhor1.DAT'
>>> [station, event] = GRP_Event.split_basename(filename=f)
>>> station
RH10585x
>>> event
EVhor1
"""
if filename is None:
return None, None
basename = os.path.splitext(os.path.basename(filename))[0]
try:
[station, event] = basename.split('-')
except ValueError as ve:
raise ValueError("Le nom de fichier ne respecte pas le "
"nommage de GRP") from ve
return station, event