Jags gets wired, returns redefining node errer occasionally, due to different data - jags

I created my code based on this :
http://users.aims.ac.za/~mackay/BUGS/Manual05/Examples1/node29.html
Now I use different seeds to simulate data. It is strange enough that some seeds give me a redefining node dN[1,1] on line 18 error, while others do not. Could someone help please? BTW why is dN[1,1] on line 18 at the first place? How does Jags count lines?
error message :
"
RUNTIME ERROR:
Compilation error on line 18.
Attempt to redefine node dN[1,1]
"
bugsmodel <- "
# Set up data
data{
for(i in 1:N)
{
for(j in 1:bigt)
{
Y[i,j] <- step(obs.t[i] - t[j] + eps)
dN[i, j] <- Y[i, j] * step(t[j + 1] - obs.t[i] - eps) * fail[i]
}
}
}
# Model
model
{
for(i in 1:N){
betax[i,1] <- 0
for(k in 2:(p+1)){
betax[i,k] <- betax[i,k-1] + beta[k-1]*x[i,k-1]
}
}
for(j in 1:bigt) {
for(i in 1:N) {
dN[i, j] ~ dpois(Idt[i, j]) # Likelihood
Idt[i, j] <- Y[i, j] * exp(betax[i,p+1]) * dL0[j] # Intensity
}
dL0[j] ~ dgamma(mu[j], c)
mu[j] <- dL0.star[j] * c # prior mean hazard
}
c <- 0.001
r <- 0.1
for (j in 1 : bigt) {
dL0.star[j] <- r * (t[j + 1] - t[j])
}
for(k in 1:p){
beta[k] ~ dnorm(0.0,0.000001)
}
}"

Related

hi all . i am trying to run the bym2 model . at this stage, i have a problem.are you help me?

library(“rstan”)
library(“rstudioapi”)
library(“parallel”)
library(“brms”)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectgores())
library(pkgbuild) # load packAge
find_rtools() # should be TRUE, assuming you have Rtools 3.5
#fit model icar.stan to NYC census tracts neighborhood map
install.packages(‘tidyverse’, dependencies = TRUE)
install.packages(‘rstanarm’, dependencies = TRUE)
library(rstan);
library(tidyverse)
library(rstanarm)
"data {
int<lower=0> N;
int<lower=0> N_edges;
int<lower=1, upper=N> node1[N_edges]; // node1[i] adjacent to node2[i]
int<lower=1, upper=N> node2[N_edges]; // and node1[i] < node2[i]
int<lower=0> y[N]; // count outcomes
vector<lower=0>[N] E; // exposure
int<lower=1> K; // num covariates
matrix[N, K] x; // design matrix
real<lower=0> scaling_factor; // scales the variance of the spatial effects
}
transformed data {
vector[N] log_E = log(E);
}
parameters {
real beta0; // intercept
vector[K] betas; // covariates
real<lower=0> sigma; // overall standard deviation
real<lower=0, upper=1> rho; // proportion unstructured vs. spatially structured variance
vector[N] theta; // heterogeneous effects
vector[N] phi; // spatial effects
}
transformed parameters {
vector[N] convolved_re;
// variance of each component should be approximately equal to 1
convolved_re = sqrt(1 - rho) * theta + sqrt(rho / scaling_factor) * phi;
}
model {
y ~ poisson_log(log_E + beta0 + x * betas + convolved_re * sigma); // co-variates
// This is the prior for phi! (up to proportionality)
target += -0.5 * dot_self(phi[node1] - phi[node2]);
beta0 ~ normal(0.0, 1.0);
betas ~ normal(0.0, 1.0);
theta ~ normal(0.0, 1.0);
sigma ~ normal(0, 1.0);
rho ~ beta(0.5, 0.5);
// soft sum-to-zero constraint on phi)
sum(phi) ~ normal(0, 0.001 * N); // equivalent to mean(phi) ~ normal(0,0.001)
}
generated quantities {
real logit_rho = log(rho / (1.0 - rho));
vector[N] eta = log_E + beta0 + x * betas + convolved_re * sigma; // co-variates
vector[N] mu = exp(eta);
}"
options(mc.cores = parallel::detectCores())
library(INLA)
source(“mungecardata4stan.R”)
source(“iran_data.R”)
y = data$y;
E = data$E;
K = 1;
x = 0.1 * data$x;
nbs = mungeCARdata4stan(data$adj, data$num);
N = nbs$N;
node1 = nbs$node1;
node2 = nbs$node2;
N_edges = nbs$N_edges;
adj.matrix = sparseMatrix(i=nbs$node1,j=nbs$node2,x=1,symmetric=TRUE)
Q= Diagonal(nbs$N, rowSums(adj.matrix)) - adj.matrix
Q_pert = Q + Diagonal(nbs$N) * max(diag(Q)) * sqrt(.Machine$double.eps)
Q_inv = inla.qinv(Q_pert, constr=list(A = matrix(1,1,nbs$N),e=0))
scaling_factor = exp(mean(log(diag(Q_inv))))
scot_stanfit = stan(“bym2_predictor_plus_offset.stan”, data=list(N,N_edges,node1,node2,y,x,E,scaling_factor), warmup=5000, iter=6000);
Error in new_CppObject_xp(fields$.module, fields$.pointer, …) : **
** Exception: variable does not exist; processing stage=data initialization; variable name=N; base type=int (in ‘string’, line 3, column 2 to column 17)
In addition: Warning message:
In readLines(file, warn = TRUE) :
** incomplete final line found on ‘C:\Users\Uaer\Downloads\bym2_predictor_plus_offset.stan’
failed to create the sampler;** sampling not done
in my opinion , in source(“mungecardata4stan.R”) you should type the address of mungecardata4stan.R that is placed in your pc. and also for source(“iran_data.R”). like this: source("C:/Users/me/Desktop/iran_data.R").

