Python rpy2.robjects.pandas2ri.activate() Examples

The following are 9 code examples of rpy2.robjects.pandas2ri.activate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rpy2.robjects.pandas2ri , or try the search function .
Example #1
Source File: baseline_runner.py    From SnowAlert with Apache License 2.0 5 votes vote down vote up
def query_log_source(source, time_filter, time_column):
    from rpy2.robjects import pandas2ri

    cutoff = f"DATEADD(day, -{time_filter}, CURRENT_TIMESTAMP())"
    query = f"SELECT * FROM {source} WHERE {time_column} > {cutoff};"
    try:
        data = list(db.fetch(query))
    except Exception as e:
        log.error("Failed to query log source: ", e)
    f = pack(data)
    frame = pandas.DataFrame(f)
    pandas2ri.activate()
    r_dataframe = pandas2ri.py2rpy(frame)
    return r_dataframe 
Example #2
Source File: psm.py    From perfect_match with MIT License 5 votes vote down vote up
def _build(self, **kwargs):
        from rpy2.robjects import numpy2ri, pandas2ri
        match_it = self.install_matchit()

        self.num_treatments = kwargs["num_treatments"]
        self.batch_size = kwargs["batch_size"]
        self.match_it = match_it
        numpy2ri.activate()
        pandas2ri.activate()

        return super(PSM, self)._build(**kwargs) 
Example #3
Source File: bart.py    From perfect_match with MIT License 5 votes vote down vote up
def _build(self, **kwargs):
        from rpy2.robjects import numpy2ri, pandas2ri
        n_jobs = int(np.rint(kwargs["n_jobs"]))

        bart = self.install_bart()
        bart.set_bart_machine_num_cores(n_jobs)

        self.bart = bart
        numpy2ri.activate()
        pandas2ri.activate()

        return None 
Example #4
Source File: PipelineTimeseries.py    From CGATPipelines with MIT License 5 votes vote down vote up
def dtwWrapper(data, rows, columns, k):
    '''
    wrapper function for dynamic time warping.
    includes use of exponential adaptive tuning function
    with temporal correlation if k > 0
    '''

    # not explicitly called, but needs to be in R environment
    DTW = importr("dtw")

    # create a data frame of zeros of size number of ids x number of ids
    # fill it with the calculated distance metric for each pair wise comparison

    df_ = pd.DataFrame(index=rows,
                       columns=columns)
    df_ = df_.fillna(0.0).astype(np.float64)

    # fill the array with dtw-distance values
    pandas2ri.activate()

    for i in rows:
        E.info("DTW %s" % i)
        for j in columns:
            series1 = data.loc[i].values.tolist()
            series2 = data.loc[j].values.tolist()
            DTW_value = (R.dtw(series1,
                               series2)).rx('distance')[0][0]
            cort_value = temporalCorrelate(series1, series2)
            tuned_value = adaptiveTune(cort_value, k)
            time_dist = DTW_value * tuned_value
            df_.loc[i][j] = float(time_dist)
            df_[j][i] = float(time_dist)

    return df_ 
Example #5
Source File: test_pandas_conversions.py    From rpy2 with GNU General Public License v2.0 5 votes vote down vote up
def testActivate(self):
        #FIXME: is the following still making sense ?
        assert rpyp.py2rpy != robjects.conversion.py2rpy
        l = len(robjects.conversion.py2rpy.registry)
        k = set(robjects.conversion.py2rpy.registry.keys())
        rpyp.activate()
        assert len(conversion.py2rpy.registry) > l
        rpyp.deactivate()
        assert len(conversion.py2rpy.registry) == l
        assert set(conversion.py2rpy.registry.keys()) == k 
Example #6
Source File: test_pandas_conversions.py    From rpy2 with GNU General Public License v2.0 5 votes vote down vote up
def testActivateTwice(self):
        #FIXME: is the following still making sense ?
        assert rpyp.py2rpy != robjects.conversion.py2rpy
        l = len(robjects.conversion.py2rpy.registry)
        k = set(robjects.conversion.py2rpy.registry.keys())
        rpyp.activate()
        rpyp.deactivate()
        rpyp.activate()
        assert len(conversion.py2rpy.registry) > l
        rpyp.deactivate()
        assert len(conversion.py2rpy.registry) == l
        assert set(conversion.py2rpy.registry.keys()) == k 
