#!/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 - Temps-réel prévision
"""
import os.path
import pandas as pnd
import pyspc.core.exception as _exception
from pyspc.convention.grp18 import (
RT_DATA_SCENFILEPREFIX, RT_DATA_LINEPREFIX)
[docs]
class GRPRT_Metscen():
"""
Structure de données GRPRT GRPRT_Metscen (GRP *Temps Réel*)
Fichiers
- Scen_NNN_Plu*_nnJnnHnnM.txt
- ScenT_NNN_Tem*_nnJnnHnnM.txt
Attributes
----------
filename : str
Nom du fichier de données
varname : str
Nom de la variable
timestep : str, None
Pas de temps
scen : str
Code du scénario
lineprefix : str
Préfixe des lignes de données du fichier
"""
[docs]
def __init__(self, filename=None):
"""
Initialisation de l'instance de la classe GRPRT_Metscen
Parameters
----------
filename : str
Nom du fichier de données
"""
self.varname, self.scen, self.timestep = self.split_basename(
filename=filename)
self.lineprefix = self.get_lineprefix(varname=self.varname)
self.filename = filename
def __str__(self):
"""
Afficher les méta-données de l'instance GRPRT_Metscen
"""
text = """
*************************************
*********** GRP 2018 - RT Metscen ***
*************************************
* NOM FICHIER = {filename}
* NOM VARIABLE = {varname}
* PAS DE TEMPS = {timestep}
* SCENARIO = {scen}
* PREFIXE DONNEE = {lineprefix}
*************************************
"""
return text.format(**vars(self))
[docs]
def read(self):
"""
Lecture d'un fichier de scénarios météo pour GRP RT
Returns
-------
pandas.DataFrame
Tableau des prévisions de GRP Temps-Réel
Examples
--------
>>> from pyspc.model.grp18 import GRPRT_Metscen
Cas de données pluviométriques
>>> f = 'data/model/grp18/rt/Scen_001_PluRR_00J01H00M.txt'
>>> reader = GRPRT_Metscen(filename=f)
>>> reader
*************************************
*********** GRP 2018 - RT Metscen ***
*************************************
* NOM FICHIER = data/model/grp18/rt/Scen_001_PluRR_00J01H00M.txt
* NOM VARIABLE = P
* PAS DE TEMPS = 00J01H00M
* SCENARIO = 001
* PREFIXE DONNEE = PLU
*************************************
>>> df = reader.read()
>>> df
PREFIX CODE DATETIME VALUE
0 PLU RH10585x 202105310100 0.02
1 PLU RH10585x 202105310200 0.02
2 PLU RH10585x 202105310300 0.02
3 PLU RH10585x 202105310400 0.02
4 PLU RH10585x 202105310500 0.02
5 PLU RH10585x 202105310600 0.02
6 PLU RH10585x 202105310700 1.07
7 PLU RH10585x 202105310800 1.07
8 PLU RH10585x 202105310900 1.07
9 PLU RH10585x 202105311000 2.37
10 PLU RH10585x 202105311100 2.37
11 PLU RH10585x 202105311200 2.37
12 PLU RH10585x 202105311300 3.35
13 PLU RH10585x 202105311400 3.35
14 PLU RH10585x 202105311500 3.35
15 PLU RH10585x 202105311600 4.07
16 PLU RH10585x 202105311700 4.07
17 PLU RH10585x 202105311800 4.07
18 PLU RH10585x 202105311900 0.00
19 PLU RH10585x 202105312000 0.00
"""
return pnd.read_csv(
self.filename,
sep=';',
header=None,
index_col=False,
skiprows=1,
engine='python',
skipfooter=1,
names=['PREFIX', 'CODE', 'DATETIME', 'VALUE'],
)
[docs]
def write(self, data=None):
"""
Ecrire le fichier de données GRPRT Data
Parameters
----------
pandas.DataFrame
Tableau des prévisions de GRP Temps-Réel
"""
_exception.check_dataframe(data)
with open(self.filename, 'w', encoding='utf-8', newline='\r\n') as f:
f.write('Ligne_Entete\n')
data.to_csv(
self.filename,
mode='a',
sep=';',
float_format='%.3f',
header=False,
index=False,
lineterminator='\r\n'
)
with open(self.filename, 'a', encoding='utf-8', newline='\r\n') as f:
f.write('FIN;OBS\n')
[docs]
@staticmethod
def get_lineprefix(varname=None):
"""
Préfixe des lignes de données
Parameters
----------
varname : str
Nom de la variable
Returns
-------
p : str
Préfixe des lignes de données
Examples
--------
>>> from pyspc.model.grp18 import GRPRT_Metscen
>>> v = 'P'
>>> p = GRPRT_Metscen.get_lineprefix(varname=v)
>>> p
PLU
>>> v = 'T'
>>> p = GRPRT_Metscen.get_lineprefix(varname=v)
>>> p
TEM
"""
try:
p = RT_DATA_LINEPREFIX[varname.split('_')[0]]
except KeyError as ke:
raise ValueError('Type de donnée incorrect pour la '
'définition du préfixe') from ke
return p
[docs]
@staticmethod
def split_basename(filename=None):
"""
Extraire les méta-données du nom du fichier GRPRT Data
Parameters
----------
filename : str
Nom du fichier GRPRT Data
Returns
-------
varname : str
Grandeur
timestep : str, None
Pas de temps
scen : str
Code du scénario
"""
# ---------------------------------------------------------------------
# 0- Initialisation
# ---------------------------------------------------------------------
basename = os.path.splitext(os.path.basename(filename))[0]
# ---------------------------------------------------------------------
# 1- Détermination de la grandeur et du pas de temps
# ---------------------------------------------------------------------
infos = basename.split('_')
try:
prefix = infos.pop(0) + '_'
scen = infos.pop(0)
infos.pop(0)
timestep = infos.pop(0)
except IndexError as ie:
raise ValueError(
f"Le nommage du fichier '{filename}' est incorrect") from ie
for v, p in RT_DATA_SCENFILEPREFIX.items():
if prefix == p:
return v, scen, timestep
# ---------------------------------------------------------------------
# 3- Cas inconnu
# ---------------------------------------------------------------------
raise ValueError(f"Le nommage du fichier '{filename}' est incorrect")