#!/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/>.
#
########################################################################
"""
Données (observations, prévisions) - Vigicrues - Prévisions
"""
import collections
from datetime import datetime as dt, timedelta as td, timezone as tz
import json
import pandas as pnd
from pyspc.convention.vigicrues import TRENDS, VARNAMES
[docs]
class Vigicrues_Fcst():
"""
Structure liée aux prévisions Vigicrues
"""
[docs]
def __init__(self, filename=None):
"""
Initialisation de l'instance de la classe Vigicrues_Fcst
Parameters
----------
filename : str
Fichier json
"""
self.filename = filename
def __str__(self):
"""
Afficher les méta-données de l'instance <Vigicrues_Fcst>
"""
text = """
*************************************
*********** VIGICRUES - Fcst ********
*************************************
* FICHIER = {filename}
*************************************
"""
return text.format(**vars(self))
def _check_trends(self, trend=None):
"""
Contrôler la tendance
Parameters
----------
trend : str
Nom de la tendance.
Raises
------
ValueError
Si la tendance n'est pas reconnue par pyspc
"""
if trend not in self.get_trends():
raise ValueError("Tendance mal renseignée")
def _check_varname(self, varname=None):
"""
Contrôler la variable
Parameters
----------
varname : str
Nom de la variable.
Raises
------
ValueError
Si la variable n'est pas reconnue par pyspc
"""
if varname not in self.get_varnames():
raise ValueError("Variable mal renseignée")
[docs]
def read(self, content=None):
"""
Lire le résultat GeoJson des tronçons de Vigicrues
- si Vigicrues_Reach.filename est défini, alors le contenu est lu
directement depuis ce fichier
- sinon le contenu est celui défini par le paramètre content
Parameters
----------
content : str
- Si cela correspond à un fichier, celui-ci est lu
i.e, correspond au retour de urlretrieve
- Sinon, il est considéré comme étant le résultés de urlopen
Returns
-------
data : pandas.DataFrame
Tableau de données
Examples
--------
>>> import pyspc.data.vigicrues as _vigicrues
>>> f = 'data/data/vigicrues/K118001010_prevision.json'
>>> vigi = _vigicrues.Vigicrues_Fcst(filename=f)
>>> df = vigi.read()
>>> df
K118001010
Q
2022-03-29 12:06:52
ResMinPrev ResMoyPrev ResMaxPrev
2022-03-29 15:00:00 19.00 19.61 20.10
2022-03-29 16:00:00 18.97 19.60 20.11
2022-03-29 17:00:00 18.95 19.59 20.11
2022-03-29 18:00:00 18.92 19.58 20.11
2022-03-29 19:00:00 18.90 19.57 20.11
2022-03-29 20:00:00 18.87 19.55 20.12
2022-03-29 21:00:00 18.84 19.54 20.12
2022-03-29 22:00:00 18.82 19.53 20.12
2022-03-29 23:00:00 18.79 19.52 20.12
Notes
-----
L'horodatage est forcé à UTC.
L'information relative au fuseau horaire est retirée.
"""
if self.filename is not None:
with open(self.filename, 'r', encoding='utf-8') as j:
data = json.load(j)
else:
data = json.loads(content)
self._check_varname(varname=data['Simul']['GrdSimul'])
# astimezone(tz(td(0))) : pour passer de UTC + Xh à UTC
# replace(tzinfo=None) : pour supprimer tzinfo
index = [dt.fromisoformat(
x['DtPrev']).astimezone(tz(td(0))).replace(tzinfo=None)
for x in data['Simul']['Prevs']]
runtime = dt.fromisoformat(
data['Simul']['DtProdSimul']).astimezone(tz(td(0))).replace(
tzinfo=None)
values = collections.OrderedDict()
for t in TRENDS:
try:
vs = [float(x[t]) for x in data['Simul']['Prevs']]
except KeyError:
continue
key = (data['Simul']['CdStationHydro'], data['Simul']['GrdSimul'],
runtime, t)
values[key] = vs
return pnd.DataFrame(values, index=index)
[docs]
@classmethod
def get_trends(cls):
"""
Définir le nom de la tendance
"""
return sorted(TRENDS.keys())
[docs]
@classmethod
def get_varnames(cls):
"""
Définir le nom de la variable
"""
return sorted(VARNAMES)