RcppAramadillo Cube::operator() : index out of bounds

I have been fiddling with the following C++ code for integration with R code that I have written (too much to include here), but keep getting an error that the Cube::operator() index is out of bounds and I am unsure as to why this is occurring. My suspicion is that the 3D array is not being filled correctly as described in
making 3d array with arma::cube in Rcpp shows cube error
but I am uncertain how to properly solve the issue.
Below is my full C++ code:
// [[Rcpp::depends(RcppArmadillo)]]
#define ARMA_DONT_PRINT_OPENMP_WARNING
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
#include <set>
using namespace Rcpp;
int sample_one(int n) {
return n * unif_rand();
}
int sample_n_distinct(const IntegerVector& x,
int k,
const int * pop_ptr) {
IntegerVector ind_index = RcppArmadillo::sample(x, k, false);
std::set<int> distinct_container;
for (int i = 0; i < k; i++) {
distinct_container.insert(pop_ptr[ind_index[i]]);
}
return distinct_container.size();
}
// [[Rcpp::export]]
arma::Cube<int> fillCube(const arma::Cube<int>& pop,
const IntegerVector& specs,
int perms,
int K) {
int num_specs = specs.size();
arma::Cube<int> res(perms, num_specs, K);
IntegerVector specs_C = specs - 1;
const int * pop_ptr;
int i, j, k;
for (i = 0; i < K; i++) {
for (k = 0; k < num_specs; k++) {
for (j = 0; j < perms; j++) {
pop_ptr = &(pop(0, sample_one(perms), sample_one(K)));
res(j, k, i) = sample_n_distinct(specs_C, k + 1, pop_ptr);
}
}
}
return res;
}
Does someone have an idea as to what may be producing the said error?
Below is the R code with a call to the C++ function (including a commented-out triply-nested 'for' loop that the C++ code reproduces).
## Set up container(s) to hold the identity of each individual from each permutation ##
num.specs <- ceiling(N / K)
## Create an ID for each haplotype ##
haps <- 1:Hstar
## Assign individuals (N) to each subpopulation (K) ##
specs <- 1:num.specs
## Generate permutations, assume each permutation has N individuals, and sample those individuals' haplotypes from the probabilities ##
gen.perms <- function() {
sample(haps, size = num.specs, replace = TRUE, prob = probs)
}
pop <- array(dim = c(perms, num.specs, K))
for (i in 1:K) {
pop[,, i] <- replicate(perms, gen.perms())
}
## Make a matrix to hold individuals from each permutation ##
# HAC.mat <- array(dim = c(perms, num.specs, K))
## Perform haplotype accumulation ##
# for (k in specs) {
# for (j in 1:perms) {
# for (i in 1:K) {
# select.perm <- sample(1:nrow(pop), size = 1, replace = TRUE) # randomly sample a permutation
# ind.index <- sample(specs, size = k, replace = FALSE) # randomly sample individuals
# select.subpop <- sample(i, size = 1, replace = TRUE) # randomly sample a subpopulation
# hap.plot <- pop[select.perm, ind.index, select.subpop] # extract data
# HAC.mat[j, k, i] <- length(unique(hap.plot)) # how many haplotypes are recovered
# }
# }
# }
HAC.mat <- fillCube(pop, specs, perms, K)
This is an out-of-bounds error. The gist of problem is the call
pop_ptr = &(pop(0, sample_one(perms), sample_one(K)));
since
sample_one(perms)
is being placed as an access index where the max length is num_specs. This is seen by how res is defined:
arma::Cube<int> res(perms, num_specs, K);
Thus, moving out perms out of num_specs place should resolve the issue.
// [[Rcpp::export]]
arma::Cube<int> fillCube(const arma::Cube<int>& pop,
const IntegerVector& specs,
int perms,
int K) {
int num_specs = specs.size();
arma::Cube<int> res(perms, num_specs, K);
IntegerVector specs_C = specs - 1;
const int * pop_ptr;
int i, j, k;
for (i = 0; i < K; i++) {
for (k = 0; k < num_specs; k++) {
for (j = 0; j < perms; j++) {
// swapped location
pop_ptr = &(pop(sample_one(perms), 0, sample_one(K)));
// should the middle index be 0?
res(j, k, i) = sample_n_distinct(specs_C, k + 1, pop_ptr);
}
}
}
return res;
}

