Skip to content

Instantly share code, notes, and snippets.

@jonlachmann
jonlachmann / weekdays.R
Created June 7, 2023 15:13
Calculate the number of days, weekdays or weeks in a month, quarter, half-year or year.
library(lubridate)
# Function to count days, weekdays and weeks in a given month
counts <- function (year, month) {
# Get the number of days in the month
num_days <- days_in_month(as.Date(paste(year, month, "01", sep = "-")))
# Initialize a counter
weekday_count <- 0
week_count <- 0
@jonlachmann
jonlachmann / var_shapr.R
Created November 30, 2022 10:03
Explain a VAR model with shapr, using the branch output_size from my fork.
# Generate mock data (two variable which go from 1-100 and 101-200 with some random noise).
data <- matrix(rnorm(200, 1:200, 0.5), 100, 2)
K <- ncol(data) # Number of variables in model
horizon <- 12 # Forecast horizon
p <- 2 # Lag order of model
# Create the lagged matrix of data X
X <- embed(data, p+1)[,-seq_len(K)]
X <- cbind(X, 1)
@jonlachmann
jonlachmann / common.py
Created February 3, 2022 08:40
Many to many LSTM in both keras and pytorch
from numpy import array
from numpy import linspace
from numpy import random
from numpy import zeros
from numpy import vstack
import torch
# Split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
@jonlachmann
jonlachmann / gist:ed792797c83fe3d2d8dc06fac0a47936
Last active January 1, 2022 11:35
Nedis 16A WiFi Smart Plug ESPHome configuration
esphome:
name: nedis-16a
esp8266:
board: esp01_1m
# Enable logging
logger:
# Enable Home Assistant API
@jonlachmann
jonlachmann / Rcpp_Address_Sanitizing.txt
Last active May 29, 2023 13:32
Running address sanitizing in R/Rcpp/RcppEigen
To be able to run address sanitizing in your own Rcpp/RcppEigen code, you need a version of R that is compiled with support for it. You also need to compile all Rcpp libraries that you will use using address sanitizing. Finally, your own code must also be compiled with it. This is the steps that I have found that works.
1. Download Docker for your platform
2. Install the rocker docker image and give it 8GB of memory (installation of Rcpp will fail on 2GB)
docker pull rocker/r-devel-san
docker container run --memory=8g -it --entrypoint bash rocker/r-devel-san
3. Set the Makevars to be used for ALL compiling of C++ code in R by creating /root/.R/Makevars with
PKG_CXXFLAGS = -fsanitize=address -I../inst/include
@jonlachmann
jonlachmann / Metropolis_hastings.R
Created May 17, 2020 11:44
Metropolis hastrings estimation of covariance matrix
# Title : Multivariate Metropolis Hastings for covariance matrix estimation
# Objective : Estimate distribution of multivariate covariances
# Created by: jonlachmann
# Created on: 2020-05-17
# Jeffreys prior, log transformed
jeffreys_log = function (sigma) {
-(nrow(sigma)+1)/2 * log(det(sigma))
}