Code source de pyspc.model.premhyce.forecast

#!/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 - Projet PREMHYCE - Données de prévision
"""
from datetime import datetime as dt
import os.path
import pandas as pnd
import pyspc.core.exception as _exception

DATE_FORMAT = '%Y%m%d'
"""Format des dates dans les fichiers de prévision PREMHYCE"""


def date_parser(txt):
    """Conversion de date"""
    return dt.strptime(txt, DATE_FORMAT)


[docs] class Fcst(): """ Structure de prévisions QMJ de PREMHYCE Attributes ---------- filename : str Nom du fichier de données runtime : dt Instant de prévision station : str Identifiant de la station model : str Identifiant du modèle hydro meteo : str Identifiant de l'ensemble météo """
[docs] def __init__(self, filename=None): """ Initialisation de l'instance de la classe Fcst (projet Premhyce) Parameters ---------- filename : str Nom du fichier de données """ self.filename = filename if self.filename is not None: self.runtime, self.station, self.model, self.meteo = \ self.split_basename(self.filename) else: self.runtime = None self.station = None self.model = None self.meteo = None
def __str__(self): """ Afficher les méta-données de l'instance Fcst (projet Premhyce) """ text = """ ************************************* ********* PREMHYCE - Fcst *********** ************************************* * NOM FICHIER = {filename} * INSTANT DE PREVISION = {runtime} * STATION DE PREVISION = {station} * MODELE DE PREVISION = {model} * ENSEMBLE METEO = {meteo} ************************************* """ return text.format(**vars(self))
[docs] def read(self): """ Lecture d'un fichier de prévision QMJ par PREMHYCE Returns ------- pandas.DataFrame Tableau des données de prévision QMJ de PREMHYCE Examples -------- >>> import pyspc.model.premhyce as _model >>> f = 'data/model/premhyce/20200612_K0253030_GR6J_CEP.txt' >>> d = _model.Fcst(filename=f) >>> print(d) ************************************* ********* PREMHYCE - Fcst *********** ************************************* * NOM FICHIER = data/model/premhyce/20200612_K0253030_GR6J_CEP.txt * INSTANT DE PREVISION = 2020-06-12 00:00:00 * STATION DE PREVISION = K0253030 * MODELE DE PREVISION = GR6J * ENSEMBLE METEO = CEP ************************************* >>> df = d.read() >>> df Date Membre jp1 jp2 jp3 ... jp7 jp8 0 2020-06-11 cf 5059 12811 8097 ... 3782 3300 1 2020-06-11 pf1 3907 6181 3927 ... 3909 3266 2 2020-06-11 pf2 3117 2821 2013 ... 1795 1646 3 2020-06-11 pf3 4524 9394 5792 ... 3276 2947 4 2020-06-11 pf4 4482 9159 5665 ... 2675 2475 5 2020-06-11 pf5 4054 6900 4366 ... 2867 3453 6 2020-06-11 pf6 4838 11319 7054 ... 3479 3030 7 2020-06-11 pf7 3160 2983 2095 ... 1449 1346 8 2020-06-11 pf8 4821 11248 7086 ... 2977 2624 9 2020-06-11 pf9 4564 9725 6228 ... 2847 2528 10 2020-06-11 pf10 3449 4132 2676 ... 3109 2506 """ return pnd.read_csv( self.filename, sep=';', header=0, index_col=False, engine='python', converters={'Date': date_parser}, )
[docs] def write(self, data=None, dirname='.'): """ Ecrire le fichier de prévision QMJ par PREMHYCE Parameters ---------- data : pandas.DataFrame Tableau des données de prévision QMJ de PREMHYCE dirname : str Répertoire du fichier de prévision QMJ de PREMHYCE """ _exception.check_dataframe(data) if self.filename is None: self.filename = self.join_basename( runtime=self.runtime, station=self.station, model=self.model, meteo=self.meteo ) self.filename = os.path.join(dirname, self.filename) data.to_csv( self.filename, mode='w', sep=';', header=True, index=False, date_format=DATE_FORMAT, lineterminator='\r\n' )
[docs] @staticmethod def split_basename(filename=None): """ Extraire les informations depuis le nom du fichier de prévisions QMJ de PREMHYCE Parameters ---------- filename : str Fichier de prévisions QMJ de PREMHYCE Returns ------- runtime : dt Instant de prévision station : str Identifiant de la station model : str Identifiant du modèle hydro meteo : str Identifiant de l'ensemble météo """ if filename is None: return None, None, None, None basename = os.path.basename(filename).replace('.txt', '') try: [runtime, station, model, meteo] = basename.split('_') except ValueError as ve: raise ValueError("Le nom de fichier ne respecte pas le " "nommage de PREMHYCE") from ve runtime = dt.strptime(runtime, '%Y%m%d') return runtime, station, model, meteo
[docs] @staticmethod def join_basename(runtime=None, station=None, model=None, meteo=None): """ Définir le nom du fichier à partir d'informations sur la prévision prévisions QMJ de PREMHYCE Parameters ---------- runtime : dt Instant de prévision station : str Identifiant de la station model : str Identifiant du modèle hydro meteo : str Identifiant de l'ensemble météo Returns ------- filename : str Fichier de prévisions QMJ de PREMHYCE """ if runtime is None or not isinstance(runtime, dt) or \ station is None or model is None or meteo is None: raise ValueError('Définition incorrecte des arguments') return f"{runtime.strftime('%Y%m%d')}_{station}_{model}_{meteo}.txt"