Esempio n. 1
0
 def __init__(self,
              db: str,
              schema: str,
              table: str,
              geom_name: str = None):
     """
     args:
         db: database
         schema: schema
         table: table
         if your table has a point geometry column you musy supply
             the column name
     """
     self.con = None
     try:
         self.db = db
         self.schema = schema
         self.table = table
         self.geom = geom_name
         self.con = con_get('postgres', db)
         self.cur = self.con.cursor()
         self.cur.execute(f'select * from {schema}.{table} limit 1')
         # self.data will be a DataFrame object when it be written the
         # excel file to be imported
         self.data = None
     except:
         if self.con is not None:
             self.con.close()
         raise ValueError('Error al instanciar Upsert')
Esempio n. 2
0
    def hs(self, select1: str, select2: str, dir_out: str, xygraph: bool):
        """
        calculo de la ET por el metodo de Hargreaves
        """
        from os.path import join
        import sqlite3
        from db_connection import con_get
        from graphs import xy_ts_plot_1g

        select_r0 = 'select r0 from r0 where lat = ? order by "month"'

        con = con_get(self.dbtype, self.dbname)
        cur = con.cursor()

        con3 = sqlite3.connect('r0.db')
        cur3 = con3.cursor()

        cur.execute(select1)
        stations = [row for row in cur.fetchall()]

        for station in stations:
            print(station[0])
            if station[1] > 70:
                station[1] = 70
            elif station[1] < -70:
                station[1] = -70
            ilat = int(round(station[1], 0))
            cur3.execute(select_r0, (ilat, ))
            r0s = [row[0] for row in cur3.fetchall()]
            if not r0s:
                raise ValueError(f'{station[0]}: no r0 at {ilat}º')
            cur.execute(select2, (station[0], ))
            ts = np.array([row for row in cur.fetchall()])
            tmax = ts[:, 1] / 10.
            tmin = ts[:, 2] / 10.
            tavg = ts[:, 3] / 10.
            im = np.array([row[0].month - 1 for row in ts], np.int32)
            #            self._hargreaves_samani(r0s, im, tmax, tmin, tavg,
            #                                    np.empty(len(im), np.float32))

            etp = np.empty(len(im), np.float32)
            _hargreaves_samani_01(np.array(r0s, np.float32), im,
                                  tmax.astype(np.float32),
                                  tmin.astype(np.float32),
                                  tavg.astype(np.float32), etp)
            self._write(station[0],
                        [row[0].strftime('%Y-%m-%d') for row in ts], etp,
                        dir_out)

            if xygraph:
                title = f'{station[0]}'
                x = [row[0] for row in ts]
                ylabel = 'etp (mm)'
                dst = join(dir_out, f'{station[0]}.png')
                xy_ts_plot_1g(title, x, etp, ylabel, dst)

        con3.close()
        con.close()
        self._h_metadata(select1, select2, dir_out, xygraph, stations)
Esempio n. 3
0
    def __init__(self,
                 db: str,
                 schema: str,
                 table: str,
                 fi: str,
                 sheet_name: str,
                 converters: dict = {},
                 lowercase: tuple = (),
                 check_data: bool = True):
        """
        args:
            db: database
            schema: schema
            table: table
            fi: path to csv, xls or xlsx file
            col_names: diccionario en el que las claves son los nombres de
                las columnas en la tabla en que se van a importar los datos y
                los contenidos son los correspondientes nombres de las
                columnas en fi
            si fi tiene extensión csv
            sep: column separatos in fi (sólo para csv)
            si fi tiene extensión Excel
            sheet_name: nombre de la hoja en fi
            converters: al leer un fichero xls o xlsx deduce el tipo de los
                contenidos de las columnas; si se desea forzar un tipo utilice
                converters, que es un diccionario cuya clave es el nombre de
                la columna en el fichero xls o xlsx que se desea contertir
                el tipo y el contenido es el tipo de python al que se desea
                convertir
            lowercase: column names in sheet_name to transform to lowercase
        """
        tree = ET.parse(self.xml_org)
        root = tree.getroot()
        db_element = self.__read_atrib_element(root, 'db', 'name', db)
        self.db = db
        self.table = self.__read_atrib_element(db_element, 'table', 'name',
                                               f'{schema}.{table}')

        self.fi = fi
        self.data = pd.read_excel(fi,
                                  sheet_name=sheet_name,
                                  converters=converters)

        if check_data:
            self.__check_fks()

        if lowercase is not None:
            for col in lowercase:
                self.data[col] = self.data[col].str.lower()
        self.data = self.data.where(pd.notnull(self.data), None)
        self.con = con_get('postgres', 'ipa')
        self.cur = self.con.cursor()
Esempio n. 4
0
def _data1_get():
    from db_connection import con_get

    con = con_get('postgres', 'bda')
    cur = con.cursor()

    for i in range(1, 13):
        select1 = f'select lat x, r{i:02n} y from met.r0 order by lat'
        cur.execute(select1)
        row = [r for r in cur.fetchall()]
        x = np.array([r[0] for r in row], np.float32)
        y = np.array([r[1] for r in row], np.float32)
        yield i, x, y
    con.close()
