Giter Site home page Giter Site logo

metr's Introduction

metR

R-CMD-check Coverage status CRAN status DOI

metR packages several functions and utilities that make R better for handling meteorological data in the tidy data paradigm. It started mostly sa a packaging of assorted wrappers and tricks that I wrote for my day to day work as a researcher in atmospheric sciences. Since then, it has grown organically and for my own needs and feedback from users.

Conceptually it’s divided into visualization tools and data tools. The former are geoms, stats and scales that help with plotting using ggplot2, such as stat_contour_fill() or scale_y_level(), while the later are functions for common data processing tools in the atmospheric sciences, such as Derivate() or EOF(); these are implemented to work in the data.table paradigm, but also work with regular data frames.

Currently metR is in development but maturing. Most functions check arguments and there are some tests. However, some functions might change it’s interface, and functionality can be moved to other packages, so please bear that in mind.

Installation

You can install metR from CRAN with:

install.packages("metR")

Or the development version with:

if (!requireNamespace("pak", quietly = TRUE)) {
    install.packages("pak")
}
pak::pak("metR")

If you need to read netcdf files, you might need to install the netcdf and udunits2 libraries. On Ubuntu and it’s derivatives this can be done by typing

sudo apt install libnetcdf-dev netcdf-bin libudunits2-dev

Citing the package

If you use metR in your research, please consider citing it. You can get citation information with

citation("metR")
#> To cite metR in publications use:
#> 
#> 
#> 
#> A BibTeX entry for LaTeX users is
#> 
#>   @Manual{,
#>     title = {metR: Tools for Easier Analysis of Meteorological Fields},
#>     author = {Elio Campitelli},
#>     year = {2021},
#>     note = {R package version 0.15.0.9000},
#>     url = {https://eliocamp.github.io/metR/},
#>     doi = {10.5281/zenodo.2593516},
#>   }

Examples

In this example we easily perform Principal Components Decomposition (EOF) on monthly geopotential height, then compute the geostrophic wind associated with this field and plot the field with filled contours and the wind with streamlines.

library(metR)
library(data.table)
library(ggplot2)
data(geopotential)
# Use Empirical Orthogonal Functions to compute the Antarctic Oscillation
geopotential <- copy(geopotential)
geopotential[, gh.t.w := Anomaly(gh)*sqrt(cos(lat*pi/180)),
      by = .(lon, lat, month(date))]
aao <- EOF(gh.t.w ~ lat + lon | date, data = geopotential, n = 1)
aao$left[, c("u", "v") := GeostrophicWind(gh.t.w/sqrt(cos(lat*pi/180)), 
                                                    lon, lat)]

# AAO field
binwidth <- 0.01
ggplot(aao$left, aes(lon, lat)) +
    geom_contour_fill(aes(z = gh.t.w/sqrt(cos(lat*pi/180)), 
                          fill = after_stat(level)), binwidth = binwidth,
                      xwrap = c(0, 360)) +
    geom_streamline(aes(dx = dlon(u, lat), dy = dlat(v)),
                    linewidth = 0.4, L = 80, skip = 3, xwrap = c(0, 360)) +
    scale_x_longitude() +
    scale_y_latitude(limits = c(-90, -20)) +
    scale_fill_divergent_discretised(name = "AAO pattern") +
    coord_polar()
#> Warning in .check_wrap_param(list(...)): 'xwrap' and 'ywrap' will be
#> deprecated. Use ggperiodic::periodic insead.

# AAO signal
ggplot(aao$right, aes(date, gh.t.w)) +
    geom_line() +
    geom_smooth(span = 0.4)
#> `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

You can read more in the vignettes: Visualization tools and Working with data.

metr's People

Contributors

eliocamp avatar m-saenger avatar paocorrales avatar pmur002 avatar teunbrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

metr's Issues

Resolver bug con stat_contour_fill()

¿Qué carajo pasa acá? Cierra los contornos por cualquier lado y manda cualquiera con el color.

library(data.table)
library(ggplot2)
library(metR)

qs.wave.season <- readRDS("~/Documents/Tesis/DATA/qs.wave.season.Rds")
binwidth <- 5
plot.levs <- c(500, 300, 200, 100, 30)
setkey(qs.wave.season, season, lev, lon, lat)
ggplot(RepeatLon(qs.wave.season[lev == 200 & season == "Invierno"]), aes(lon, lat)) +
    stat_contour_fill(aes(z = QS3), color = "black", binwidth = binwidth) +
    scale_color_divergent(binwidth = binwidth, name = "QS3") 