Example #7
Source File: functions.py    From hants with Apache License 2.0 4 votes vote down vote up
def Kriging_Interpolation_Array(input_array, x_vector, y_vector):
    """
    Interpolate data in an array using Ordinary Kriging

    Reference: https://cran.r-project.org/web/packages/automap/automap.pdf
    """
    # Total values in array
    n_values = np.isfinite(input_array).sum()
    # Load function
    pandas2ri.activate()
    robjects.r('''
                library(gstat)
                library(sp)
                library(automap)
                kriging_interpolation <- function(x_vec, y_vec, values_arr,
                                                  n_values){
                  # Parameters
                  shape <- dim(values_arr)
                  counter <- 1
                  df <- data.frame(X=numeric(n_values),
                                   Y=numeric(n_values),
                                   INFZ=numeric(n_values))
                  # Save values into a data frame
                  for (i in seq(shape[2])) {
                    for (j in seq(shape[1])) {
                      if (is.finite(values_arr[j, i])) {
                        df[counter,] <- c(x_vec[i], y_vec[j], values_arr[j, i])
                        counter <- counter + 1
                      }
                    }
                  }
                  # Grid
                  coordinates(df) = ~X+Y
                  int_grid <- expand.grid(x_vec, y_vec)
                  names(int_grid) <- c("X", "Y")
                  coordinates(int_grid) = ~X+Y
                  gridded(int_grid) = TRUE
                  # Kriging
                  krig_output <- autoKrige(INFZ~1, df, int_grid)
                  # Array
                  values_out <- matrix(krig_output$krige_output$var1.pred,
                                       nrow=length(y_vec),
                                       ncol=length(x_vec),
                                       byrow = TRUE)
                  return(values_out)
                }
                ''')
    kriging_interpolation = robjects.r['kriging_interpolation']
    # Execute kriging function and get array
    r_array = kriging_interpolation(x_vector, y_vector, input_array, n_values)
    array_out = np.array(r_array)
    # Return
    return array_out 
Example #8
Source File: functions.py    From wa with Apache License 2.0 4 votes vote down vote up
def array_interpolation(lon_ls, lat_ls, infz_array_in, min_infz,
                        return_single_value):
    '''
    Interpolate missing values in an array using kriging in R
    '''
    # Replace values smaller than the minimum
    infz_array_in[infz_array_in < min_infz] = np.nan
    # Total values in array
    n_values = np.isfinite(infz_array_in).sum()
    # Load function
    pandas2ri.activate()
    robjects.r('''
                library(gstat)
                library(sp)
                library(automap)
                kriging_interpolation <- function(x_vec, y_vec, values_arr,
                                                  n_values){
                  # Parameters
                  shape <- dim(values_arr)
                  counter <- 1
                  df <- data.frame(X=numeric(n_values),
                                   Y=numeric(n_values),
                                   INFZ=numeric(n_values))
                  # Save values into a data frame
                  for (i in seq(shape[2])) {
                    for (j in seq(shape[1])) {
                      if (is.finite(values_arr[j, i])) {
                        df[counter,] <- c(x_vec[i], y_vec[j], values_arr[j, i])
                        counter <- counter + 1
                      }
                    }
                  }
                  # Grid
                  coordinates(df) = ~X+Y
                  int_grid <- expand.grid(x_vec, y_vec)
                  names(int_grid) <- c("X", "Y")
                  coordinates(int_grid) = ~X+Y
                  gridded(int_grid) = TRUE
                  # Kriging
                  krig_output <- autoKrige(INFZ~1, df, int_grid)
                  # Array
                  values_out <- matrix(krig_output$krige_output$var1.pred,
                                       nrow=length(y_vec),
                                       ncol=length(x_vec),
                                       byrow = TRUE)
                  return(values_out)
                }
                ''')
    kriging_interpolation = robjects.r['kriging_interpolation']
    # Execute kriging function and get array
    r_array = kriging_interpolation(lon_ls, lat_ls, infz_array_in, n_values)
    infz_array_out = np.array(r_array)
    # Return
    if not return_single_value:
        return infz_array_out
    else:
        x, y = return_single_value
        return infz_array_out[y, x] 
Example #9
Source File: functions.py    From wa with Apache License 2.0 4 votes vote down vote up
def Kriging_Interpolation_Array(input_array, x_vector, y_vector):
    """
    Interpolate data in an array using Ordinary Kriging

    Reference: https://cran.r-project.org/web/packages/automap/automap.pdf
    """
    # Total values in array
    n_values = np.isfinite(input_array).sum()
    # Load function
    pandas2ri.activate()
    robjects.r('''
                library(gstat)
                library(sp)
                library(automap)
                kriging_interpolation <- function(x_vec, y_vec, values_arr,
                                                  n_values){
                  # Parameters
                  shape <- dim(values_arr)
                  counter <- 1
                  df <- data.frame(X=numeric(n_values),
                                   Y=numeric(n_values),
                                   INFZ=numeric(n_values))
                  # Save values into a data frame
                  for (i in seq(shape[2])) {
                    for (j in seq(shape[1])) {
                      if (is.finite(values_arr[j, i])) {
                        df[counter,] <- c(x_vec[i], y_vec[j], values_arr[j, i])
                        counter <- counter + 1
                      }
                    }
                  }
                  # Grid
                  coordinates(df) = ~X+Y
                  int_grid <- expand.grid(x_vec, y_vec)
                  names(int_grid) <- c("X", "Y")
                  coordinates(int_grid) = ~X+Y
                  gridded(int_grid) = TRUE
                  # Kriging
                  krig_output <- autoKrige(INFZ~1, df, int_grid)
                  # Array
                  values_out <- matrix(krig_output$krige_output$var1.pred,
                                       nrow=length(y_vec),
                                       ncol=length(x_vec),
                                       byrow = TRUE)
                  return(values_out)
                }
                ''')
    kriging_interpolation = robjects.r['kriging_interpolation']
    # Execute kriging function and get array
    r_array = kriging_interpolation(x_vector, y_vector, input_array, n_values)
    array_out = np.array(r_array)
    # Return
    return array_out