Esempio n. 5
0
 def __init__(self,
              fi: str,
              col_names: dict,
              sep: str = ';',
              sheet_name: str = None,
              converters: dict = {},
              lowercase: tuple = ()):
     """
     args:
         fi: path to csv, xls or xlsx file
         col_names: diccionario en el que las claves son los nombres de
             las columnas en la tabla en que se van a importar los datos y
             los contenidos son los correspondientes nombres de las
             columnas en fi
         si fi tiene extensión csv
         sep: column separatos in fi (sólo para csv)
         si fi tiene extensión Excel
         sheet_name: nombre de la hoja en fi
         converters: al leer un fichero xls o xlsx deduce el tipo de los
             contenidos de las columnas; si se desea forzar un tipo utilice
             converters, que es un diccionario cuya clave es el nombre de
             la columna en el fichero xls o xlsx que se desea contertir
             el tipo y el contenido es el tipo de python al que se desea
             convertir
         lowercase: column names in sheet_name to transform to lowercase
     """
     from os.path import splitext
     self.fi = fi
     self.col_names = Upsert_ipas_ipa2.column_names.copy()
     for k in self.col_names.keys():
         self.col_names[k] = col_names[k]
     self.sep = sep
     self.checked_data_in_tables = False
     if splitext(fi)[1] == '.csv':
         self.data = pd.read_csv(self.fi, sep=self.sep)
     else:
         self.data = pd.read_excel(fi,
                                   sheet_name=sheet_name,
                                   converters=converters)
         if lowercase is not None:
             for col in lowercase:
                 self.data[col] = self.data[col].str.lower()
         self.data = self.data.where(pd.notnull(self.data), None)
     self.con = con_get('postgres', 'ipa')
Esempio n. 6
0
    def idw_ts(self, xygraph: bool):
        """
        Interpolación de una serie temporal en una serie de puntos sin datos
        xygraph: True si se graba un gráficos con cada punto interpolado
        """
        import sqlite3
        from os.path import join
        from time import time
        from scipy import spatial
        from db_connection import con_get
        import idw

        create_table1 = \
        f"""
        create table if not exists {IDW.table_name_interpolated_values} (
        fid TEXT,
        fecha TEXT,
        value REAL,
        PRIMARY KEY (fid, fecha))"""

        insert1 = \
        f"""
        insert into {IDW.table_name_interpolated_values}
        (fid, fecha, value)
        values(?, ?, ?)"""

        start_time = time()

        # datos donde hay que interpolar, devuelve numpy array of objects
        rows = IDW.__read_file_points(join(self.pathin, self.fpoints),
                                      self.skip_lines)
        # array con los id de los puntos donde se quiere interpolar
        fidi = rows[:, 0]
        # array con las coord. de los puntos
        xi = np.array(rows[:, [1, 2]], np.float32)
        # array para los valores interpolados en xi en cada fecha
        zi = np.empty((len(xi)), np.float32)

        # cursor a los datos para hacer las interpolaciones
        con = con_get(self.dbtype, self.db)
        cur = con.cursor()

        # cursor para los valores interpolados
        con1 = sqlite3.connect(':memory:')
        cur1 = con1.cursor()
        cur1.execute(create_table1)

        t0 = IDW.PRINT_SECS
        if self.tstep_type == 2:
            datei = IDW.__month_lastday(self.datei)
        else:
            datei = self.datei

        # los puntos con datos cambian de una fecha a otra por lo que hay que
        # hacer una select para cada fecha; esto hace que el proceso sea
        # sea largo para series temporales largas
        date_nodata = []
        while datei <= self.datefin:
            date_str = datei.strftime(self.date_format)
            if time() - t0 > IDW.PRINT_SECS:
                t0 = time()
                print(date_str)

            # datos en la fecha datei
            cur.execute(self.select, (datei, ))
            data = np.array([row for row in cur], np.float32)
            # puede haber fechas sin datos
            if data.size == 0:
                date_nodata.append(date_str)
                logging.append(f'{date_str} no data', False)
                datei = self.__next_date(datei)
                continue

            # builds kdtree tree and set distances
            xydata = data[:, [0, 1]]
            tree = spatial.cKDTree(xydata)
            dist, ii = tree.query(xi, k=min(self.kidw, xydata.shape[0]))

            # sort data by distance
            values0 = data[:, 2]
            values = np.empty((dist.shape), np.float32)
            idw.sortn(values0, ii, values)

            # idw interpolation
            idw.idwn(self.poweridw, dist, values, self.epsidw, zi)

            # insert interpolated values in sqlite
            for i in range(len(fidi)):
                cur1.execute(insert1, (fidi[i], date_str, float(zi[i])))

            datei = self.__next_date(datei)

        con.close()
        elapsed_time = time() - start_time
        print(f'La interpolación idw tardó {elapsed_time:0.1f} s')

        con1.commit()

        # las fechas sin datos se tratan de interpolar con medianas
        missed = self._fill_with_median(fidi, date_nodata, con1, cur1, insert1)

        # graba interpolación en ficheros de texto
        self.__write_interpolated_values(cur1)

        # graba fichero con los metadatos de la interpolación
        self.__write_idw_metadata(fidi.size, elapsed_time, missed)

        # graba el fichero de puntos donde se realizó la interpolación
        self.__write_interpolated_points(fidi, xi)

        # graba los gráficos
        if xygraph:
            self.__xy(cur1)