Generalizar función EOF

Por ahora EOF está dirigida únicamente a hacer EOF en modo S para campos. Se puede hacer más general.

ConvertWindDirection

Función para convertir la dirección del viento desde y hacia convención meteorológica.

Leer subset en `ReadNetCDF()`

Usar start y count de ncdf4::ncvar_get() para permitir leer sólo un subset de los datos.

La principal complicación es que en ncvar_get() requiere un orden particular (X, Y, Z, T) que no necesariamente es el orden en el que están organizadas las variables. También hay que tener en cuenta casos donde las variables a leer no tienen una dimensión (como Z).

¿Atributo `circular`?

Se puede agregar un atributo a columnas de data.frame (y data.table). Podría usar eso para hacer más fácil el tratamiento de grillas donde haya una coordenada circular. Se puede:

  • Hacer casi automático RepeatLon().
  • Hacer rosa de los vientos (o histogramas en general).
  • Aplicar las condiciones de contorno automaticamente en Derivate()

Chequear paquete circular https://cran.r-project.org/web/packages/circular/circular.pdf

Escala de colores circular

Buscar una forma de hacer una escala de colores "circular". Es decir, que use (casi, porque la escala tiene que ser biyectiva) el mismo color para los extremos.

Faster MakeMask

Hacer que MakeMask sea más rápido cuando se tiene un campo con muchos niveles. Hay que hacer la máscara sólo para cada combinación única de lon + lat y luego expandir a todo.

Skip de geom_arrow

Hacer que el skip de geom_arrow funcione como se debe en una grilla regular.
Por ejemplo haciendo un subset de los datos con %in% JumpBy(ubique(x|y), skip).

Synop

Herramientas para manejar códigos synop.

  • Traductor (ida y vuelta)

  • Símbolos para plotear

  • Crear un geom para plotear synops completos. <- JODIDO!

`stat_contour_fill()` no anda bien cuando el promedio del campo es igual a un `break`

Ejemplo:

library(ggplot2)
library(metR)
df <- expand.grid(x = 1:10, y = 1:10)
df$z <- with(df, x*y - mean(x*y))

ggplot(df, aes(x, y, z = z)) +
    geom_contour_fill(binwidth = 20) +
    geom_contour(breaks = 0) +
    scale_fill_divergent(guide = guide_colorstrip(),
                         breaks = MakeBreaks(20))

El problema está acá:

correction <- (breaks.keep[i + sign(mean.z - mean.level)] - mean.level)/2

Cuando mean.z == mean.level, la corrección es nula y queda blanco. En principio no es trivial saber para qué lado tendría que ser la corrección. La forma "ideal" sería encontrar un punto que no esté "cubierto" por polígonos y fijarse para qué sentido hay que asignar el fill. Pero esto potencialmente puede ser muy difícil.

Constantes

Constantes atmosféricas

  • Constante de gas (aire seco)
  • ??

Consistencia en el output

Algunas funciones devuelven data frames y otras data tables. Hay que hacer que todo devuelva una o la otra (data.table, jiji)

¿Grados o radianes?

geom_arrow() toma el ángulo y el start en grados. ¿Está bien así o es preferible en radianes?
Es más cómodo e intuitivo usar grados, pero usar radianes es más "científico" y lógico. Debería preguntar..

Geom_arrow

Que funcione bien. Con líneas en vez de texto.

Nombre

"There are only two hard things in Computer Science: cache invalidation and naming things"

Ponerle nombre a la criatura. Opciones por ahora:

  • meteoR:

    • + Copado
    • + Ya tengo el logo :P
    • - Ya hay mil cosas llamadas "meteor".
    • - Puede no ser muy claro
  • metR

    • + Copado
    • + Misma notación que metPy (aunque, de nuevo, le puede quedar grande)
    • + Vale casi el mismo logo que meteoR.
    • - Medio que es aún menos claro que meteoR.
  • tidyweather

    • + Es explícita la inserción en el tidyverse
    • - Medio que le queda grande (¿este va a ser el paquete para tidy data en meteorología?)
    • - No tiene "r".

Vectorizar `%~%`

Para que x %~% c(20, 30) funcione realmente como %in% aproximado.

Datos

Guardar datos para ejemplos y vignettes:

  • Campos espaciales (NCEP)
  • Series temporales + espaciales (CLARIS?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.