Cannot evaluate subset expression in Jags

I am sort of new to Jags, and I have been racking my brain trying to see what I am doing wrong with my code, which is giving this error message:
'Cannot evaluate subset expression for precd'.
I am attaching my code which has the data coded in it, as well. I'd appreciate all the help I can get.
nS=number of studies,
r=number of events,
n=sample size,
tau.sq=heterogeneity,
na=number of arms,
sw='correction' for multi-arm trials.
Model<- function(){
for(i in 1:nS) {
w[i,1]<- 0
theta[i,t[i,1]]<- 0
for (k in 1:na[i]) {r[i,t[i,k]] ~ dbin(p[i,t[i,k]],n[i,t[i,k]])}
logit(p[i,t[i,1]])<- u[i]
for (k in 2:na[i]) {
logit(p[i,t[i,k]])<- u[i] + theta[i,t[i,k]]
theta[i,t[i,k]] ~ dnorm(md[i,t[i,k]],precd[i,t[i,k]])
md[i,t[i,k]]<- mean[i,k] + sw[i,k]
w[i,k]<- (theta[i,t[i,k]] - mean[i,k])
sw[i,k]<- sum(w[i,1:k-1])/(k-1)
precd[i,t[i,k]]<- prec*2*(k-1)/k
mean[i,k] <-d[t[i,k]] - d[t[i,1]]
}}
Priors for basic parameters
for (i in 1:nS) {u[i] ~ dnorm(0,.01)}
tau ~ dnorm(0,.01)
prec<- 1/pow(tau,2)
tau.sq<- pow(tau,2)
d[ref] <- 0
for(k in 1:(ref-1)) {d[k] ~ dnorm(0,.01)}
for(k in (ref+1):nT) {d[k] ~ dnorm(0,.01)}
Collection of results from this point
for(i in 1:(nT-1)) {
for (j in (i+1):nT) {
OR[j,i]<- exp(d[j] - d[i])
LOR[j,i]<- d[j] - d[i]}}
for(j in 1:(ref-1)){ORref[j]<- exp(d[j] - d[ref])}
for(j in (ref+1):nT) {ORref[j]<- exp(d[j] - d[ref])}
Ranking of treatments
for(k in 1:nT) {
order[k]<- rank(d[],k)
most.effective[k]<-equals(order[k],1)
for(j in 1:nT) {effectiveness[k,j]<- equals(order[k],j)
cumeffectiveness[k,j]<- sum(effectiveness[k,1:j])}}
for(k in 1:nT) {
SUCRA[k]<- sum(cumeffectiveness[k,1:(nT-1)]) /(nT-1)
}
for(i in 1:nS) {
for (k in 1:na[i]) {
Darm[i,k]<- -2*( r[i,t[i,k]] *log(n[i,t[i,k]]*p[i,t[i,k]]/
r[i,t[i,k]])+(n[i,t[i,k]] - r[i,t[i,k]])*log((n[i,t[i,k]]-
n[i,t[i,k]]* p[i,t[i,k]])/(n[i,t[i,k]]- r[i,t[i,k]])))}
D[i]<- sum(Darm[i,1:na[i]])}
D.bar<- sum(D[])
}
The data are coded below
library(R2jags)
library(mcmc)
setwd("PATH-NAME")
# *******************************************************
# Data are coded below:
# BA -1
# BMS -2 *** REFERENCE
# DCB -3
# EES -4
# PES -5
# ROTA -6
# SES -7
# VBT -8
# *******************************************************
t_RCT = structure(.Data=c(1,6,NA,
1,6,NA,
1,2,NA,
1,2,NA,
2,6,NA,
1,2,NA,
1,8,NA,
1,8,NA,
1,8,NA,
5,8,NA,
5,8,NA,
1,5,7,
1,7,NA,
7,8,NA,
7,8,NA,
5,7,NA,
1,7,NA,
1,7,NA,
4,7,NA,
3,4,NA,
3,4,NA,
1,3,NA,
3,5,NA,
1,3,NA,
1,3,NA,
1,3,NA,
1,3,5,
3,5,NA), .Dim=c(28,3))
na_RCT <- c(2,2,2,2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,2)
r_RCT = structure(.Data=c(45,NA,NA,NA,NA,60,NA,NA,
45,NA,NA,NA,NA,32,NA,NA,
65,55,NA,NA,NA,NA,NA,NA,
5,1,NA,NA,NA,NA,NA,NA,
NA,8,NA,NA,NA,12,NA,NA,
7,4,NA,NA,NA,NA,NA,NA,
51,NA,NA,NA,NA,NA,NA,32,
76,NA,NA,NA,NA,NA,NA,57,
21,NA,NA,NA,NA,NA,NA,11,
NA,NA,NA,NA,19,NA,NA,40,
NA,NA,NA,NA,0,NA,NA,0,
33,NA,NA,NA,19,NA,8,NA,
24,NA,NA,NA,NA,NA,12,NA,
NA,NA,NA,NA,NA,NA,64,39,
NA,NA,NA,NA,NA,NA,3,12,
NA,NA,NA,NA,30,NA,35,NA,
8,NA,NA,NA,NA,NA,8,NA,
3,NA,NA,NA,NA,NA,0,NA,
NA,NA,NA,2,NA,NA,1,NA,
NA,NA,6,1,NA,NA,NA,NA,
NA,NA,20,7,NA,NA,NA,NA,
21,NA,5,NA,NA,NA,NA,NA,
NA,NA,4,NA,10,NA,NA,NA,
10,NA,1,NA,NA,NA,NA,NA,
14,NA,11,NA,NA,NA,NA,NA,
22,NA,4,NA,NA,NA,NA,NA,
56,NA,30,NA,17,NA,NA,NA,
NA,NA,16,NA,11,NA,NA,NA), .Dim=c(28,8))
n_RCT = structure(.Data=c(146,1,1,1,1,152,1,1,
100,1,1,1,1,100,1,1,
226,224,1,1,1,1,1,1,
29,29,1,1,1,1,1,1,
1,25,1,1,1,30,1,1,
20,20,1,1,1,1,1,1,
121,1,1,1,1,1,1,131,
232,1,1,1,1,1,1,244,
78,1,1,1,1,1,1,78,
1,1,1,1,195,1,1,201,
1,1,1,1,20,1,1,17,
100,1,1,1,100,1,100,1,
74,1,1,1,1,1,76,1,
1,1,1,1,1,1,259,125,
1,1,1,1,1,1,65,64,
1,1,1,1,225,1,225,1,
61,1,1,1,1,1,136,1,
48,1,1,1,1,1,48,1,
1,1,1,34,1,1,32,1,
1,1,95,94,1,1,1,1,
1,1,154,155,1,1,1,1,
54,1,54,1,1,1,1,1,
1,1,66,1,65,1,1,1,
25,1,25,1,1,1,1,1,
38,1,72,1,1,1,1,1,
72,1,138,1,1,1,1,1,
134,1,137,1,131,1,1,1,
1,1,109,1,106,1,1,1), .Dim=c(28,8))
dataR <- list(nS=28, nT=8, ref=2, t=t_RCT, na=na_RCT, r=r_RCT, n=n_RCT)
initR<-list(list(u=rep(0,28), tau=0.5),list(u=rep(0.2,28), tau=0.7))
Params<-c("u","OR")
ModelFit<-jags(data=dataR, inits=initR, Params, n.chains=2,
n.iter=5000, n.burnin=2500, model.file=Model, n.thin=5)
Result<-ModelFit$BUGSoutput$summary
write.table(round(Result,digits=3),
"Results.txt",row.names=T,col.names=T)
DIC<- ModelFit$BUGSoutput$DIC
write.table(round(DIC,digits=3), "Dic.txt",row.names=T,col.names=T)
postscript("PostDen.ps")
ModelFit.mcmc <- as.mcmc(ModelFit)
densplot(ModelFit.mcmc)
dev.off()
You are subsetting your data with the object t, which within your R environment, is t_RCT. This object has NA values within it. So, for example, if i = 1 and k = 3 then you are trying to subset the object p in JAGS as:
p[i,t[i,k]] = p[1,NA]
You cannot subset like this, as rows and columns must be indexed as an integer.

Is possible to define a random limit for a loop in JAGS?

I am trying to implement a Weibull proportional hazards model with a cure fraction following the approach outlined by Hui, Ibrahim and Sinha (1999) - A New Bayesian Model for Survival Data with a Surviving Fraction. However, I am not sure if it is possible to define a random limit for a looping in JAGS.
library(R2OpenBUGS)
library(rjags)
set.seed(1234)
censored <- c(1, 1)
time_mod <- c(NA, NA)
time_cens <- c(5, 7)
tau <- 4
design_matrix <- rbind(c(1, 0, 0, 0), c(1, 0.2, 0.2, 0.04))
jfun <- function() {
for(i in 1:nobs) {
censored[i] ~ dinterval(time_mod[i], time_cens[i])
time_mod[i] <- ifelse(N[i] == 0, tau, min(Z))
for (k in 1:N[i]){
Z[k] ~ dweib(1, 1)
}
N[i] ~ dpois(fc[i])
fc[i] <- exp(inprod(design_matrix[i, ], beta))
}
beta[1] ~ dnorm(0, 10)
beta[2] ~ dnorm(0, 10)
beta[3] ~ dnorm(0, 10)
beta[4] ~ dnorm(0, 10)
}
inits <- function() {
time_init <- rep(NA, length(time_mod))
time_init[which(!status)] <- time_cens[which(!status)] + 1
out <- list(beta = rnorm(4, 0, 10),
time_mod = time_init,
N = rpois(length(time_mod), 5))
return(out)
}
data_base <- list('time_mod' = time_mod, 'time_cens' = time_cens,
'censored' = censored, 'design_matrix' = design_matrix,
'tau' = tau,
'nobs' = length(time_cens[!is.na(time_cens)]))
tc1 <- textConnection("jmod", "w")
write.model(jfun, tc1)
close(tc1)
# Calling JAGS
tc2 <- textConnection(jmod)
j <- jags.model(tc2,
data = data_base,
inits = inits(),
n.chains = 1,
n.adapt = 1000)
I observed the below error:
Error in jags.model(tc2, data = data_base, inits = inits(), n.chains = 1, :
RUNTIME ERROR:
Compilation error on line 6.
Unknown variable N
Either supply values for this variable with the data
or define it on the left hand side of a relation.
I am not entirely certain, but I am pretty sure that you cannot declare a random number of nodes in BUGS in general, so it would not be a specific JAGS' quirk.
Nevertheless, you can get a way around that.
Since BUGS is a declarative language instead of a procedural one, it is enough to declare an arbitrary but deterministic number of nodes (let's say "large enough") and then associate only a random number of them with a distribution and with observed data, leaving the remaining nodes deterministic.
Once you have observed the maximum value of N[i] (let's say N.max), you can pass it as a parameter to JAGS and then change this code of yours:
for (k in 1:N[i]){
Z[k] ~ dweib(1, 1)
}
into this:
for (k in 1:N.max){
if (k <= N[i]){
Z[k] ~ dweib(1, 1)
} else {
Z[k] <- 0
}
}
I hope this will do the trick in your case. So please give feedback latter about it.
Needless to say, if you have some non-zero, observed data associated to a deterministic Z[k], then all hell breaks loose inside Jags...

Generate all compositions of an integer into k parts

I can't figure out how to generate all compositions (http://en.wikipedia.org/wiki/Composition_%28number_theory%29) of an integer N into K parts, but only doing it one at a time. That is, I need a function that given the previous composition generated, returns the next one in the sequence. The reason is that memory is limited for my application. This would be much easier if I could use Python and its generator functionality, but I'm stuck with C++.
This is similar to Next Composition of n into k parts - does anyone have a working algorithm?
Any assistance would be greatly appreciated.
Preliminary remarks
First start from the observation that [1,1,...,1,n-k+1] is the first composition (in lexicographic order) of n over k parts, and [n-k+1,1,1,...,1] is the last one.
Now consider an exemple: the composition [2,4,3,1,1], here n = 11 and k=5. Which is the next one in lexicographic order? Obviously the rightmost part to be incremented is 4, because [3,1,1] is the last composition of 5 over 3 parts.
4 is at the left of 3, the rightmost part different from 1.
So turn 4 into 5, and replace [3,1,1] by [1,1,2], the first composition of the remainder (3+1+1)-1 , giving [2,5,1,1,2]
Generation program (in C)
The following C program shows how to compute such compositions on demand in lexicographic order
#include <stdio.h>
#include <stdbool.h>
bool get_first_composition(int n, int k, int composition[k])
{
if (n < k) {
return false;
}
for (int i = 0; i < k - 1; i++) {
composition[i] = 1;
}
composition[k - 1] = n - k + 1;
return true;
}
bool get_next_composition(int n, int k, int composition[k])
{
if (composition[0] == n - k + 1) {
return false;
}
// there'a an i with composition[i] > 1, and it is not 0.
// find the last one
int last = k - 1;
while (composition[last] == 1) {
last--;
}
// turn a b ... y z 1 1 ... 1
// ^ last
// into a b ... (y+1) 1 1 1 ... (z-1)
// be careful, there may be no 1's at the end
int z = composition[last];
composition[last - 1] += 1;
composition[last] = 1;
composition[k - 1] = z - 1;
return true;
}
void display_composition(int k, int composition[k])
{
char *separator = "[";
for (int i = 0; i < k; i++) {
printf("%s%d", separator, composition[i]);
separator = ",";
}
printf("]\n");
}
void display_all_compositions(int n, int k)
{
int composition[k]; // VLA. Please don't use silly values for k
for (bool exists = get_first_composition(n, k, composition);
exists;
exists = get_next_composition(n, k, composition)) {
display_composition(k, composition);
}
}
int main()
{
display_all_compositions(5, 3);
}
Results
[1,1,3]
[1,2,2]
[1,3,1]
[2,1,2]
[2,2,1]
[3,1,1]
Weak compositions
A similar algorithm works for weak compositions (where 0 is allowed).
bool get_first_weak_composition(int n, int k, int composition[k])
{
if (n < k) {
return false;
}
for (int i = 0; i < k - 1; i++) {
composition[i] = 0;
}
composition[k - 1] = n;
return true;
}
bool get_next_weak_composition(int n, int k, int composition[k])
{
if (composition[0] == n) {
return false;
}
// there'a an i with composition[i] > 0, and it is not 0.
// find the last one
int last = k - 1;
while (composition[last] == 0) {
last--;
}
// turn a b ... y z 0 0 ... 0
// ^ last
// into a b ... (y+1) 0 0 0 ... (z-1)
// be careful, there may be no 0's at the end
int z = composition[last];
composition[last - 1] += 1;
composition[last] = 0;
composition[k - 1] = z - 1;
return true;
}
Results for n=5 k=3
[0,0,5]
[0,1,4]
[0,2,3]
[0,3,2]
[0,4,1]
[0,5,0]
[1,0,4]
[1,1,3]
[1,2,2]
[1,3,1]
[1,4,0]
[2,0,3]
[2,1,2]
[2,2,1]
[2,3,0]
[3,0,2]
[3,1,1]
[3,2,0]
[4,0,1]
[4,1,0]
[5,0,0]
Similar algorithms can be written for compositions of n into k parts greater than some fixed value.
You could try something like this:
start with the array [1,1,...,1,N-k+1] of (K-1) ones and 1 entry with the remainder. The next composition can be created by incrementing the (K-1)th element and decreasing the last element. Do this trick as long as the last element is bigger than the second to last.
When the last element becomes smaller, increment the (K-2)th element, set the (K-1)th element to the same value and set the last element to the remainder again. Repeat the process and apply the same principle for the other elements when necessary.
You end up with a constantly sorted array that avoids duplicate compositions

Resources