content
stringlengths
0
14.9M
filename
stringlengths
44
136
BayesClassification = function(Data,Means,SDs,Weights,IsLogDistribution=Means*0, ClassLabels=c(1:length(Means))){ # Cls = BayesClassification(Data,M,S,W) # [Cls, DecisonBoundaries] = BayesClassification(Data,M,S,W,IsLogDistribution,ClassLabels) # Bayes Klassifikation den Daten zuordnen # INPUT # Data(1:n,1:d) Data # Means(1:L),SDs(1:L),Weights(1:L) parameters of the Gaussians/LogNormals # # OPTIONAL # IsLogDistribution(1:L) ==1 if distribution(i) is a LogNormal, default Zeros # # OUTPUT # Cls # DecisonBoundaries(1:L-1) DecisionBoundaries = BayesDecisionBoundaries(Means,SDs,Weights,IsLogDistribution) Cls = ClassifyByDecisionBoundaries(Data,DecisionBoundaries,ClassLabels) return(list(Cls=Cls, DecisionBoundaries=DecisionBoundaries)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/BayesClassification.R
BayesDecisionBoundaries <- function(Means, SDs, Weights, IsLogDistribution, MinData, MaxData, Ycoor = F){ # DecisionBoundaries = BayesDecisionBoundaries(Means,SDs,Weights,IsLogDistribution); # find the intersections of Gaussians or LogNormals # # INPUT # Means(1:L),SDs(1:L),Weights(1:L) parameters of the Gaussians/LogNormals # OPTIONAL # IsLogDistribution(1:L) ==1 if distribution(i) is a LogNormal, default zeros # MinData # MaxData # Ycoor Bool, if TRUE instead of vector of DecisionBoundaries # list of DecisionBoundaries and DBY is returned # OUTPUT # DecisionBoundaries(1:L-1) Bayes decision boundaries # Author: 05/2015 RG # 1.Editor: MT 08/2015 if(missing(IsLogDistribution)){ IsLogDistribution = rep(FALSE,length(Means)) } if(missing(MinData)){ MinData=(Means-3*SDs)[which.min(Means-3*SDs)] } if(missing(MaxData)){ MaxData=(Means+3*SDs)[which.max(Means+3*SDs)] } L = length(Means) # number of Gaussians if(length(IsLogDistribution)!=L){ warning(paste('Length of Means',L,'does not equal length of IsLogDistribution',length(IsLogDistribution),'Generating new IsLogDistribution')) IsLogDistribution = rep(FALSE,L) } # sortieren nach Means Sind = order(Means) Means = sort(na.last=T,Means) SDs = SDs[Sind] Weights = Weights[Sind] for(i in 1:length(Means)){ # If there are equal means, order them regarding their SD EqIdx = which(Means == Means[i]) if(length(EqIdx) > 1){ NewInternalOrder = order(SDs[EqIdx]) SDs[EqIdx] = SDs[EqIdx][NewInternalOrder] Weights[EqIdx] = Weights[EqIdx][NewInternalOrder] } } IsLogDistribution = IsLogDistribution[Sind] L1 = L-1 DecisionBoundaries <- Means[1:L1] # init DBY = DecisionBoundaries*0 # init # now intersect 2 Gauss for(i in 1:L1){ i1 = i+1 Decision = Intersect2Mixtures(Means[i], SDs[i], Weights[i], Means[i1], SDs[i1], Weights[i1], IsLogDistribution[i:i1]) DecisionBoundaries[i] = Decision$CutX DBY[i] = Decision$CutY DecisionBoundaries[i] = min(MaxData,DecisionBoundaries[i]); DecisionBoundaries[i] = max(MinData,DecisionBoundaries[i]); } if(Ycoor){ return(list(DecisionBoundaries = DecisionBoundaries,DBY=DBY)) }else{ return(DecisionBoundaries = DecisionBoundaries) } }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/BayesDecisionBoundaries.R
BayesFor2GMM <- function(Data, Means, SDs, Weights, IsLogDistribution = Means*0, Ind1 = c(1:floor(length(Means)/2)), Ind2 = c((floor(length(Means)/2)+1):length(Means)), PlotIt = 0, CorrectBorders = 0){ # die Berechnung der Posteriors wobei das gegeben GMM als zwei Gruppen Ind1 und Ind2 aufgefasst werden. # INPUT # Data(1:N) vector of data, may contain NaN, where lay the kernels? # Means(1:C),SDs(1:C),Weights(1:C) parameters of the Gaussians # assume for now Means is sorted; # OPTIONAL # IsLogDistribution(1:C) oder 0, gibt an ob die jeweilige Verteilung eine Lognormalverteilung ist,(default ==0*(1:C)) # Ind1, Ind2 indices from (1:C) such that [Means(Ind1),SDs(Ind1) ,Weights(Ind1) ]is one mixture, [Means(Ind2),SDs(Ind2) ,Weights(Ind2) ] the second mixture # default Ind1= 1:C/2, Ind2= C/2+1:C; # PlotIt ==1 Verteilungen und Posteriors werden gezeichnet (default ==0); # CorrectBorders ==1 Daten an den Grenzen werden den Randverteilungen zugeordnet # (default ==0) d.h. ganz gewoehnlicher Bayes mit allen seinen Problemen # OUTPUT # Posteriors(1:N,1:C) Vektor der Posteriors korrespondierend zu Data # NormalizationFactor(1:N) Nenner des Bayes Theorems korrespondierend zu Data # sort Means and equal SDs,Weights,... # Author: reimplemented from Matlab, ALU # 1. Editor: MT 2014 AnzMixtures <- length(Means) Ind1=as.vector(Ind1) Ind2=as.vector(Ind2) Kernels <- unique(Data) AnzKernels <- length(Kernels) ##Unique liefer keine Sortierten Indizies: #MT: Wird in matlab zwar berechnet, aber nie benutzt # z <- order(Means) # returns a permutation which rearranges its first argument into descending order, # Means <- Means[z] # SDs <- SDs[z] # Weights <- Weights[z] # IsLogDistribution <- IsLogDistribution[z] # ind <- c() # for(i in Ind1){ # ind <- c(ind,grep(i, z)) # } # Ind1 <- sort(ind) # # ind <- c() # for(i in Ind2){ # ind <- c(ind,grep(i, z)) # } # Ind2 <- sort(ind) PDataGivenClass <- matrix(0,AnzKernels,AnzMixtures) for( i in 1:AnzMixtures){ if(IsLogDistribution[i] ==1){ # Log Normal PDataGivenClass[,i] <- dlnorm(Kernels,Means[i],SDs[i]) }else{ PDataGivenClass[,i] <- dnorm(Kernels,Means[i],SDs[i]) } } NormalizationFactor <- PDataGivenClass %*% Weights # Gewichtete Summe der Priors Pmax <- max(NormalizationFactor) ZeroIndv <- which(NormalizationFactor==0, arr.ind = TRUE) ZeroInd <- ZeroIndv[,2] if(length(ZeroInd > 0)){ NormalizationFactor[ZeroInd] <- 10^(-7) } Xones <- Kernels * 0 + 1 PClassGivenData <- matrix(0,AnzKernels,2) #MT: If-Abfrage Erg?nzung: if(length(Weights[Ind1])>1){ PClassGivenData[,1] <- PDataGivenClass[,Ind1] %*% Weights[Ind1] }else{ PClassGivenData[,1] <- PDataGivenClass[,Ind1] * Weights[Ind1] } if(length(Weights[Ind2])>1){ PClassGivenData[,2] <- PDataGivenClass[,Ind2] %*% Weights[Ind2] }else{ PClassGivenData[,2] <- PDataGivenClass[,Ind2] * Weights[Ind2] } PClassGivenData <- PClassGivenData / (NormalizationFactor %*% matrix(1,1,2)) Posteriors <- PClassGivenData if(CorrectBorders == 1 & (sum(IsLogDistribution) == 0)){ # randkorrekturen anbringen # Daten kleiner kleinstem Modus werden diesem zugeschlagen KleinsterModus <- min(Means) SmallModInd <- which.min(Means) LowerInd <- which(Kernels < KleinsterModus) PClassGivenData[LowerInd,1] <- 1 PClassGivenData[LowerInd,2] <- 0 # Daten groesser groesstem Modus werden diesem zugeschlagen GroessterModus <- max(Means) BigModInd <- which.max(Means) HigherInd <- which(Kernels > GroessterModus) PClassGivenData[HigherInd,1] <- 0 PClassGivenData[HigherInd,2] <- 1 } #browser() if (PlotIt == 1){ if (!requireNamespace('ggplot2', quietly = TRUE)) { message( 'ggplot2 package is needed for plotting. Please install the package which is defined in "Suggests".') } else { def.par <- par(no.readonly = TRUE) # save default, for resetting... on.exit(par(def.par)) print( 'BayesFor2GMM(): Plot is in development') gPlot <- ggplot2::ggplot() for (i in 1:AnzMixtures){ df = data.frame(x = Kernels, y=PDataGivenClass[,i]*Weights[i]/Pmax) gPlot = gPlot + ggplot2::geom_line(data = df, ggplot2::aes_string(x="x",y="y"), color="blue") } df = data.frame(x = Kernels, y=Posteriors[,1]) gPlot = gPlot + ggplot2::geom_line(data = df, ggplot2::aes_string(x="x",y="y"), color="green") df = data.frame(x = Kernels, y=Posteriors[,2]) gPlot = gPlot + ggplot2::geom_line(data = df, ggplot2::aes_string(x="x",y="y"), color="red") # hold on; plot(Kernels,PDataGivenClass(:,i)*Weights(i)/Pmax,'b-');hold off; # end;% i = 1:AnzMixtures # hold on; plot(Kernels,Posteriors(:,1),'g-');hold off; # hold on; plot(Kernels,Posteriors(:,2),'r-');hold off; # xlabel('Data');ylabel('ro/gn=Bayes Entscheidung, bl= GMM'); # title(['Bayes fuer zwei GMM , Ind1 = ' num2str(Ind1')]); # end; % if PlotIt ==1; print(gPlot) } } # jetzt zurueck auf Daten UNsortInd <- match(Data, Kernels) # Data == Kernels[UNsortInd] Posteriors <- PClassGivenData[UNsortInd,] NormalizationFactor <- NormalizationFactor[UNsortInd] res <- list(Posteriors = Posteriors, NormalizationFactor = NormalizationFactor) return(res) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/BayesFor2GMM.R
CDFMixtures <- function(Kernels,Means,SDs,Weights = (Means*0)+1,IsLogDistribution = Means*0){ # [CDFGaussMixture,CDFSingleGaussian] = CDFMixtures(Kernels,Means,SDs,Weights,IsLogDistribution); # gibt die cdf (cumulierte Dichte) einer aus Gauss bzw. LogGauss zusammengesetzten GMM Verteilung zuruck. # # INPUT # Kernels(1:N) at these locations N(Means,SDs)*Weights is used for cdf calcuation # NOTE: Kernels are usually (but not necessarily) sorted and unique # Means(1:L,1) Means of Gaussians, L == Number of Gaussians # SDs(1:L,1) estimated Gaussian Kernels = standard deviations # # OPTIONAL # Weights(1:L,1) relative number of points in Gaussians (prior probabilities): # sum(Weights) ==1, default weight is 1/L # IsLogDistribution(1:L,1) oder 0 if IsLogDistribution(i)==1, then mixture is lognormal # default == 0*(1:L)' # # OUTPUT # CDFGaussMixture(1:N,1) cdf of Sum of SingleGaussians at Kernels # CDFSingleGaussian(1:N,1:L) cdf of mixtures at Kernels # Autor: RG 06/15 #Weights = Weights/sum(Weights) # Gleichgewichtung if(length(IsLogDistribution) == 1 && IsLogDistribution == 0) IsLogDistribution = Means*0 # default Gauss AnzGaussians=length(Means) CDFSingleGaussian = matrix(0,length(Kernels),AnzGaussians) CDFGaussMixture =CDFSingleGaussian[,1] for(g in 1:AnzGaussians){ if(IsLogDistribution[g] == 1){ # LogNormal sig = sqrt(log(SDs[g]*SDs[g]/(Means[g]*Means[g])+1)) mu = log(abs(Means[g]))-0.5*sig*sig if(Means[g] > 0) CDFSingleGaussian[,g] = plnorm(Kernels,mu,sig)*Weights[g] else CDFSingleGaussian[,g] = (1 -plnorm(-Kernels,mu,sig))*Weights[g] } else{ # Gaussian CDFSingleGaussian[,g] = pnorm(Kernels,Means[g],SDs[g])*Weights[g] # Gaussian } CDFGaussMixture = CDFGaussMixture + CDFSingleGaussian[,g] } return(list(CDFGaussMixture = CDFGaussMixture, CDFSingleGaussian = CDFSingleGaussian)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/CDFMixtures.R
Chi2testMixtures <- function(Data,Means,SDs,Weights,IsLogDistribution = Means*0,PlotIt = 0,UpperLimit=max(Data,na.rm=TRUE),VarName='Data',NoRepetitions){ # V=Chi2testMixtures(Data,Means,SDs,Weights,IsLogDistribution,PlotIt,UpperLimit) # V$Pvalue V$BinCenters V$ObsNrInBin V$ExpectedNrInBin # chi-square test of Data vs a given Gauss Mixture Model # komfortabler Plot mit allen Mess und Fehlerwerten sowie der cdf fuer die entsprechende Chi-Quadrat funktion # # INPUT # Data(1:N) data points # Means(1:L,1) Means of Gaussians, L == Number of Gaussians # SDs(1:L,1) estimated Gaussian Kernels = standard deviations # Weights(1:L,1) relative number of points in Gaussians (prior probabilities): # # OPTIONAL # IsLogDistribution(1:L,1) oder 0 if IsLogDistribution(i)==1, then mixture is lognormal # default == 0*(1:L)' # PlotIt do a Plot of the compared cdf's and the KS-test distribution (Diff) # UpperLimit test only for Data <= UpperLimit, Default = max(Data) i.e all Data. # VarName Variable Name for Plots # NoRepetitions Should the Chi2 Distribution be sampled with number of repetitions (instead of looked up in a table for =1) # OUTP # Pvalue Pvalue of a suiting chi-square , Pvalue ==0 if Pvalue <0.001 # BinCenters bin centers # ObsNrInBin nr of data in bin # ExpectedNrInBin nr of data that should be in bin according to GMM # Chi2Value the TestStatistic i.e.: # sum((ObsNrInBin(Ind)-ExpectedNrInBin(Ind)).^2./ExpectedNrInBin(Ind)) with # Ind = find(ExpectedNrInBin>=10); # uses histopt_hlp,CDFMixtures,randomLogMix_hlp,PlotMixtures matlab's histc(..) # Autor: RG 06/15 #1.Editor: MT 08/2015 plotten, Fehlerabfang bei kleinen Datensaetzen #2.Editor: FL 12/16 moeglichkeit, chi2 dist. direkt in tabelle nachzuschlagen eingefuegt. #3.Editor: MT 03/19 deutliche effizienzsteigerung eingepflegt. par.defaults <- par(no.readonly=TRUE) if(length(IsLogDistribution) == 1 && IsLogDistribution == 0) IsLogDistribution = Means*0 NumberOfData=length(Data) #s.Zeile 128, Zeile 110 DataSmall=80 #Abwann ist ein Datensatz klein ##################################################### # mit histopt-Algorithmus die Bins bestimmen, anzahl= OptimalNrOfBins histopt_hlp <- function(Data){ # histopt(Data); # Histogram optimaler Binanzahl. Bins besitzen alle die gleiche Groess?e. # # INPUT # Data[d,1] Vektor der zu zeichneten Variable # OUTPUT # nrOfBins Anzahl der Bins # nrInBins[1,d] Startpunkt jedes Bins als Vektor # binMids Mitte des Bins ?? # Letzte Ergaenzung MT, Autor unbekannt # Ergaenzung RG, Autor unbekannt Data[is.infinite(Data)] = NA #MT: Korrektur, bereinigung von Inf optNrOfBins<-DataVisualizations::OptimalNoBins(Data) optNrOfBins = min(100,optNrOfBins) #RG: Aus Matlab uebernommen # temp<-hist(Data,breaks=optNrOfBins) #print(optNrOfBins[1]) #temp <- hist(Data, breaks=optNrOfBins[1], col="blue", border="light blue", main=Title) minData <- min(Data,na.rm = TRUE) maxData <- max(Data,na.rm = TRUE) i <- maxData-minData optBreaks <- seq(minData, maxData, i/optNrOfBins) # bins haben alle die gleiche groesse temp <- hist(Data, breaks=optBreaks, plot=FALSE) #box(); Breaks <- temp$breaks nB <- length(Breaks) y <- temp$counts; invisible(list(nrOfBins=length(Breaks)-1, nrInBins=y, binMids=temp$mids)) } ##################################################### ho <-histopt_hlp(Data) OptimalNrOfBins <- ho$nrOfBins ObsNrInBin <- ho$nrInBins BinCenters <- ho$binMids # BinLimits errechnen und mit histc die ObsNrInBin nachrechnen; binwidth = diff(BinCenters) # differences between adjacent BinCenters binwidth = c(binwidth,binwidth[length(binwidth)]) xx = cbind(BinCenters-binwidth/2,BinCenters+binwidth/2) xx[1] = min(xx[1],which.min(Data)) xx[length(xx)] = max(xx[length(xx)],which.max(Data)) # in xx[,1] stehen die unteren Grenzen der Bins, in xx(:,2) die oberen Grenzen # Shift bins so the interval is ( ] instead of [ ). xx = Re(xx) #xx =xx +eps(xx); #####eps! BinLimits = c(xx[1,1],xx[,2]) # dies sind jetzt die Bin Grenzen #print(BinLimits) # # Nachrechnen: fuer diese Bin Grenzen mit histc schauen wieviele in die jeweilgen bins fallen # nn = histc(full(real(Data)),BinLimits); % matlab' schnelle counting Funktion benutzen # # Combine last bin with next to last bin # nn(end-1) = nn(end-1)+nn(end); # nn = nn(1:end-1); # [nn,ObsNrInBin] # AllOK = sum(nn-ObsNrInBin)==0 % wenn die mit histopt gerechnete anz der mit histc ger. uebeeinstimmt # jetzt die erwartete Anzahl berechnen CDFGaussMixture = CDFMixtures(BinLimits,Means,SDs,Weights,IsLogDistribution)$CDFGaussMixture # cdf(GMM) AnzData =length(Data) ExpectedNrInBinCDF = CDFGaussMixture*AnzData ExpectedNrInBin = diff(ExpectedNrInBinCDF) # jetzt den Vergleich Anstellen AnzDiff = ObsNrInBin-ExpectedNrInBin Chi2Diffs = AnzDiff*0 # init if(NumberOfData<DataSmall){ Ind = which(ExpectedNrInBin>=2, arr.ind=TRUE) #Bei Kleinen Datensetzen schranke runterstellen warning(paste('Chi2testMixtures(): Datasize',NumberOfData,'is too small. Pvalue could be misleading')) }else{ Ind = which(ExpectedNrInBin>=10, arr.ind=TRUE) # ObsNrInBin mindestens 10 sonst gelten die Werte als identisch => Diff ==0 } Chi2Diffs[Ind] =((ObsNrInBin[Ind]-ExpectedNrInBin[Ind])^2)/ExpectedNrInBin[Ind] Chi2Value = sum(Chi2Diffs) # dies soll angeblich Chi2 Verteilt sein # Die Chi2 Funktion via Monte-Carlo errechnen #AnzData =length(Data); MonteCarloSampling=TRUE AnzBins = length(BinCenters); if(missing(NoRepetitions)){ NoRepetitions = 1000; if(AnzBins<100) NoRepetitions = 2000 if(AnzBins<10) NoRepetitions = 5000 }else{ if(as.numeric(NoRepetitions)<1) NoRepetitions=1 } if(NoRepetitions==1){ MonteCarloSampling=FALSE } if(MonteCarloSampling){ #MT 2019/03: das waere die schnelle version, grad nur keine zeit das anzupassen # nB1 <- AnzBins # delt <- 3/nB1 # fuzz <- 1e-7 * c(-delt, rep.int(delt, nB1)) # breaks <- seq(0, 3, by = delt) + fuzz RandGMMDataDiff = matrix(0,AnzBins,NoRepetitions) #zukeunftig with parSapply Ri=sapply(1:NoRepetitions, function(i,...) return(RandomLogGMM(...)),Means,SDs,Weights,IsLogDistribution,AnzData) #zukeunftig with parApply RandNrInBini=apply(Ri,MARGIN = 2, function(R,BinLimits) hist(Re(abs(R)),c(0,BinLimits,max(abs(R))),plot=F)$counts,BinLimits) #MT 2019/03: das waere die schnelle version, grad nur keine zeit das anzupassen #noch in apply zu integrieren # nB1 <- 99 # delt <- 3/nB1 # fuzz <- 1e-7 * c(-delt, rep.int(delt, nB1)) # breaks <- seq(0, 3, by = delt) + fuzz #RandNrInBin=.Call(graphics:::C_BinCount, x, breaks, TRUE, TRUE) for(i in 1:NoRepetitions){ #R = Ri[,i]#RandomLogGMM(Means,SDs,Weights,IsLogDistribution,AnzData) #BinLimits = c(0,BinLimits,max(abs(R))) #RandNrInBin = hist(Re(abs(R)),c(0,BinLimits,max(abs(R))),plot=F)$counts # R's schnelle Funktion benutzen RandNrInBin=as.vector(RandNrInBini[,i]) #BinLimits = BinLimits[2:(length(BinLimits)-1)] RandNrInBin[2] = RandNrInBin[1]+RandNrInBin[2] RandNrInBin[length(RandNrInBin)-1] = RandNrInBin[length(RandNrInBin)-1]+RandNrInBin[length(RandNrInBin)] RandNrInBin = RandNrInBin[3:length(RandNrInBin)-1] AnzDiffRand = RandNrInBin-ExpectedNrInBin RandChi2Diffs = AnzDiffRand*0; # init if(NumberOfData<DataSmall){ Ind = which(ExpectedNrInBin>=2, arr.ind=TRUE) #Bei Kleinen Datensetzen schranke runterstellen }else{ Ind = which(ExpectedNrInBin>=10, arr.ind=TRUE) # ObsNrInBin mindestens 10 sonst gelten die Werte als identisch => Diff ==0 } RandChi2Diffs[Ind] = ( (RandNrInBin[Ind]-ExpectedNrInBin[Ind])^2)/ExpectedNrInBin[Ind] RandGMMDataDiff[,i] = RandChi2Diffs; } AllDiff = colSums(RandGMMDataDiff); # die Verteilung aller Differenzen #[AllDiffCDF,AllDiffKernels] = ecdfUnique(AllDiff); dummy <- ecdf(AllDiff) # cdf(Diff) } else{ dummy <- ecdf(rchisq(2000,length(BinCenters)-1)) # cdf(Diff) } AllDiffCDF <- c(0,get("y", envir = environment(dummy))) AllDiffKernels <- c(knots(dummy)[1],knots(dummy))#CDFuniq # upper Limit Berucksichtigen ClipInd = which(BinCenters<UpperLimit,arr.ind=TRUE) BinCenters = BinCenters[ClipInd] Chi2Value = sum(Chi2Diffs[ClipInd]) ExpectedNrInBin = ExpectedNrInBin[ClipInd] ObsNrInBin = ObsNrInBin[ClipInd] Chi2Diffs = Chi2Diffs[ClipInd] # CHi2statistik berechnen if (Chi2Value-AllDiffKernels[length(AllDiffKernels)] >1){ # Summe der Abweichungen liegt zu weit rechts Ch2cdfValue = 1; } else{ #durch interpolation den wert bestimmen #matlab: #Ch2cdfValue = interp1([0;AllDiffKernels],[0;AllDiffCDF],Chi2Value, 'linear'); #den MaxDiff in cdf(Diff) lokalisieren Ch2cdfValue = approx(rbind(0,unname(AllDiffKernels)),rbind(0,unname(AllDiffCDF)),Chi2Value, 'linear')$y; # den MaxDiff in cdf(Diff) lokalisieren } # if (Chi2Value-AllDiffKernels(end)) >1 # der wert liegt zu weit rechts Pvalue = Ch2cdfValue # P- value fuer Chi sqare -test ausrechnen Pvalue = round(Pvalue,5) # runden auf gueltige stellen if(PlotIt ==1){ def.par <- par(no.readonly = TRUE) # save default, for resetting... on.exit(par(def.par)) par(mfrow = c(2,2)) #subplot(2,2,1) xlim=c(min(Data,na.rm = TRUE),max(Data,na.rm = TRUE)) ylim=c(min(min(ObsNrInBin,na.rm = TRUE),min(ExpectedNrInBin,na.rm = TRUE)),max(max(ObsNrInBin,na.rm = TRUE),max(ExpectedNrInBin,na.rm = TRUE))) plot(BinCenters,ObsNrInBin,type='h',xlim=xlim,ylim=ylim,xlab="",ylab="",axes=FALSE) axis(1,xlim=xlim,col="black",las=1) #x-Achse axis(2,ylim=ylim,col="black",las=1) #y-Achse par(new = TRUE) for (i in 1:length(BinLimits)){ points(c(BinLimits[i],BinLimits[i]),ylim,type='l',lwd=1,col='magenta'); par(new = TRUE); } #hold on ; par(new=TRUE) plot(BinCenters,ExpectedNrInBin,col='red',xlab="",ylab="",xlim=xlim,ylim=ylim,axes=FALSE) title(ylab=paste0('No. ',VarName,' in bin')) title(xlab=paste0(VarName,' and bins')) title('bar = observed, red= expected(GMM)') #axis tight; #ax=axis; #subplot(2,2,2) # hier die fraglichen PDFs zeichnen #xlim=c(min(abs(Data),na.rm=TRUE),max(abs(Data),na.rm=TRUE)) plot(BinCenters,Chi2Diffs,col='red',xlab="",ylab="",type='b',xlim=xlim) grid() #ax = axis; #yaxis(0,max(2,ax(4))); for (i in 1:length(BinLimits)){ points(c(BinLimits[i],BinLimits[i]),ylim,type='l',lwd=1,col='magenta') par(new = TRUE); } #xaxis(min(BinLimits),max(BinLimits)); title(xlab=paste0(VarName,', differences in bins')) title('squared bin differences : C2V=(Exp-Obs)^2/Exp') title(ylab='C2V'); #subplot(2,2,3) Ylimits=c(0,1) plot(AllDiffKernels,AllDiffCDF,ylim=Ylimits,xlab="",ylab="") abline(v=Chi2Value,col='green') grid() abline(h=Ch2cdfValue,col='green'); title(ylab=c('cdf(chi2)')) title(xlab=c('bl =Chi2;gn = sum(C2V) = ', paste(Chi2Value))) if (Pvalue==0){ title(c('cdf(Chi2), Pvalue< 10e-4' )); }else{ title(c('cdf(Chi2), Pvalue=', paste(1-Pvalue) )) } #subplot(2,2,4) Xlimits = c(min(Data,na.rm=TRUE),max(Data,na.rm=TRUE)) #PDEplot(Data,xlim=Xlimits,ylim=Ylimits,defaultAxes=FALSE) paretoRadius<-DataVisualizations::ParetoRadius(Data) pdeVal <- DataVisualizations::ParetoDensityEstimation(Data,paretoRadius,NULL) paretoDensity <- pdeVal$paretoDensity Ylimits = c(min(paretoDensity,na.rm=TRUE),max(paretoDensity,na.rm=TRUE)) plot(pdeVal$kernels,paretoDensity,typ='l',col="blue",xlim = Xlimits, ylim = Ylimits, xlab = VarName, ylab = '',axes=FALSE,xaxs='i',yaxs='i') title(ylab='PDE') #hold on; par(new=TRUE) PlotMixtures(Data,Means,SDs,Weights=Weights,IsLogDistribution=IsLogDistribution,xlim=Xlimits,ylim=Ylimits, axes=T,xlab="",ylab="",SingleGausses=T,xaxs='i',yaxs='i',MixtureColor='black', SingleColor = 'green') for (i in 1:length(BinLimits)){ points(c(BinLimits[i],BinLimits[i]),ylim,type='l',lwd=1,col='magenta'); par(new = TRUE); } #xaxis(min(BinLimits),max(BinLimits)); title(paste0('black=pdf(GMM),green=pdf(',VarName,')')) axis(1,xlim=c(0,ceiling(max(Data,na.rm=TRUE))),col="black",las=1) #x-Achse axis(2,ylim=c(0,2),col="black",las=1) #y-Achse #drawnow; } par(par.defaults) #kleiner Pvalue: schlecht #grosser pvalue: gut return(list(Pvalue=1-Pvalue,BinCenters=BinCenters,ObsNrInBin=ObsNrInBin,ExpectedNrInBin=ExpectedNrInBin,Chi2Value=Chi2Value)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/Chi2testMixtures.R
ClassifyByDecisionBoundaries=function(Data,DecisionBoundaries,ClassLabels){ # Cls = ClassifyByDecisionBoundaries(Data,DecisionBoundaries) # Classify Data according to decision Boundaries # # INPUT # Data(1:n,1) vector of Data # DecisionBoundaries(1:L) decision boundaries # OPTIONAL # ClassLabels(1:L+1) numbered class labels that are assigned to the classes. default (1:L) # OUTPUT # Cls(1:n,1:d) classiffication of Data # Author MT 04/2015 if(!is.vector(Data)){ warning('Data converted to vector') Data=as.vector(Data) } if(is.list(DecisionBoundaries)){ DecisionBoundaries=as.vector(DecisionBoundaries$DecisionBoundaries) print('DecisionBoundaries was a list, assuming usage of BayesDecisionBoundaries()') } AnzBounds= length(DecisionBoundaries) if(missing(ClassLabels)){ ClassLabels=seq(from=1,by=1,to=(AnzBounds+1)) } Cls=rep(1,length(Data)) # default alles in Klasse 1 nonan=which(is.finite(Data)) if(length(nonan)!=length(Data)){ warning('Datavector contains NaN. These values cannot be classified.') names(Cls)=1:length(Data) ClsTmp=Cls[nonan] DataTmp=Data[nonan] for(b in 1:AnzBounds){ ind=DataTmp>DecisionBoundaries[b] ClsTmp[ind] = rep(ClassLabels[b+1],sum(ind)) } # for c Cls[as.numeric(names(ClsTmp))]=ClsTmp Cls[setdiff(1:length(Cls),as.numeric(names(ClsTmp)))]=NaN }else{ for(b in 1:AnzBounds){ ind=Data>DecisionBoundaries[b] Cls[ind] = rep(ClassLabels[b+1],sum(ind)) } # for c } return(Cls) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/ClassifyByDecisionBoundaries.R
EMGauss = function(Data, K=NULL, Means=NULL,SDs=NULL,Weights=NULL,MaxNumberofIterations=10, fast=F){ #em=EMGauss(Data,K,Means,SDs,Weights) # EM- Algorithm to calculate optimal Gaussian Mixture Model for given data in one Dimension # In particular, no adding or removing of Gaussian kernels # NOTE: this is probably not numerical stable, log(gauss) is not used. # # DESCRIPTION # # INPUT # Data(1:AnzCases) the data points as a vector # K estimated number of Gaussian kernels # Means(1:L) estimated Gaussian Kernels = means(clustercenters), # L == Number of Clustercenters; default=meanrobust(Data) # SDs(1:L) estimated Gaussian Kernels = standard deviations; default=stdrobust(Data) # Weights(1:L) relative number of points in Gaussians (prior probabilities): sum(Weights) ==1; default=1 # MaxNumberofIterations Number of Iterations; default=10 # fast Default: FALSE: Using mclust EM, TRUE: Own faster but maybe numerical unstable implementation # OUTPUT # Means means of GMM generated by EM algorithm # SDs standard deviations of GMM generated by EM algorithm # Weights prior probabilities of Gaussians # # Author Hansen-Goos 2014 # 1.Editor: MT 08/2015 bugfixes, new EM # 2.Editor: FL 10/2016 Parameter k hinzugefuegt #MT: Funktionen nach vorne verschoben # meanrobust ################################################# `meanrobust` <- function(x, p=0.1){ if(is.matrix(x)){ mhat<-c() for(i in 1:dim(x)[2]){ mhat[i]<-mean(x[,i],trim=p,na.rm=TRUE) } } else mhat<-mean(x,trim=p,na.rm=TRUE) return (mhat) } ################################################# # stdrobust ################################################# `stdrobust` <- function(x,lowInnerPercentile=25){ #MT: nach vorne verschoben, damit es keinen Bug gibt prctile<-function(x,p){ # matlab: # Y = prctile(X,p) returns percentiles of the values in X. # p is a scalar or a vector of percent values. When X is a # vector, Y is the same size as p and Y(i) contains the p(i)th # percentile. When X is a matrix, the ith row of Y contains the # p(i)th percentiles of each column of X. For N-dimensional arrays, # prctile operates along the first nonsingleton dimension of X. if(length(p)==1){ if(p>1){p=p/100} } if(is.matrix(x) && ncol(x)>1){ cols<-ncol(x) quants<-matrix(0,nrow=length(p),ncol=cols) for(i in 1:cols){ quants[,i]<-quantile(x[,i],probs=p,type=5,na.rm=TRUE) } }else{ quants<-quantile(x,p,type=5,na.rm=TRUE) } return(quants) } if(is.vector(x) || (is.matrix(x) && dim(x)[1]==1)) dim(x)<-c(length(x),1) lowInnerPercentile<-max(1,min(lowInnerPercentile,49)) hiInnerPercentile<- 100 - lowInnerPercentile faktor<-sum(abs(qnorm(t(c(lowInnerPercentile,hiInnerPercentile)/100),0,1))) std<-sd(x,na.rm=TRUE) p<-c(lowInnerPercentile,hiInnerPercentile)/100 quartile<-prctile(x,p) if (ncol(x)>1) iqr<-quartile[2,]-quartile[1,] else iqr<-quartile[2]-quartile[1] shat<-c() for(i in 1:ncol(x)){ shat[i]<-min(std[i],iqr[i]/faktor,na.rm=TRUE) } dim(shat)<-c(1,ncol(x)) colnames(shat)<-colnames(x) return (shat) } ################################################# # normpdf ################################################# `normpdf` <- function(X,Mean,Sdev){ # computes the normal pdf at each of the values in X # R funktion fuer PDF = normpdf(X,Mean,Sdev) return(dnorm(X,Mean,Sdev)) } # end function normpdf ################################################# #MT/FL: Fehlerabfang if(!is.null(K)){ if(!is.null(Means)){ if(K != length(Means)) stop("K should be equal to length(Means)") }else{ if(K == 1) Means = meanrobust(Data) else Means = sample(Data, K) } if(!is.null(SDs)){ if(K != length(SDs)) stop("k should be equal to length(SDs)") }else{ if(K == 1) SDs = stdrobust(Data) else SDs = runif(K,0,sd(Data)) } if(is.null(Weights)) Weights = rep(1/K, K) }else{ if(!is.null(Means)) K = length(Means) else if(!is.null(SDs)) K = length(SDs) else if(!is.null(Weights)) K = length(Weights) else K = 1 if(is.null(Means)) Means=meanrobust(Data) if(is.null(SDs)) SDs=stdrobust(Data) if(is.null(Weights)) Weights=rep(1/K,K) } # how many Clustercenters L <- length(Means) Ls <- length(SDs) La <- length(Weights) if (!((L == Ls ) && (L== La))){ warning('EMgauss: Number of means not equal to number of sdevs or Weights') } if(fast){ if (!(abs(sum(Weights)-1) <0.001)){ sumWeight <- sum(Weights) for (i in 1:length(Weights)){ Weights[i] <- Weights[i]/sumWeight } } AnzCases <- length(Data) EMmean <- Means EMsdev <- SDs EMweights <- Weights for (t in 1:MaxNumberofIterations){ # update EM Parameters #1.) compute actual alpha weighted probability for each point Na <- matrix(0,AnzCases,L) for (i in 1:L) {# compute actual Distributions Na[1:AnzCases,i] <- normpdf(Data,EMmean[i],EMsdev[i])* EMweights[i] } # for (i in 1:L) # compute actual Distributions #2.) compute total probability for each point TotalEMGauss <- seq(0,0,length.out=AnzCases) for (j in 1:AnzCases){ TotalEMGauss[j] <- sum(Na[j,1:L]) } #3.) compute point's weight as 1.) divided by 2.) w <- matrix(0,AnzCases,L) for (j in 1:L){ w[1:AnzCases,j] <- Na[1:AnzCases,j]/TotalEMGauss } #4.) update Weightstrich AND weights Weightstrich <- seq(0,0,length.out=L) for (j in 1:L){ Weightstrich[j] <- sum(w[1:AnzCases,j]) # = alpha * AnzCases if (is.nan(Weightstrich[j]) || is.na(Weightstrich[j])){ Weightstrich[j] <- 0 } } for (j in 1:L){ if (Weightstrich[j]<0.01){ Weightstrich[j] <- 0.009 } } EMweights <- Weightstrich/AnzCases ZeroInd <- seq(0,0,length.out=L) for (j in 1:L){ if (EMweights[j]<0.01){ ZeroInd[j] <- 1 EMweights[j] <- 0 } } if (sum(EMweights) <0.01){ # no right solution found: give up search & return robust values EMweights <- seq(0,0,length.out=L) EMmean <- EMweights EMsdev <- EMweights EMweights[1] <- 1 EMmean[1] <- meanrobust(Data) EMsdev[1] <- stdrobust(Data) # output <- list(mean=EMmean,sdev=EMsdev,weight=EMweights) output <- list(Means=EMmean,SDs=EMsdev,Weights=EMweights) # edited: OHG 05.2016 warning("EM: no right solution found --> give up search & return robust values") return(output) break } #5.) update means for (j in 1:L){ EMmean[j] <- sum(w[1:AnzCases,j]*Data)/Weightstrich[j] } # account for weight ==0 for (j in 1:L){ if (ZeroInd[j]){ EMmean[j] <- 0 } } #6. update std devs for (j in 1:L){ EMsdev[j] <- sqrt(sum(w[1:AnzCases,j]*(Data-seq(1,1,length.out=AnzCases)*EMmean[j])^2)/Weightstrich[j]) } # account for weight ==0 for (j in 1:L){ if (ZeroInd[j]){ EMsdev[j] <- 0 } } }# for t=1:MaxNumberofIterations # update EM Parameters #output <- list(mean=EMmean,sdev=EMsdev,weight=EMweights) output <- list(Means=EMmean,SDs=EMsdev,Weights=EMweights) }else{ #fast=f #requireRpackage('mclust') #iterations??? requireNamespace('mclust') em=mclust::densityMclust(Data,G=L, modelName='V', parameters=list(pro=Weights,mean=Means,variance=sqrt(SDs),control=list(itmax=c(MaxNumberofIterations,MaxNumberofIterations)))) res=em$parameters # sigmasq entspricht hier sigma^2 = sd^2 => fuer SD nochmal Wurzel ziehen output <- list(Means=unname(res$mean),SDs=sqrt(unname(res$variance$sigmasq)),Weights=unname(res$pro)) #output <- list(mean=unname(res$mean),sdev=unname(res$variance$sigmasq),weight=unname(res$pro)) return(output) } # end if fast } # eof
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/EMGauss.R
GMMplot_ggplot2 <- function(Data, Means, SDs, Weights, BayesBoundaries, SingleGausses = TRUE, Hist = FALSE) { if (!requireNamespace('ggplot2', quietly = TRUE)) { message( 'ggplot2 package is needed for plotting. Please install the package which is defined in "Suggests".') return(NULL) } if (!requireNamespace('reshape2', quietly = TRUE)) { message( 'reshape2 package is missing. Please install the package which is defined in "Suggests".') return(NULL) } if(missing(BayesBoundaries)) BayesBoundaries=AdaptGauss::BayesDecisionBoundaries(Means, SDs, Weights,Ycoor = FALSE) MeansO <- Means[order(Means)] SDsO <- SDs[order(Means)] WeightsO <- Weights[order(Means)] PDE <- DataVisualizations::ParetoDensityEstimation(Data) GMMn <- data.frame(cbind(PDE$kernels, PDE$paretoDensity)) for (i in 1:length(MeansO)) GMMn <- cbind(GMMn, WeightsO[i]*dnorm(PDE$kernels, mean=MeansO[i],sd=SDsO[i],log=F)) GMMn <- cbind(GMMn, rowSums(GMMn[3:(2+length(MeansO))])) names(GMMn) <- c("kernels", "density", paste0("M",1:i), "Sum") dfGMM <- reshape2::melt(data = GMMn, id="kernels") dfGMM$Cls=factor(dfGMM$variable) #require(grDevices) if (SingleGausses == TRUE & length(Means) > 1) p1 <- ggplot2::ggplot(data = dfGMM, ggplot2::aes_string(colour = 'Cls')) else p1 <- ggplot2::ggplot(data = subset(dfGMM, dfGMM$variable %in% c("density", "Sum")), ggplot2::aes_string(colour = 'Cls')) if(Hist == TRUE) { breaks <- pretty(range(Data), n = nclass.FD(Data), min.n = 1) bwidth <- breaks[2]-breaks[1] p1 <- p1 + ggplot2::geom_histogram(data = data.frame(Data), ggplot2::aes_string(x = Data, "..density.."), fill = "grey85", color = "grey95", binwidth=bwidth) + ggplot2::guides(fill = FALSE) } GMMplot <- p1 + ggplot2::geom_line(ggplot2::aes_string(x = 'kernels', y = 'value'), size = ggplot2::rel(0.9)) + ggplot2::labs(colour = "Lines") + ggplot2::labs(x = "Data", y = "Probability Density") if(length(MeansO) > 1) GMMplot <- GMMplot + ggplot2::geom_vline(xintercept=BayesBoundaries, color = "magenta", linetype = 2) + ggplot2::annotate("text", x = MeansO, y = rep(.01,length(MeansO)), size = ggplot2::rel(4), label = paste0("M#", 1:length(MeansO))) return(GMMplot) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/GMMplot_ggplot2.R
InformationCriteria4GMM=function(Data,Means,SDs,Weights,IsLogDistribution=Means*0){ # Vres = InformationCriteria4GMM(Data,M,S,W,IsLogDistribution) # berechnung von AIC (Akaike Information Criterium) und BIC (Bayes Information Criterium) # fuer GMM in einer Variablen # # INPUT #Data[1:N] Vector (1:N) of data points; May Contain NaN #Means[1:L] vector[1:L] of Means of Gaussians (of GMM),L == Number of # Gaussians #SDs[1:L] vector of standard deviations, estimated Gaussian Kernels, # has to be the same length as Means #Weights[1:L] vector of relative number of points in Gaussians (prior # probabilities), has to be the same length as Means # sum(Weights)=1 # OPTIONAL #IsLogDistribution[1:L] Optional, ==1 if distribution(i) is a LogNormal, # default vector of zeros of length L} # # OUTPUT # K Number of gaussian mixtures # AIC Akaike Informations criterium # BIC Bayes Information criterium # LogLikelihood LogLikelihood of GMM, see # \code{\link{LogLikelihood4Mixtures}} # PDFmixture(1:N) probability density function of GMM, see # \code{\link{Pdf4Mixtures}} # LogPDFdata(1:N) log(PDFmixture) # author: MT 01/2016 # Source # Aho, K., Derryberry, D., & Peterson, T. (2014). Model selection for ecologists: the worldviews of AIC and BIC. Ecology, 95(3), 631-636. #Note: Variablenbezeichnungen mit package AdaptGauss vereinheitlicht. # pdfV=Pdf4Mixtures(Data,Means,SDs,Weights,IsLogDistribution,PlotIt=F) # PDFmixture <- PdfForMix$PDF # pdf=colSums(PDFmixture) # pdf[<=0]=NaN # LogLikelylihood=sum(log(pdf),na.rm=T) kkk=length(Means) if(kkk>1) #Normalfall K=kkk*3 else #Bei einem Gauss gibt es kein gewicht! K=2 LL4GMM=LogLikelihood4Mixtures(Data,Means,SDs,Weights,IsLogDistribution) LogLikelihood=LL4GMM$LogLikelihood N=length(Data) AIC=2*K-2*LogLikelihood if(N<40) AIC= AIC + (2*K*(K+1))/(N-K-1) #AIC=LogLikelihood-K #S. Bishop 2006, p. 33 (1.73) #BIC=LogLikelihood-1/2*K*log(length(Data))#S. Bishop 2006, p 217 (4.139) BIC= K*log(N)-2*LogLikelihood return(list(K=K, AIC=AIC, BIC=BIC,LogLikelihood =LogLikelihood, PDFmixture=LL4GMM$PDFmixture,LogPDFdata=LL4GMM$LogPDF)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/InformationCriteria4GMM.R
Intersect2Mixtures <- function(Mean1,SD1,Weight1,Mean2,SD2,Weight2,IsLogDistribution = c(FALSE,FALSE),MinData,MaxData){ # [CutX,CutY] = Intersect2Mixtures(Mean1,SD1,Weight1,Mean2,SD2,Weight2,IsLogDistribution); # INPUT # Mean1,SD1,Weight1,Mean2,SD2,Weight2 parameters of the gaussians # OPTIONAL # IsLogDistribution(1:2) ==1 if distribution(i) is a LogNormal, default c(0,0) # OUTPUT # CutX, CutY [CutX, CutY] is where N1 == N2 # Author: RG # 1.Editor: MT 08/2015 # in /dbt/BayesDecision/ M = c(Mean1,Mean2) S = c(SD1,SD2) X0 = min(M) MinInd = which(M==X0,arr.ind=TRUE) X1 = max(M) MaxInd = which(M==X1,arr.ind=TRUE) if(missing(MinData)){ X0 = X0-2*S[MinInd] }else{ X0 = MinData } if(missing(MaxData)){ X1 = X1+2*S[MaxInd] } else{ X1 = MaxData } if(abs(Mean1-Mean2) < 0.00001){ # no differences in mean CutX = Mean1 CutY = 1 }else if((Weight1 == 0) | (Weight2 == 0)){ CutX=NA CutY=NA }else{ # simple solution: look at NrOfIteration points between Modi NrOfIteration = 20000 dx = (X1 - X0)/NrOfIteration X = seq(from = X0, to = X1, by = dx) # X sind Werte an denen die Gaussians ausgewertet werden if(IsLogDistribution[1] == TRUE) N1 = Symlognpdf(X,Mean1,SD1)*Weight1 # LogNormal else # N1 ist normalverteilt N1 = dnorm(X,Mean1,SD1)*Weight1 # Gauss if(IsLogDistribution[2] == TRUE) N2 = Symlognpdf(X,Mean2,SD2)*Weight2 # LogNormal else # N2 ist normalverteilt N2 = dnorm(X,Mean2,SD2)*Weight2 # Gauss # N1 ist die pdf von Mean1 # N2 ist die pdf des Mean2 Difference = N1 - N2 Vorzeichen = unique(sign(Difference)) AnzVorzeichen = length(Vorzeichen) # jetzt noch Bereucksichtigen dass die sich garnicht schneiden if(AnzVorzeichen < 2){ # schneiden sich nicht CutY = 0; if(Mean1 < Mean2) CutX = X0 else CutX = X1 }else{ # sie schneiden sich MinDiff = min(abs(Difference)) CutInd = which(abs(Difference)==MinDiff,arr.ind=TRUE) CutX = X[CutInd] CutY = N1[CutInd] } } # test # figure;plot(X,N1,'b-',X,N2,'r-'); # vline(CutX); hline(CutY) return(list(CutX=CutX,CutY=CutY)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/Intersect2Mixtures.R
KStestMixtures=function(Data,Means,SDs,Weights,IsLogDistribution=Means*0,PlotIt=FALSE,UpperLimit=max(Data,na.rm=TRUE),NoRepetitions,Silent=TRUE){ # res= KStestMixtures(Data,Means,SDs,Weights,IsLogDistribution,PlotIt,UpperLimit) # Kolmogorov-Smirnov Test Data vs a given Gauss Mixture Model # # INPUT # Data(1:N) data points # Means(1:L,1) Means of Gaussians, L == Number of Gaussians # SDs(1:L,1) estimated Gaussian Kernels = standard deviations # Weights(1:L,1) relative number of points in Gaussians (prior probabilities): # # OPTIONAL # IsLogDistribution(1:L,1) oder 0 if IsLogDistribution(i)==1, then mixture is lognormal # default == 0*(1:L)' # PlotIt do a Plot of the compared cdf's and the KS-test distribution (Diff) # UpperLimit test only for Data <= UpperLimit, Default = max(Data) i.e all Data. # Silent Shows progress of computation by points # OUTPUT # PvalueKS Pvalue of a suiting Kolmogorov Smirnov Test, PvalueKS==0 if PvalueKS<0.001 # DataKernels,DataCDF such that plot(DataKernels,DataCDF) gives the cdf(Data) # CDFGaussMixture such that plot(DataKernels,DataCDF) gives the cdf(Data) # MT 2015, reimplemented from ALUs matlab version #1.Editor: MT 03/19 deutliche effizienzsteigerung eingepflegt fuer normale gausse. par.defaults <- par(no.readonly=TRUE) ################################ #Hilfsfunktionen ################################ ################################ ################################ #[DataCDF,DataKernels] = ecdfUnique(Data) dummy <- ecdf(Data) # cdf(Diff) DataCDF <- c(0,get("y", envir = environment(dummy))) DataKernels <- c(knots(dummy)[1],knots(dummy))#CDFuniq# cdf(Data) CDFGaussMixture = CDFMixtures(DataKernels,Means,SDs,Weights,IsLogDistribution)$CDFGaussMixture # cdf(GMM) # UpperLimit bereucksichtigen, alles auf <=UpperLimit kuerzen Data=Data[Data<=UpperLimit] Ind = which(DataKernels<=UpperLimit, arr.ind=T) DataKernels = DataKernels[Ind] DataCDF = DataCDF[Ind] CDFGaussMixture= CDFGaussMixture[Ind] # KS messgroesse bestimmen CDFdiff = abs(CDFGaussMixture-DataCDF) # Unterschied = KS- testgroesse MaxDiff= max(CDFdiff,na.rm=TRUE) # wo steckt der groesste Unterschied MaxInd=which(CDFdiff==MaxDiff, arr.ind=T) KernelMaxDiff = DataKernels[MaxInd] # wo steckt der groesste Unterschied DataCDFmaxDiff = DataCDF[MaxInd] # wo steckt der groesste Unterschied GMMCDFmaxDiff = CDFGaussMixture[MaxInd] # wo steckt der groesste Unterschied regularize.values_spec <- function(x, y,HandleTiesFUN=meanC) { #MT: not necessary for this special case # x <- xy.coords(x, y, setLab = FALSE) # -> (x,y) numeric of same length # y <- x$y # x <- x$x # if(any(na <- is.na(x) | is.na(y))) { # ok <- !na # x <- x[ok] # y <- y[ok] # } nx <- length(x) o <- order(x) x <- x[o] y <- y[o] if (length(ux <- unique(x)) < nx) { # tapply bases its uniqueness judgement on character representations; # we want to use values (PR#14377) #y <- as.vector(tapply(y, match(x,x), meanC))# as.v: drop dim & dimn. #MT: not necessary for this secial case y <- tapply(y, match(x,x), HandleTiesFUN) #requireNamespace('fastmatch') #fmatch is also slower #y <- tapply(y, fastmatch::fmatch(x,x), HandleTiesFUN) #slower # y <- as.vector(fastmatch::ctapply(y, match(x,x), meanC))# x <- ux #mt:not necessary #stopifnot(length(y) == length(x))# (did happen in 2.9.0-2.11.x) } list(x=x, y=y) } # Die Miller Funktion via Monte-Carlo errechnen AnzData =length(Data) if(missing(NoRepetitions)){ NoRepetitions = 1000 if(AnzData<1000) NoRepetitions = 2000 if(AnzData<100) NoRepetitions = 5000 }else{ if(as.numeric(NoRepetitions)<1) NoRepetitions=1 } RandGMMDataDiff = matrix(0,NoRepetitions,1) Ri=sapply(1:NoRepetitions, function(i,...) return(RandomLogGMM(...)),Means,SDs,Weights,IsLogDistribution,AnzData) for(i in c(1:NoRepetitions)){ #R = RandomLogGMM(Means,SDs,Weights,IsLogDistribution,AnzData) R = Ri[,i] #[RandCDF,RandKernels] = ecdfUnique(R) dummy <- ecdf(R) # cdf(Diff) RandCDF <- c(0,get("y", envir = environment(dummy))) RandKernels <- c(knots(dummy)[1],knots(dummy))#CDFuniq# cdf(Data) # #RandCDF = interp1(RandKernels,RandCDF,DataKernels, 'linear') #matlab #MT: resolves ties, order values regval <- regularize.values_spec(RandKernels, RandCDF) # -> (x,y) numeric of same length y <- regval$y x <- regval$x #MT: then approx is very fast RandCDF = approx(x,y,DataKernels, 'linear')$y # den MaxDiff in cdf(Diff) lokalisieren RandGMMDataDiff[i] = max(abs(CDFGaussMixture-RandCDF),na.rm=TRUE) if(!Silent){ #if(Sys.info()['sysname'] == 'Windows'){ # if(i==1) # pb <- winProgressBar(title = "progress bar", min = 0, # max = NoRepetitions, width = 300) # setWinProgressBar(pb, i, title=paste( round(i/NoRepetitions*100, 0),"% done")) # if(i==NoRepetitions) close(pb) # }else{ if(i %%10==0){ cat('.') } # } } }# for i AllDiff = RandGMMDataDiff#[is.finite(RandGMMDataDiff)] # die Verteilung aller Differenzen #matlab #[AllDiffCDF,AllDiffKenels] = ecdfUnique(AllDiff); # cdf(Diff) #R dummy <- ecdf(AllDiff) # cdf(AllDiff) ##Berechnet eine Funktion # AllDiffCDF <- c(0,get("y", envir = environment(dummy))) # AllDiffKernels <- c(knots(dummy)[1],knots(dummy))#CDFuniq# cdf(Data) ##Extrahiert aus der Funktion die x und y Werte AllDiffCDF=environment(dummy)$y AllDiffKernels=environment(dummy)$x #matlab #MaxDiffCDFwert = interp1([0;AllDiffKenels],[0;AllDiffCDF],MaxDiff, 'linear'); # den MaxDiff in cdf(Diff) lokalisieren #R regval <- regularize.values_spec(rbind(0,unname(AllDiffKernels)), rbind(0,unname(AllDiffCDF))) # -> (x,y) numeric of same length y1 <- regval$y x1 <- regval$x MaxDiffCDFwert = approx(x1,y1,xout=MaxDiff, 'linear')$y # den MaxDiff in cdf(Diff) lokalisieren #MaxDiffCDFwert = linearapprox(rbind(0,unname(AllDiffKernels)),rbind(0,unname(AllDiffCDF)),MaxDiff,) # den MaxDiff in cdf(Diff) lokalisieren #print(MaxDiffCDFwert) if(is.na(MaxDiffCDFwert)){ ##Wenn nicht approximierbar if(MaxDiff>max(AllDiffKernels,na.rm=T)){#Wenn Ursache daran liegt, das kein x-werte gefunden werden kann (zu weit nach rechts in der ecdf) MaxDiffCDFwert=1 PvalueKS=MaxDiffCDFwert }else if(MaxDiff<min(AllDiffKernels,na.rm=T)){#Wenn Ursache daran liegt, das kein x-werte gefunden werden kann (zu weit nach rechts in der ecdf) MaxDiffCDFwert=0 PvalueKS=MaxDiffCDFwert }else{ warning('Pvalue could not be computed, something went wrong') PvalueKS=NaN } }else{ #Standardfall PvalueKS = MaxDiffCDFwert # P- value fuer KS-test ausrechnen PvalueKS = round(PvalueKS,3) # runden auf 3 gueltige stellen } Controls=list(MaxDiffCDFwert=MaxDiffCDFwert,AllDiffKernels=AllDiffKernels,AllDiffCDF=AllDiffCDF,AllDiff=AllDiff) if(PlotIt ==1){ tryCatch({ par.defaults <- par(no.readonly=TRUE) par(mfrow = c(2,2)) xlim=c(min(DataKernels,na.rm = T), max(DataKernels,na.rm = T)) #ylim=c(min(min(DataCDF,na.rm = TRUE),min(CDFGaussMixture,na.rm = TRUE)),max(max(DataCDF,na.rm = TRUE),max(CDFGaussMixture,na.rm = TRUE))) ylim=c(0,1) plot(DataKernels,DataCDF,col='blue',xlim=xlim,ylim=ylim,xlab="",ylab="",axes=FALSE) points(DataKernels,CDFGaussMixture,col='red',type='l',lwd=2) points(KernelMaxDiff,DataCDFmaxDiff,col='green',pch=1) points(KernelMaxDiff,GMMCDFmaxDiff,col='green',pch=1) abline(v=KernelMaxDiff,col='green') axis(1,xlim=xlim,col="black",las=1) #x-Achse axis(2,ylim=ylim,col="black",las=1) #y-Achse title('KS-test: comparison CDF(GMM) vs CDF(Data)',xlab='Data',ylab='red =CDF(GMM), blue=CDF(Data)'); # subplot(2,2,2); # hier die fraglichen PDFs zeichnen PlotMixtures(Data,Means,SDs,Weights,IsLogDistribution=IsLogDistribution,xlim=xlim,xlab='',ylab='',SingleGausses = T,SingleColor='magenta',MixtureColor='blue') title(paste0('max(Diff) at: ',KernelMaxDiff),xlab='Data',ylab='pdf(GMM), red= pdf(Data)') abline(v=KernelMaxDiff,col='green') # subplot(2,2,3); pdeVal2 <- DataVisualizations::ParetoDensityEstimation(AllDiff) xlim=c(min(MaxDiff*0.90,pdeVal2$kernels,na.rm = T),max(pdeVal2$kernels,na.rm = T)) ylim=c(0,1.05*max(pdeVal2$paretoDensity,na.rm = T)) plot(pdeVal2$kernels,pdeVal2$paretoDensity,type='l',xaxs='i', yaxs='i',xlab='MaxDiff, mag = max(Diff)',ylab='pdf(KS-MaxDiff)',main='KS-Distribution of MaxDiff',xlim=xlim,col='blue',ylim=ylim) abline(v=MaxDiff,col='magenta') box() # subplot(2,2,4); xlim=c(min(MaxDiff*0.90,AllDiffKernels,na.rm = T),max(AllDiffKernels,na.rm = T)) ylim=c(min(MaxDiffCDFwert*0.90,AllDiffCDF,na.rm = T),max(AllDiffCDF,na.rm = T)) tryCatch({ plot(AllDiffKernels,AllDiffCDF,type='p',ylab='cdf(KS-MaxDiff)',xlab='Diff, mag = max(Diff)',main= paste0('Pvalue: ',100-PvalueKS*100,' [#]'),ylim=ylim,xlim=xlim,col='blue') },er=function(ex){ plot(AllDiffKernels,AllDiffCDF,type='p',ylab='cdf(KS-MaxDiff)',xlab='Diff, mag = max(Diff)',main= paste0('Pvalue: ',100-PvalueKS*100,' [#]'),col='blue') }) abline(v=MaxDiff,col='magenta') #abline(a=c(MaxDiffCDFwert,MaxDiffCDFwert),b=c(0,MaxDiff)) abline(h=MaxDiffCDFwert,col='magenta') box() par(par.defaults) },er=function(ex){ return(list(PvalueKS=PvalueKS,DataKernels=DataKernels,DataCDF=DataCDF,CDFGaussMixture=CDFGaussMixture,Controls)) }) } #if PlotIt ==1 #kleiner Pvalue: schlecht #grosser pvalue: gut par(par.defaults) return(invisible(list(PvalueKS=1-PvalueKS,DataKernels=DataKernels,DataCDF=DataCDF,CDFGaussMixture=CDFGaussMixture,Controls))) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/KStestMixtures.R
LikelihoodRatio4Mixtures <- function(Data,NullMixture,OneMixture,PlotIt=FALSE, LowerLimit = min(Data, na.rm=TRUE), UpperLimit = max(Data, na.rm=TRUE)){ # V = LikelihoodRatio4Mixtures(Data,NullModel,OneModel,PlotIt,LowerLimit,UpperLimit) # Likelihood Ratio Test for 2 Gauss mixture Models # # INPUT # Data[1:N] data points # NullMixture =cbind(M0,S0,W0) or cbind(M0,S0,W0,IsLog0); # the null model usually with less Gaussians than the OneMixture # OneMixture =cbind(M1,S2,W1) or cbind(M1,S1,W1,IsLog1); # the alternative model usually with more Gaussians than the OneMixture # # OPTIONAL # PlotIt do a Plot of the compared cdf's and the KS-test distribution (Diff) # LowerLimit test only for Data >= LowerLimit, Default = min(Data) i.e all Data. # UpperLimit test only for Data <= UpperLimit, Default = max(Data) i.e all Data. # # OUTPUT # List of 3: # Pvalue the error that we make, if we accept OneMixture as the better Model over the NullMixture # NullLogLikelihood log likelihood of GMM Null # OneLogLikelihood log likelihood of GMM One # uses LogLikelihood4Mixtures in that PdfForMixes # ALU 2015 # Uebertrag von Matlab nach R: CL 02/2016 #1. Editor: MT 03/2016 # library(grid)# fuer multiplot ValidDataInd = which((Data >= LowerLimit) & (Data <= UpperLimit)) ## NullMixture NullAnzMixes <- dim(NullMixture)[1] AnzCol <- dim(NullMixture)[2] M0 = NullMixture[,1] S0 = NullMixture[,2] W0 = NullMixture[,3] if(AnzCol >3){ # IsLog0 gegeben; IsLog0 = NullMixture[,4] }else{ IsLog0 = M0*0; }#end if IsLog0 gegeben ## OneMixture OneAnzMixes <- dim(OneMixture)[1] AnzCol <- dim(OneMixture)[2] M1 = OneMixture[,1] S1 = OneMixture[,2] W1 = OneMixture[,3] if(AnzCol >3){ # IsLog1 gegeben; IsLog1 = OneMixture[,4] }else{ IsLog1 = M1 *0; }#end if IsLog1 gegeben # die LogLikelihood der beiden Mixturen ausrechnen NullLL <- LogLikelihood4Mixtures(Data[ValidDataInd],M0,S0,W0,IsLog0) NullLogLikelihood <- NullLL$LogLikelihood NullLogPDF <- NullLL$LogPDF NullPDF <- NullLL$PDFmixture OneLL <- LogLikelihood4Mixtures(Data[ValidDataInd],M1,S1,W1,IsLog1) OneLogLikelihood <- OneLL$LogLikelihood OneLogPDF <- OneLL$LogPDF OnePDF <- OneLL$PDFmixture D <- 2*(OneLogLikelihood - NullLogLikelihood) DegreesOfFreedom <- abs(length(M1)*3-length(M0)*3) # Wkeitsverteilung von D folgt naeherungsweise einer Chi-Quadrat-Verteilung mit DegreesOfFreedom-vielen Frei- # heitsgraden. Pvalue = 1 - pchisq(D, DegreesOfFreedom) # cdf der Chi-sq-Verteilung an Teststatistik-Wert auswerten. if(PlotIt ==TRUE){ if (!requireNamespace('ggplot2', quietly = TRUE)) { message( 'ggplot2 package is needed for plotting. Please install the package which is defined in "Suggests".') return(list(Pvalue=Pvalue, NullLogLikelihood=NullLogLikelihood, OneLogLikelihood=OneLogLikelihood)) }else if (!requireNamespace('grid', quietly = TRUE)) { message( 'grid package is needed for plotting. Please install the package which is defined in "Suggests".') return(list(Pvalue=Pvalue, NullLogLikelihood=NullLogLikelihood, OneLogLikelihood=OneLogLikelihood)) } else { y=NULL x=NULL kernels=NULL paretoRadius<-DataVisualizations::ParetoRadius(Data[ValidDataInd]) pdeVal <- DataVisualizations::ParetoDensityEstimation(Data[ValidDataInd],paretoRadius,NULL) paretoDensity <- pdeVal$paretoDensity*1 dfframe = as.data.frame(cbind(kernels = pdeVal$kernels, density = paretoDensity)) #colnames(dfframe)=c('kernels','density') # kernels=pdeVal$kernels pdePlot <- ggplot2::ggplot()+ ggplot2::geom_line(data = dfframe, ggplot2::aes(x = kernels, y = density), colour = "black") nullmodell=as.data.frame(cbind(kernels = Data[ValidDataInd],density = NullPDF[ValidDataInd])) onemodell=as.data.frame(cbind(kernels = Data[ValidDataInd],density = OnePDF[ValidDataInd])) pdePlot <- pdePlot + ggplot2::geom_line(data = nullmodell, ggplot2::aes(x=kernels, y=density), colour="blue") pdePlot <- pdePlot + ggplot2::geom_line(data = onemodell, ggplot2::aes(x=kernels, y=density), colour="red") pdePlot <- pdePlot + ggplot2::ggtitle("PDE and Mixture Models") pdePlot <- pdePlot + ggplot2::ylab("blue = Nullmodel, red = Onemodel") pdePlot <- pdePlot + ggplot2::xlab("Data") nulllogmodell=as.data.frame(cbind(kernels = Data[ValidDataInd],density = NullLogPDF[ValidDataInd])) onelogmodell=as.data.frame(cbind(kernels = Data[ValidDataInd],density = OneLogPDF[ValidDataInd])) # Erstelle plot von LogPDF beider Modelle LogPDFplot = ggplot2::ggplot() + ggplot2::geom_line(data = nulllogmodell, ggplot2::aes(x=kernels, y=density), colour="blue") LogPDFplot = LogPDFplot + ggplot2::geom_line(data = onelogmodell, ggplot2::aes(x=kernels, y=density), colour="red") LogPDFplot <- LogPDFplot + ggplot2::ggtitle(paste0("LogPDF, LogLikeli Null= ",NullLogLikelihood, ", One = ", OneLogLikelihood)) LogPDFplot <- LogPDFplot + ggplot2::ylab("blue = Nullmodel, red = Onemodel") LogPDFplot <- LogPDFplot + ggplot2::xlab("Data") nuller=as.data.frame(cbind(x = c(D,D), y = c(0,pchisq(D, DegreesOfFreedom)))) einser=as.data.frame(cbind(x = c(0,D), y = c(pchisq(D, DegreesOfFreedom),pchisq(D, DegreesOfFreedom)))) # Erstelle plot der CDF der Chi-quadrat-Verteilung und markiere den Wert der Teststatistik # Find xlim for ChisqCDF plot by 0.98 pchi_lim = stats::qchisq(0.99, DegreesOfFreedom) ChisqCDF <- ggplot2::ggplot() + ggplot2::stat_function(fun = pchisq, args=list(df=DegreesOfFreedom), xlim=c(0,pchi_lim)) ChisqCDF <- ChisqCDF + ggplot2::geom_line(data= nuller, ggplot2::aes(x,y) , colour = 'blue') ChisqCDF <- ChisqCDF + ggplot2::geom_line(data= einser, ggplot2::aes(x,y, color ='Myline') , colour = 'blue') ChisqCDF <- ChisqCDF + ggplot2::ggtitle(paste0('Chi^2 CDF with DF = ', DegreesOfFreedom)) ChisqCDF <- ChisqCDF + ggplot2::ylab("blue = value of test statistic") ChisqCDF <- ChisqCDF + ggplot2::xlab(paste0("Pvalue = ", Pvalue)) nullminuseins=as.data.frame(cbind(kernels = Data[ValidDataInd],density = OneLogPDF[ValidDataInd]-NullLogPDF[ValidDataInd])) # Erstelle plot von LogPDF des OneModels minus LogPDF des NullModels LogPDFOneMinusNullplot <- ggplot2::ggplot() + ggplot2::geom_line(data = nullminuseins, ggplot2::aes(x=kernels, y=density), colour="black") LogPDFOneMinusNullplot <- LogPDFOneMinusNullplot + ggplot2::ggtitle('LogPDF OneModel - NullModel') LogPDFOneMinusNullplot <- LogPDFOneMinusNullplot + ggplot2::ylab("LogPDF OneModel - LogPDF NullModel") LogPDFOneMinusNullplot <- LogPDFOneMinusNullplot + ggplot2::xlab("Data") # Multiple plot function # # ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects) # - cols: Number of columns in layout # - layout: A matrix specifying the layout. If present, 'cols' is ignored. # # If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE), # then plot 1 will go in the upper left, 2 will go in the upper right, and # 3 will go all the way across the bottom. # #author: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/ multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) { # Make a list from the ... arguments and plotlist plots <- c(list(...), plotlist) numPlots = length(plots) # If layout is NULL, then use 'cols' to determine layout if (is.null(layout)) { # Make the panel # ncol: Number of columns of plots # nrow: Number of rows needed, calculated from # of cols layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), ncol = cols, nrow = ceiling(numPlots/cols)) } if (numPlots==1) { print(plots[[1]]) } else { # Set up the page grid::grid.newpage() grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout)))) # Make each plot, in the correct location for (i in 1:numPlots) { # Get the i,j matrix positions of the regions that contain this subplot matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE)) print(plots[[i]], vp = grid::viewport(layout.pos.row = matchidx$row, layout.pos.col = matchidx$col)) } } } # plotte alle 4 Zeichnungen in einer Uebersicht: multiplot(pdePlot,LogPDFplot, ChisqCDF, LogPDFOneMinusNullplot, layout=matrix(c(1,2,3,4), nrow=2, byrow=TRUE)) } } return(list(Pvalue=Pvalue, NullLogLikelihood=NullLogLikelihood, OneLogLikelihood=OneLogLikelihood)) }#end function
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/LikelihoodRatio4Mixtures.R
LogLikelihood4Mixtures <- function(Data, Means, SDs, Weights, IsLogDistribution=Means*0){ # LogLikelihood <- LogLikelihood4Mixtures(Data,Means,SDs,Weights,IsLogDistribution) # berechnung der Loglikelihood fuer ein Mixture model: LogLikelihood = sum(log(PDFmixture)) # # INPUT # Data[1:n] Daten, deren Verteilung verglichen werden soll # Means[1:L] Means of Gaussians, L == Number of Gaussians # SDs[1:L] estimated Gaussian Kernels = standard deviations # Weights[1:L] relative number of points in Gaussians (prior probabilities): sum(Weights) ==1 # # OPTIONAL # IsLogDistribution[1:L] gibt an, ob die Einzelverteilung einer (generalisierten)Lognormaverteilung ist # wenn IsLogDistribution[i]==0 dann Mix(i) = W[i] * N(M[i],S[i]) # wenn IsLogDistribution[i]==1 dann Mix(i) = W[i] * LogNormal(M[i],S[i]) # Default: IsLogDistribution = Means*0; # # OUTPUT # LogLikelihood die Loglikelihood der Verteilung = LogLikelihood = = sum(log(PDFmixture)) # LogPDF(1:n) = log(PDFmixture); # PDFmixture die Probability density function an jedem Datenpunkt # Author: ALU, 2015 # Uebertrag von Matlab nach R: CL 02/2016 # 1.Editor: MT 02/2016: umbenannt in LogLikelihood4Mixture, da auch LGL Modelle moegliech und analog zu LikelihoodRatio4Mixtures, Chi2testMixtures, KStestMixtures #Pattern Recogintion and Machine Learning, C.M. Bishop, 2006, isbn: ISBN-13: 978-0387-31073-2, p. 433 (9.14) PdfForMix = Pdf4Mixtures(Data,Means,SDs,Weights,IsLogDistribution) # PDF ausrechnen PDFmixture <- PdfForMix$PDFmixture PDFmixture[PDFmixture<=0] = NaN # null zu NaN LogPDF = log(PDFmixture) # logarithmieren (natuerlicher Logarithmus) LogLikelihood = sum(LogPDF, na.rm=TRUE) # summieren return(list(LogLikelihood=LogLikelihood, LogPDF = LogPDF, PDFmixture = PDFmixture)) }#end function
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/LogLikelihood4Mixtures.R
Pdf4Mixtures=function(Data,Means,SDs,Weights,IsLogDistribution,PlotIt=F){ # pdfV=Pdf4Mixtures(Data,Means,SDs,Weights,IsLogDistribution,PlotIt=T) # generate the pdf for the Mixture # INPUT # Data(1:AnzCases) this data column for which the distribution # was modelled # Means(1:L,1) Means of Gaussians, L == Number of Gaussians # SDs(1:L,1) estimated Gaussian Kernels = standard # deviations # Weights(1:L,1) relative number of points in Gaussians # (prior probabilities): sum(Weights) ==1, # default 1/L # Optional # IsLogDistribution(1:L) default ==0*(1:L), gibt an ob die jeweilige # Verteilung eine Lognormaverteilung ist # PlotIt PDF wird gezeichnet # OUTPUT # PDF(1:N) Vektor der PDF korrespondierend zu Data # PDF4modes(1:N,1:C) Vektor der PDF der teilmodi # PDFmixture vector der Superposition, wird in # PlotMixtures() genutzt # # author: MT 01/2016 ausgelagert von PlotMixtures # Note: Funktionsnamen vereinheitlicht mit LikelihoodRatio4Mixtures, LogLikelihood4Mixtures, Chi2testMixtures, CDFMixtures, KStestMixtures, in matlab unter PdfForMixes ######################################################### if(missing(IsLogDistribution)) IsLogDistribution = rep(FALSE,length(Means)) AnzGaussians = length(Means) PDF4modes=matrix(0,nrow=length(Data),ncol=AnzGaussians) GaussMixture=Data*0 for(g in c(1:AnzGaussians)){ if(IsLogDistribution[g] == TRUE){ # LogNormal PDF4modes[,g] <- Symlognpdf(Data,Means[g],SDs[g]) # LogNormal }else{ # Gaussian PDF4modes[,g] = dnorm(Data,Means[g],SDs[g]) }# if IsLogDistribution(i) ==T GaussMixture = GaussMixture + PDF4modes[,g]*Weights[g] } # for AnzGaussians #PDF4modes gewichtet: PDF=PDF4modes for(g in c(1:AnzGaussians)) PDF[,g] = PDF4modes[,g] * Weights[g] if(PlotIt){ X=sort(na.last=T,Data) Sind=order(Data) plot(X,GaussMixture[Sind],type='l',xlim=c(X[1],X[length(X)]),ylab='pdf (Superposition of Gaussians)',xlab='Data') } return(list(PDF4modes=PDF4modes,PDF=PDF,PDFmixture=GaussMixture )) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/Pdf4Mixtures.R
PlotMixtures <- function(Data, Means, SDs, Weights = rep(1/length(Means),length(Means)), IsLogDistribution = rep(FALSE,length(Means)), Plotter = "native", SingleColor = 'blue', MixtureColor = 'red', DataColor = 'black', SingleGausses = FALSE, axes = TRUE, xlab = "", ylab = "PDE", xlim = NULL, ylim = NULL, Title = "GMM", ParetoRad = NULL, ...){ # PlotMixtures(Data,Means,SDs,Weights,IsLogDistribution,SingleColor,MixtureColor); # PlotMixtures(Data,Means,SDs,Weights,IsLogDistribution); # Plot a Mixture of Gaussians # INPUT # Data(1:AnzCases) this data column for which the distribution was modelled # Means(1:L,1) Means of Gaussians, L == Number of Gaussians # SDs(1:L,1) estimated Gaussian Kernels = standard deviations # OPTIONAL # Weights(1:L,1) relative number of points in Gaussians (prior probabilities): sum(Weights) ==1, default 1/L # IsLogDistribution(1:L) default ==0*(1:L), gibt an ob die jeweilige Verteilung eine Lognormalverteilung ist # # SingleColor PlotSymbol of all the single gaussians, default magenta # MixtureColor PlotSymbol of the mixture default black # # SingleGausses Sollen die einzelnen Gauss auch gezeichnet werden, dann TRUE # ParetoRad Vorberechneter Pareto Radius # ... other plot arguments like xlim = c(1,10) # # Author: MT 08/2015, # 1.Editor: MT 1/2016: PDF4Mixtures als eigene Funktion ausgelagert # 2. Editor: FL 9/2016: ... wird auch an title weitergegeben # 3. Editor: QMS 10/2022: Plotly #Nota: Based on a Version of HeSa Feb14 (reimplemented from ALUs matlab version) def.par <- par(no.readonly = TRUE) # save default, for resetting... on.exit(par(def.par)) if(missing(Data)) stop('Data is missing.') if(!(Plotter %in% c("native", "plotly"))){ warning("PlotMixtures: Incorrect plotter selected. Doing nothing.") } if(!inherits(Data,'numeric')){ warning('Data is not a numerical vector. calling as.vector') Data=as.vector(Data) } if(length(Data)==length(Means)){ warning('Probably "Data" interchanged with "Means" ') } if(!is.null(ParetoRad)){ pareto_radius = ParetoRad }else{ pareto_radius<-DataVisualizations::ParetoRadius(Data) } pdeVal <- DataVisualizations::ParetoDensityEstimation(Data,pareto_radius) if(missing(IsLogDistribution)){ IsLogDistribution = rep(FALSE,length(Means)) } if(length(IsLogDistribution)!=length(Means)){ warning(paste('Length of Means',length(Means),'does not equal length of IsLogDistribution',length(IsLogDistribution),'Generating new IsLogDistribution')) IsLogDistribution = rep(FALSE,length(Means)) } X = sort(na.last=T,unique(Data)) # sort ascending and make sure of uniqueness AnzGaussians = length(Means) MyPlot = NULL pdfV=Pdf4Mixtures(X, Means, SDs, Weights,IsLogDistribution = IsLogDistribution) SingleGaussian=pdfV$PDF GaussMixture=pdfV$PDFmixture # Limits GaussMixtureInd=which(GaussMixture>0.00001) if(missing(xlim)){ # if no limits for x-axis are comitted xl = max(X[GaussMixtureInd],na.rm=T) xa = min(X[GaussMixtureInd], 0,na.rm=T) xlim = c(xa,xl) } # Je plot xlim und ylim uebergeben # Falls dies nicht geschieht, werden beide Achsen falsch skaliert! if(is.null(ylim)){ # if no limits for y-axis are comitted yl <- max(GaussMixture,pdeVal$paretoDensity,na.rm=T) ya <- min(GaussMixture, 0,na.rm=T) ylim <- c(ya,yl+0.1*yl) #ylim= par("yaxp")[1:2] } if(Plotter=="plotly"){ MyPlot = plotly::plot_ly(type = "scatter", mode = "markers") if(SingleColor != 0){ MyPlot = plotly::add_lines(p = MyPlot, x = X, y = pdfV$PDFmixture, line = list(color = MixtureColor), name = "GMM") for(i in 1:AnzGaussians){ MyPlot = plotly::add_lines(p = MyPlot, x = X, y = pdfV$PDF[,i], line = list(color = SingleColor), name = paste0("GMM Comp.", i)) } MyPlot = plotly::add_lines(p = MyPlot, x = pdeVal$kernels, y = pdeVal$paretoDensity, line = list(color = DataColor), name = "Empirical Density Est.") MyPlot = plotly::layout(p = MyPlot, title = Title, xaxis = list(title = xlab, range = xlim)) MyPlot }else{ MyPlot = plotly::add_lines(p = MyPlot, x = X, y = pdfV$PDFmixture, line = list(color = MixtureColor), name = "GMM") MyPlot } }else if(Plotter=="native"){ if(SingleColor != 0){ # for(g in c(1:AnzGaussians)){ # if(IsLogDistribution[g] == TRUE){ # LogNormal # SingleGaussian[,g] <- Symlognpdf(X,Means[g],SDs[g])*Weights[g] # LogNormal # }else{ # Gaussian # SingleGaussian[,g] = dnorm(X,Means[g],SDs[g])*Weights[g] # }# if IsLogDistribution(i) ==T # GaussMixture = GaussMixture + SingleGaussian[,g] # } # for g plot.new() par(xaxs='i') par(yaxs='i') par(usr=c(xlim,ylim)) #par(mar=c(5.1,4.1,4.1,2.1)) #par(ann=F) if(SingleGausses){ for(g in c(1:AnzGaussians)){ #par(new = TRUE) points(X, SingleGaussian[,g], col = SingleColor, type = 'l', xlim = xlim, ylim = ylim, ylab="PDE", ...) } } points(X, GaussMixture, col = MixtureColor, type = 'l',xlim = xlim,...) } else{#SingleColor == 0 points(X, GaussMixture, col = MixtureColor, type = 'l', xlim, ylim,axes=FALSE, ...) } if(axes){ axis(1,xlim=xlim,col="black",las=1) #x-Achse axis(2,ylim=ylim,col="black",las=1) #y-Achse #title(xlab=xlab,ylab=ylab,main = "") #box() #Kasten um Graphen title(xlab=xlab,ylab=ylab,...) } #par(oldpar) # geht nicht, da sonst zB. abline( v = 0.4) nicht bei 0.4 sitzt... points(pdeVal$kernels,pdeVal$paretoDensity,type='l', xlim = xlim, ylim = ylim,col=DataColor,...) } return(list("MyPlot" = MyPlot, "xlim" = xlim, "ylim" = ylim)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/PlotMixtures.R
PlotMixturesAndBoundaries <-function(Data, Means, SDs, Weights, IsLogDistribution = rep(FALSE,length(Means)), Plotter="native", SingleColor = 'blue', MixtureColor = 'red', DataColor='black', BoundaryColor = 'magenta', xlab, ylab, SingleGausses = TRUE, ...){ #PlotGaussMixesAndBoundaries(Data,Means,SDs,Weights,SingleColor,MixtureColor) # Plot a Mixture of Gaussian/LogNormal and Bayesian decision boundaries # INPUT # Data[1:n] data column for which the distribution was modelled # Means[1:L] Means of Gaussians, L == Number of Gaussians # SDs[1:L] estimated Gaussian Kernels = standard deviations # Weights[1:L] relative number of points in Gaussians (prior # probabilities): sum(Weights) ==1 # OPTIONAL # IsLogDistribution(1:L) gibt an ob die jeweilige Verteilung eine # Lognormaverteilung ist,(default ==0*(1:L)) # SingleColor PlotSymbol of all the single gaussians, default # magenta # MixtureColor PlotSymbol of the mixture, default black # BoundaryColor PlotSymbol of the boundaries default green # RoundNpower Decision Boundaries are rounded by # roundn(DecisionBoundariesRoundNpower) # ... other plot arguments, like xlim = c(1,10) # OUTPUT # DecisonBoundaries(1:L-1) Bayes decision boundaries # DBY(1:L-1) y values at the cross points of the Gaussians # author MT 08/2015 # Editor QS 10/2022 def.par <- par(no.readonly = TRUE) # save default, for resetting... on.exit(par(def.par)) if(!(Plotter %in% c("native", "plotly"))){ warning("PlotMixtures: Incorrect plotter selected. Doing nothing.") } # Labels if(missing(xlab)){ xlab = '' # no label for x axis } if(missing(ylab)){ ylab = '' # no label for y axis } # Calculate intersections dec = BayesDecisionBoundaries(Means, SDs, Weights, IsLogDistribution, Ycoor = T) #MT: Bugifx #if(is.list(dec)){ DecisionBoundaries = as.vector(dec$DecisionBoundaries) #print('dec was a list, assuming usage of BayesDecisionBoundaries()') #} # Plot Gaussians VPM = PlotMixtures(Data = Data, Means = Means, SDs = SDs, Weights = Weights, Plotter = Plotter, IsLogDistribution = IsLogDistribution, SingleColor = SingleColor, MixtureColor = MixtureColor, DataColor = DataColor, xlab = xlab, ylab = ylab, SingleGausses = SingleGausses, ...) MyPlot = VPM$MyPlot if(Plotter == "plotly"){ for(i in 1:length(DecisionBoundaries)){ MyPlot = plotly::add_segments(p = MyPlot, x = DecisionBoundaries[i], xend = DecisionBoundaries[i], y = 0, yend = VPM$ylim[2], line = list("color" = BoundaryColor), showlegend = FALSE) } MyPlot }else if(Plotter == "native"){ # Intersections for(i in 1:length(DecisionBoundaries)){ abline(v = DecisionBoundaries[i], col = BoundaryColor) } } return(list("MyPlot" = MyPlot, "DecisionBoundaries" = DecisionBoundaries, "DBY" = dec$DBY)) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/PlotMixturesAndBoundaries.R
QQplotGMM=function(Data, Means, SDs, Weights, IsLogDistribution = Means*0, Method = 1, Line = TRUE, PlotSymbol = 20, col = "red", xug = NULL, xog = NULL, LineWidth = 2, PointWidth = 0.8, PositiveData = FALSE, Type = 8, NoQuantiles = 10000, ylabel = 'Data', main = 'QQ-plot Data vs GMM', lwd = 3, pch = 20, xlabel='Gaussian Mixture Model', ...){ # QQplotGMM(Data,Means,SDs,Weights,IsLogDistribution,Line,PlotSymbol,xug,xog,LineWidth,PointWidth) # Quantile/Quantile = QQ-Plot im Vergleich. zu einem Gauss Mixture Model oder LGL Model # INPUT # Data(1:n) Daten, deren Verteilung verglichen werden soll # Means(1:L), SDs(1:L), Weights(1:L) die Paramter von Gaussians N(i) = Weights(i) * N(Means(i),SDs(i) # die Gesamtverteilung ergibst sich als Summe der N(i) # OPTIONAL # Method Integer: Old version stays as default (Method = 1) # New method: Method == 2 (enforces new properties and robustness) # IsLogDistribution(1:L) gibt an ob die Einzelverteilung einer (generalisierten)Lognormaverteilung ist # wenn IsLogDistribution(i)==0 dann Mix(i) = Weights(i) * N(Means(i),SDs(i) # wenn IsLogDistribution(i)==1 dann Mix(i) = Weights(i) * LogNormal(Means(i),SDs(i) # Default: IsLogDistribution = Means*0; # Line Line in QQplot: =TRUE (Default), without False # PlotSymbol Symbol fur den qqplot, wenn nicht angegeben: PlotSymbol='b.' # col Character: color of regression line (only for Method = 2) # Type Integer: number of method used for computing the quantiles # NoQuantiles Integer: Number of quantiles to compute (only for Method = 2) # xug,xog Grenzen der Interpolationsgeraden, interpoliert wird fuer percentiles(x) in [xug,xog] # Default: xug==min(x),xog==max(x), MT: Noch nicht implementiert! # LineWidth Linienbreite der Interpolationsgeraden; Default =3 # PointWidth Dicke der Punkte im QQplot, existert nicht in Matlab # LineSymbol Liniensymbol der Interpolationsgerade; Default ='r-' MT: Nicht Implementiert # lwd Integer: graphic parameter - line width option (only for Method = 2) # pch Integer: graphic parameter for points (only for Method = 2) # in \dbt\Plot # benutzt randomLogMix und qqplotfit # MT 2014, reimplementiert aus Matlab von ALU # Aus historischen Gr?nden QQplotGMM MIT Ausgleichgerade # QMS 2023: Integrate the DataVisualization approach of QQPlot (Method == 2) #xug = min(Data); xog = max(Data); zu implementieren # LineSymbol='r-' nicht implementiert GMM = RandomLogGMM(Means,SDs,Weights,IsLogDistribution); if(PositiveData == TRUE){ GMM = GMM[GMM >= 0] } if(Method == 1){ quants<-qqplot(GMM, Data, pch=PlotSymbol, col="blue", cex=PointWidth, xlab=xlabel, ylab=ylabel, main=main,...) #MT: na.rm=TRUE argument weglassen if(Line){ fit<-lm(quants$y~quants$x) summary(fit) abline(fit, col="red", lwd=LineWidth) } return(invisible(quants)) }else{ Res = DataVisualizations::QQplot(X = GMM, Y = Data, Type = Type, NoQuantiles = NoQuantiles, xlab = xlabel, ylab = ylabel, col = col, main = main, lwd = lwd, pch = pch, ...) return(Res) } }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/QQplotGMM.R
RandomLogGMM=function(Means,SDs,Weights,IsLogDistribution,TotalNoPoints=1000){ # GMM = RandomLogGMM(Means,SDs,Weights,IsLogDistribution,TotalNoPoints) # genereierung von ZufalsDaten, die einer Mischung von Vereilungen aus # Gauss & Log-Normalen folgt # INPUT # Means(1:L), SDs(1:L), Weights(1:L) die Paramter von der Verteilungen # IsLogDistribution(1:L) gibt an ob die einzelverteilung einer (generalisierten)Lognormaverteilung ist # wenn IsLogDistribution(i)==0 dann Mix(i) = Weights(i) * N(Means(i),SDs(i) # wenn IsLogDistribution(i)==1 dann Mix(i) = Weights(i) * LogNormal(Means(i),SDs(i) # Die Gesamtverteilung ergibst sich als Summe der GMM(1:L) # # OPTIONAL # TotalNoPoints Mix enthalet so viele Punkte am Schluss. # Default: TotalNrOfPoints ca 1000 # # NOTA: die Log-Normalverteilung ist generaisiert d.h.: L(Means,SDs) = sign(Means)*lognrnd(abs(Means),SDs); #author: ?, RG #1.Eitor: MT 06/2015 #2.Editor: MT 03/19 deutliche effizienzsteigerung eingepflegt fuer normale gausse. L= length(Means) AnzPoints = round(Weights*TotalNoPoints*1.1) # Verteilung der Mischungen erzeugen Mix = c() # init if(missing(Means)){ stop('Means are missing.') } if(is.null(Means)){ stop('Means are NULL.') } if(missing(IsLogDistribution)) IsLogDistribution=Means*0 #requireNamespace('dqrng') for(d in 1:L){ if(IsLogDistribution[d]==1){ # Mixi = symlogrnd(Means[d],SDs[d],AnzPoints[d],1) # Mix(i) als LogNormal erzeugen #temp <- symlognSigmaMue(Means[d],SDs[d]) variance<-log(SDs[d]*SDs[d]/(Means[d]*Means[d])+1) sig<-sqrt(variance) mu<-log(abs(Means[d]))-0.5*variance temp=list(variance=variance,sig=sig,mu=mu) mu <- temp$mu sig <- temp$sig n <- AnzPoints[d]*1 Mixi <- matrix(sign(Means[d]) * rlnorm(n, abs(mu), sig), AnzPoints[d], 1) }else{ # Mormalverteilung #Mixi = normrnd(Means[d],SDs[d],AnzPoints[d],1) # Mix(i) als Gauss erzeugen x <- 1*AnzPoints[d] #Mixi <- matrix(rnorm(n=x, mean=Means[d], sd=SDs[d]), nrow=AnzPoints[d], ncol=1) #MT 2019/03: das ist die schnelle version fuer den bottleneck #Mixi <- matrix(dqrng::dqrnorm(n=x, mean=Means[d], sd=SDs[d]), nrow=AnzPoints[d], ncol=1) # 2019/12: Using Ralf's Stubner suggestions if(requireNamespace("dqrng", quietly = TRUE)){ Mixi <- matrix(dqrng::dqrnorm(n=x, mean=Means[d], sd=SDs[d]), nrow=AnzPoints[d], ncol=1) }else{ Mixi <- matrix(rnorm(n=x, mean=Means[d], sd=SDs[d]), nrow=AnzPoints[d], ncol=1) } } Mix = c(Mix,Mixi) } # for d # hier enthaelt Mix die der Vereilung entsprechende Punkte # Dureinanderwuerfeln und auf gewuenschte Anzahl bringen #MT 2019/03: das ist die schnelle version, noch anzupassen #internal disabled for cran # if(sum(AnzPoints)>TotalNoPoints) # Ind = .Internal(sample(sum(AnzPoints),TotalNoPoints, FALSE, NULL)) # else # Ind = .Internal(sample(sum(AnzPoints),TotalNoPoints, TRUE, NULL)) # if(sum(AnzPoints)>TotalNoPoints) Ind = sample(sum(AnzPoints),TotalNoPoints, FALSE, NULL) else Ind = sample(sum(AnzPoints),TotalNoPoints, TRUE, NULL) #Ind = sample(c(1:sum(AnzPoints)),TotalNoPoints) GMM=Mix[Ind] return(GMM) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/RandomLogGMM.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 meanC <- function(x) { .Call(`_AdaptGauss_meanC`, x) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/RcppExports.R
Symlognpdf = function(Data, Mean, SD){ #pdf = Symlognpdf(Data, Means, SDs); # for M>0 same as dlnorm(Data,M,S); (Dichte der log-Normalverteilung) # for M < 0: mirrored at y axis #INPUT #Data[1:n] x-values # Means, SDs Mean and Sdev of lognormal symlognSigmaMue <- function(M,S){ variance<-log(S*S/(M*M)+1) sig<-sqrt(variance) mu<-log(abs(M))-0.5*variance return (list(variance=variance,sig=sig,mu=mu)) } temp<-symlognSigmaMue(Mean,SD) mu<-temp$mu sig<-temp$sig if(Mean>=0){ pdfkt<-dlnorm(Data,meanlog=mu,sdlog=sig) }else{ pdfkt<-Data*0 negDataInd<-which(Data<0) pdfkt[negDataInd] <- dlnorm(-Data[negDataInd],meanlog=mu,sdlog =sig) # plot(Data,pdfkt) } return (pdfkt) }
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/Symlognpdf.R
# getOptGauss ######################################################################### `getOptGauss` <- function(Data, Kernels, ParetoDensity,fast){ # Teste RMS fuer einen Gauss Mean1 <- mean(Data) Deviation1 <- sd(Data) Weight1 <- 1 Var=EMGauss(Data,fast=fast) Mean1 <- Var$Means Deviation1 <- Var$SDs Weight1 <- Var$Weights Fi <- dnorm(Kernels,Mean1,Deviation1)*Weight1 RMS1 <- sqrt(sum((Fi-ParetoDensity)^2)) # Teste RMS fuer 3 Gauss Means2 <- c(0,0,0) Deviations2 <- c(0,0,0) Weights2 <- c(0,0,0) Valskmeans <- kmeans(Data,3,iter.max=100) KValues <- Valskmeans$cluster #print(KValues2) for (i in 1:3){ Means2[i] <- mean(Data[KValues==i]) Deviations2[i] <- sd(Data[KValues==i]) Weights2[i] <- sum(KValues==i) if (is.na(Deviations2[i])) {Deviations2[i] <- 0} } Weights2 <- Weights2/length(KValues) Var=EMGauss(Data,K=length(Means2), Means2,Deviations2,Weights2,10,fast=fast) Means2 <- Var$Means Deviations2 <- Var$SDs Weights2 <- Var$Weights Fi <- 0 for (i in 1:3){ Fi <- Fi+dnorm(Kernels,Means2[i],Deviations2[i])*Weights2[i] } RMS2 <- sqrt(sum((Fi-ParetoDensity)^2)) # ueberpruefe ob RMS1( 1 Gauss) oder RMS2 (3 Gauss ) kleiner ist. Speichere zugehoerige means, deviations und weights SSE1=RMS1^2*log(3) SSE2=RMS2^2*log(3*3) if (SSE1<SSE2){ means <- Mean1 deviations <- Deviation1 weights <- Weight1 } else { means <- Means2 deviations <- Deviations2 weights <- Weights2 } # Ordne gaussians nach mean order <- order(means) means <- means[order] deviations <- deviations[order] weights <- weights[order] out=list(means=means,deviations=deviations,weights=weights) return(out) } #########################################################################
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/getOptGauss.R
# rsampleAdaptGauss ############################################################ `rsampleAdaptGauss` <- function(k,n,uniq=TRUE,exact=TRUE){ index = ceiling(runif(k)*n) # Calculate k of n values. if(uniq==TRUE){# if unique, avoide duplicates. if(k>n&exact){ # Don't run in infinite loop. print("The first parameter has to be <= the second.") print("You choose uniq = TRUE. This would cause an infinite loop.") print("Abort function.") } else{ index = unique(index) while(exact&(length(index)<k)){ index = c(index,ceiling(runif(k-length(index))*n)) index = unique(index) } return(index) } } else{ return(index) } } ############################################################
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/R/rsampleAdaptGauss.R
## ----setup, include=FALSE----------------------------------------------------- # library(rgl) # #library(rglwidget) # setupKnitr() # knitr::opts_chunk$set(echo = TRUE, # fig.align = "center", # warning = FALSE, # webgl = TRUE, # fig.width = 8, # fig.height = 8, # fig.keep = "all", # fig.ext = "jpeg" # )
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/inst/doc/AdaptGauss.R
--- title: "Short Intro into Gaussian Mixture Models" author: "Michael C. Thrun" date: "`r format(Sys.time(), '%d %b %Y')`" output: html_document: theme: united highlight: tango toc: true number_sections: true doc_depth: 2 toc_float: true fig.width: 8 fig.height: 8 vignette: > %\VignetteIndexEntry{Short Intro into Gaussian Mixture Models} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} # library(rgl) # #library(rglwidget) # setupKnitr() # knitr::opts_chunk$set(echo = TRUE, # fig.align = "center", # warning = FALSE, # webgl = TRUE, # fig.width = 8, # fig.height = 8, # fig.keep = "all", # fig.ext = "jpeg" # ) ``` # Gaussian Mixture Models (GMM) Examples in which using the EM algorithm for GMM itself is insufficient but a visual modelling approach appropriate can be found in [Ultsch et al., 2015]. In general, a GMM is explainable if the overlapping of Gaussians remains small. An good example for modeling of such a GMM in the case of natural data can be found in the ECDA presentation available on Research Gate in [Thrun/Ultsch, 2015]. In the example below the data is generated specifcally such that a the resulting GMM is statistitically signficant. The interactive approach of AdaptGauss uses shiny. Hence, I dont know how to illustrate these examples in Rmarkdown. ```{} data=c(rnorm(3000,2,1),rnorm(3000,7,3),rnorm(3000,-2,0.5)) gmm=AdaptGauss::AdaptGauss(data, Means = c(-2, 2, 7), SDs = c(0.5, 1, 4), Weights = c(0.3333, 0.3333, 0.3333)) AdaptGauss::Chi2testMixtures(data, gmm$Means,gmm$SDs,gmm$Weights,PlotIt=T) AdaptGauss::QQplotGMM(data,gmm$Means,gmm$SDs,gmm$Weights) ``` ## Multimodal Natural Dataset not Suitable for a GMM Not every multimodal dataset should be modelled with GMMs. This is an example for a non-statistically significant model of a multimodal dataset. ```{} data('LKWFahrzeitSeehafen2010') gmm=AdaptGauss::AdaptGauss(LKWFahrzeitSeehafen2010, Means = c(52.74, 385.38, 619.46, 162.08), SDs = c(38.22, 93.21, 57.72, 48.36), Weights = c(0.2434, 0.5589, 0.1484, 0.0749)) AdaptGauss::Chi2testMixtures(LKWFahrzeitSeehafen2010, gmm$Means,gmm$SDs,gmm$Weights,PlotIt=T) AdaptGauss::QQplotGMM(LKWFahrzeitSeehafen2010,gmm$Means,gmm$SDs,gmm$Weights) ``` # References Thrun, M. C., & Ultsch, A. : Models of Income Distributions for Knowledge Discovery, Proc. European Conference on Data Analysis (ECDA), DOI: 10.13140/RG.2.1.4463.0244, pp. 136-137, Colchester, 2015. Ultsch, A., Thrun, M. C., Hansen-Goos, O., & Lotsch, J. : Identification of Molecular Fingerprints in Human Heat Pain Thresholds by Use of an Interactive Mixture Model R Toolbox (AdaptGauss), International journal of molecular sciences, Vol. 16(10), pp. 25897-25911, 2015.
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/inst/doc/AdaptGauss.Rmd
--- title: "Short Intro into Gaussian Mixture Models" author: "Michael C. Thrun" date: "`r format(Sys.time(), '%d %b %Y')`" output: html_document: theme: united highlight: tango toc: true number_sections: true doc_depth: 2 toc_float: true fig.width: 8 fig.height: 8 vignette: > %\VignetteIndexEntry{Short Intro into Gaussian Mixture Models} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} # library(rgl) # #library(rglwidget) # setupKnitr() # knitr::opts_chunk$set(echo = TRUE, # fig.align = "center", # warning = FALSE, # webgl = TRUE, # fig.width = 8, # fig.height = 8, # fig.keep = "all", # fig.ext = "jpeg" # ) ``` # Gaussian Mixture Models (GMM) Examples in which using the EM algorithm for GMM itself is insufficient but a visual modelling approach appropriate can be found in [Ultsch et al., 2015]. In general, a GMM is explainable if the overlapping of Gaussians remains small. An good example for modeling of such a GMM in the case of natural data can be found in the ECDA presentation available on Research Gate in [Thrun/Ultsch, 2015]. In the example below the data is generated specifcally such that a the resulting GMM is statistitically signficant. The interactive approach of AdaptGauss uses shiny. Hence, I dont know how to illustrate these examples in Rmarkdown. ```{} data=c(rnorm(3000,2,1),rnorm(3000,7,3),rnorm(3000,-2,0.5)) gmm=AdaptGauss::AdaptGauss(data, Means = c(-2, 2, 7), SDs = c(0.5, 1, 4), Weights = c(0.3333, 0.3333, 0.3333)) AdaptGauss::Chi2testMixtures(data, gmm$Means,gmm$SDs,gmm$Weights,PlotIt=T) AdaptGauss::QQplotGMM(data,gmm$Means,gmm$SDs,gmm$Weights) ``` ## Multimodal Natural Dataset not Suitable for a GMM Not every multimodal dataset should be modelled with GMMs. This is an example for a non-statistically significant model of a multimodal dataset. ```{} data('LKWFahrzeitSeehafen2010') gmm=AdaptGauss::AdaptGauss(LKWFahrzeitSeehafen2010, Means = c(52.74, 385.38, 619.46, 162.08), SDs = c(38.22, 93.21, 57.72, 48.36), Weights = c(0.2434, 0.5589, 0.1484, 0.0749)) AdaptGauss::Chi2testMixtures(LKWFahrzeitSeehafen2010, gmm$Means,gmm$SDs,gmm$Weights,PlotIt=T) AdaptGauss::QQplotGMM(LKWFahrzeitSeehafen2010,gmm$Means,gmm$SDs,gmm$Weights) ``` # References Thrun, M. C., & Ultsch, A. : Models of Income Distributions for Knowledge Discovery, Proc. European Conference on Data Analysis (ECDA), DOI: 10.13140/RG.2.1.4463.0244, pp. 136-137, Colchester, 2015. Ultsch, A., Thrun, M. C., Hansen-Goos, O., & Lotsch, J. : Identification of Molecular Fingerprints in Human Heat Pain Thresholds by Use of an Interactive Mixture Model R Toolbox (AdaptGauss), International journal of molecular sciences, Vol. 16(10), pp. 25897-25911, 2015.
/scratch/gouwar.j/cran-all/cranData/AdaptGauss/vignettes/AdaptGauss.Rmd
asggm <- function(x, ...) UseMethod("asggm") asggm.default <- function(x, iterations = 100000000, init = NULL, epsilon = 0.001, ...) { x <- as.matrix(x) if (!is.null(init)) { init <- as.matrix(init) } result <- rCSL(x, iterations, init, epsilon, ...) class(result) <- "asggm" result } # TODO do we really want a formula interface? # if so, we need to add the model response as a column in x instead of putting it in y asggm.formula <- function(formula, data=list(), ...) { mf <- model.frame(formula=formula, data=data) x <- model.matrix(attr(mf, "terms"), data=mf) y <- model.response(mf) result <- asggm.default(x, ...) result } genL = function(kNodes, spP) { L = matrix(0, kNodes, kNodes) for (i in 2:kNodes) { for (j in 1:(i-1)) { L[i,j] = (runif(1) < spP) * rnorm(1, 0, 1) } } # diag(L) = 1 for (k in 1:kNodes) { L[k,k] = rnorm(1, 1, 0.1) } L } genData = function(L, nSamples) { kNodes = nrow(L) xTemp = matrix(rnorm(kNodes*nSamples, mean = 0, sd = 1), nrow = nSamples, ncol = kNodes) #### x = t(t(solve(L))%*%t(xTemp)) x = xTemp%*%solve(L) x } rCSL = function(x, iterations = 500, init = NULL, epsilon = 1e-5, ansL = NULL){ # TODO, compute init if it's null (init is L matrix) # TODO call C++ CSL # TODO return something LInit = init nSamples = nrow(x) kNodes = ncol(x) S = cov(x) * (nSamples-1) if (is.null(init)) { # LInit = .Call("olsInit", x, PACKAGE = "AdaptiveSparsity") # LInit = LInit[["OLS L"]] # LInit = t(chol(solve(S))) Sinv = ginv(S) LUSinv = expand(lu(Sinv)) LInit = as.matrix(LUSinv$L) } if (is.null(ansL)) { ansQ = LInit%*%t(LInit) } else { ansQ = ansL%*%t(ansL) } print(norm(ansQ-LInit%*%t(LInit),'f')) CSLOut = .Call(C_CSL, iterations, LInit, kNodes, nSamples, epsilon, S, ansQ, PACKAGE = "AdaptiveSparsity") CSLOut }
/scratch/gouwar.j/cran-all/cranData/AdaptiveSparsity/R/asggm.R
# adaptive sparse linear model using Figueiredo EM algorithm for adaptive sparsity (Jeffreys prior) # Followed example from Leisch - CreatingPackages # TODO: According to Leisch, this example is minimalistic, production code should handle more cases such as: # missing values, weights, offsets, subsetting, etc. (Ie see beginning of lm() in R) # TODO: pick better names! # TODO: implement plot, deviance, anova, step, vcov, extractAIC, logLik # TODO: how many of these methods above can just call lm's implementation? aslm <- function(x, ...) UseMethod("aslm") aslm.default <- function(x, y, ...) { x <- as.matrix(x) y <- as.numeric(y) est <- figEM(x, y, ...) est$fitted.values <- as.vector(x %*% est$coefficients) est$residuals <- y - est$fitted.values # TODO better rank calculation!!!! est$rank <- 0 # set rank to 0 for now to avoid use of qr.lm in places such as plot.lm est$call <- match.call() # TODO how to handle formula and data etc. to support summary.aslm? est$data <- c(x, y) est$contrasts <- attr(x, "contrasts") class(est) <- c("aslm","lm") est } getSparseModel <- function(object) { zeros = which(object$coefficients==0) zeronames = names(object$coefficients[zeros]) allnames = attr(object$terms,"term.labels") #zeronames = attr(object$terms,"term.labels")[zeros] sparse.model = ". ~ ." contrastnames = names(object$contrasts) namelens = sapply(contrastnames, nchar) if (length(namelens) > 0) { sortednames = sort(namelens, decreasing=TRUE, index.return=TRUE) } else { sortednames = c() } for (nn in zeronames) { if (nn %in% allnames) { # not a factor sparse.model = paste(sparse.model, " -", nn, sep="") } else { if (nn == "(Intercept)") { sparse.model = paste(sparse.model, " -1", sep="") } else if (is.null(sortednames)) { warning(paste(nn, " had a zero coefficient, but is not in term.labels and is not a factor. Cannot remove it from the model.")) } else { factor.found = FALSE for (cc in contrastnames[sortednames$ix]) { # go through contrastnames, starting with the longest name first # for the case when one variable's name is the same as another variable's name with # extra characters added on. if (substr(nn,1,nchar(cc))==cc) { # now make sure ALL levels with this factor are 0 # tricky for now just handle 2 level case (since we don't have to check any other coefficients) # TODO handle more than two levels sparse.model = paste(sparse.model, " -", cc, sep="") } } } } } sparse.formula = deparse(update(formula(object), sparse.model), width.cutoff=500) m <- lm(sparse.formula, data=object$data) return(m) } print.aslm <- function(x, ...) { cat("Call:\n") print(x$call) cat("\nCoefficients:\n") print(x$coefficients) } summary.aslm <- function(object, ...) { # TODO do we have a vcov? Yes, but it's wrong (just the identity matrix) # so instead of calculating things ourselves, lets feed the new sparse model # in to lm to get lm's summary calculations m <-getSparseModel(object) res <- summary(m) res$lm <- m res$call <- object$call res$formula <- formula(object) class(res) <- c("summary.aslm","summary.lm") res } print.summary.aslm <- function(x, ...) { cat("Call:\n") print(x$call) cat("\n") cat("Original formula:\n") print(x$formula) cat("\n") cat("Sparse formula:\n") print(formula(x$lm)) cat("\n") cat("Residuals:\n") print(summary(x$residuals)) cat("\n") printCoefmat(x$coefficients, P.values=TRUE, has.Pvalue=TRUE) } aslm.formula <- function(formula, data=list(), na.action=na.omit, ...) { mf <- model.frame(formula=formula, data=data, na.action = na.action) x <- model.matrix(attr(mf, "terms"), data=mf) y <- model.response(mf) est <- aslm.default(x, y, ...) est$call <- match.call() est$formula <- formula # TODO return all terms or only nonzero terms est$terms <- attr(mf, "terms") est$data <- mf est } predict.aslm <- function(object, newdata=NULL, ...) { if (is.null(newdata)) y <- fitted(object) else { if (!is.null(object$formula)) { ## model has been fitted using formula interface x <- model.matrix(object$formula, newdata) } else { x <- newdata } y <- as.vector(x %*% coef(object)) } y } logLik.aslm <- function(object, ...) NextMethod() nobs.aslm <- function(object, ...) NextMethod() fit.ols.lm <- function(x, y) { lmf = lm.fit(x, y) beta = lmf$coefficients sigma = sqrt(sum((lmf$residuals)^2) / length(y)) return(list(beta = beta, sigma = sigma)) } init.ones <- function(x,y) { n = length(y) beta <- as.numeric(matrix(1,dim(x)[2],1)) sigma = sqrt(sum((y - x %*% beta)^2) / n) return(list(beta = beta, sigma = sigma)) } init.runif <- function(x,y) { n = length(y) beta <- as.numeric(matrix(runif(dim(x)[2]),dim(x)[2],1)) sigma = sqrt(sum((y - x %*% beta)^2) / n) return(list(beta = beta, sigma = sigma)) } init.rnorm <- function(x,y) { n = length(y) beta <- as.numeric(matrix(rnorm(dim(x)[2],0,50),dim(x)[2],1)) sigma = sqrt(sum((y - x %*% beta)^2) / n) return(list(beta = beta, sigma = sigma)) } # Figueiredo EM algorithm for adaptive sparsity (Jeffreys prior) figEM <- function(x, y, init = NULL, stopDiff = 1e-8, epsilon = 1e-6, a = 1) { n = dim(x)[1] d = dim(x)[2] if (n < d) { stop(paste('number of observations or rows (',n,') is less than number of dimensions or columns (',d,')')) } if(is.null(init)) { init = fit.ols.lm(x,y) #init = init.ones(x,y) #init = init.runif(x,y) #init = init.rnorm(x,y) } beta = init$beta # TODO ok, perhaps we can use a better estimate of variance of beta than max(abs(beta))/2 # also, should this somehow be related to the scale of x or y? naidx = is.na(beta) betavar = max(abs(beta[!naidx])) / 2 beta[naidx] = rnorm(length(beta[naidx]),0,betavar) sigma = sqrt(sum((y - x %*% beta)^2) / length(y)) sigmaSqr = sigma^2 diff = stopDiff + 1 while(diff > stopDiff) { oldBeta = beta oldSigmaSqr = sigmaSqr # TODO, now that we are throwing out nonzero components, is it still necessary to add in epsilon for stability? U = diag((abs(beta) + epsilon),d,d) cols <- which((U>2*epsilon) & !is.na(U), arr.ind=TRUE)[,1] if (length(cols) > 0) { Unz <- U[cols,cols] xnz <- x[,cols] betanz = try(as.numeric(Unz %*% solve(diag(a*sigmaSqr,length(cols),length(cols)) + Unz %*% t(xnz) %*% xnz %*% Unz, Unz %*% t(xnz) %*% y))); if(class(betanz) == "try-error") break beta[cols] <- betanz beta[-cols] <- 0 } sigmaSqr = sum((y - x %*% beta)^2 / n) diff = sqrt(sum((oldBeta - beta)^2) + (oldSigmaSqr - sigmaSqr)^2) } vcov <- diag(d) colnames(vcov) <- rownames(vcov) <- colnames(x) names(beta) <- colnames(x) # TODO return covariances? return(list(coefficients = beta, vcov = vcov, sigma = sqrt(sigmaSqr), df = n - d )) }
/scratch/gouwar.j/cran-all/cranData/AdaptiveSparsity/R/aslm.R
TTT <- function(x,lwd=2,lty=2,col="black",grid=TRUE,...) { n <- length(x) y <- order(x) sortx <- x[y] Trn <- rep(NA, times = n) r <- rep(NA, times = n) Trn[1] <- n*sortx[1] r[1] <- 1/n for(i in 2:n) { Trn[i] <- Trn[i-1]+(n-i+1)*(sortx[i]-sortx[i-1]) r[i] <- i/n } plot(r,Trn/Trn[n],xlab="i/n",ylab="T(i/n)",xlim=c(0,1), ylim=c(0,1), main="",type="l",lwd=lwd, lty=1,col=col,...) lines(c(0,1),c(0,1),lty=lty,lwd=1,...) if(grid=="TRUE") grid() }
/scratch/gouwar.j/cran-all/cranData/AdequacyModel/R/TTT.R
descriptive <- function(x) { is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol mode <- function(x){ if(all(is.wholenumber(x))==TRUE){ matrix_number = matrix(0,nrow=length(x),ncol=2) for(i in 1:length(x)){ id = which(x==x[i]) matrix_number[i,] = c(x[i],length(id)) } mode = unique(x[which(as.numeric(matrix_number[,2])==max(as.numeric(matrix_number[,2])))]) if(all(matrix_number[,2]==matrix_number[1,2])==TRUE){ mode = NA } } if(all(is.wholenumber(x))==FALSE){ histogram = hist(x) if(all(histogram$counts==histogram$counts[1])==TRUE) mode = NA else{ id = which(histogram$counts==max(histogram$counts)) mode = histogram$mids[id] } if(all(histogram$counts==histogram$counts[1])==TRUE) mode = NA } return(mode) } skewness <- function(x){ (1/length(x) * sum((x-mean(x))^3))/(1/length(x) * sum((x-mean(x))^2))^(3/2) } kurtosis <- function(x){ (1/length(x) * sum((x-mean(x))^4))/(1/length(x) * sum((x-mean(x))^2))^2 - 3 } statistics <- list(mean = round(mean(x), 5),median = round(median(x), 5), mode = round(mode(x), 5), variance = round(var(x), 5), Skewness = round(skewness(x), 5), Kurtosis = round(kurtosis(x), 5), minimum = round(min(x), 5), maximum = round(max(x), 5), n = length(x)) return(statistics) }
/scratch/gouwar.j/cran-all/cranData/AdequacyModel/R/descriptive.R
goodness.fit <- function(pdf, cdf, starts, data, method = "PSO", domain = c(0,Inf), mle = NULL,...){ if(missingArg(cdf)==TRUE) stop("Unknown cumulative distribution function. The function needs to be informed.") if(missingArg(pdf)==TRUE) stop("Unknown probability density function. The function needs to be informed.") if(class(pdf)!="function") stop("The argument pdf must be a function. See the example in the documentation!") if(class(cdf)!="function") stop("The argument cdf must be a function. See the example in the documentation!") if(missingArg(data)==TRUE) stop("Database missing!") if(TRUE%in%is.nan(data)==TRUE) warning("The data have missing information!") if(length(domain)!=2) stop("The domain must have two arguments!") if(is.null(mle)==TRUE){ if(missingArg(starts)==TRUE) stop("The initial shots were not informed!") }else{ starts = mle } # Verifying properties of cumulative distribution function. if(cdf(par=starts, x = domain[2])!=1) warning("The cdf function informed is not a cumulative distribution function! The function no takes value 1 in Inf.") if(cdf(par=starts, x = domain[1])!=0) warning("Check if the cumulative distribution informed is actually a distribution function.") myintegrate = function(...) tryCatch(integrate(...), error=function(e) NA) value_int = as.numeric(myintegrate(f=pdf,par=starts,lower=domain[1], upper=domain[2])[1]) if(isTRUE(is.na(value_int))==TRUE) warning("Make sure that pdf is a probability density function. The integral in the domain specified is not convergent.") if(isTRUE(is.na(value_int))!=TRUE){ #Verifying properties of probability density function. if(value_int<0.90){ warning("The integral from ", domain[1], " to ", domain[2]," of the probability density function has different from 1. Make sure the option domain is correct.") } if(round(value_int)!=1){ warning("pdf is not a probability density function.") } } if(is.null(mle)==TRUE){ likelihood = function(par,x){ -sum(log(pdf(par,x))) } if(method == "PSO" || method == "P"){ result = pso(func = likelihood, data = data,...) } if(method == "Nelder-Mead" || method == "N"){ result = optim(par = starts, fn = likelihood, x = data, method = "Nelder-Mead", hessian = TRUE) } if(method == "CG" || method == "C"){ result = optim(par = starts, fn = likelihood, x = data, method = "CG", hessian = TRUE) } if(method == "SANN" || method == "S"){ result = optim(par = starts, fn = likelihood, x = data, method = "SANN", hessian = TRUE) } if(method == "BFGS" || method == "B"){ result = optim(par = starts, fn = likelihood, x = data, method = "BFGS", hessian = TRUE) } if((FALSE %in% (method != c("PSO", "L", "BFGS", "B", "Nelder-Mead", "P", "N", "SANN", "S", "CG", "C")))==FALSE){ stop("Valid options are: PSO or P, BFGS or B, Nelder-Mead or N, SANN or S, CG or C.") } parameters = result$par hessiana = result$hessian # matriz hessiana. data_orderdenados = sort(data) v = cdf(as.vector(parameters), data_orderdenados) # Dados ordenados. n = length(data) # Tamanho da amostra. y = qnorm(v) # Inversa da acumulada da normal. y[which(y==Inf)] = 10 u = pnorm((y-mean(y))/sqrt(var(y))) W_temp <- vector() A_temp <- vector() for(i in 1:n){ W_temp[i] = (u[i] - (2*i-1)/(2*n))^2 A_temp[i] = (2*i-1)*log(u[i]) + (2*n+1-2*i)*log(1-u[i]) } A_2 = -n - mean(A_temp) W_2 = sum(W_temp) + 1/(12*n) W_star = W_2*(1+0.5/n) A_star = A_2*(1+0.75/n + 2.25/n^2) p = length(parameters) log.likelihood = -1*likelihood(parameters,data) AICc = -2*log.likelihood + 2*p + 2*(p*(p+1))/(n-p-1) AIC = -2*log.likelihood + 2*p BIC = -2*log.likelihood + p*log(n) HQIC = -2*log.likelihood + 2*log(log(n))*p ks.testg = function(...) tryCatch(ks.test(...), warning = function(war) NA) KS = ks.test(x = data, y= "cdf", par = as.vector(parameters)) if(method=="PSO" || method=="P"){ result = (list("W" = W_star,"A" = A_star, "KS" = KS, "mle" = parameters, "AIC" = AIC ,"CAIC " = AICc, "BIC" = BIC, "HQIC" = HQIC, "Value" = result$f[length(result$f)])) class(result) <- "list" return(result) }else{ result = (list("W" = W_star,"A" = A_star, "KS" = KS, "mle" = parameters, "AIC" = AIC ,"CAIC " = AICc, "BIC" = BIC, "HQIC" = HQIC, "Erro" = sqrt(diag(solve(hessiana))), "Value" = result$value, "Convergence" = result$convergence)) class(result) <- "list" return(result) } } if(class(mle)=="numeric"){ likelihood = function(par,x){ -sum(log(pdf(par,x))) } parameters = mle data_orderdenados = sort(data) v = cdf(as.vector(parameters),data_orderdenados) # Dados ordenados. n = length(data) # Tamanho da amostra. y = qnorm(v) # Inversa da acumulada da normal. y[which(y==Inf)] = 10 u = pnorm((y-mean(y))/sqrt(var(y))) W_temp <- vector() A_temp <- vector() for(i in 1:n){ W_temp[i] = (u[i] - (2*i-1)/(2*n))^2 A_temp[i] = (2*i-1)*log(u[i]) + (2*n+1-2*i)*log(1-u[i]) } A_2 = -n - mean(A_temp) W_2 = sum(W_temp) + 1/(12*n) W_star = W_2*(1+0.5/n) A_star = A_2*(1+0.75/n + 2.25/n^2) p = length(parameters) log.likelihood = -1*likelihood(parameters,data) AICc = -2*log.likelihood + 2*p + 2*(p*(p+1))/(n-p-1) AIC = -2*log.likelihood + 2*p BIC = -2*log.likelihood + p*log(n) HQIC = -2*log.likelihood + 2*log(log(n))*p ks.testg = function(...) tryCatch(ks.test(...), warning = function(war) NA) KS = ks.test(x = data, y= "cdf", par = as.vector(parameters)) result = (list("W" = W_star,"A" = A_star, "KS" = KS, "AIC" = AIC, "CAIC" = AICc, "BIC" = BIC, "HQIC" = HQIC)) class(result) <- "list" return(result) } }
/scratch/gouwar.j/cran-all/cranData/AdequacyModel/R/goodness.fit.R
pso <- function(func, S = 350, lim_inf, lim_sup, e = 0.0001, data = NULL, N = 500, prop = 0.2) { b_lo = min(lim_inf) b_up = max(lim_sup) integer_max = .Machine$integer.max if (length(lim_sup) != length(lim_inf)) { stop("The vectors lim_inf and lim_sup must have the same dimension.") } dimension = length(lim_sup) swarm_xi = swarm_pi = swarm_vi = matrix(NA, nrow = S, ncol = dimension) # The best position of the particles. g = runif(n = dimension, min = lim_inf, max = lim_sup) # Objective function calculated in g. f_g = func(par = as.vector(g), x = as.vector(data)) if (NaN %in% f_g == TRUE || Inf %in% abs(f_g) == TRUE) { while (NaN %in% f_g == TRUE || Inf %in% abs(f_g) == TRUE) { g = runif(n = dimension, min = lim_inf, max = lim_sup) f_g = func(par = g, x = as.vector(data)) } } # Here begins initialization of the algorithm. x_i = mapply(runif, n = S, min = lim_inf, max = lim_sup) # Initializing the best position of particularities i to initial position. swarm_pi = swarm_xi = x_i f_pi = apply( X = x_i, MARGIN = 1, FUN = func, x = as.vector(data) ) is.integer0 <- function(x) { is.integer(x) && length(x) == 0L } if (NaN %in% f_pi == TRUE || Inf %in% abs(f_pi)) { while (NaN %in% f_pi == TRUE || Inf %in% abs(f_pi)) { id_inf_fpi = which(abs(f_pi) == Inf) if (is.integer0(id_inf_fpi) != TRUE) { f_pi[id_inf_fpi] = integer_max } id_nan_fpi = which(f_pi == NaN) if (is.integer0(id_nan_fpi) != TRUE) { x_i[id_nan_fpi,] = mapply(runif, n = length(id_nan_fpi), min = lim_inf, max = lim_sup) swarm_pi = swarm_xi = x_i f_pi = apply( X = x_i, MARGIN = 1, FUN = func, x = as.vector(data) ) } } } minimo_fpi = min(f_pi) if (minimo_fpi < f_g) g = x_i[which.min(f_pi),] # Initializing the speeds of the particles. swarm_vi = mapply(runif, n = S, min = -abs(rep(abs(b_up - b_lo), dimension)), max = abs(rep(abs(b_up - b_lo), dimension))) # Here ends the initialization of the algorithm omega = 0.5 phi_p = 0.5 phi_g = 0.5 m = 1 vector_f_g <- vector() #vector_par <- vector() while (1) { # r_p and r_g are randomized numbers in (0.1). r_p = runif(n = dimension, min = 0, max = 1) r_g = runif(n = dimension, min = 0, max = 1) # Updating the vector speed. swarm_vi = omega * swarm_vi + phi_p * r_p * (swarm_pi - swarm_xi) + phi_g * r_g * (g - swarm_xi) # Updating the position of each particle. swarm_xi = swarm_xi + swarm_vi myoptim = function(...) tryCatch( optim(...), error = function(e) NA ) f_xi = apply( X = as.matrix(swarm_xi), MARGIN = 1, FUN = func, x = as.vector(data) ) f_pi = apply( X = as.matrix(swarm_pi), MARGIN = 1, FUN = func, x = as.vector(data) ) f_g = func(par = g, x = as.vector(data)) #vector_par[m] = g if (NaN %in% f_xi == TRUE || NaN %in% f_pi == TRUE) { while (NaN %in% f_xi == TRUE) { id_comb = c(which(is.na(f_xi) == TRUE), which(is.na(f_pi) == TRUE)) if (is.integer0(id_comb) != TRUE) { new_xi = mapply(runif, n = length(id_comb), min = lim_inf, max = lim_sup) swarm_pi[id_comb,] = swarm_xi[id_comb,] = new_xi if (length(id_comb) > 1) { f_xi[id_comb] = apply( X = as.matrix(swarm_xi[id_comb,]), MARGIN = 1, FUN = func, x = as.vector(data) ) f_pi[id_comb] = apply( X = as.matrix(swarm_pi[id_comb,]), MARGIN = 1, FUN = func, x = as.vector(data) ) } else{ f_xi[id_comb] = func(par = new_xi, x = as.vector(data)) } } } } if (Inf %in% abs(f_xi) == TRUE) { f_xi[which(is.infinite(f_xi))] = integer_max } if (Inf %in% abs(f_pi) == TRUE) { f_pi[which(is.infinite(f_pi))] = integer_max } # There are values below the lower limit of restrictions? id_test_inf = which(apply(swarm_xi < t(matrix( rep(lim_inf, S), dimension, S )), 1, sum) >= 1) id_test_sup = which(apply(swarm_xi > t(matrix( rep(lim_sup, S), dimension, S )), 1, sum) >= 1) if (is.integer0(id_test_inf) != TRUE) { swarm_pi[id_test_inf,] = swarm_xi[id_test_inf,] = mapply(runif, n = length(id_test_inf), min = lim_inf, max = lim_sup) } if (is.integer0(id_test_sup) != TRUE) { swarm_pi[id_test_sup,] = swarm_xi[id_test_sup,] = mapply(runif, n = length(id_test_sup), min = lim_inf, max = lim_sup) } if (is.integer0(which((f_xi <= f_pi) == TRUE))) { swarm_pi[which((f_xi <= f_pi)),] = swarm_pi[which((f_xi <= f_pi)),] } if (f_xi[which.min(f_xi)] <= f_pi[which.min(f_pi)]) { swarm_pi[which.min(f_pi),] = swarm_xi[which.min(f_xi),] if (f_pi[which.min(f_pi)] < f_g) g = swarm_pi[which.min(f_pi),] } # Here ends the block if. vector_f_g[m] = f_g m = m + 1 if(length(vector_f_g)>=N){ n_var = ceiling(length(vector_f_g)*prop) id_var = seq(length(vector_f_g),length(vector_f_g)-n_var,-1) if(var(vector_f_g[id_var])<=e){ break } } } # Here ends the block while. f_x = apply( X = swarm_xi, MARGIN = 1, FUN = func, x = as.vector(data) ) list(par = g, f = vector_f_g) } # Here ends the function.
/scratch/gouwar.j/cran-all/cranData/AdequacyModel/R/pso.R
############################################################################################### # # AdhereR: an R package for computing various estimates of medication adherence. # Copyright (C) 2015-2018 Dan Dediu & Alexandra Dima # Copyright (C) 2018-2019 Dan Dediu, Alexandra Dima & Samuel Allemann # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### #' @import grDevices #' @import graphics #' @import stats #' @import data.table #' @import utils #' @import methods NULL # Declare some variables as global to avoid NOTEs during package building: globalVariables(c(".OBS.START.DATE", ".OBS.START.DATE.PRECOMPUTED", ".OBS.START.DATE.UPDATED", ".OBS.WITHIN.FU", ".PROCESSING.CHUNK", ".START.BEFORE.END.WITHIN.OBS.WND", ".WND.ID", ".WND.START.DATE", "CMA", ".CARRY.OVER.FROM.BEFORE", ".DATE.as.Date", ".END.EVENT.DATE", ".EVENT.STARTS.AFTER.OBS.WINDOW", ".EVENT.STARTS.BEFORE.OBS.WINDOW", ".EVENT.WITHIN.FU.WINDOW", ".FU.START.DATE", ".FU.START.DATE.UPDATED", ".INTERSECT.EPISODE.OBS.WIN.END", ".INTERSECT.EPISODE.OBS.WIN.START", ".OBS.DURATION.UPDATED", ".OBS.END.DATE", ".OBS.END.DATE.PRECOMPUTED", "PERDAY", "CATEGORY", "episode.ID", "episode.duration", "end.episode.gap.days", "cma.class.name", "events.in.episode")); # Reserved column names that cannot be used: .special.colnames <- c("..ORIGINAL.ROW.ORDER..", ".CARRY.OVER.FROM.BEFORE", ".DATE.as.Date", ".EVENT.INTERVAL", ".EVENT.STARTS.AFTER.OBS.WINDOW", ".EVENT.STARTS.BEFORE.OBS.WINDOW", ".EVENT.WITHIN.FU.WINDOW", ".FU.END.DATE", ".FU.START.DATE", ".FU.START.DATE.PER.PATIENT.ACROSS.MGS", ".FU.START.DATE.UPDATED", ".GAP.DAYS", ".INTERSECT.EPISODE.OBS.WIN.DURATION", ".INTERSECT.EPISODE.OBS.WIN.END", ".INTERSECT.EPISODE.OBS.WIN.START", ".MED_GROUP_ID", ".OBS.DURATION.UPDATED", ".OBS.END.DATE", ".OBS.END.DATE.PRECOMPUTED", ".OBS.START.DATE", ".OBS.START.DATE.PER.PATIENT.ACROSS.MGS", ".OBS.START.DATE.PRECOMPUTED", ".OBS.START.DATE.UPDATED", ".OBS.WITHIN.FU", ".PATIENT.EPISODE.ID", ".START.BEFORE.END.WITHIN.OBS.WND", ".TDIFF1", ".TDIFF2", ".WND.DURATION", ".WND.ID", ".WND.START.DATE", "CMA", "CMA.to.apply", "end.episode.gap.days", "episode.duration", "episode.end", "episode.ID", "episode.start", "events.in.episode", "window.end", "window.ID", "window.start"); ## Package private info #### # Store various info relevant to the package (such as info about the last plot or the last error). # As this is inside a package and we must avoid locking, we need to use an environment (see, e.g. https://www.r-bloggers.com/package-wide-variablescache-in-r-packages/) .adherer.env <- new.env(); # Info about the last plot (initially, none): assign(".last.cma.plot.info", NULL, envir=.adherer.env); # Info about errors, warnings and messages (initially, none): assign(".ewms", NULL, envir=.adherer.env); assign(".record.ewms", FALSE, envir=.adherer.env); # initially, do not record the errors, warnings and message, but just display them # Clear the info about errors, warnings and messages: .clear.ewms <- function() { assign(".ewms", NULL, envir=.adherer.env); } # Get the info about errors, warnings and messages (basically, a data.frame contaning all the important info, one thing per row): .get.ewms <- function() { return (get(".ewms", envir=.adherer.env)); } # Are we recording the errors, warnings and messages? .is.recording.ewms <- function() { return (!is.null(.record.ewms <- get(".record.ewms", envir=.adherer.env)) && .record.ewms); } # Start/stop recording the errors, warnings and messages: .record.ewms <- function(record=TRUE) { .clear.ewms(); assign(".record.ewms", record, envir=.adherer.env); } # Reporting an error, warning or message: .report.ewms <- function(text, # the text type=c("error", "warning", "message")[1], # the type fnc.name=NA, pkg.name=NA, # which function and package generated it generate.exception=TRUE, # should we throw an actual error or watning using R's exceptions mechanism? error.as.warning=TRUE # when reporting an error, should it stop() the whole process or be thrown as a warning() so the processes continues? ) { # Make sure text is really a text: text <- as.character(text); if( length(text) > 1 ) text <- paste0("[ ", paste0("'", as.character(text), "'", collapse="; "), " ]"); # Add this new ewms info: if( .is.recording.ewms() ) { assign(".ewms", rbind(.get.ewms(), data.frame("text"=text, "type"=type, "function"=fnc.name, "package"=pkg.name, "exception.was.thrown"=generate.exception)), envir=.adherer.env); } # Throw an exception (if the case): if( generate.exception ) { if( type == "error" ) { if( !error.as.warning ) { stop(text); } else { warning(text); } } else if( type == "warning" ) { warning(text); } else { print(paste0("Info: ",text, if(!is.na(fnc.name)) paste0(" [from function ",fnc.name, if(!is.na(pkg.name)) paste0(", package ",pkg.name), "]"), collapse="")); } } } #' Example medication events records for 100 patients. #' #' An artificial dataset containing medication events (one per row) for 100 #' patients (1080 events in total). This is the dataset format appropriate for #' medication adherence analyses performed with the R package AdhereR. #' Medication events represent individual records of prescribing or dispensing #' a specific medication for a patient at a given date. Dosage and medication #' type is optional (only needed if calculation of adherence or persistence #' takes into account changes in dosage and type of medication). #' #' @format A data frame with 1080 rows and 5 variables: #' \describe{ #' \item{PATIENT_ID}{\emph{integer} here; patient unique identifier. Can also #' be \emph{string}}. #' \item{DATE}{\emph{character};the medication event date, by default in the #' mm/dd/yyyy format. It may represent a prescribing or dispensing date.} #' \item{PERDAY}{\emph{integer}; the daily dosage prescribed for the #' medication supplied at this medication event (i.e. how many doses should #' be taken daily according to the prescription). This column is optional, #' as it is not considered in all functions but may be relevant for specific #' research or clinical contexts. All values should be > 0.} #' \item{CATEGORY}{\emph{character}; the medication type, here two placeholder #' labels, 'medA' and 'medB'. This is a researcher-defined classification #' depending on study aims (e.g., based on therapeutic use, mechanism of #' action, chemical molecule, or pharmaceutical formulation). This column is #' optional, as it is not considered in all functions but may be relevant for #' specific research or clinical contexts.} #' \item{DURATION}{\emph{integer}; the medication event duration in days (i.e. #' how many days the mediation supplied would last if used as prescribed); #' may be available in the extraction or computed based on quantity supplied #' (the number of doses prescribed or dispensed on that occasion) and daily #' dosage. All values should be > 0.} #' } "med.events" # Check, parse and evaluate the medication groups: # The idea is to transform each group into a function and let R do the heavy lifting: # Returns a list with two components: # - defs (contains the group names and definitions) and # - obs (logical matrix saying for each observation (row) if it belongs to a group (column)) # or NULL if error occurred: .apply.medication.groups <- function(medication.groups, # the medication groups data, # the data on which to apply them suppress.warnings=FALSE) { if( is.null(medication.groups) || length(medication.groups) == 0 ) { # by definition, there's nothing wrong with NULL return (list("groups"=NULL, "obs_in_groups"=NULL, "errors"=NULL)); } # Basic checks: if( is.null(data) || !inherits(data, "data.frame") || nrow(data) == 0 ) { if( !suppress.warnings ) .report.ewms("The data must be a non-emtpy data.frame (or derived) object!\n", "error", ".apply.medication.groups", "AdhereR"); return (NULL); } data <- as.data.frame(data); # make sure we convert it to a data.frame if( !(is.character(medication.groups) || is.factor(medication.groups)) ) { if( !suppress.warnings ) .report.ewms("The medication groups must be a vector of characters!\n", "error", ".apply.medication.groups", "AdhereR"); return (NULL); } if( length(medication.groups) == 1 && (medication.groups %in% names(data)) ) { # It is a column in the data: transform it into the corresponding explicit definitions: mg.vals <- unique(data[,medication.groups]); mg.vals <- mg.vals[!is.na(mg.vals)]; # the unique non-NA values if( is.null(mg.vals) || length(mg.vals) == 0 ) { if( !suppress.warnings ) .report.ewms("The column '",medication.groups,"' in the data must contain at least one non-missing value!\n", "error", ".apply.medication.groups", "AdhereR"); return (NULL); } mg.vals <- sort(mg.vals); # makes it easier to view if ordered medication.groups.defs <- paste0('(',medication.groups,' == "',mg.vals,'")'); names(medication.groups.defs) <- mg.vals; medication.groups <- medication.groups.defs; } if( length(names(medication.groups)) != length(medication.groups) || any(duplicated(names(medication.groups))) || ("" %in% names(medication.groups)) ) { if( !suppress.warnings ) .report.ewms("The medication groups must be a named list with unique and non-empty names!\n", "error", ".apply.medication.groups", "AdhereR"); return (NULL); } # The safe environment for evaluating the medication groups (no parent) containing only the needed variables and functions (as per https://stackoverflow.com/a/18391779): safe_env <- new.env(parent = emptyenv()); # ... add the safe functions: for( .f in c(getGroupMembers("Math"), getGroupMembers("Arith"), getGroupMembers("Logic"), getGroupMembers("Compare"), "(", "[", "!") ) { safe_env[[.f]] <- get(.f, "package:base"); } # ... and variables: assign(".data", data, envir=safe_env); # the data assign(".res", matrix(NA, nrow=nrow(data), ncol=length(medication.groups)), envir=safe_env); # matrix of results from evaluating the medication classes assign(".evald", rep(FALSE, length(medication.groups)), envir=safe_env); # records which the medication groups were already evaluated (to speed up things) assign(".errs", NULL, envir=safe_env); # possible errors encountered during the evaluation # The safe eval function (use evalq to avoid searching in the current environment): evalq(expr, env = safe_env); # Check, transform, parse and add the group definitions as functions to the .mg_safe_env_original environment to be later used in the safe evaluation environment: mg <- data.frame("name"=names(medication.groups), "def"=medication.groups, "uid"=make.names(names(medication.groups), unique=TRUE, allow_=TRUE), "fnc_name"=NA); # convert the names to valid identifiers mg$fnc_name <- paste0(".mg_fnc_", mg$uid); for( i in 1:nrow(mg) ) { # Cache the definition: s <- mg$def[i]; if( is.na(s) || is.null(s) || s == "" ) { # Empty definition! if( !suppress.warnings ) .report.ewms(paste0("Error parsing the medication class definition '",mg$name[i],"': this definition is empty!\n"), "error", ".apply.medication.groups", "AdhereR"); return (NULL); } # Search for medication group references of the form {name} : ss <- gregexpr("\\{[^(\\})]+\\}",s); #gregexpr("\\{[[:alpha:]]+\\}",s); if( ss[[1]][1] != (-1) ) { # There's at least one group reference: replace it by the corresponding function call: ss_calls <- regmatches(s, ss)[[1]]; ss_calls_replaced <- vapply(ss_calls, function(x) { if( length(ii <- which(mg$name == substr(x, 2, nchar(x)-1))) != 1 ) { if( !suppress.warnings ) .report.ewms(paste0("Error parsing the medication class definition '",mg$name[i],"': there is a call to the undefined medication class '",substr(x, 2, nchar(x)-1),"'!\n"), "error", ".apply.medication.groups", "AdhereR"); return (NA); } else { return (paste0("safe_env$",mg$fnc_name[ii],"()")); } }, character(1)); if( anyNA(ss_calls_replaced) ) { # Error parsing medication class definitions (the message should be already generated): return (NULL); } regmatches(s, ss)[[1]] <- ss_calls_replaced; } # Make it into a function definition: s_fnc <- paste0("function() { if( !safe_env$.evald[",i,"] ) { # not already evaluated: tmp <- try(with(safe_env$.data, ",s,"), silent=TRUE); if( inherits(tmp, 'try-error') ) { # fail gracefully and informatively: safe_env$.errs <- rbind(safe_env$.errs, data.frame('fnc'='",mg$fnc_name[i],"', 'error'=as.character(tmp))); stop('Error in ",mg$fnc_name[i],"'); } # sanity checks: if( is.null(tmp) || !is.logical(tmp) || length(tmp) != nrow(safe_env$.data) ) { # fail gracefully and informatively: safe_env$.errs <- rbind(safe_env$.errs, data.frame('fnc'='",mg$fnc_name[i],"', 'error'='Error: evaluation did not produce logical results')); stop('Error in ",mg$fnc_name[i],"'); } safe_env$.res[,",i,"] <- tmp; safe_env$.evald[",i,"] <- TRUE; } # else, it should have already been evaluated! # return the value return (safe_env$.res[,",i,"]); }"); # Parse it: s_parsed <- NULL; try(s_parsed <- parse(text=s_fnc), silent=TRUE); if( is.null(s_parsed) ) { if( !suppress.warnings ) .report.ewms(paste0("Error parsing the medication class definition '",mg$name[i],"'!\n"), "error", ".apply.medication.groups", "AdhereR"); return (NULL); } # Add the function: safe_env[[mg$fnc_name[i]]] <- eval(s_parsed); } # Evaluate the medication groups on the data: for( i in 1:nrow(mg) ) { # Call the corresponding function: res <- NULL; try(res <- eval(parse(text=paste0(mg$fnc_name[i],"()")), envir=safe_env), silent=TRUE); # the errors will be anyway recorded in the .errs variable in safe_env if( is.null(res) || inherits(res, 'try-error') || !safe_env$.evald[i] ) { # Evaluation error: if( !is.null(safe_env$.errs) ) { err_msgs <- unique(safe_env$.errs); err_msgs$error <- vapply(err_msgs$error, function(s) trimws(strsplit(s,":",fixed=TRUE)[[1]][2]), character(1)); err_msgs$fnc <- vapply(err_msgs$fnc, function(s) mg$name[ mg$fnc_name == s ], character(1)); ss <- gregexpr(".mg_fnc_",err_msgs$error); regmatches(err_msgs$error, ss) <- ""; if( !suppress.warnings ) .report.ewms(paste0("Error(s) during the evaluation of medication class(es): ",paste0("'",err_msgs$error," (for ",err_msgs$fnc,")'",colapse=", "),"!\n"), "warning", ".apply.medication.groups", "AdhereR"); } return (NULL); } } # Retrieve the results and compute __ALL_OTHERS__: groups_info <- cbind(rbind(mg[,c("name", "def")], c("__ALL_OTHERS__", "*all observations not included in the defined groups*")), "evaluated"=c(safe_env$.evald, TRUE)); rownames(groups_info) <- NULL; obs_in_groups <- cbind(safe_env$.res, rowSums(!is.na(safe_env$.res) & safe_env$.res) == 0); colnames(obs_in_groups) <- c(mg$name, "__ALL_OTHERS__"); # ... and return them: return (list("defs"=groups_info[,c("name", "def")], "obs"=obs_in_groups)); } #' CMA0 constructor. #' #' Constructs a basic CMA (continuous multiple-interval measures of medication #' availability/gaps) object. #' #' In most cases this should not be done directly by the user, #' but it is used internally by the other CMAs. #' #' @param data A \emph{\code{data.frame}} containing the medication events #' (prescribing or dispensing) used to compute the CMA. Must contain, at a #' minimum, the patient unique ID, the event date and duration, and might also #' contain the daily dosage and medication type (the actual column names are #' defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID, or \code{NA} if not defined. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter), or \code{NA} if not defined. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days), or \code{NA} if not #' defined. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the classes/types/groups of medication, or \code{NA} #' if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carryover.within.obs.window \emph{Logical}, if \code{TRUE} consider #' the carry-over within the observation window, or \code{NA} if not defined. #' @param carryover.into.obs.window \emph{Logical}, if \code{TRUE} consider the #' carry-over from before the starting date of the observation window, or #' \code{NA} if not defined. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE} the #' carry-over applies only across medications of the same type, or \code{NA} #' if not defined. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE} the carry-over #' is adjusted to reflect changes in dosage, or \code{NA} if not defined. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units #' after the first event (the column must be of type \code{numeric}) or as #' actual dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in #' the \code{data} and the other parameters; see the \code{format} parameters #' of the \code{\link[base]{as.Date}} function for details (NB, this concerns #' only the dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA0} with the following fields: #' \itemize{ #' \item \code{data} The actual event (prescribing or dispensing) data, as #' given by the \code{data} parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing #' the unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carryover.within.obs.window} whether to consider the carry-over #' within the observation window, as given by the #' \code{carryover.within.obs.window} parameter. #' \item \code{carryover.into.obs.window} whether to consider the carry-over #' from before the starting date of the observation window, as given by the #' \code{carryover.into.obs.window} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, #' as given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} #' parameter. #' } #' @examples #' cma0 <- CMA0(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' @export CMA0 <- function(data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carryover.within.obs.window=NA, # if TRUE consider the carry-over within the observation window (NA = undefined) carryover.into.obs.window=NA, # if TRUE consider the carry-over from before the starting date of the observation window (NA = undefined) carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary="Base CMA object", # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=FALSE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=NULL, # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # Preconditions: if( !is.null(data) ) { # data's class and dimensions: if( inherits(data, "matrix") || inherits(data, "tbl") || inherits(data, "data.table") ) data <- as.data.frame(data); # convert various things to data.frame if( !inherits(data, "data.frame") ) { if( !suppress.warnings ) .report.ewms("The 'data' for a CMA must be of type 'data.frame'!\n", "error", "CMA0", "AdhereR"); return (NULL); } if( nrow(data) < 1 ) { if( !suppress.warnings ) .report.ewms("The 'data' for a CMA must have at least one row!\n", "error", "CMA0", "AdhereR"); return (NULL); } # the column names must exist in data: if( !is.na(ID.colname) && !(ID.colname %in% names(data)) ) { if( !suppress.warnings ) .report.ewms(paste0("Column ID.colname='",ID.colname,"' must appear in the 'data'!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(event.date.colname) && !(event.date.colname %in% names(data)) ) { if( !suppress.warnings ) .report.ewms(paste0("Column event.date.colname='",event.date.colname,"' must appear in the 'data'!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(event.duration.colname) && !(event.duration.colname %in% names(data)) ) { if( !suppress.warnings ) .report.ewms(paste0("Column event.duration.colname='",event.duration.colname,"' must appear in the 'data'!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(event.daily.dose.colname) && !(event.daily.dose.colname %in% names(data)) ) { if( !suppress.warnings ) .report.ewms(paste0("Column event.daily.dose.colname='",event.daily.dose.colname,"' must appear in the 'data'!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(medication.class.colname) && !(medication.class.colname %in% names(data)) ) { if( !suppress.warnings ) .report.ewms(paste0("Column medication.class.colname='",medication.class.colname,"' must appear in the 'data'!\n"), "error", "CMA0", "AdhereR"); return (NULL); } # carry-over conditions: if( !is.na(carryover.within.obs.window) && !is.logical(carryover.within.obs.window) ) { if( !suppress.warnings ) .report.ewms(paste0("Parameter 'carryover.within.obs.window' must be logical!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(carryover.into.obs.window) && !is.logical(carryover.into.obs.window) ) { if( !suppress.warnings ) .report.ewms(paste0("Parameter 'carryover.into.obs.window' must be logical!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(carry.only.for.same.medication) && !is.logical(carry.only.for.same.medication) ) { if( !suppress.warnings ) .report.ewms(paste0("Parameter 'carry.only.for.same.medication' must be logical!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( !is.na(consider.dosage.change) && !is.logical(consider.dosage.change) ) { if( !suppress.warnings ) .report.ewms(paste0("Parameter 'consider.dosage.change' must be logical!\n"), "error", "CMA0", "AdhereR"); return (NULL); } if( (!is.na(carryover.within.obs.window) && !is.na(carryover.into.obs.window) && !is.na(carry.only.for.same.medication)) && (!carryover.within.obs.window && !carryover.into.obs.window && carry.only.for.same.medication) ) { if( !suppress.warnings ) .report.ewms("Cannot carry over only for same medication when no carry over at all is considered!\n", "error", "CMA0", "AdhereR") return (NULL); } # the follow-up window: if( !is.na(followup.window.start) && !inherits(followup.window.start,"Date") && !is.numeric(followup.window.start) && !(followup.window.start %in% names(data)) ) { # See if it can be forced to a valid Date: if( !is.na(followup.window.start) && (is.character(followup.window.start) || is.factor(followup.window.start)) && !is.na(followup.window.start <- as.Date(followup.window.start, format=date.format, optional=TRUE)) ) { # Ok, it was apparently successfully converted to Date: nothing else to do... } else { if( !suppress.warnings ) .report.ewms("The follow-up window start must be either a number, a Date, or a valid column name in 'data'!\n", "error", "CMA0", "AdhereR") return (NULL); } } if( !inherits(followup.window.start,"Date") && !is.na(followup.window.start.unit) && !(followup.window.start.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The follow-up window start unit is not recognized!\n", "error", "CMA0", "AdhereR") return (NULL); } if( !is.na(followup.window.duration) && is.numeric(followup.window.duration) && followup.window.duration < 0 ) { if( !suppress.warnings ) .report.ewms("The follow-up window duration must be a positive number of time units after the first event!\n", "error", "CMA0", "AdhereR") return (NULL); } else if( !is.na(followup.window.duration) && !is.numeric(followup.window.duration) && !(followup.window.duration %in% names(data)) ) { if( !suppress.warnings ) .report.ewms("The follow-up window duration must be either a positive number or a valid column name in 'data'!\n", "error", "CMA0", "AdhereR") return (NULL); } if( !is.na(followup.window.duration.unit) && !(followup.window.duration.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The follow-up window duration unit is not recognized!\n", "error", "CMA0", "AdhereR") return (NULL); } # the observation window: if( !is.na(observation.window.start) && is.numeric(observation.window.start) && observation.window.start < 0 ) { if( !suppress.warnings ) .report.ewms("The observation window start must be a positive number of time units after the first event!\n", "error", "CMA0", "AdhereR") return (NULL); } else if( !is.na(observation.window.start) && !inherits(observation.window.start,"Date") && !is.numeric(observation.window.start) && !(observation.window.start %in% names(data)) ) { # See if it can be forced to a valid Date: if( !is.na(observation.window.start) && (is.character(observation.window.start) || is.factor(observation.window.start)) && !is.na(observation.window.start <- as.Date(observation.window.start, format=date.format, optional=TRUE)) ) { # Ok, it was apparently successfully converted to Date: nothing else to do... } else { if( !suppress.warnings ) .report.ewms("The observation window start must be either a positive number, a Date, or a valid column name in 'data'!\n", "error", "CMA0", "AdhereR") return (NULL); } } if( !inherits(observation.window.start,"Date") && !is.na(observation.window.start.unit) && !(observation.window.start.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The observation window start unit is not recognized!\n", "error", "CMA0", "AdhereR") return (NULL); } if( !is.na(observation.window.duration) && is.numeric(observation.window.duration) && observation.window.duration < 0 ) { if( !suppress.warnings ) .report.ewms("The observation window duration must be a positive number of time units after the first event!\n", "error", "CMA0", "AdhereR") return (NULL); } else if( !is.na(observation.window.duration) && !is.numeric(observation.window.duration) && !(observation.window.duration %in% names(data)) ) { if( !suppress.warnings ) .report.ewms("The observation window duration must be either a positive number or a valid column name in 'data'!\n", "error", "CMA0", "AdhereR") return (NULL); } if( !is.na(observation.window.duration.unit) && !(observation.window.duration.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The observation window duration unit is not recognized!\n", "error", "CMA0", "AdhereR") return (NULL); } # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA0", "AdhereR"); } } } } else { return (NULL); } # Parse, check and evaluate the medication groups (if any): if( !is.null(medication.groups) ) { if( is.null(mg <- .apply.medication.groups(medication.groups=medication.groups, data=data, suppress.warnings=suppress.warnings)) ) { return (NULL); } } else { mg <- NULL; } structure(list("data"=data, "ID.colname"=ID.colname, "event.date.colname"=event.date.colname, "event.duration.colname"=event.duration.colname, "event.daily.dose.colname"=event.daily.dose.colname, "medication.class.colname"=medication.class.colname, "medication.groups"=mg, "flatten.medication.groups"=flatten.medication.groups, "medication.groups.colname"=medication.groups.colname, "carryover.within.obs.window"=carryover.within.obs.window, "carryover.into.obs.window"=carryover.into.obs.window, "carry.only.for.same.medication"=carry.only.for.same.medication, "consider.dosage.change"=consider.dosage.change, "followup.window.start"=followup.window.start, "followup.window.start.unit"=followup.window.start.unit, "followup.window.start.per.medication.group"=followup.window.start.per.medication.group, "followup.window.duration"=followup.window.duration, "followup.window.duration.unit"=followup.window.duration.unit, "observation.window.start"=observation.window.start, "observation.window.start.unit"=observation.window.start.unit, "observation.window.duration"=observation.window.duration, "observation.window.duration.unit"=observation.window.duration.unit, "date.format"=date.format, "summary"=summary), class="CMA0"); } #' Print CMA0 (and derived) objects. #' #' Prints and summarizes a basic CMA0, or derived, object. #' #' Can produce output for the console (text), R Markdown or LaTeX, #' showing various types of information. #' #' @param x A \emph{\code{CMA0}} or derived object, representing the CMA to #' print. #' @param inline \emph{Logical}, should print inside a line of text or as a #' separate, extended object? #' @param format A \emph{string}, the type of output: plain text ("text"; #' default), LaTeX ("latex") or R Markdown ("markdown"). #' @param print.params \emph{Logical}, should print the parameters? #' @param print.data \emph{Logical}, should print a summary of the data? #' @param exclude.params A vector of \emph{strings}, the names of the object #' fields to exclude from printing (usually, internal information irrelevant to #' the end-user). #' @param skip.header \emph{Logical}, should the header be printed? #' @param cma.type A \emph{string}, used to override the reported object's class. #' @param ... other possible parameters #' @examples #' cma0 <- CMA0(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' cma0; #' print(cma0, format="markdown"); #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' cma1; #' @export print.CMA0 <- function(x, # the CMA0 (or derived) object ..., # required for S3 consistency inline=FALSE, # print inside a line of text or as a separate, extended object? format=c("text", "latex", "markdown"), # the format to print to print.params=TRUE, # show the parameters? print.data=TRUE, # show the summary of the data? exclude.params=c("event.info", "real.obs.windows"), # if so, should I not print some? skip.header=FALSE, # should I print the generic header? cma.type=class(cma)[1] ) { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA0") ) return (invisible(NULL)); if( format[1] == "text" ) { # Output text: if( !inline ) { # Extended print: if( !skip.header ) cat(paste0(cma.type,":\n")); if( print.params ) { params <- names(cma); params <- params[!(params %in% c("data",exclude.params))]; # exlude the 'data' (and any other requested) params from printing if( length(params) > 0 ) { if( "summary" %in% params ) { cat(paste0(" \"",cma$summary,"\"\n")); params <- params[!(params %in% "summary")]; } cat(" [\n"); for( p in params ) { if( p == "CMA" ) { cat(paste0(" ",p," = CMA results for ",nrow(cma[[p]])," patients\n")); } else if( p == "medication.groups" ) { if( !is.null(cma[[p]]) ) { cat(paste0(" ", p, " = ", nrow(cma[[p]]$defs), " [", ifelse(nrow(cma[[p]]$defs)<4, paste0("'",cma[[p]]$defs$name,"'", collapse=", "), paste0(paste0("'",cma[[p]]$defs$name[1:4],"'", collapse=", ")," ...")), "]\n")); } else { cat(paste0(" ", p, " = <NONE>\n")); } } else if( !is.null(cma[[p]]) && length(cma[[p]]) > 0 && !is.na(cma[[p]]) ) { cat(paste0(" ",p," = ",cma[[p]],"\n")); } } cat(" ]\n"); } if( print.data && !is.null(cma$data) ) { # Data summary: cat(paste0(" DATA: ",nrow(cma$data)," (rows) x ",ncol(cma$data)," (columns)"," [",length(unique(cma$data[,cma$ID.colname]))," patients]",".\n")); } } } else { # Inline print: cat(paste0(cma$summary,ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } } else if( format[1] == "latex" ) { # Output LaTeX: no difference between inline and not inline: cat(paste0("\\textbf{",cma$summary,"} (",cma.type,"):", ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } else if( format[1] == "markdown" ) { # Output Markdown: no difference between inline and not inline: cat(paste0("**",cma$summary,"** (",cma.type,"):", ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } else { .report.ewms("Unknown format for printing!\n", "error", "print.CMA0", "AdhereR"); return (invisible(NULL)); } } #' Plot CMA0 objects. #' #' Plots the events (prescribing or dispensing) data encapsulated in a basic #' CMA0 object. #' #' The x-axis represents time (either in days since the earliest date or as #' actual dates), with consecutive events represented as ascending on the y-axis. #' #' Each event is represented as a segment with style \code{lty.event} and line #' width \code{lwd.event} starting with a \code{pch.start.event} and ending with #' a \code{pch.end.event} character, coloured with a unique color as given by #' \code{col.cats}, extending from its start date until its end date. #' Consecutive events are thus represented on consecutive levels of the y-axis #' and are connected by a "continuation" line with \code{col.continuation} #' colour, \code{lty.continuation} style and \code{lwd.continuation} width; #' these continuation lines are purely visual guides helping to perceive the #' sequence of events, and carry no information about the availability of #' medication in this interval. #' #' When several patients are displayed on the same plot, they are organized #' vertically, and alternating bands (white and gray) help distinguish #' consecutive patients. #' Implicitly, all patients contained in the \code{cma} object will be plotted, #' but the \code{patients.to.plot} parameter allows the selection of a subset #' of patients. #' #' @param x A \emph{\code{CMA0}} or derived object, representing the CMA to #' plot #' @param patients.to.plot A vector of \emph{strings} containing the list of #' patient IDs to plot (a subset of those in the \code{cma} object), or #' \code{NULL} for all #' @param duration A \emph{number}, the total duration (in days) of the whole #' period to plot; in \code{NA} it is automatically determined from the event #' data such that the whole dataset fits. #' @param align.all.patients \emph{Logical}, should all patients be aligned #' (i.e., the actual dates are discarded and all plots are relative to the #' earliest date)? #' @param align.first.event.at.zero \emph{Logical}, should the first event be #' placed at the origin of the time axis (at 0)? #' @param show.period A \emph{string}, if "dates" show the actual dates at the #' regular grid intervals, while for "days" (the default) shows the days since #' the beginning; if \code{align.all.patients == TRUE}, \code{show.period} is #' taken as "days". #' @param period.in.days The \emph{number} of days at which the regular grid is #' drawn (or 0 for no grid). #' @param show.legend \emph{Logical}, should the legend be drawn? #' @param legend.x The position of the legend on the x axis; can be "left", #' "right" (default), or a \emph{numeric} value. #' @param legend.y The position of the legend on the y axis; can be "bottom" #' (default), "top", or a \emph{numeric} value. #' @param legend.bkg.opacity A \emph{number} between 0.0 and 1.0 specifying the #' opacity of the legend background. #' @param cex,cex.axis,cex.lab,legend.cex,legend.cex.title \emph{numeric} values #' specifying the cex of the various types of text. #' @param xlab Named vector of x-axis labels to show for the two types of periods #' ("days" and "dates"), or a single value for both, or \code{NULL} for nothing. #' @param ylab Named vector of y-axis labels to show without and with CMA estimates, #' or a single value for both, or \code{NULL} for nonthing. #' @param title Named vector of titles to show for and without alignment, or a #' single value for both, or \code{NULL} for nonthing. #' @param col.cats A \emph{color} or a \emph{function} that specifies the single #' colour or the colour palette used to plot the different medication; by #' default \code{rainbow}, but we recommend, whenever possible, a #' colorblind-friendly palette such as \code{viridis} or \code{colorblind_pal}. #' @param unspecified.category.label A \emph{string} giving the name of the #' unspecified (generic) medication category. #' @param medication.groups.to.plot the names of the medication groups to plot or #' \code{NULL} (the default) for all. #' @param medication.groups.separator.show a \emph{boolean}, if \code{TRUE} (the #' default) visually mark the medication groups the belong to the same patient, #' using horizontal lines and alternating vertical lines. #' @param medication.groups.separator.lty,medication.groups.separator.lwd,medication.groups.separator.color #' graphical parameters (line type, line width and colour describing the visual #' marking og medication groups as beloning to the same patient. #' @param medication.groups.allother.label a \emph{string} giving the label to #' use for the implicit \code{__ALL_OTHERS__} medication group (defaults to "*"). #' @param lty.event,lwd.event,pch.start.event,pch.end.event The style of the #' event (line style, width, and start and end symbols). #' @param plot.events.vertically.displaced Should consecutive events be plotted #' on separate rows (i.e., separated vertically, the default) or on the same row? #' @param print.dose \emph{Logical}, should the daily dose be printed as text? #' @param cex.dose \emph{Numeric}, if daily dose is printed, what text size #' to use? #' @param print.dose.outline.col If \emph{\code{NA}}, don't print dose text with #' outline, otherwise a color name/code for the outline. #' @param print.dose.centered \emph{Logical}, print the daily dose centered on #' the segment or slightly below it? #' @param plot.dose \emph{Logical}, should the daily dose be indicated through #' segment width? #' @param lwd.event.max.dose \emph{Numeric}, the segment width corresponding to #' the maximum daily dose (must be >= lwd.event but not too big either). #' @param plot.dose.lwd.across.medication.classes \emph{Logical}, if \code{TRUE}, #' the line width of the even is scaled relative to all medication classes (i.e., #' relative to the global minimum and maximum doses), otherwise it is scale #' relative only to its medication class. #' @param col.continuation,lty.continuation,lwd.continuation The style of the #' "continuation" lines connecting consecutive events (colour, line style and #' width). #' @param col.na The colour used for missing event data. #' @param highlight.followup.window \emph{Logical}, should the follow-up window #' be plotted? #' @param followup.window.col The follow-up window's colour. #' @param highlight.observation.window \emph{Logical}, should the observation #' window be plotted? #' @param observation.window.col,observation.window.density,observation.window.angle,observation.window.opacity #' Attributes of the observation window (colour, shading density, angle and #' opacity). #' @param alternating.bands.cols The colors of the alternating vertical bands #' distinguishing the patients; can be \code{NULL} = don't draw the bandes; #' or a vector of colors. #' @param bw.plot \emph{Logical}, should the plot use grayscale only (i.e., the #' \code{\link[grDevices]{gray.colors}} function)? #' @param rotate.text \emph{Numeric}, the angle by which certain text elements #' (e.g., axis labels) should be rotated. #' @param force.draw.text \emph{Logical}, if \code{TRUE}, always draw text even #' if too big or too small #' @param min.plot.size.in.characters.horiz,min.plot.size.in.characters.vert #' \emph{Numeric}, the minimum size of the plotting surface in characters; #' horizontally (min.plot.size.in.characters.horiz) refers to the the whole #' duration of the events to plot; vertically (min.plot.size.in.characters.vert) #' refers to a single event. If the plotting is too small, possible solutions #' might be: if within \code{RStudio}, try to enlarge the "Plots" panel, or #' (also valid outside \code{RStudio} but not if using \code{RStudio server} #' start a new plotting device (e.g., using \code{X11()}, \code{quartz()} #' or \code{windows()}, depending on OS) or (works always) save to an image #' (e.g., \code{jpeg(...); ...; dev.off()}) and display it in a viewer. #' @param suppress.warnings \emph{Logical}: show or hide the warnings? #' @param max.patients.to.plot \emph{Numeric}, the maximum patients to attempt #' to plot. #' @param export.formats a \emph{string} giving the formats to export the figure #' to (by default \code{NULL}, meaning no exporting); can be any combination of #' "svg" (just an \code{SVG} file), "html" (\code{SVG} + \code{HTML} + \code{CSS} #' + \code{JavaScript}, all embedded within one \code{HTML} document), "jpg", #' "png", "webp", "ps" or "pdf". #' @param export.formats.fileprefix a \emph{string} giving the file name prefix #' for the exported formats (defaults to "AdhereR-plot"). #' @param export.formats.height,export.formats.width \emph{numbers} giving the #' desired dimensions (in pixels) for the exported figure (defaults to sane #' values if \code{NA}). #' @param export.formats.save.svg.placeholder a \emph{logical}, if TRUE, save an #' image placeholder of type given by \code{export.formats.svg.placeholder.type} #'for the \code{SVG} image. #' @param export.formats.svg.placeholder.type a \emph{string}, giving the type of #' placeholder for the \code{SVG} image to save; can be "jpg", #' "png" (the default) or "webp". #' @param export.formats.svg.placeholder.embed a \emph{logical}, if \code{TRUE}, #' embed the placeholder image in the HTML document (if any) using \code{base64} #' encoding, otherwise (the default) leave it as an external image file (works #' only when an \code{HTML} document is exported and only for \code{JPEG} or #' \code{PNG} images. #' @param export.formats.html.template,export.formats.html.javascript,export.formats.html.css #' \emph{character strings} or \code{NULL} (the default) giving the path to the #' \code{HTML}, \code{JavaScript} and \code{CSS} templates, respectively, to be #' used when generating the HTML+CSS semi-interactive plots; when \code{NULL}, #' the default ones included with the package will be used. If you decide to define #' new templates please use the default ones for inspiration and note that future #' version are not guaranteed to be backwards compatible! #' @param export.formats.directory a \emph{string}; if exporting, which directory #' to export to; if \code{NA} (the default), creates the files in a temporary #' directory. #' @param generate.R.plot a \emph{logical}, if \code{TRUE} (the default), #' generate the standard (base \code{R}) plot for plotting within \code{R}. #' @param do.not.draw.plot a \emph{logical}, if \code{TRUE} (\emph{not} the default), #' does not draw the plot itself, but only the legend (if \code{show.legend} is #' \code{TRUE}) at coordinates (0,0) irrespective of the given legend coordinates. #' This is intended to allow (together with the \code{get.legend.plotting.area()} #' function) the separate plotting of the legend. #' @param ... other possible parameters #' @examples #' cma0 <- CMA0(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' plot(cma0, patients.to.plot=c("1","2")); #' @export plot.CMA0 <- function(x, # the CMA0 (or derived) object ..., # required for S3 consistency patients.to.plot=NULL, # list of patient IDs to plot or NULL for all duration=NA, # duration to plot in days (if missing, determined from the data) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? and, if so, place the first event as the horizontal 0? show.period=c("dates","days")[2], # draw vertical bars at regular interval as dates or days? period.in.days=90, # the interval (in days) at which to draw veritcal lines show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend params and position cex=1.0, cex.axis=0.75, cex.lab=1.0, # various graphical params xlab=c("dates"="Date", "days"="Days"), # Vector of x labels to show for the two types of periods, or a single value for both, or NULL for nothing ylab=c("withoutCMA"="patient", "withCMA"="patient (& CMA)"), # Vector of y labels to show without and with CMA estimates, or a single value for both, or NULL ofr nonthing title=c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns"), # Vector of titles to show for and without alignment, or a single value for both, or NULL for nonthing col.cats=rainbow, # single color or a function mapping the categories to colors unspecified.category.label="drug", # the label of the unspecified category of medication medication.groups.to.plot=NULL, # the names of the medication groups to plot (by default, all) medication.groups.separator.show=TRUE, medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", # group medication events by patient? medication.groups.allother.label="*", # the label to use for the __ALL_OTHERS__ medication class (defaults to *) lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, # event style plot.events.vertically.displaced=TRUE, # display the events on different lines (vertical displacement) or not (defaults to TRUE)? print.dose=FALSE, cex.dose=0.75, print.dose.outline.col="white", print.dose.centered=FALSE, # print daily dose plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # draw daily dose as line width col.continuation="black", lty.continuation="dotted", lwd.continuation=1, # style of the contuniation lines connecting consecutive events col.na="lightgray", # color for missing data highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, alternating.bands.cols=c("white", "gray95"), # the colors of the alternating vertical bands across patients (NULL=don't draw any; can be >= 1 color) rotate.text=-60, # some text (e.g., axis labels) may be rotated by this much degrees force.draw.text=FALSE, # if true, always draw text even if too big or too small bw.plot=FALSE, # if TRUE, override all user-given colors and replace them with a scheme suitable for grayscale plotting min.plot.size.in.characters.horiz=0, min.plot.size.in.characters.vert=0, # the minimum plot size (in characters: horizontally, for the whole duration, vertically, per event) suppress.warnings=FALSE, # suppress warnings? max.patients.to.plot=100, # maximum number of patients to plot export.formats=NULL, # the formats to export the figure to (by default, none); can be any subset of "svg" (just SVG file), "html" (SVG + HTML + CSS + JavaScript all embedded within the HTML document), "jpg", "png", "webp", "ps" and "pdf" export.formats.fileprefix="AdhereR-plot", # the file name prefix for the exported formats export.formats.height=NA, export.formats.width=NA, # desired dimensions (in pixels) for the exported figure (defaults to sane values) export.formats.save.svg.placeholder=TRUE, export.formats.svg.placeholder.type=c("jpg", "png", "webp")[2], export.formats.svg.placeholder.embed=FALSE, # save a placeholder for the SVG image? export.formats.html.template=NULL, export.formats.html.javascript=NULL, export.formats.html.css=NULL, # HTML, JavaScript and CSS templates for exporting HTML+SVG export.formats.directory=NA, # if exporting, which directory to export to (if not give, creates files in the temporary directory) generate.R.plot=TRUE, # generate standard (base R) plot for plotting within R? do.not.draw.plot=FALSE # if TRUE, don't draw the actual plot, but only the legend (if required) ) { .plot.CMAs(x, patients.to.plot=patients.to.plot, duration=duration, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, show.period=show.period, period.in.days=period.in.days, show.legend=show.legend, legend.x=legend.x, legend.y=legend.y, legend.bkg.opacity=legend.bkg.opacity, legend.cex=legend.cex, legend.cex.title=legend.cex.title, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, show.cma=FALSE, # for CMA0, there's no CMA to show by definition xlab=xlab, ylab=ylab, title=title, col.cats=col.cats, unspecified.category.label=unspecified.category.label, medication.groups.to.plot=medication.groups.to.plot, medication.groups.separator.show=medication.groups.separator.show, medication.groups.separator.lty=medication.groups.separator.lty, medication.groups.separator.lwd=medication.groups.separator.lwd, medication.groups.separator.color=medication.groups.separator.color, medication.groups.allother.label=medication.groups.allother.label, lty.event=lty.event, lwd.event=lwd.event, show.event.intervals=FALSE, # not for CMA0 plot.events.vertically.displaced=plot.events.vertically.displaced, pch.start.event=pch.start.event, pch.end.event=pch.end.event, print.dose=print.dose, cex.dose=cex.dose, print.dose.outline.col=print.dose.outline.col, print.dose.centered=print.dose.centered, plot.dose=plot.dose, lwd.event.max.dose=lwd.event.max.dose, plot.dose.lwd.across.medication.classes=plot.dose.lwd.across.medication.classes, col.na=col.na, col.continuation=col.continuation, lty.continuation=lty.continuation, lwd.continuation=lwd.continuation, print.CMA=FALSE, # for CMA0, there's no CMA to show by definition plot.CMA=FALSE, # for CMA0, there's no CMA to show by definition plot.partial.CMAs.as=NULL, # for CMA0, there's no "partial" CMAs by definition highlight.followup.window=highlight.followup.window, followup.window.col=followup.window.col, highlight.observation.window=highlight.observation.window, observation.window.col=observation.window.col, observation.window.density=observation.window.density, observation.window.angle=observation.window.angle, observation.window.opacity=observation.window.opacity, alternating.bands.cols=alternating.bands.cols, bw.plot=bw.plot, rotate.text=rotate.text, force.draw.text=force.draw.text, min.plot.size.in.characters.horiz=min.plot.size.in.characters.horiz, min.plot.size.in.characters.vert=min.plot.size.in.characters.vert, max.patients.to.plot=max.patients.to.plot, export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.height=export.formats.height, export.formats.width=export.formats.width, export.formats.save.svg.placeholder=export.formats.save.svg.placeholder, export.formats.svg.placeholder.type=export.formats.svg.placeholder.type, export.formats.svg.placeholder.embed=export.formats.svg.placeholder.embed, export.formats.html.template=export.formats.html.template, export.formats.html.javascript=export.formats.html.javascript, export.formats.html.css=export.formats.html.css, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot, do.not.draw.plot=do.not.draw.plot, suppress.warnings=suppress.warnings); } #' Access the medication groups of a CMA object. #' #' Retrieve the medication groups and the observations they refer to (if any). #' #' @param x a CMA object. #' @return a \emph{list} with two members: #' \itemize{ #' \item \code{defs} A \code{data.frame} containing the names and definitions of #' the medication classes; please note that there is an extra class #' \emph{__ALL_OTHERS__} containing all the observations not selected by any of #' the explicitly given medication classes. #' \item \code{obs} A \code{logical matrix} where the columns are the medication #' classes (the last being \emph{__ALL_OTHERS__}), and the rows the observations in #' the x's data; element \eqn{(i,j)} is \code{TRUE} iff observation \eqn{j} was #' selected by medication class \eqn{i}. #' } #' @export getMGs <- function(x) UseMethod("getMGs") #' @export getMGs.CMA0 <- function(x) { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA0") || is.null(cma$medication.groups) ) return (NULL); return (cma$medication.groups); } #' Access the actual CMA estimate from a CMA object. #' #' Retrieve the actual CMA estimate(s) encapsulated in a simple, per episode, #' or sliding window CMA object. #' #' @param x a CMA object. #' @param flatten.medication.groups \emph{Logical}, if \code{TRUE} and there are #' medication groups defined, then the return value is flattened to a single #' \code{data.frame} with an extra column containing the medication group (its #' name is given by \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @return a \emph{data.frame} containing the CMA estimate(s). #' @examples #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' getCMA(cma1); #' \dontrun{ #' cmaE <- CMA_per_episode(CMA="CMA1", #' data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=0, #' observation.window.start=0, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' getCMA(cmaE);} #' @export getCMA <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") UseMethod("getCMA") #' @export getCMA.CMA0 <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA0") || !("CMA" %in% names(cma)) || is.null(cma$CMA) ) return (NULL); if( inherits(cma$CMA, "data.frame") || !flatten.medication.groups ) { return (cma$CMA); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$CMA); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$CMA), function(i) if(!is.null(cma$CMA[[i]])){rep(names(cma$CMA)[i], nrow(cma$CMA[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' Access the event info from a CMA object. #' #' Retrieve the event info encapsulated in a simple, per episode, #' or sliding window CMA object. #' #' @param x a CMA object. #' @param flatten.medication.groups \emph{Logical}, if \code{TRUE} and there are #' medication groups defined, then the return value is flattened to a single #' \code{data.frame} with an extra column containing the medication group (its #' name is given by \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @return a \emph{data.frame} containing the CMA estimate(s). #' @examples #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' getEventInfo(cma1); #' @export getEventInfo <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") UseMethod("getEventInfo") #' @export getEventInfo.CMA0 <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA0") || !("event.info" %in% names(cma)) || is.null(cma$event.info) ) return (NULL); if( inherits(cma$event.info, "data.frame") || !flatten.medication.groups ) { return (cma$event.info); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$event.info); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$event.info), function(i) if(!is.null(cma$event.info[[i]])){rep(names(cma$event.info)[i], nrow(cma$event.info[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' Access the inner event info from a complex CMA object. #' #' Retrieve the event info encapsulated in a complex (i.e., per episode #' or sliding window) CMA object. #' #' @param x a CMA object. #' @param flatten.medication.groups \emph{Logical}, if \code{TRUE} and there are #' medication groups defined, then the return value is flattened to a single #' \code{data.frame} with an extra column containing the medication group (its #' name is given by \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @return a \emph{data.frame} containing the CMA estimate(s). #' @export getInnerEventInfo <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") UseMethod("getInnerEventInfo") #' Restrict a CMA object to a subset of patients. #' #' Restrict a CMA object to a subset of patients. #' #' @param cma a CMA object. #' @param patients a list of patient IDs to keep. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @return a CMA object containing only the information for the given patients. #' @examples #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' getCMA(cma1); #' cma1a <- subsetCMA(cma1, patients=c(1:3,7)); #' cma1a; getCMA(cma1a); #' @export subsetCMA <- function(cma, patients, suppress.warnings) UseMethod("subsetCMA") #' @export subsetCMA.CMA0 <- function(cma, patients, suppress.warnings=FALSE) { if( inherits(patients, "factor") ) patients <- as.character(patients); all.patients <- unique(cma$data[,cma$ID.colname]); patients.to.keep <- intersect(patients, all.patients); if( length(patients.to.keep) == length(all.patients) ) { # Keep all patients: return (cma); } if( length(patients.to.keep) == 0 ) { if( !suppress.warnings ) .report.ewms("No patients to subset on!\n", "error", "subsetCMA.CMA0", "AdhereR"); return (NULL); } if( length(patients.to.keep) < length(patients) && !suppress.warnings ) .report.ewms("Some patients in the subsetting set are not in the CMA itself and are ignored!\n", "warning", "subsetCMA.CMA0", "AdhereR"); ret.val <- cma; ret.val$data <- ret.val$data[ ret.val$data[,ret.val$ID.colname] %in% patients.to.keep, ]; if( !is.null(ret.val$event.info) ) { if( inherits(ret.val$event.info, "data.frame") ) { ret.val$event.info <- ret.val$event.info[ ret.val$event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( nrow(ret.val$event.info) == 0 ) ret.val$event.info <- NULL; } else if( is.list(ret.val$event.info) && length(ret.val$event.info) > 0 ) { ret.val$event.info <- lapply(ret.val$event.info, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } if( ("CMA" %in% names(ret.val)) && !is.null(ret.val$CMA) ) { if( inherits(ret.val$CMA, "data.frame") ) { ret.val$CMA <- ret.val$CMA[ ret.val$CMA[,ret.val$ID.colname] %in% patients.to.keep, ]; } else if( is.list(ret.val$CMA) && length(ret.val$CMA) > 0 ) { ret.val$CMA <- lapply(ret.val$CMA, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } return (ret.val); } # Auxiliary function: add time units to date: .add.time.interval.to.date <- function( start.date, # a Date object time.interval=0, # the number of "units" to add to the start.date (must be numeric and is rounded) unit="days", # can be "days", "weeks", "months", "years" suppress.warnings=FALSE ) { # Checks if( !inherits(start.date,"Date") ) { if( !suppress.warnings ) .report.ewms("Parameter start.date of .add.time.interval.to.date() must be a Date() object.\n", "error", ".add.time.interval.to.date", "AdhereR"); return (NA); } if( !is.numeric(time.interval) ) { if( inherits(time.interval, "difftime") ) # check if a difftime and, if so, attempt conversion to number of units { # Time difference: if( units(time.interval) == as.character(unit) ) { time.interval <- as.numeric(time.interval); } else { # Try to convert it: time.interval <- as.numeric(time.interval, unit="days"); time.interval <- switch( as.character(unit), "days" = time.interval, "weeks" = time.interval/7, "months" = {if( !suppress.warnings ) .report.ewms("Converting to months assuming a 30-days month!", "warning", ".add.time.interval.to.date", "AdhereR"); time.interval/30;}, "years" = {if( !suppress.warnings ) .report.ewms("Converting to years assuming a 365-days year!", "warning", ".add.time.interval.to.date", "AdhereR"); time.interval/365;}, {if( !suppress.warnings ) .report.ewms(paste0("Unknown unit '",unit,"' to '.add.time.interval.to.date'.\n"), "error", ".add.time.interval.to.date", "AdhereR"); return(NA);} # default ); } } else { if( !suppress.warnings ) .report.ewms("Parameter start.date of .add.time.interval.to.date() must be a number.\n", "error", ".add.time.interval.to.date", "AdhereR"); return (NA); } } # time.interval <- round(time.interval); # return (switch( as.character(unit), # "days" = (start.date + time.interval), # "weeks" = (start.date + time.interval*7), # "months" = {tmp <- (start.date + months(time.interval)); # i <- which(is.na(tmp)); # if( length(i) > 0 ) tmp[i] <- start.date[i] + lubridate::days(1) + months(time.interval); # tmp;}, # "years" = {tmp <- (start.date + lubridate::years(time.interval)); # i <- which(is.na(tmp)); # if( length(i) > 0 ) tmp[i] <- start.date[i] + lubridate::days(1) + lubridate::years(time.interval); # tmp;}, # {if( !suppress.warnings ) .report.ewms(paste0("Unknown unit '",unit,"' to '.add.time.interval.to.date'.\n"), "error", ".add.time.interval.to.date", "AdhereR"); NA;} # default # )); # Faster but assumes that the internal representation of "Date" object is in number of days since the begining of time (probably stably true): return (switch( as.character(unit), "days" = structure(unclass(start.date) + round(time.interval), class="Date"), "weeks" = structure(unclass(start.date) + round(time.interval*7), class="Date"), "months" = lubridate::add_with_rollback(start.date, lubridate::period(round(time.interval),"months"), roll_to_first=TRUE), # take care of cases such as 2001/01/29 + 1 month "years" = lubridate::add_with_rollback(start.date, lubridate::period(round(time.interval),"years"), roll_to_first=TRUE), # take care of cases such as 2000/02/29 + 1 year {if( !suppress.warnings ) .report.ewms(paste0("Unknown unit '",unit,"' to '.add.time.interval.to.date'.\n"), "error", ".add.time.interval.to.date", "AdhereR"); NA;} # default )); } # Auxiliary function: subtract two dates to obtain the number of days in between: # WARNING! Faster than difftime() but makes the assumption that the internal representation of Date objects is the number of days since a given beginning of time # (true as of R 3.4 and probably conserved in future versions) .difftime.Dates.as.days <- function( start.dates, end.dates, suppress.warnings=FALSE ) { # Checks if( !inherits(start.dates,"Date") || !inherits(end.dates,"Date") ) { if( !suppress.warnings ) .report.ewms("start.dates and end.dates to '.difftime.Dates.as.days' must be a Date() objects.\n", "error", ".difftime.Dates.as.days", "AdhereR"); return (NA); } return (unclass(start.dates) - unclass(end.dates)); # the difference between the raw internal representations of Date objects is in days } # Auxiliary function: call a given function sequentially or in parallel: .compute.function <- function(fnc, # the function to compute fnc.ret.vals=1, # how many distinct values (as elements in a list) does fnc return (really useful for binding results from multi-cpu processing)? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # The parameters with which to call the function: # - NULL indicates that they are not used at all; the values, including defaults, must be fed by the caller # - all consistency checks have been already been done in the caller (except for the parallel procssing params: these are checked here) data=NULL, # this is a per-event *data.table* already keyed by patient ID and event date! ID.colname=NULL, # the name of the column containing the unique patient ID event.date.colname=NULL, # the start date of the event in the date.format format event.duration.colname=NULL, # the event duration in days event.daily.dose.colname=NULL, # the prescribed daily dose medication.class.colname=NULL, # the classes/types/groups of medication event.interval.colname=NULL, # contains number of days between the start of current event and the start of the next gap.days.colname=NULL, # contains the number of days when medication was not available carryover.within.obs.window=NULL, # if TRUE consider the carry-over within the observation window carryover.into.obs.window=NULL, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=NULL, # if TRUE the carry-over applies only across medication of same type consider.dosage.change=NULL, # if TRUE carry-over is adjusted to reflect changes in dosage followup.window.start=NULL, # if a number, date earliest event per participant + number of units, otherwise a date.format date or variable date followup.window.start.unit=NULL, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) followup.window.duration=NULL, # the duration of the follow-up window in the time units given below followup.window.duration.unit=NULL, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) observation.window.start=NULL, # the number of time units relative to followup.window.start, otherwise a date.format date or variable date observation.window.start.unit=NULL, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) observation.window.duration=NULL, # the duration of the observation window in time units observation.window.duration.unit=NULL, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) date.format=NULL, # the format of the dates used in this function suppress.warnings=NULL, suppress.special.argument.checks=FALSE ) { # Quick decision for sequential processing: if( parallel.backend == "none" || (is.numeric(parallel.threads) && parallel.threads == 1) ) { # Single threaded: simply call the function with the given data: return (fnc(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks )); } # Could be Multicore: if( parallel.backend == "multicore" ) { if( .Platform$OS.type == "windows" ) { # Can't do multicore on Windows! if( !suppress.warnings ) .report.ewms(paste0("Parallel processing backend \"multicore\" is not currently supported on Windows: will use SNOW instead.\n"), "warning", ".compute.function", "AdhereR"); parallel.backend <- "snow"; # try to do SNOW... } else { # Okay, seems we're on some sort of *NIX, so can do multicore! # Pre-process parallel.threads: if( parallel.threads == "auto" ) { parallel.threads <- getOption("mc.cores", 2L); } else if( is.na(parallel.threads) || !is.numeric(parallel.threads) || (parallel.threads < 1) || (parallel.threads %% 1 != 0) ) { if( !suppress.warnings ) .report.ewms(paste0("Number of parallel processing threads \"",parallel.threads,"\" must be either \"auto\" or a positive integer; forcing \"auto\".\n"), "warning", ".compute.function", "AdhereR"); parallel.threads <- getOption("mc.cores", 2L); } # Pre-split the participants into a number of chunks equal to the number of threads to reduce paying the overheads multiple times # and call the function for each thread in parallel: patids <- unique(data[,get(ID.colname)]); # data is a data.table, so careful with column selection! if( length(patids) < 1 ) return (NULL); tmp <- parallel::mclapply( lapply(parallel::splitIndices(length(patids), min(parallel.threads, length(patids))), function(i) patids[i]), # simulate snow::clusterSplit() to split patients by thread function(IDs) fnc(data=data[list(IDs),], # call the function sequentially for the patients in the current chunk ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks), mc.cores=parallel.threads, # as many cores as threads mc.preschedule=FALSE # don't preschedule as we know that we have relatively few jobs to do ); # Combine the results (there may be multiple returned data.frames intermingled!) if( fnc.ret.vals == 1 ) { # Easy: just one! ret.val <- data.table::rbindlist(tmp); } else { # Combine them in turn: ret.val <- lapply(1:fnc.ret.vals, function(i) { x <- data.table::rbindlist(lapply(tmp, function(x) x[[i]])); }); if( length(tmp) > 0 ) names(ret.val) <- names(tmp[[1]]); } return (ret.val); } } # Could be SNOW: cluster.type <- switch(parallel.backend, "snow"=, "snow(SOCK)"="SOCK", # socket cluster "snow(MPI)"="MPI", # MPI cluster (required Rmpi) "snow(NWS)"="NWS", # NWS cluster (requires nws) NA # unknown type of cluster ); if( is.na(cluster.type) ) { if( !suppress.warnings ) .report.ewms(paste0("Unknown parallel processing backend \"",parallel.backend,"\": will force sequential (\"none\").\n"), "warning", ".compute.function", "AdhereR"); # Force single threaded: simply call the function with the given data: return (fnc(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks )); } patids <- unique(data[,get(ID.colname)]); # data is a data.table, so careful with column selection! if( length(patids) < 1 ) return (NULL); # Pre-process parallel.threads: if( length(parallel.threads) == 1 ) { if( parallel.threads == "auto" ) { parallel.threads <- 2L; } else if( is.na(parallel.threads) || (is.numeric(parallel.threads) && ((parallel.threads < 1) || (parallel.threads %% 1 != 0))) ) { if( !suppress.warnings ) .report.ewms(paste0("Number of parallel processing threads \"",parallel.threads,"\", if numeric, must be either a positive integer; forcing \"auto\".\n"), "warning", ".compute.function", "AdhereR"); parallel.threads <- 2L; } if( is.numeric(parallel.threads) ) parallel.threads <- min(parallel.threads, length(patids)); # make sure we're not starting more threads than patients } # Attempt to create the SNOW cluster: cluster <- parallel::makeCluster(parallel.threads, # process only "auto", otherwise trust makeCluster() to interpret the parameters type = cluster.type); if( is.null(cluster) ) { if( !suppress.warnings ) .report.ewms(paste0("Failed to create the cluster \"",parallel.backend,"\" with parallel.threads \"",parallel.threads,"\": will force sequential (\"none\").\n"), "warning", ".compute.function", "AdhereR"); # Force single threaded: simply call the function with the given data: return (fnc(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks )); } # Pre-split the participants into a number of chunks equal to the number of created cluster nodes to reduce paying the overheads multiple times # and call the function for each cluster in parallel: tmp <- parallel::parLapply(cluster, parallel::clusterSplit(cluster, patids), function(IDs) fnc(data=data[list(IDs),], # call the function sequentially for the patients in the current chunk ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks)); parallel::stopCluster(cluster); # stop the cluster # Combine the results (there may be multiple return data.frames intermingled!) if( fnc.ret.vals == 1 ) { # Easy: just one! ret.val <- data.table::rbindlist(tmp); } else { # Combine them in turn: ret.val <- lapply(1:fnc.ret.vals, function(i) { x <- data.table::rbindlist(lapply(tmp, function(x) x[[i]])); }); if( length(tmp) > 0 ) names(ret.val) <- names(tmp[[1]]); } return (ret.val); } #' Gap Days and Event (prescribing or dispensing) Intervals. #' #' For a given event (prescribing or dispensing) database, compute the gap days #' and event intervals in various scenarious. #' #' This should in general not be called directly by the user, but is provided as #' a basis for the extension to new CMAs. #' #' @param data A \emph{\code{data.frame}} containing the events used to #' compute the CMA. Must contain, at a minimum, the patient unique ID, the event #' date and duration, and might also contain the daily dosage and medication #' type (the actual column names are defined in the following four parameters); #' the \code{CMA} constructors call this parameter \code{data}. #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the classes/types/groups of medication, or \code{NA} #' if not defined. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param carryover.within.obs.window \emph{Logical}, if \code{TRUE} consider #' the carry-over within the observation window, or \code{NA} if not defined. #' @param carryover.into.obs.window \emph{Logical}, if \code{TRUE} consider the #' carry-over from before the starting date of the observation window, or #' \code{NA} if not defined. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE} the #' carry-over applies only across medication of the same type, or \code{NA} #' if not defined. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE} the carry-over #' is adjusted to reflect changes in dosage, or \code{NA} if not defined. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param keep.window.start.end.dates \emph{Logical}, should the computed start #' and end dates of the windows be kept? #' @param keep.event.interval.for.all.events \emph{Logical}, should the computed #' event intervals be kept for all events, or \code{NA}'ed for those outside the #' OW? #' @param remove.events.outside.followup.window \emph{Logical}, should the #' events that fall outside the follo-wup window be removed from the results? #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param ... extra arguments. #' @return A \code{data.frame} or \code{data.table} extending the #' \code{event.info} parameter with: #' \itemize{ #' \item \code{event.interval} Or any other name given in #' \code{event.interval.colname}, containing the number of days between the #' start of the current event and the start of the next one. #' \item \code{gap.days} Or any other name given in \code{gap.days.colname}, #' containing the number of days when medication was not available for the #' current event (i.e., the "gap days"). #' \item \code{.FU.START.DATE,.FU.END.DATE} if kept, the actual start and end #' dates of the follow-up window (after adjustments due to the various #' parameters). #' \item \code{.OBS.START.DATE,.OBS.END.DATE} if kept, the actual start and end #' dates of the observation window (after adjustments due to the various #' parameters). #' \item \code{.EVENT.STARTS.BEFORE.OBS.WINDOW} if kept, \code{TRUE} if the #' current event starts before the start of the observation window. #' \item \code{.TDIFF1,.TDIFF2} if kept, various auxiliary time differences #' (in days). #' \item \code{.EVENT.STARTS.AFTER.OBS.WINDOW} if kept, \code{TRUE} if the #' current event starts after the end of the observation window. #' \item \code{.CARRY.OVER.FROM.BEFORE} if kept, the carry-over (if any) from #' the previous events. #' \item \code{.EVENT.WITHIN.FU.WINDOW} if kept, \code{TRUE} if the current #' event is within the follow-up window. #' } #' @export compute.event.int.gaps <- function(data, # this is a per-event data.frame with columns: ID.colname=NA, # the name of the column containing the unique patient ID event.date.colname=NA, # the start date of the event in the date.format format event.duration.colname=NA, # the event duration in days event.daily.dose.colname=NA, # the prescribed daily dose medication.class.colname=NA, # the classes/types/groups of medication # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Various types methods of computing gaps: carryover.within.obs.window=FALSE, # if TRUE consider the carry-over within the observation window carryover.into.obs.window=FALSE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage # The follow-up window: followup.window.start=0, # if a number, date earliest event per participant + number of units, otherwise a date.format date or variable date followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) followup.window.duration=365*2, # the duration of the follow-up window in the time units given below followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start, otherwise a date.format date or variable date observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) observation.window.duration=365*2, # the duration of the observation window in time units observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function # Keep the follow-up and observation window start and end dates? keep.window.start.end.dates=FALSE, remove.events.outside.followup.window=TRUE, # remove events outside the follow-up window? keep.event.interval.for.all.events=FALSE, # keep the event.interval estimates for all events # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=FALSE, # used internally to suppress the check that we don't use special argument names return.data.table=FALSE, # should the result be converted to data.frame (default) or returned as a data.table (keyed by patient ID and event date)? ... # other stuff ) { # preconditions concerning column names: if( is.null(data) || !inherits(data,"data.frame") || nrow(data) < 1 ) { if( !suppress.warnings ) .report.ewms("Event data must be a non-empty data frame!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } data.names <- names(data); # cache names(data) as it is used a lot if( is.null(ID.colname) || is.na(ID.colname) || # avoid empty stuff !(is.character(ID.colname) || # it must be a character... (is.factor(ID.colname) && is.character(ID.colname <- as.character(ID.colname)))) || # ...or a factor (forced to character) length(ID.colname) != 1 || # make sure it's a single value !(ID.colname %in% data.names) # make sure it's a valid column name ) { if( !suppress.warnings ) .report.ewms(paste0("The patient ID column \"",ID.colname,"\" cannot be empty, must be a single value, and must be present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(event.date.colname) || is.na(event.date.colname) || # avoid empty stuff !(is.character(event.date.colname) || # it must be a character... (is.factor(event.date.colname) && is.character(event.date.colname <- as.character(event.date.colname)))) || # ...or a factor (forced to character) length(event.date.colname) != 1 || # make sure it's a single value !(event.date.colname %in% data.names) # make sure it's a valid column name ) { if( !suppress.warnings ) .report.ewms(paste0("The event date column \"",event.date.colname,"\" cannot be empty, must be a single value, and must be present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(event.duration.colname) || is.na(event.duration.colname) || # avoid empty stuff !(is.character(event.duration.colname) || # it must be a character... (is.factor(event.duration.colname) && is.character(event.duration.colname <- as.character(event.duration.colname)))) || # ...or a factor (forced to character) length(event.duration.colname) != 1 || # make sure it's a single value !(event.duration.colname %in% data.names) # make sure it's a valid column name ) { if( !suppress.warnings ) .report.ewms(paste0("The event duration column \"",event.duration.colname,"\" cannot be empty, must be a single value, and must be present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( (!is.null(event.daily.dose.colname) && !is.na(event.daily.dose.colname)) && # if actually given: (!(is.character(event.daily.dose.colname) || # it must be a character... (is.factor(event.daily.dose.colname) && is.character(event.daily.dose.colname <- as.character(event.daily.dose.colname)))) || # ...or a factor (forced to character) length(event.daily.dose.colname) != 1 || # make sure it's a single value !(event.daily.dose.colname %in% data.names)) # make sure it's a valid column name ) { if( !suppress.warnings ) .report.ewms(paste0("If given, the event daily dose column \"",event.daily.dose.colname,"\" must be a single value and must be present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( (!is.null(medication.class.colname) && !is.na(medication.class.colname)) && # if actually given: (!(is.character(medication.class.colname) || # it must be a character... (is.factor(medication.class.colname) && is.character(medication.class.colname <- as.character(medication.class.colname)))) || # ...or a factor (forced to character) length(medication.class.colname) != 1 || # make sure it's a single value !(medication.class.colname %in% data.names)) # make sure it's a valid column name ) { if( !suppress.warnings ) .report.ewms(paste0("If given, the event type column \"",medication.class.colname,"\" must be a single value and must be present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR") return (NULL); } # preconditions concerning carry-over: if( !is.logical(carryover.within.obs.window) || is.na(carryover.within.obs.window) || length(carryover.within.obs.window) != 1 || !is.logical(carryover.into.obs.window) || is.na(carryover.into.obs.window) || length(carryover.into.obs.window) != 1 || !is.logical(carry.only.for.same.medication) || is.na(carry.only.for.same.medication) || length(carry.only.for.same.medication) != 1 ) { if( !suppress.warnings ) .report.ewms("Carry over arguments must be single value logicals!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( !carryover.within.obs.window && !carryover.into.obs.window && carry.only.for.same.medication ) { if( !suppress.warnings ) .report.ewms("Cannot carry over only for same medication when no carry over at all is considered!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } # preconditions concerning dosage change: if( !is.logical(consider.dosage.change) || is.na(consider.dosage.change) || length(consider.dosage.change) != 1 ) { if( !suppress.warnings ) .report.ewms("Consider dosage change must be single value logical!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } # preconditions concerning follow-up window (as all violations result in the same error, aggregate them in a single if): if( (is.null(followup.window.start) || is.na(followup.window.start) || length(followup.window.start) != 1) || # cannot be missing or have more than one values (!inherits(followup.window.start,"Date") && !is.numeric(followup.window.start) && # not a Date or number: (!(is.character(followup.window.start) || # it must be a character... (is.factor(followup.window.start) && is.character(followup.window.start <- as.character(followup.window.start)))) || # ...or a factor (forced to character) !(followup.window.start %in% data.names))) ) # make sure it's a valid column name { if( !suppress.warnings ) .report.ewms("The follow-up window start must be a single value, either a number, a Date object, or a string giving a column name in the data!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(followup.window.start.unit) || (is.na(followup.window.start.unit) && !(is.factor(followup.window.start) || is.character(followup.window.start))) || length(followup.window.start.unit) != 1 || ((is.factor(followup.window.start.unit) || is.character(followup.window.start.unit)) && !(followup.window.start.unit %in% c("days", "weeks", "months", "years"))) ) { if( !suppress.warnings ) .report.ewms("The follow-up window start unit must be a single value, one of \"days\", \"weeks\", \"months\" or \"years\"!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.numeric(followup.window.duration) && (followup.window.duration <= 0 || length(followup.window.duration) != 1) || # cannot be missing or have more than one values (!is.numeric(followup.window.duration) && (!(is.character(followup.window.duration) || # it must be a character... (is.factor(followup.window.duration) && is.character(followup.window.duration <- as.character(followup.window.duration)))) || # ...or a factor (forced to character) !(followup.window.duration %in% data.names)))) # make sure it's a valid column name { if( !suppress.warnings ) .report.ewms("The follow-up window duration must be a single value, either a positive number, or a string giving a column name in the data!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(followup.window.duration.unit) || is.na(followup.window.duration.unit) || length(followup.window.duration.unit) != 1 || !(followup.window.duration.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The follow-up window duration unit must be a single value, one of \"days\", \"weeks\", \"months\" or \"years\"!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } # preconditions concerning observation window (as all violations result in the same error, aggregate them in a single if): if( (is.null(observation.window.start) || is.na(observation.window.start) || length(observation.window.start) != 1) || # cannot be missing or have more than one values (is.numeric(observation.window.start) && (observation.window.start < 0)) || # if a number, must be a single positive one (!inherits(observation.window.start,"Date") && !is.numeric(observation.window.start) && # not a Date or number: (!(is.character(observation.window.start) || # it must be a character... (is.factor(observation.window.start) && is.character(observation.window.start <- as.character(observation.window.start)))) || # ...or a factor (forced to character) !(observation.window.start %in% data.names))) ) # make sure it's a valid column name { if( !suppress.warnings ) .report.ewms("The observation window start must be a single value, either a positive number, a Date object, or a string giving a column name in the data!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(observation.window.start.unit) || (is.na(observation.window.start.unit) && !(is.factor(observation.window.start) || is.character(observation.window.start))) || length(observation.window.start.unit) != 1 || ((is.factor(observation.window.start.unit) || is.character(observation.window.start.unit)) && !(observation.window.start.unit %in% c("days", "weeks", "months", "years"))) ) { if( !suppress.warnings ) .report.ewms("The observation window start unit must be a single value, one of \"days\", \"weeks\", \"months\" or \"years\"!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.numeric(observation.window.duration) && (observation.window.duration <= 0 || length(observation.window.duration) != 1) || # cannot be missing or have more than one values (!is.numeric(observation.window.duration) && (!(is.character(observation.window.duration) || # it must be a character... (is.factor(observation.window.duration) && is.character(observation.window.duration <- as.character(observation.window.duration)))) || # ...or a factor (forced to character) !(observation.window.duration %in% data.names)))) # make sure it's a valid column name { if( !suppress.warnings ) .report.ewms("The observation window duration must be a single value, either a positive number, or a string giving a column name in the data!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } if( is.null(observation.window.duration.unit) || is.na(observation.window.duration.unit) || length(observation.window.duration.unit) != 1 || !(observation.window.duration.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The observation window duration unit must be a single value, one of \"days\", \"weeks\", \"months\" or \"years\"!\n", "error", "compute.event.int.gaps", "AdhereR") return (NULL); } # Check the patient IDs: if( anyNA(data[,ID.colname]) ) { if( !suppress.warnings ) .report.ewms(paste0("The patient unique identifiers in the \"",ID.colname,"\" column must not contain NAs; the first occurs on row ",min(which(is.na(data[,ID.colname]))),"!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Check the date format (and save the conversion to Date() for later use): if( is.na(date.format) || is.null(date.format) || length(date.format) != 1 || !is.character(date.format) ) { if( !suppress.warnings ) .report.ewms(paste0("The date format must be a single string!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } if( anyNA(Date.converted.to.DATE <- as.Date(data[,event.date.colname],format=date.format)) ) { if( !suppress.warnings ) .report.ewms(paste0("Not all entries in the event date \"",event.date.colname,"\" column are valid dates or conform to the date format \"",date.format,"\"; first issue occurs on row ",min(which(is.na(Date.converted.to.DATE))),"!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Check the duration: tmp <- data[,event.duration.colname]; # caching for speed if( !is.numeric(tmp) || any(is.na(tmp) | tmp <= 0) ) { if( !suppress.warnings ) .report.ewms(paste0("The event durations in the \"",event.duration.colname,"\" column must be non-missing strictly positive numbers!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Check the event daily dose: if( !is.na(event.daily.dose.colname) && !is.null(event.daily.dose.colname) && # if actually given: (!is.numeric(tmp <- data[,event.daily.dose.colname]) || any(is.na(tmp) | tmp <= 0)) ) # must be a non-missing strictly positive number (and cache it for speed) { if( !suppress.warnings ) .report.ewms(paste0("If given, the event daily dose in the \"",event.daily.dose.colname,"\" column must be a non-missing strictly positive numbers!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Check the newly created columns: if( is.na(event.interval.colname) || is.null(event.interval.colname) || !is.character(event.interval.colname) || (event.interval.colname %in% data.names) ) { if( !suppress.warnings ) .report.ewms(paste0("The column name where the event interval will be stored \"",event.interval.colname,"\" cannot be missing nor already present in the event data!\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } if( is.na(gap.days.colname) || is.null(gap.days.colname) || !is.character(gap.days.colname) || (gap.days.colname %in% data.names) ) { if( !suppress.warnings ) .report.ewms(paste0("The column name where the gap days will be stored \"",gap.days.colname,"\" cannot be mising nor already present in the event data.\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Make a data.table copy of data so we can alter it without altering the original input data: ret.val <- data.table(data); event.date2.colname <- ".DATE.as.Date"; # name of column caching the event dates ret.val[,c(event.interval.colname, # output column event.interval.colname gap.days.colname, # output column gap.days.colname ".DATE.as.Date", # cache column .DATE.as.Date ".FU.START.DATE", # cache FUW start date ".FU.END.DATE", # cache FUW end date ".OBS.START.DATE", # cache OW start date ".OBS.END.DATE", # cache OW end date ".OBS.WITHIN.FU", # cache if the OW falls within the FUW ".EVENT.STARTS.BEFORE.OBS.WINDOW", # cache if the event starts before the OW begins ".EVENT.STARTS.AFTER.OBS.WINDOW", # cache if the event starts after the OW ends ".EVENT.WITHIN.FU.WINDOW", # cache if the event is within the FUW ".TDIFF1", # cache time difference betwen the event duration and (OW start - event start) ".TDIFF2", # cache time difference betwen the next event start date and the current event start date ".CARRY.OVER.FROM.BEFORE" # cache if there is carry over from before the current event ) := list(NA_real_, # event.interval.colname: initially NA (numeric) NA_real_, # gap.days.colname: initially NA (numeric) Date.converted.to.DATE, # .DATE.as.Date: convert event.date.colname from formatted string to Date (speeding calendar computations) as.Date(NA), # .FU.START.DATE: initially NA (of type Date) as.Date(NA), # .FU.END.DATE: initially NA (of type Date) as.Date(NA), # .OBS.START.DATE: initially NA (of type Date) as.Date(NA), # .OBS.END.DATE: initially NA (of type Date) NA, # .OBS.WITHIN.FU: initially NA (logical) NA, # .EVENT.STARTS.BEFORE.OBS.WINDOW: initially NA (logical) NA, # .EVENT.STARTS.AFTER.OBS.WINDOW: initially NA (logical) NA, # .EVENT.WITHIN.FU.WINDOW: initially NA (logical) NA_real_, # .TDIFF1: initially NA (numeric) NA_real_, # .TDIFF2: initially NA (numeric) NA_real_ # .CARRY.OVER.FROM.BEFORE: initially NA (numeric) )]; # Cache types of followup.window.start and observation.window.start (1 = numeric, 2 = column with Dates, 3 = column with units, 4 = a Date), as well as durations: followup.window.start.type <- ifelse(is.numeric(followup.window.start), 1, # a number in the appropriate units ifelse(followup.window.start %in% data.names, ifelse(inherits(data[,followup.window.start],"Date"), 2, # column of Date objects 3), # column of numbers in the appropriate units 4)); # a Date object followup.window.duration.is.number <- is.numeric(followup.window.duration) observation.window.start.type <- ifelse(is.numeric(observation.window.start), 1, # a number in the appropriate units ifelse(observation.window.start %in% data.names, ifelse(inherits(data[,observation.window.start],"Date"), 2, # column of Date objects 3), # column of numbers in the appropriate units 4)); # a Date object observation.window.duration.is.number <- is.numeric(observation.window.duration) setkeyv(ret.val, c(ID.colname, ".DATE.as.Date")); # key (and sorting) by patient ID and event date # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: For a given patient, compute the gaps and return the required columns: .process.patient <- function(data4ID) { # Number of events: n.events <- nrow(data4ID); # Force the selection, evaluation of promises and caching of the needed columns: # ... which columns to select (with their indices): columns.to.cache <- c(event.date2.colname, event.duration.colname); event.date2.colname.index <- 1; event.duration.colname.index <- 2; curr.index <- 3; if( !is.na(medication.class.colname) ){ columns.to.cache <- c(columns.to.cache, medication.class.colname); medication.class.colname.index <- curr.index; curr.index <- curr.index + 1;} if( !is.na(event.daily.dose.colname) ){ columns.to.cache <- c(columns.to.cache, event.daily.dose.colname); event.daily.dose.colname.index <- curr.index; curr.index <- curr.index + 1;} if( followup.window.start.type %in% c(2,3) ){ columns.to.cache <- c(columns.to.cache, followup.window.start); followup.window.start.index <- curr.index; curr.index <- curr.index + 1;} if( !followup.window.duration.is.number ){ columns.to.cache <- c(columns.to.cache, followup.window.duration); followup.window.duration.index <- curr.index; curr.index <- curr.index + 1;} if( observation.window.start.type %in% c(2,3) ){ columns.to.cache <- c(columns.to.cache, observation.window.start); observation.window.start.index <- curr.index; curr.index <- curr.index + 1;} if( !observation.window.duration.is.number ){ columns.to.cache <- c(columns.to.cache, observation.window.duration); observation.window.duration.index <- curr.index; curr.index <- curr.index + 1;} # ... select these columns: data4ID.selected.columns <- data4ID[, columns.to.cache, with=FALSE]; # alternative to: data4ID[,..columns.to.cache] # ... cache the columns based on their indices: event.date2.column <- data4ID.selected.columns[[event.date2.colname.index]]; event.duration.column <- data4ID.selected.columns[[event.duration.colname.index]]; if( !is.na(medication.class.colname) ) medication.class.column <- data4ID.selected.columns[[medication.class.colname.index]]; if( !is.na(event.daily.dose.colname) ) event.daily.dose.column <- data4ID.selected.columns[[event.daily.dose.colname.index]]; if( followup.window.start.type %in% c(2,3) ) followup.window.start.column <- data4ID.selected.columns[[followup.window.start.index]]; if( !followup.window.duration.is.number ) followup.window.duration.column <- data4ID.selected.columns[[followup.window.duration.index]]; if( observation.window.start.type %in% c(2,3) ) observation.window.start.column <- data4ID.selected.columns[[observation.window.start.index]]; if( !observation.window.duration.is.number ) observation.window.duration.column <- data4ID.selected.columns[[observation.window.duration.index]]; # Cache also follow-up window start and end dates: # start dates .FU.START.DATE <- switch(followup.window.start.type, .add.time.interval.to.date(event.date2.column[1], followup.window.start, followup.window.start.unit, suppress.warnings), # 1 followup.window.start.column[1], # 2 .add.time.interval.to.date(event.date2.column[1], followup.window.start.column[1], followup.window.start.unit, suppress.warnings), # 3 followup.window.start); # 4 if( is.na(.FU.START.DATE) ) { # Return a valid but empty object: return (list(".FU.START.DATE"=as.Date(NA), ".FU.END.DATE"=as.Date(NA), ".OBS.START.DATE"=as.Date(NA), ".OBS.END.DATE"=as.Date(NA), ".EVENT.STARTS.BEFORE.OBS.WINDOW"=NA, ".EVENT.STARTS.AFTER.OBS.WINDOW"=NA, ".EVENT.WITHIN.FU.WINDOW"=NA, ".TDIFF1"=NA_real_, ".TDIFF2"=NA_real_, ".OBS.WITHIN.FU"=FALSE, ".EVENT.INTERVAL"=NA_real_, ".GAP.DAYS"=NA_real_, ".CARRY.OVER.FROM.BEFORE"=NA_real_)); } # end dates .FU.END.DATE <- .add.time.interval.to.date(.FU.START.DATE, ifelse(followup.window.duration.is.number, followup.window.duration, followup.window.duration.column[1]), followup.window.duration.unit, suppress.warnings); if( is.na(.FU.END.DATE) ) { # Return a valid but empty object: return (list(".FU.START.DATE"=.FU.START.DATE, ".FU.END.DATE"=as.Date(NA), ".OBS.START.DATE"=as.Date(NA), ".OBS.END.DATE"=as.Date(NA), ".EVENT.STARTS.BEFORE.OBS.WINDOW"=NA, ".EVENT.STARTS.AFTER.OBS.WINDOW"=NA, ".EVENT.WITHIN.FU.WINDOW"=NA, ".TDIFF1"=NA_real_, ".TDIFF2"=NA_real_, ".OBS.WITHIN.FU"=FALSE, ".EVENT.INTERVAL"=NA_real_, ".GAP.DAYS"=NA_real_, ".CARRY.OVER.FROM.BEFORE"=NA_real_)); } # Is the event within the FU window? .EVENT.WITHIN.FU.WINDOW <- (event.date2.column >= .FU.START.DATE) & (event.date2.column <= .FU.END.DATE); # Cache also observation window start and end dates: # start dates .OBS.START.DATE <- switch(observation.window.start.type, .add.time.interval.to.date(.FU.START.DATE, observation.window.start, observation.window.start.unit, suppress.warnings), # 1 observation.window.start.column[1], # 2 .add.time.interval.to.date(.FU.START.DATE, observation.window.start.column[1], observation.window.start.unit, suppress.warnings), # 3 observation.window.start); # 4 if( is.na(.OBS.START.DATE) ) { # Return a valid but empty object: return (list(".FU.START.DATE"=.FU.START.DATE, ".FU.END.DATE"=.FU.END.DATE, ".OBS.START.DATE"=as.Date(NA), ".OBS.END.DATE"=as.Date(NA), ".EVENT.STARTS.BEFORE.OBS.WINDOW"=NA, ".EVENT.STARTS.AFTER.OBS.WINDOW"=NA, ".EVENT.WITHIN.FU.WINDOW"=.EVENT.WITHIN.FU.WINDOW, ".TDIFF1"=NA_real_, ".TDIFF2"=NA_real_, ".OBS.WITHIN.FU"=FALSE, ".EVENT.INTERVAL"=NA_real_, ".GAP.DAYS"=NA_real_, ".CARRY.OVER.FROM.BEFORE"=NA_real_)); } # end dates .OBS.END.DATE <- .add.time.interval.to.date(.OBS.START.DATE, ifelse(observation.window.duration.is.number, observation.window.duration, observation.window.duration.column[1]), observation.window.duration.unit, suppress.warnings); if( is.na(.OBS.END.DATE) ) { # Return a valid but empty object: return (list(".FU.START.DATE"=.FU.START.DATE, ".FU.END.DATE"=.FU.END.DATE, ".OBS.START.DATE"=.OBS.START.DATE, ".OBS.END.DATE"=as.Date(NA), ".EVENT.STARTS.BEFORE.OBS.WINDOW"=NA, ".EVENT.STARTS.AFTER.OBS.WINDOW"=NA, ".EVENT.WITHIN.FU.WINDOW"=.EVENT.WITHIN.FU.WINDOW, ".TDIFF1"=NA_real_, ".TDIFF2"=NA_real_, ".OBS.WITHIN.FU"=FALSE, ".EVENT.INTERVAL"=NA_real_, ".GAP.DAYS"=NA_real_, ".CARRY.OVER.FROM.BEFORE"=NA_real_)); } # For each event, starts before/after the observation window start date? .EVENT.STARTS.BEFORE.OBS.WINDOW <- (event.date2.column < .OBS.START.DATE); .EVENT.STARTS.AFTER.OBS.WINDOW <- (event.date2.column > .OBS.END.DATE); # Cache some time differences: # event.duration.colname - (.OBS.START.DATE - event.date2.colname): .TDIFF1 <- (event.duration.column - .difftime.Dates.as.days(.OBS.START.DATE, event.date2.column)); # event.date2.colname[current+1] - event.date2.colname[current]: if( n.events > 1 ) { .TDIFF2 <- c(.difftime.Dates.as.days(event.date2.column[-1], event.date2.column[-n.events]),NA_real_); } else { .TDIFF2 <- NA_real_; } # Make sure the observation window is included in the follow-up window: if( (.FU.START.DATE > .OBS.START.DATE) || (.FU.END.DATE < .OBS.END.DATE) ) { # Return a valid but empty object: return (list(".FU.START.DATE"=.FU.START.DATE, ".FU.END.DATE"=.FU.END.DATE, ".OBS.START.DATE"=.OBS.START.DATE, ".OBS.END.DATE"=.OBS.END.DATE, ".EVENT.STARTS.BEFORE.OBS.WINDOW"=.EVENT.STARTS.BEFORE.OBS.WINDOW, ".EVENT.STARTS.AFTER.OBS.WINDOW"=.EVENT.STARTS.AFTER.OBS.WINDOW, ".EVENT.WITHIN.FU.WINDOW"=.EVENT.WITHIN.FU.WINDOW, ".TDIFF1"=.TDIFF1, ".TDIFF2"=.TDIFF2, ".OBS.WITHIN.FU"=FALSE, ".EVENT.INTERVAL"=NA_real_, ".GAP.DAYS"=NA_real_, ".CARRY.OVER.FROM.BEFORE"=NA_real_)); } else { .OBS.WITHIN.FU <- TRUE; } .CARRY.OVER.FROM.BEFORE <- .EVENT.INTERVAL <- .GAP.DAYS <- rep(NA_real_,n.events); # initialize to NA # Select only those events within the FUW and OW (depending on carryover into OW): if( !carryover.into.obs.window ) { s <- which(.EVENT.WITHIN.FU.WINDOW & !.EVENT.STARTS.BEFORE.OBS.WINDOW & !.EVENT.STARTS.AFTER.OBS.WINDOW); # select all events for this patient within the observation window } else { s <- which(.EVENT.WITHIN.FU.WINDOW & !.EVENT.STARTS.AFTER.OBS.WINDOW); # select all events for patient ID within the follow-up window } slen <- length(s); # cache it up if( slen == 1 ) # only one event in the observation window { # Computations happen within the observation window .EVENT.INTERVAL[s] <- .difftime.Dates.as.days(.OBS.END.DATE, event.date2.column[s]); # for last event, the interval ends at the end of OW .CARRY.OVER.FROM.BEFORE[s] <- 0.0; # no carry-over into this unique event .GAP.DAYS[s] <- max(0.0, (.EVENT.INTERVAL[s] - event.duration.column[s])); # the actual gap cannot be negative } else if( slen > 1 ) # at least one event in the observation window { # Computations happen within the observation window if( carryover.within.obs.window ) { # do carry over within the observation window: # was there a change in medication? if( !is.na(medication.class.colname) ) { medication.changed <- c((medication.class.column[s[-slen]] != medication.class.column[s[-1]]), FALSE); } else { medication.changed <- rep(FALSE,slen); } # was there a change in dosage? if( !is.na(event.daily.dose.colname) ) { dosage.change.ratio <- c((event.daily.dose.column[s[-slen]] / event.daily.dose.column[s[-1]]), 1.0); } else { dosage.change.ratio <- rep(1.0,slen); } # event intervals: .EVENT.INTERVAL[s] <- .TDIFF2[s]; # save the time difference between next and current event start dates, but .EVENT.INTERVAL[s[slen]] <- .difftime.Dates.as.days(.OBS.END.DATE, event.date2.column[s[slen]]); # for last event, the interval ends at the end of OW # event.interval - event.duration: .event.interval.minus.duration <- (.EVENT.INTERVAL[s] - event.duration.column[s]); # cache various medication and dosage change conditions: cond1 <- (carry.only.for.same.medication & medication.changed); cond2 <- ((carry.only.for.same.medication & consider.dosage.change & !medication.changed) | (!carry.only.for.same.medication & consider.dosage.change)); carry.over <- 0; # Initially, no carry-over into the first event # for each event: for( i in seq_along(s) ) # this for loop is not a performance bottleneck! { si <- s[i]; # caching s[i] as it's used a lot # Save the carry-over into the event: .CARRY.OVER.FROM.BEFORE[si] <- carry.over; # Computing the gap between events: gap <- (.event.interval.minus.duration[i] - carry.over); # subtract the event duration and carry-over from event interval if( gap < 0.0 ) # the actual gap cannot be negative { .GAP.DAYS[si] <- 0.0; carry.over <- (-gap); } else { .GAP.DAYS[si] <- gap; carry.over <- 0.0; } if( cond1[i] ) { # Do not carry over across medication changes: carry.over <- 0; } else if( cond2[i] ) { # Apply the dosage change ratio: carry.over <- carry.over * dosage.change.ratio[i]; # adjust the carry-over relative to dosage change } } } else { # do not consider carry over within the observation window: # event intervals: .EVENT.INTERVAL[s] <- .TDIFF2[s]; # save the time difference between next and current event start dates, but .EVENT.INTERVAL[s[slen]] <- .difftime.Dates.as.days(.OBS.END.DATE, event.date2.column[s[slen]]); # for last event, the interval ends at the end of OW # event.interval - event.duration: .event.interval.minus.duration <- (.EVENT.INTERVAL[s] - event.duration.column[s]); # no carry over in this case: .CARRY.OVER.FROM.BEFORE[s] <- 0.0; # for each event: for( i in seq_along(s) ) # this for loop is not a performance bottleneck! { si <- s[i]; # caching s[i] as it's used a lot # Computing the gap between events: gap <- .event.interval.minus.duration[i]; # the event duration if( gap < 0.0 ) # the actual gap cannot be negative { .GAP.DAYS[si] <- 0.0; } else { .GAP.DAYS[si] <- gap; } } } } # Return the computed columns: return (list(".FU.START.DATE"=.FU.START.DATE, ".FU.END.DATE"=.FU.END.DATE, ".OBS.START.DATE"=.OBS.START.DATE, ".OBS.END.DATE"=.OBS.END.DATE, ".EVENT.STARTS.BEFORE.OBS.WINDOW"=.EVENT.STARTS.BEFORE.OBS.WINDOW, ".EVENT.STARTS.AFTER.OBS.WINDOW"=.EVENT.STARTS.AFTER.OBS.WINDOW, ".EVENT.WITHIN.FU.WINDOW"=.EVENT.WITHIN.FU.WINDOW, ".TDIFF1"=.TDIFF1, ".TDIFF2"=.TDIFF2, ".OBS.WITHIN.FU"=.OBS.WITHIN.FU, ".EVENT.INTERVAL"=.EVENT.INTERVAL, ".GAP.DAYS"=.GAP.DAYS, ".CARRY.OVER.FROM.BEFORE"=.CARRY.OVER.FROM.BEFORE)); } # Don't attempt to proces an empty dataset: if( is.null(data) || nrow(data) == 0 ) return (NULL); data[, c(".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE", ".EVENT.STARTS.BEFORE.OBS.WINDOW", ".EVENT.STARTS.AFTER.OBS.WINDOW", ".EVENT.WITHIN.FU.WINDOW", ".TDIFF1", ".TDIFF2", ".OBS.WITHIN.FU", event.interval.colname, gap.days.colname, ".CARRY.OVER.FROM.BEFORE") := .process.patient(.SD), # for each patient, compute the various columns and assign them back into the data.table by=ID.colname # group by patients ]; return (data); } # Compute the workhorse function: ret.val <- .compute.function(.workhorse.function, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=ret.val, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) || nrow(ret.val) < 1 ) { if( !suppress.warnings ) .report.ewms("Computing event intervals and gap days failed!\n", "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } if( any(!ret.val$.OBS.WITHIN.FU) ) { if( !suppress.warnings ) .report.ewms(paste0("The observation window is not within the follow-up window for participant(s) ",paste0(unique(ret.val[!ret.val$.OBS.WITHIN.FU,get(ID.colname)]),collapse=", ")," !\n"), "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Make sure events outside the observation window are NA'ed: if( !keep.event.interval.for.all.events ) ret.val[ .OBS.WITHIN.FU & (.EVENT.STARTS.BEFORE.OBS.WINDOW | .EVENT.STARTS.AFTER.OBS.WINDOW), c(event.interval.colname) := NA_real_ ]; # Remove the events that fall outside the follow-up window: if( remove.events.outside.followup.window ) ret.val <- ret.val[ which(.OBS.WITHIN.FU & .EVENT.WITHIN.FU.WINDOW), ]; # If the results are empty return NULL: if( is.null(ret.val) || nrow(ret.val) < 1 ) { if( !suppress.warnings ) .report.ewms("No observations fall within the follow-up and observation windows!\n", "error", "compute.event.int.gaps", "AdhereR"); return (NULL); } # Final clean-up: delete temporary columns: if( !keep.window.start.end.dates ) { ret.val[,c(".DATE.as.Date", ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE", ".OBS.WITHIN.FU", ".EVENT.STARTS.BEFORE.OBS.WINDOW", ".TDIFF1", ".TDIFF2", ".EVENT.STARTS.AFTER.OBS.WINDOW", ".CARRY.OVER.FROM.BEFORE", ".EVENT.WITHIN.FU.WINDOW") := NULL]; } # If the results are empty return NULL: if( is.null(ret.val) || nrow(ret.val) < 1 ) return (NULL); if( !return.data.table ) { return (as.data.frame(ret.val)); } else { if( ".DATE.as.Date" %in% names(ret.val) ) { setkeyv(ret.val, c(ID.colname, ".DATE.as.Date")); # make sure it is keyed by patient ID and event date } else { setkeyv(ret.val, c(ID.colname)); # make sure it is keyed by patient ID (as event date was removed) } return (ret.val); } } #' Compute Treatment Episodes. #' #' For a given event (prescribing or dispensing) database, compute the treatment #' episodes for each patient in various scenarious. #' #' This should in general not be called directly by the user, but is provided as #' a basis for the extension to new CMAs. #' #' For the last treatment episode, the gap is considered only when longer than #' the maximum permissible gap. #' Please note the following: #' \itemize{ #' \item episode starts at first medication event for a particular medication, #' \item episode ends on the day when the last supply of that medication #' finished or if a period longer than the permissible gap preceded the next #' medication event, or at the end of the FUW, #' \item end episode gap days represents either the number of days after the #' end of the treatment episode (if medication changed, or if a period longer #' than the permissible gap preceded the next medication event) or at the #' end of (and within) the episode, i.e. the number of days after the last #' supply finished (if no other medication event followed until the end of the #' FUW), #' \item the duration of the episode is the interval between the episode start #' and episode end (and may include the gap days at the end, in the latter #' condition described above), #' \item the number of gap days after the end of the episode can be computed #' as all values larger than the permissible gap and 0 otherwise, #' \item if medication change starts new episode, then previous episode ends #' when the last supply is finished (irrespective of the length of gap compared #' to a maximum permissible gap); any days before the date of the new #' medication supply are considered a gap; this maintains consistency with gaps #' between episodes (whether they are constructed based on the maximum #' permissible gap rule or the medication change rule). #' } #' #' @param data A \emph{\code{data.frame}} containing the events used to #' compute the CMA. Must contain, at a minimum, the patient unique ID, the event #' date and duration, and might also contain the daily dosage and medication #' type (the actual column names are defined in the following four parameters); #' the \code{CMA} constructors call this parameter \code{data}. #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID, or \code{NA} if not defined. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter), or \code{NA} if not defined. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days), or \code{NA} if not #' defined. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the classes/types/groups of medication, or \code{NA} #' if not defined. #' @param carryover.within.obs.window \emph{Logical}, if \code{TRUE} consider #' the carry-over within the observation window, or \code{NA} if not defined. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE} the #' carry-over applies only across medication of the same type, or \code{NA} if #' not defined. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE} the carry-over #' is adjusted to reflect changes in dosage, or \code{NA} if not defined. #' @param medication.change.means.new.treatment.episode \emph{Logical}, should #' a change in medication automatically start a new treatment episode? #' @param dosage.change.means.new.treatment.episode \emph{Logical}, should #' a change in dosage automatically start a new treatment episode? #' @param maximum.permissible.gap The \emph{number} of units given by #' \code{maximum.permissible.gap.unit} representing the maximum duration of #' permissible gaps between treatment episodes (can also be a percent, see #' \code{maximum.permissible.gap.unit} for details). #' @param maximum.permissible.gap.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"}, \emph{"years"} or \emph{"percent"}, and #' represents the time units that \code{maximum.permissible.gap} refers to; #' if \emph{percent}, then \code{maximum.permissible.gap} is interpreted as a #' percent (can be greater than 100\%) of the duration of the current #' prescription. #' @param maximum.permissible.gap.append.to.episode a \emph{logical} value #' specifying of the \code{maximum.permissible.gap} should be append at the #' end of an episode with a gap larger than the \code{maximum.permissible.gap}; #' \code{FALSE} (the default) mean no addition, while \code{TRUE} mean that the #' full \code{maximum.permissible.gap} is added. #' @param followup.window.start If a \emph{\code{Date}} object it is the actual #' start date of the follow-up window; if a \emph{string} it is the name of the #' column in \code{data} containing the start date of the follow-up window; if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, \emph{"weeks"}, #' \emph{"months"} or \emph{"years"}, and represents the time units that #' \code{followup.window.start} refers to (when a number), or \code{NA} if not #' defined. #' @param followup.window.duration a \emph{number} representing the duration of #' the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or \code{NA} if not defined. #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param return.mapping.events.episodes A \emph{Logical}, if \code{TRUE} then #' the mapping between events and episodes is returned as the attribute #' \code{mapping.episodes.to.events}, which is a \code{data.table} giving, for #' each episode, the events that belong to it (an event is given by its row #' number in the \code{data}). Please note that the episodes returned are quite #' "generic" (e.g., they include all the events in the FUW), because which events #' will be actually used in the computation of a \code{CMA_per_episode} depend on #' which simple CMA is used (see also \code{CMA_per_episode}), and should be used #' with care (we recommend using the mappings given by \code{CMA_per_episode} #' instead). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param ... extra arguments. #' @return A \code{data.frame} or \code{data.table} with the following columns #' (or \code{NULL} if no #' treatment episodes could be computed): #' \itemize{ #' \item \code{patid} the patient ID. #' \item \code{episode.ID} the episode unique ID (increasing sequentially). #' \item \code{episode.start} the episode start date. #' \item \code{end.episode.gap.days} the corresponding gap days of the last event in this episode. #' \item \code{episode.duration} the episode duration in days. #' \item \code{episode.end} the episode end date. #' } #' If \code{mapping.episodes.to.events} is \code{TRUE}, then this also has an #' \emph{attribute} \code{mapping.episodes.to.events} that gives the mapping between #' episodes and events as a \code{data.table} with the following columns: #' \itemize{ #' \item \code{patid} the patient ID. #' \item \code{episode.ID} the episode unique ID (increasing sequentially). #' \item \code{event.index.in.data} the event given by its row number in the \code{data}. #' } #' @export compute.treatment.episodes <- function( data, # this is a per-event data.frame with columns: ID.colname=NA, # the name of the column containing the unique patient ID event.date.colname=NA, # the start date of the event in the date.format format event.duration.colname=NA, # the event duration in days event.daily.dose.colname=NA, # the prescribed daily dose medication.class.colname=NA, # the classes/types/groups of medication # Various types methods of computing gaps: carryover.within.obs.window=TRUE, # if TRUE consider the carry-over within the observation window carry.only.for.same.medication=TRUE, # if TRUE the carry-over applies only across medication of same type consider.dosage.change=TRUE, # if TRUE carry-over is adjusted to reflect changes in dosage # Treatment episodes: medication.change.means.new.treatment.episode=TRUE, # does a change in medication automatically start a new treatment episode? dosage.change.means.new.treatment.episode=FALSE, # does a change in dosage automatically start a new treatment episode? maximum.permissible.gap=90, # if a number, is the duration in units of max. permissible gaps between treatment episodes maximum.permissible.gap.unit=c("days", "weeks", "months", "years", "percent")[1], # time units; can be "days", "weeks" (fixed at 7 days), "months" (fixed at 30 days), "years" (fixed at 365 days), or "percent", in which case maximum.permissible.gap is interpreted as a percent (can be > 100%) of the duration of the current prescription maximum.permissible.gap.append.to.episode=FALSE, # should the maximum permissible gap be appended at the end of an episode with a gap larger than the maximum permissible gap? FALSE = no addition (the default), TRUE = the full maximum permissible gap is added # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, otherwise a date.format date followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) followup.window.duration=365*2, # the duration of the follow-up window in the time units given below followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Return also the mapping between episodes and events? return.mapping.events.episodes=FALSE, # return the mapping? # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=FALSE, # used internally to suppress the check that we don't use special argument names return.data.table=FALSE, ... # other stuff ) { # Consistency checks: if( is.null(CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.change.means.new.treatment.episode=medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=dosage.change.means.new.treatment.episode, maximum.permissible.gap=maximum.permissible.gap, maximum.permissible.gap.unit=maximum.permissible.gap.unit, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, date.format=date.format, parallel.backend=parallel.backend, parallel.threads=parallel.threads, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=return.data.table, ...)) ) # delegate default checks to CMA0! { return (NULL); } # Episode-specific stuff: if( is.na(medication.class.colname) && medication.change.means.new.treatment.episode ) { if( !suppress.warnings ) .report.ewms("When 'medication.class.colname' is NA, 'medication.change.means.new.treatment.episode' must be FALSE!\n", "error", "compute.treatment.episodes", "AdhereR"); return (NULL); } if( is.na(event.daily.dose.colname) && dosage.change.means.new.treatment.episode ) { if( !suppress.warnings ) .report.ewms("When 'event.daily.dose.colname' is NA, 'dosage.change.means.new.treatment.episode' must be FALSE!\n", "error", "compute.treatment.episodes", "AdhereR"); return (NULL); } # Convert maximum permissible gap units into days or proportion: maximum.permissible.gap.as.percent <- FALSE; # is the maximum permissible gap a percent of the current duration? maximum.permissible.gap <- switch(maximum.permissible.gap.unit, "days" = maximum.permissible.gap, "weeks" = maximum.permissible.gap * 7, "months" = maximum.permissible.gap * 30, "years" = maximum.permissible.gap * 365, "percent" = {maximum.permissible.gap.as.percent <- TRUE; maximum.permissible.gap / 100;}, # transform it into a proportion for faster computation {if(!suppress.warnings) .report.ewms(paste0("Unknown maximum.permissible.gap.unit '",maximum.permissible.gap.unit,"': assuming you meant 'days'."), "warning", "compute.treatment.episodes", "AdhereR"); maximum.permissible.gap;} # otherwise force it to "days" ); if( maximum.permissible.gap < 0 ) maximum.permissible.gap <- 0; # make sure this is positive # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { # Cache things up: n.events <- nrow(data4ID); last.event <- max(which(data4ID$.EVENT.WITHIN.FU.WINDOW), na.rm=TRUE); # the last event in the follow-up window event.duration.column <- data4ID[,get(event.duration.colname)]; gap.days.column <- data4ID[,get(gap.days.colname)]; if( !is.na(medication.class.colname) ) medication.class.column <- data4ID[,get(medication.class.colname)]; event.id.column <- data4ID$.EVENT.UNIQUE.ID; MAX.PERMISSIBLE.GAP <- switch(as.numeric(maximum.permissible.gap.as.percent)+1, rep(maximum.permissible.gap,n.events), # FALSE: maximum.permissible.gap is fixed in days maximum.permissible.gap * event.duration.column); # TRUE: maximum.permissible.gap is a percent of the duration # Select those gaps bigger than the maximum.permissible.gap: s <- (gap.days.column > MAX.PERMISSIBLE.GAP); if( medication.change.means.new.treatment.episode && n.events > 1 ) { # If medication change triggers a new episode and there is more than one event, consider these changes as well: s <- (s | c(medication.class.column[1:(n.events-1)] != medication.class.column[2:n.events], TRUE)); } if( dosage.change.means.new.treatment.episode && n.events > 1 ) { # If dosage change triggers a new episode and there is more than one event, consider these changes as well: s <- (s | c(event.daily.dose.colname[1:(n.events-1)] != event.daily.dose.colname[2:n.events], TRUE)); } s <- which(s); s.len <- length(s); if( n.events == 1 || s.len == 0 || (s.len==1 && s==n.events) ) { # One single treatment episode starting with the first event within the follow-up window and the end of the follow-up window: episode.starting.index <- 1; treatment.episodes <- data.table("episode.ID"=as.numeric(1), "episode.start"=data4ID$.DATE.as.Date[episode.starting.index], "end.episode.gap.days"=gap.days.column[last.event], "events.in.episode"=paste0(event.id.column[ episode.starting.index : last.event ], collapse=",")); # the events contained in each episode if( maximum.permissible.gap.append.to.episode ) { # Should we add the maximum permissible gap? gap.correction <- MAX.PERMISSIBLE.GAP[last.event]; } else { # Don't add the maximum permissible gap to the episode: gap.correction <- 0.0; } n.episodes <- nrow(treatment.episodes); treatment.episodes[, episode.duration := as.numeric(data4ID$.FU.END.DATE[1] - episode.start[n.episodes]) - ifelse(end.episode.gap.days[n.episodes] < MAX.PERMISSIBLE.GAP[last.event], # duration of the last event of the last episode 0, end.episode.gap.days[n.episodes] + gap.correction)]; # the last episode duration is the end date of the follow-up window minus the start date of the last episode, minus the gap after the last episode plus (if requested) the maximum permissible gap, only if the gap is longer than the maximum permissible gap treatment.episodes[, episode.end := (episode.start + episode.duration)]; } else { # Define the treatment episodes: if( s[s.len] != n.events ) { # The last event with gap > maximum permissible is not the last event for this patient: episode.starting.index <- c(1, # the 1st event in the follow-up window s+1); # the next event treatment.episodes <- data.table("episode.ID"=as.numeric(1:(s.len+1)), "episode.start"=data4ID$.DATE.as.Date[episode.starting.index], "end.episode.gap.days"=c(gap.days.column[s], # the corresponding gap.days of the last event in this episode gap.days.column[last.event]), # the corresponding gap.days of the last event in this follow-up window "events.in.episode"=c(vapply(1:(length(episode.starting.index)-1), function(i) paste0(event.id.column[ episode.starting.index[i]:(episode.starting.index[i+1]-1) ], collapse=","), character(1)), paste0(event.id.column[ episode.starting.index[length(episode.starting.index)]:last.event ], collapse=","))); # the events contained in each episode if( maximum.permissible.gap.append.to.episode ) { # Should we add the maximum permissible gap? episode.gap.smaller.than.max <- c(gap.days.column[s] <= MAX.PERMISSIBLE.GAP[s], gap.days.column[last.event] <= MAX.PERMISSIBLE.GAP[last.event]); # gap days less than the maximum permissible gap gap.correction <- MAX.PERMISSIBLE.GAP[c(s, last.event)]; } } else { # The last event with gap > maximum permissible is the last event for this patient: episode.starting.index <- c(1, # the 1st event in the follow-up window s[-s.len]+1); # the next event treatment.episodes <- data.table("episode.ID"=as.numeric(1:s.len), "episode.start"=data4ID$.DATE.as.Date[episode.starting.index], "end.episode.gap.days"=gap.days.column[s], # the corresponding gap.days of the last event in this follow-up window "events.in.episode"=c(vapply(1:(length(episode.starting.index)-1), function(i) paste0(event.id.column[ episode.starting.index[i]:(episode.starting.index[i+1]-1) ], collapse=","), character(1)), paste0(event.id.column[ episode.starting.index[length(episode.starting.index)]:s[s.len] ], collapse=","))); # the events contained in each episode if( maximum.permissible.gap.append.to.episode ) { # Should we add the maximum permissible gap? episode.gap.smaller.than.max <- c(gap.days.column[s] <= MAX.PERMISSIBLE.GAP[s]); # gap days less than the maximum permissible gap gap.correction <- MAX.PERMISSIBLE.GAP[s]; } } n.episodes <- nrow(treatment.episodes); if( maximum.permissible.gap.append.to.episode ) { # Should we add the maximum permissible gap? treatment.episodes[, episode.duration := c(as.numeric(episode.start[2:n.episodes] - episode.start[1:(n.episodes-1)]) - # start date of next episode minus start date of current episode ifelse(episode.gap.smaller.than.max[1:(n.episodes-1)], 0, end.episode.gap.days[1:(n.episodes-1)] - gap.correction[1:(n.episodes-1)]), # minus the start date of the current episode, minus the gap after the current episode plus a proportion of the maximum permissible gap only if the gap is larger than the maximum permissible gap (i.e., not for changes of medication or dosage) as.numeric(data4ID$.FU.END.DATE[1] - episode.start[n.episodes]) - ifelse(episode.gap.smaller.than.max[n.episodes], # duration of the last event of the last episode 0, end.episode.gap.days[n.episodes] - gap.correction[n.episodes]))]; # the last episode duration is the end date of the follow-up window minus the start date of the last episode minus the gap after the last episode plus a proportion of the maximum permissible gap only if the gap is longer than the maximum permissible gap } else { # Don't add the maximum permissible gap to the episode: treatment.episodes[, episode.duration := c(as.numeric(episode.start[2:n.episodes] - episode.start[1:(n.episodes-1)]) - end.episode.gap.days[1:(n.episodes-1)], # the episode duration is the start date of the next episode minus the start date of the current episode minus the gap after the current episode as.numeric(data4ID$.FU.END.DATE[1] - episode.start[n.episodes]) - ifelse(end.episode.gap.days[n.episodes] < MAX.PERMISSIBLE.GAP[last.event], # duration of the last event of the last episode 0, end.episode.gap.days[n.episodes]))]; # the last episode duration is the episode duration is the end date of the follow-up window minus the start date of the last episode minus the gap after the last episode only if the gap is longer than the maximum permissible gap } treatment.episodes[, episode.end := (episode.start + episode.duration)]; } return (treatment.episodes); } # Add the unique event ID (in fact, its row number in the original data data$.EVENT.UNIQUE.ID <- 1:nrow(data); # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (NULL); episodes <- event.info[!is.na(get(event.interval.colname)) & !is.na(get(gap.days.colname)), # only for those events that have non-NA interval and gap estimates .process.patient(.SD), by=ID.colname]; setnames(episodes, 1, ID.colname); return (episodes); } # Convert to data.table, cache event date as Date objects, and key by patient ID and event date data.copy <- data.table(data); data.copy[, .DATE.as.Date := as.Date(get(event.date.colname),format=date.format)]; # .DATE.as.Date: convert event.date.colname from formatted string to Date setkeyv(data.copy, c(ID.colname, ".DATE.as.Date")); # key (and sorting) by patient ID and event date # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=FALSE, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=0, observation.window.start.unit="days", observation.window.duration=followup.window.duration, observation.window.duration.unit=followup.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) ) return (NULL); tmp[,end.episode.gap.days := as.integer(end.episode.gap.days)]; # force end.episode.gap.days to be integer to make for pretty printing... mapping.events.episodes <- tmp[,c(ID.colname, "episode.ID", "events.in.episode"), with=FALSE]; tmp[,events.in.episode := NULL]; if( !return.data.table ) tmp <- as.data.frame(tmp); if( return.mapping.events.episodes ) { mapping.events.episodes <- mapping.events.episodes[, (function(df){if(is.null(df) || nrow(df) == 0){return (NULL)} else {strsplit(df$events.in.episode,",",fixed=TRUE)[[1]]}})(.SD), by=c(ID.colname, "episode.ID")]; names(mapping.events.episodes)[ncol(mapping.events.episodes)] <- "event.index.in.data"; attr(tmp, "mapping.episodes.to.events") <- mapping.events.episodes; } return (tmp); } # Shared code between multiple CMAs .cma.skeleton <- function(data=NULL, ret.val=NULL, cma.class.name=NA, ID.colname=NA, event.date.colname=NA, event.duration.colname=NA, event.daily.dose.colname=NA, medication.class.colname=NA, medication.groups.colname=NA, flatten.medication.groups=NA, followup.window.start.per.medication.group=NA, event.interval.colname=NA, gap.days.colname=NA, carryover.within.obs.window=NA, carryover.into.obs.window=NA, carry.only.for.same.medication=NA, consider.dosage.change=NA, followup.window.start=NA, followup.window.start.unit=NA, followup.window.duration=NA, followup.window.duration.unit=NA, observation.window.start=NA, observation.window.start.unit=NA, observation.window.duration=NA, observation.window.duration.unit=NA, date.format=NA, suppress.warnings=FALSE, suppress.special.argument.checks=FALSE, force.NA.CMA.for.failed.patients=TRUE, parallel.backend="none", parallel.threads=1, .workhorse.function=NULL) { # Convert to data.table, cache event date as Date objects keeping only the necessary columns, check for column name conflicts, and key by patient ID and event date: # columns to keep: columns.to.keep <- c(); if( !is.null(ID.colname) && !is.na(ID.colname) && length(ID.colname) == 1 && ID.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, ID.colname); if( !is.null(event.date.colname) && !is.na(event.date.colname) && length(event.date.colname) == 1 && event.date.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, event.date.colname); if( !is.null(event.duration.colname) && !is.na(event.duration.colname) && length(event.duration.colname) == 1 && event.duration.colname %in% names(data)) columns.to.keep <- c(columns.to.keep, event.duration.colname); if( !is.null(event.daily.dose.colname) && !is.na(event.daily.dose.colname) && length(event.daily.dose.colname) == 1 && event.daily.dose.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, event.daily.dose.colname); if( !is.null(medication.class.colname) && !is.na(medication.class.colname) && length(medication.class.colname) == 1 && medication.class.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, medication.class.colname); if( !is.null(mg <- getMGs(ret.val)) && !is.null(medication.groups.colname) && !is.na(medication.groups.colname) && length(medication.groups.colname) == 1 && medication.groups.colname %in% names(data)) columns.to.keep <- c(columns.to.keep, medication.groups.colname); if( !is.null(followup.window.start) && !is.na(followup.window.start) && length(followup.window.start) == 1 && (is.character(followup.window.start) || (is.factor(followup.window.start) && is.character(followup.window.start <- as.character(followup.window.start)))) && followup.window.start %in% names(data) ) columns.to.keep <- c(columns.to.keep, followup.window.start); if( !is.null(followup.window.duration) && !is.na(followup.window.duration) && length(followup.window.duration) == 1 && (is.character(followup.window.duration) || (is.factor(followup.window.duration) && is.character(followup.window.duration <- as.character(followup.window.duration)))) && followup.window.duration %in% names(data) ) columns.to.keep <- c(columns.to.keep, followup.window.duration); if( !is.null(observation.window.start) && !is.na(observation.window.start) && length(observation.window.start) == 1 && (is.character(observation.window.start) || (is.factor(observation.window.start) && is.character(observation.window.start <- as.character(observation.window.start)))) && observation.window.start %in% names(data) ) columns.to.keep <- c(columns.to.keep, observation.window.start); if( !is.null(observation.window.duration) && !is.na(observation.window.duration) && length(observation.window.duration) == 1 && (is.character(observation.window.duration) || (is.factor(observation.window.duration) && is.character(observation.window.duration <- as.character(observation.window.duration)))) && observation.window.duration %in% names(data) ) columns.to.keep <- c(columns.to.keep, observation.window.duration); # special column names that should not be used: if( !suppress.special.argument.checks ) { ..special.colnames <- c(.special.colnames, event.interval.colname, gap.days.colname); # don't forget event.interval.colname and gap.days.colname! if( any(s <- ..special.colnames %in% columns.to.keep) ) { .report.ewms(paste0("Column name(s) ",paste0("'",..special.colnames[s],"'",collapse=", "),"' are reserved: please don't use them in your input data!\n"), "error", cma.class.name, "AdhereR"); return (NULL); } } # copy only the relevant bits of the data: data.copy <- data.table(data)[, columns.to.keep, with=FALSE]; data.copy[, .DATE.as.Date := as.Date(get(event.date.colname),format=date.format)]; # .DATE.as.Date: convert event.date.colname from formatted string to Date data.copy$..ORIGINAL.ROW.ORDER.. <- 1:nrow(data.copy); # preserve the original order of the rows (needed for medication groups) setkeyv(data.copy, c(ID.colname, ".DATE.as.Date")); # key (and sorting) by patient ID and event date # Are there medication groups? if( is.null(mg) ) { # Nope: do a single estimation on the whole dataset: # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || !inherits(tmp$CMA,"data.frame") || is.null(tmp$event.info) ) return (NULL); # Convert to data.frame and return: if( force.NA.CMA.for.failed.patients ) { # Make sure patients with failed CMA estimations get an NA estimate! patids <- unique(data.copy[,get(ID.colname)]); if( length(patids) > nrow(tmp$CMA) ) { setnames(tmp$CMA, 1, ".ID"); tmp$CMA <- merge(data.table(".ID"=patids, key=".ID"), tmp$CMA, all.x=TRUE); } } setnames(tmp$CMA, c(ID.colname,"CMA")); ret.val[["CMA"]] <- as.data.frame(tmp$CMA); ret.val[["event.info"]] <- as.data.frame(tmp$event.info); class(ret.val) <- c(cma.class.name, class(ret.val)); return (ret.val); } else { # Yes # Make sure the group's observations reflect the potentially new order of the observations in the data: mb.obs <- mg$obs[data.copy$..ORIGINAL.ROW.ORDER.., ]; # Focus only on the non-trivial ones: mg.to.eval <- (colSums(!is.na(mb.obs) & mb.obs) > 0); if( sum(mg.to.eval) == 0 ) { # None selects not even one observation! .report.ewms(paste0("None of the medication classes (included __ALL_OTHERS__) selects any observation!\n"), "warning", cma.class.name, "AdhereR"); return (NULL); } mb.obs <- mb.obs[,mg.to.eval]; # keep only the non-trivial ones # How is the FUW to be estimated? if( !followup.window.start.per.medication.group ) { # The FUW and OW are estimated once per patient (i.e., all medication groups share the same FUW and OW): # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data.copy), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=FALSE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); # Add the FUW and OW start dates to the data: data.copy <- merge(data.copy, unique(event.info[,c(ID.colname, ".FU.START.DATE", ".OBS.START.DATE")]), by=ID.colname, all.x=TRUE, all.y=FALSE); names(data.copy)[ names(data.copy) == ".FU.START.DATE" ] <- ".FU.START.DATE.PER.PATIENT.ACROSS.MGS"; names(data.copy)[ names(data.copy) == ".OBS.START.DATE" ] <- ".OBS.START.DATE.PER.PATIENT.ACROSS.MGS"; # Adjust the corresponding params: actual.followup.window.start <- ".FU.START.DATE.PER.PATIENT.ACROSS.MGS"; actual.followup.window.start.unit <- NA; actual.observation.window.start <- ".OBS.START.DATE.PER.PATIENT.ACROSS.MGS"; actual.observation.window.start.unit <- NA; } else { # The FUW and OW are estimated separately for each medication group -- nothing to do... actual.followup.window.start <- followup.window.start; actual.followup.window.start.unit <- followup.window.start.unit; actual.observation.window.start <- observation.window.start; actual.observation.window.start.unit <- observation.window.start.unit; } # Check if there are medication classes that refer to the same observations (they would result in the same estimates): mb.obs.dupl <- duplicated(mb.obs, MARGIN=2); # Estimate each separately: tmp <- lapply(1:nrow(mg$defs), function(i) { # Check if these are to be evaluated: if( !mg.to.eval[i] ) { return (list("CMA"=NULL, "event.info"=NULL)); } # Translate into the index of the classes to be evaluated: ii <- sum(mg.to.eval[1:i]); # Cache the selected observations: mg.sel.obs <- mb.obs[,ii]; # Check if this is a duplicated medication class: if( mb.obs.dupl[ii] ) { # Find which one is the original: for( j in 1:(ii-1) ) # ii=1 never should be TRUE { if( identical(mb.obs[,j], mg.sel.obs) ) { # This is the original: return it and stop return (c("identical.to"=j)); } } } # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy[mg.sel.obs,], # apply it on the subset of observations covered by this medication class ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=actual.followup.window.start, followup.window.start.unit=actual.followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=actual.observation.window.start, observation.window.start.unit=actual.observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || (!is.null(tmp$CMA) && !inherits(tmp$CMA,"data.frame")) || is.null(tmp$event.info) ) return (NULL); if( !is.null(tmp$CMA) ) { # Convert to data.frame and return: if( force.NA.CMA.for.failed.patients ) { # Make sure patients with failed CMA estimations get an NA estimate! patids <- unique(data.copy[,get(ID.colname)]); if( length(patids) > nrow(tmp$CMA) ) { setnames(tmp$CMA, 1, ".ID"); tmp$CMA <- merge(data.table(".ID"=patids, key=".ID"), tmp$CMA, all.x=TRUE); } } setnames(tmp$CMA, c(ID.colname,"CMA")); tmp$CMA <- as.data.frame(tmp$CMA); } if( !is.null(tmp$event.info) ) { tmp$event.info <- as.data.frame(tmp$event.info); } return (tmp); }); # Set the names: names(tmp) <- mg$defs$name; # Solve the duplicates: for( i in seq_along(tmp) ) { if( is.numeric(tmp[[i]]) && length(tmp[[i]]) == 1 && names(tmp[[i]]) == "identical.to" ) tmp[[i]] <- tmp[[ tmp[[i]] ]]; } # Rearrange these and return: ret.val[["CMA"]] <- lapply(tmp, function(x) x$CMA); ret.val[["event.info"]] <- lapply(tmp, function(x) x$event.info); if( flatten.medication.groups && !is.na(medication.groups.colname) ) { # Flatten the CMA: tmp <- do.call(rbind, ret.val[["CMA"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["CMA"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["CMA"]]), function(i) if(!is.null(ret.val[["CMA"]][[i]])){rep(names(ret.val[["CMA"]])[i], nrow(ret.val[["CMA"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["CMA"]] <- tmp; } # ... and the event.info: tmp <- do.call(rbind, ret.val[["event.info"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["event.info"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["event.info"]]), function(i) if(!is.null(ret.val[["event.info"]][[i]])){rep(names(ret.val[["event.info"]])[i], nrow(ret.val[["event.info"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["event.info"]] <- tmp; } } class(ret.val) <- c(cma.class.name, class(ret.val)); return (ret.val); } } ############################################################################################ # # Plot CMAs greater or equal to 1 (smart enough to know what to do with specific info) # ############################################################################################ .plot.CMA1plus <- function(cma, # the CMA1 (or derived) object patients.to.plot=NULL, # list of patient IDs to plot or NULL for all duration=NA, # duration to plot in days (if missing, determined from the data) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? and, if so, place the first event as the horizintal 0? show.period=c("dates","days")[2], # draw vertical bars at regular interval as dates or days? period.in.days=90, # the interval (in days) at which to draw veritcal lines show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend params and position cex=1.0, cex.axis=0.75, cex.lab=1.0, # various graphical params show.cma=TRUE, # show the CMA type xlab=c("dates"="Date", "days"="Days"), # Vector of x labels to show for the two types of periods, or a single value for both, or NULL for nothing ylab=c("withoutCMA"="patient", "withCMA"="patient (& CMA)"), # Vector of y labels to show without and with CMA estimates, or a single value for both, or NULL ofr nonthing title=c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns"), # Vector of titles to show for and without alignment, or a single value for both, or NULL for nothing col.cats=rainbow, # single color or a function mapping the categories to colors unspecified.category.label="drug", # the label of the unspecified category of medication medication.groups.to.plot=NULL, # the names of the medication groups to plot (by default, all) medication.groups.separator.show=TRUE, medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", # group medication events by patient? medication.groups.allother.label="*", # the label to use for the __ALL_OTHERS__ medication class (defaults to *) lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, # event style show.event.intervals=TRUE, # show the actual prescription intervals plot.events.vertically.displaced=TRUE, # display the events on different lines (vertical displacement) or not (defaults to TRUE)? col.na="lightgray", # color for missing data print.CMA=TRUE, CMA.cex=0.50, # print CMA next to the participant's ID? plot.CMA=TRUE, # plot the CMA next to the participant ID? CMA.plot.ratio=0.10, # the proportion of the total horizontal plot to be taken by the CMA plot CMA.plot.col="lightgreen", CMA.plot.border="darkgreen", CMA.plot.bkg="aquamarine", CMA.plot.text=CMA.plot.border, # attributes of the CMA plot highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, # for some CMAs, the real observation window starts at a different date print.dose=FALSE, cex.dose=0.75, print.dose.outline.col="white", print.dose.centered=FALSE, # print daily dose plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # draw daily dose as line width alternating.bands.cols=c("white", "gray95"), # the colors of the alternating vertical bands across patients (NULL=don't draw any; can be >= 1 color) bw.plot=FALSE, # if TRUE, override all user-given colors and replace them with a scheme suitable for grayscale plotting rotate.text=-60, # some text (e.g., axis labels) may be rotated by this much degrees force.draw.text=FALSE, # if true, always draw text even if too big or too small min.plot.size.in.characters.horiz=0, min.plot.size.in.characters.vert=0, # the minimum plot size (in characters: horizontally, for the whole duration, vertically, per event) suppress.warnings=FALSE, # suppress warnings? max.patients.to.plot=100, # maximum number of patients to plot export.formats=NULL, # the formats to export the figure to (by default, none); can be any subset of "svg" (just SVG file), "html" (SVG + HTML + CSS + JavaScript all embedded within the HTML document), "jpg", "png", "webp", "ps" and "pdf" export.formats.fileprefix="AdhereR-plot", # the file name prefix for the exported formats export.formats.height=NA, export.formats.width=NA, # desired dimensions (in pixels) for the exported figure (defaults to sane values) export.formats.save.svg.placeholder=TRUE, export.formats.svg.placeholder.type=c("jpg", "png", "webp")[2], export.formats.svg.placeholder.embed=FALSE, # save a placeholder for the SVG image? export.formats.html.template=NULL, export.formats.html.javascript=NULL, export.formats.html.css=NULL, # HTML, JavaScript and CSS templates for exporting HTML+SVG export.formats.directory=NA, # if exporting, which directory to export to (if not give, creates files in the temporary directory) generate.R.plot=TRUE, # generate standard (base R) plot for plotting within R? do.not.draw.plot=FALSE, # if TRUE, don't draw the actual plot, but only the legend (if required) ... ) { .plot.CMAs(cma, patients.to.plot=patients.to.plot, duration=duration, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, show.period=show.period, period.in.days=period.in.days, show.legend=show.legend, legend.x=legend.x, legend.y=legend.y, legend.bkg.opacity=legend.bkg.opacity, legend.cex=legend.cex, legend.cex.title=legend.cex.title, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, show.cma=show.cma, xlab=xlab, ylab=ylab, title=title, col.cats=col.cats, unspecified.category.label=unspecified.category.label, medication.groups.to.plot=medication.groups.to.plot, medication.groups.separator.show=medication.groups.separator.show, medication.groups.separator.lty=medication.groups.separator.lty, medication.groups.separator.lwd=medication.groups.separator.lwd, medication.groups.separator.color=medication.groups.separator.color, medication.groups.allother.label=medication.groups.allother.label, lty.event=lty.event, lwd.event=lwd.event, show.event.intervals=show.event.intervals, plot.events.vertically.displaced=plot.events.vertically.displaced, pch.start.event=pch.start.event, pch.end.event=pch.end.event, print.dose=print.dose, cex.dose=cex.dose, print.dose.outline.col=print.dose.outline.col, print.dose.centered=print.dose.centered, plot.dose=plot.dose, lwd.event.max.dose=lwd.event.max.dose, plot.dose.lwd.across.medication.classes=plot.dose.lwd.across.medication.classes, col.na=col.na, print.CMA=print.CMA, CMA.cex=CMA.cex, plot.CMA=plot.CMA, CMA.plot.ratio=CMA.plot.ratio, CMA.plot.col=CMA.plot.col, CMA.plot.border=CMA.plot.border, CMA.plot.bkg=CMA.plot.bkg, CMA.plot.text=CMA.plot.text, plot.partial.CMAs.as=FALSE, # CMA1+ do not have partial CMAs highlight.followup.window=highlight.followup.window, followup.window.col=followup.window.col, highlight.observation.window=highlight.observation.window, observation.window.col=observation.window.col, observation.window.density=observation.window.density, observation.window.angle=observation.window.angle, observation.window.opacity=observation.window.opacity, show.real.obs.window.start=show.real.obs.window.start, real.obs.window.density=real.obs.window.density, real.obs.window.angle=real.obs.window.angle, alternating.bands.cols=alternating.bands.cols, bw.plot=bw.plot, rotate.text=rotate.text, force.draw.text=force.draw.text, min.plot.size.in.characters.horiz=min.plot.size.in.characters.horiz, min.plot.size.in.characters.vert=min.plot.size.in.characters.vert, max.patients.to.plot=max.patients.to.plot, export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.height=export.formats.height, export.formats.width=export.formats.width, export.formats.save.svg.placeholder=export.formats.save.svg.placeholder, export.formats.svg.placeholder.type=export.formats.svg.placeholder.type, export.formats.svg.placeholder.embed=export.formats.svg.placeholder.embed, export.formats.html.template=export.formats.html.template, export.formats.html.javascript=export.formats.html.javascript, export.formats.html.css=export.formats.html.css, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot, do.not.draw.plot=do.not.draw.plot, suppress.warnings=suppress.warnings); } #' CMA1 and CMA3 constructors. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 1 or type 3 object. #' #' \code{CMA1} considers the total number of days with medication supplied in #' all medication events in the observation window, excluding the last event. #' \code{CMA3} is identical to \code{CMA1} except that it is capped at 100\%. #' #' The formula is #' \deqn{(number of days supply excluding last) / (first to last event)} #' Thus, the durations of all events are added up, possibly resulting in an CMA #' estimate (much) bigger than 1.0 (100\%). #' #' \code{\link{CMA2}} and \code{CMA1} differ in the inclusion or not of the last #' event. #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA1} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} #' parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined and #' \code{flatten.medication.groups} is \code{FALSE}, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name), #' but if \code{flatten.medication.groups} is \code{FALSE} then they are #' \code{data.frame}s with an extra column giving the medication group (the #' column's name is given by \code{medication.groups.colname}). #' @seealso CMAs 1 to 8 are described in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' cma3 <- CMA3(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA1 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CMA estimates? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=FALSE, "carryover.into.obs.window"=FALSE, "carry.only.for.same.medication"=FALSE, "consider.dosage.change"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the observation window excluding the last event; durations of all events added up and divided by number of days from first to last event, possibly resulting in a value >1.0"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA1", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some serious error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { # Force the selection, evaluation of promises and caching of the needed columns: # ... which columns to select (with their indices): columns.to.cache <- c(".EVENT.STARTS.BEFORE.OBS.WINDOW", ".EVENT.STARTS.AFTER.OBS.WINDOW", ".DATE.as.Date", event.duration.colname); # ... select these columns: data4ID.selected.columns <- data4ID[, columns.to.cache, with=FALSE]; # alternative to: data4ID[,..columns.to.cache]; # ... cache the columns based on their indices: .EVENT.STARTS.BEFORE.OBS.WINDOW <- data4ID.selected.columns[[1]]; .EVENT.STARTS.AFTER.OBS.WINDOW <- data4ID.selected.columns[[2]]; .DATE.as.Date <- data4ID.selected.columns[[3]]; event.duration.column <- data4ID.selected.columns[[4]]; # which data to consider: s <- which(!(.EVENT.STARTS.BEFORE.OBS.WINDOW | .EVENT.STARTS.AFTER.OBS.WINDOW)); s.len <- length(s); s1 <- s[1]; ss.len <- s[s.len]; if( s.len < 2 || (.date.diff <- .difftime.Dates.as.days(.DATE.as.Date[ss.len], .DATE.as.Date[s1])) == 0 ) { # For less than two events or when the first and the last events are on the same day, CMA1 does not make sense return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Otherwise, the sum of durations of the events excluding the last divided by the number of days between the first and the last event return (list("CMA"=as.numeric(sum(event.duration.column[s[-s.len]],na.rm=TRUE) / .date.diff), "included.events.original.row.order"=data4ID$..ORIGINAL.ROW.ORDER..[s[-s.len]])); } } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name="CMA1", ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=NA, # not relevant medication.class.colname=NA, # not relevant event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=FALSE, # if TRUE consider the carry-over within the observation window carryover.into.obs.window=FALSE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA1 <- function(...) print.CMA0(...) #' Plot CMA0-derived objects. #' #' Plots the event data and estimated CMA encapsulated in objects derived from #' \code{CMA0}. #' #' Please note that this function plots objects inheriting from \code{CMA0} but #' not objects of type \code{CMA0} itself (these are plotted by #' \code{\link{plot.CMA0}}). #' #' The x-axis represents time (either in days since the earliest date or as #' actual dates), with consecutive events represented as ascending on the y-axis. #' #' Each event is represented as a segment with style \code{lty.event} and line #' width \code{lwd.event} starting with a \code{pch.start.event} and ending with #' a \code{pch.end.event} character, coloured with a unique color as given by #' \code{col.cats}, extending from its start date until its end date. #' Superimposed on these are shown the event intervals and gap days as estimated #' by the particular CMA method, more precisely plotting the start and end of #' the available events as solid filled-in rectangles, and the event gaps as #' shaded rectangles. #' #' The follow-up and the observation windows are plotted as an empty rectangle #' and as shaded rectangle, respectively (for some CMAs the observation window #' might be adjusted in which case the adjustment may also be plotted using a #' different shading). #' #' The CMA estimates can be visually represented as well in the left side of the #' figure using bars (sometimes the estimates can go above 100\%, in which case #' the maximum possible bar filling is adjusted to reflect this). #' #' When several patients are displayed on the same plot, they are organized #' vertically, and alternating bands (white and gray) help distinguish #' consecutive patients. #' Implicitely, all patients contained in the \code{cma} object will be plotted, #' but the \code{patients.to.plot} parameter allows the selection of a subset of #' patients. #' #' Finally, the y-axis shows the patient ID and possibly the CMA estimate as #' well. #' #' @param x A \emph{\code{CMA0}} or derived object, representing the CMA to #' plot #' @param patients.to.plot A vector of \emph{strings} containing the list of #' patient IDs to plot (a subset of those in the \code{cma} object), or #' \code{NULL} for all #' @param duration A \emph{number}, the total duration (in days) of the whole #' period to plot; in \code{NA} it is automatically determined from the event #' data such that the whole dataset fits. #' @param align.all.patients \emph{Logical}, should all patients be aligned #' (i.e., the actual dates are discarded and all plots are relative to the #' earliest date)? #' @param align.first.event.at.zero \emph{Logical}, should the first event be #' placed at the origin of the time axis (at 0)? #' @param show.period A \emph{string}, if "dates" show the actual dates at the #' regular grid intervals, while for "days" (the default) shows the days since #' the beginning; if \code{align.all.patients == TRUE}, \code{show.period} is #' taken as "days". #' @param period.in.days The \emph{number} of days at which the regular grid is #' drawn (or 0 for no grid). #' @param show.legend \emph{Logical}, should the legend be drawn? #' @param legend.x The position of the legend on the x axis; can be "left", #' "right" (default), or a \emph{numeric} value. #' @param legend.y The position of the legend on the y axis; can be "bottom" #' (default), "top", or a \emph{numeric} value. #' @param legend.bkg.opacity A \emph{number} between 0.0 and 1.0 specifying the #' opacity of the legend background. #' @param cex,cex.axis,cex.lab,legend.cex,legend.cex.title,CMA.cex \emph{numeric} #' values specifying the \code{cex} of the various types of text. #' @param show.cma \emph{Logical}, should the CMA type be shown in the title? #' @param col.cats A \emph{color} or a \emph{function} that specifies the single #' colour or the colour palette used to plot the different medication; by #' default \code{rainbow}, but we recommend, whenever possible, a #' colorblind-friendly palette such as \code{viridis} or \code{colorblind_pal}. #' @param unspecified.category.label A \emph{string} giving the name of the #' unspecified (generic) medication category. #' @param medication.groups.to.plot the names of the medication groups to plot or #' \code{NULL} (the default) for all. #' @param medication.groups.separator.show a \emph{boolean}, if \code{TRUE} (the #' default) visually mark the medication groups the belong to the same patient, #' using horizontal lines and alternating vertical lines. #' @param medication.groups.separator.lty,medication.groups.separator.lwd,medication.groups.separator.color #' graphical parameters (line type, line width and colour describing the visual #' marking og medication groups as beloning to the same patient. #' @param medication.groups.allother.label a \emph{string} giving the label to #' use for the implicit \code{__ALL_OTHERS__} medication group (defaults to "*"). #' @param lty.event,lwd.event,pch.start.event,pch.end.event The style of the #' event (line style, width, and start and end symbols). #' @param show.event.intervals \emph{Logical}, should the actual event intervals #' be shown? #' @param col.na The colour used for missing event data. #' @param bw.plot \emph{Logical}, should the plot use grayscale only (i.e., the #' \code{\link[grDevices]{gray.colors}} function)? #' @param rotate.text \emph{Numeric}, the angle by which certain text elements #' (e.g., axis labels) should be rotated. #' @param force.draw.text \emph{Logical}, if \code{TRUE}, always draw text even #' if too big or too small #' @param print.CMA \emph{Logical}, should the CMA values be printed? #' @param plot.CMA \emph{Logical}, should the CMA values be represented #' graphically? #' @param CMA.plot.ratio A \emph{number}, the proportion of the total horizontal #' plot space to be allocated to the CMA plot. #' @param CMA.plot.col,CMA.plot.border,CMA.plot.bkg,CMA.plot.text \emph{Strings} #' giving the colours of the various components of the CMA plot. #' @param highlight.followup.window \emph{Logical}, should the follow-up window #' be plotted? #' @param followup.window.col The follow-up window's colour. #' @param highlight.observation.window \emph{Logical}, should the observation #' window be plotted? #' @param observation.window.col,observation.window.density,observation.window.angle,observation.window.opacity #' Attributes of the observation window (colour, shading density, angle and #' opacity). #' @param show.real.obs.window.start,real.obs.window.density,real.obs.window.angle For some CMAs, the observation window might #' be adjusted, in which case should it be plotted and with that attributes? #' @param print.dose \emph{Logical}, should the daily dose be printed as text? #' @param cex.dose \emph{Numeric}, if daily dose is printed, what text size #' to use? #' @param print.dose.outline.col If \emph{\code{NA}}, don't print dose text with #' outline, otherwise a color name/code for the outline. #' @param print.dose.centered \emph{Logical}, print the daily dose centered on #' the segment or slightly below it? #' @param plot.dose \emph{Logical}, should the daily dose be indicated through #' segment width? #' @param lwd.event.max.dose \emph{Numeric}, the segment width corresponding to #' the maximum daily dose (must be >= lwd.event but not too big either). #' @param plot.dose.lwd.across.medication.classes \emph{Logical}, if \code{TRUE}, #' the line width of the even is scaled relative to all medication classes (i.e., #' relative to the global minimum and maximum doses), otherwise it is scale #' relative only to its medication class. #' @param alternating.bands.cols The colors of the alternating vertical bands #' distinguishing the patients; can be \code{NULL} = don't draw the bandes; #' or a vector of colors. #' @param min.plot.size.in.characters.horiz,min.plot.size.in.characters.vert #' \emph{Numeric}, the minimum size of the plotting surface in characters; #' horizontally (min.plot.size.in.characters.horiz) refers to the the whole #' duration of the events to plot; vertically (min.plot.size.in.characters.vert) #' refers to a single event. If the plotting is too small, possible solutions #' might be: if within \code{RStudio}, try to enlarge the "Plots" panel, or #' (also valid outside \code{RStudio} but not if using \code{RStudio server} #' start a new plotting device (e.g., using \code{X11()}, \code{quartz()} #' or \code{windows()}, depending on OS) or (works always) save to an image #' (e.g., \code{jpeg(...); ...; dev.off()}) and display it in a viewer. #' @param max.patients.to.plot \emph{Numeric}, the maximum patients to attempt #' to plot. #' @param export.formats a \emph{string} giving the formats to export the figure #' to (by default \code{NULL}, meaning no exporting); can be any combination of #' "svg" (just an \code{SVG} file), "html" (\code{SVG} + \code{HTML} + \code{CSS} #' + \code{JavaScript}, all embedded within one \code{HTML} document), "jpg", #' "png", "webp", "ps" or "pdf". #' @param export.formats.fileprefix a \emph{string} giving the file name prefix #' for the exported formats (defaults to "AdhereR-plot"). #' @param export.formats.height,export.formats.width \emph{numbers} giving the #' desired dimensions (in pixels) for the exported figure (defaults to sane #' values if \code{NA}). #' @param export.formats.save.svg.placeholder a \emph{logical}, if TRUE, save an #' image placeholder of type given by \code{export.formats.svg.placeholder.type} #'for the \code{SVG} image. #' @param export.formats.svg.placeholder.type a \emph{string}, giving the type of #' placeholder for the \code{SVG} image to save; can be "jpg", #' "png" (the default) or "webp". #' @param export.formats.svg.placeholder.embed a \emph{logical}, if \code{TRUE}, #' embed the placeholder image in the HTML document (if any) using \code{base64} #' encoding, otherwise (the default) leave it as an external image file (works #' only when an \code{HTML} document is exported and only for \code{JPEG} or #' \code{PNG} images. #' @param export.formats.html.template,export.formats.html.javascript,export.formats.html.css #' \emph{character strings} or \code{NULL} (the default) giving the path to the #' \code{HTML}, \code{JavaScript} and \code{CSS} templates, respectively, to be #' used when generating the HTML+CSS semi-interactive plots; when \code{NULL}, #' the default ones included with the package will be used. If you decide to define #' new templates please use the default ones for inspiration and note that future #' version are not guaranteed to be backwards compatible! #' @param export.formats.directory a \emph{string}; if exporting, which directory #' to export to; if \code{NA} (the default), creates the files in a temporary #' directory. #' @param generate.R.plot a \emph{logical}, if \code{TRUE} (the default), #' generate the standard (base \code{R}) plot for plotting within \code{R}. #' @param do.not.draw.plot a \emph{logical}, if \code{TRUE} (\emph{not} the default), #' does not draw the plot itself, but only the legend (if \code{show.legend} is #' \code{TRUE}) at coordinates (0,0) irrespective of the given legend coordinates. #' This is intended to allow (together with the \code{get.legend.plotting.area()} #' function) the separate plotting of the legend. #' @param ... other possible parameters #' @examples #' cma1 <- CMA1(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' plot(cma1, patients.to.plot=c("1","2")); #' @export plot.CMA1 <- function(x, # the CMA1 (or derived) object ..., # required for S3 consistency patients.to.plot=NULL, # list of patient IDs to plot or NULL for all duration=NA, # duration to plot in days (if missing, determined from the data) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? and, if so, place the first event as the horizintal 0? show.period=c("dates","days")[2], # draw vertical bars at regular interval as dates or days? period.in.days=90, # the interval (in days) at which to draw veritcal lines show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend params and position cex=1.0, cex.axis=0.75, cex.lab=1.0, # various graphical params show.cma=TRUE, # show the CMA type col.cats=rainbow, # single color or a function mapping the categories to colors unspecified.category.label="drug", # the label of the unspecified category of medication medication.groups.to.plot=NULL, # the names of the medication groups to plot (by default, all) medication.groups.separator.show=TRUE, medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", # group medication events by patient? medication.groups.allother.label="*", # the label to use for the __ALL_OTHERS__ medication class (defaults to *) lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, # event style show.event.intervals=TRUE, # show the actual rpescription intervals col.na="lightgray", # color for mising data #col.continuation="black", lty.continuation="dotted", lwd.continuation=1, # style of the contuniation lines connecting consecutive events print.CMA=TRUE, CMA.cex=0.50, # print CMA next to the participant's ID? plot.CMA=TRUE, # plot the CMA next to the participant ID? CMA.plot.ratio=0.10, # the proportion of the total horizontal plot to be taken by the CMA plot CMA.plot.col="lightgreen", CMA.plot.border="darkgreen", CMA.plot.bkg="aquamarine", CMA.plot.text=CMA.plot.border, # attributes of the CMA plot highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, # for some CMAs, the real observation window starts at a different date print.dose=FALSE, cex.dose=0.75, print.dose.outline.col="white", print.dose.centered=FALSE, # print daily dose plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # draw daily dose as line width alternating.bands.cols=c("white", "gray95"), # the colors of the alternating vertical bands across patients (NULL=don't draw any; can be >= 1 color) bw.plot=FALSE, # if TRUE, override all user-given colors and replace them with a scheme suitable for grayscale plotting rotate.text=-60, # some text (e.g., axis labels) may be rotated by this much degrees force.draw.text=FALSE, # if true, always draw text even if too big or too small min.plot.size.in.characters.horiz=0, min.plot.size.in.characters.vert=0, # the minimum plot size (in characters: horizontally, for the whole duration, vertically, per event) max.patients.to.plot=100, # maximum number of patients to plot export.formats=NULL, # the formats to export the figure to (by default, none); can be any subset of "svg" (just SVG file), "html" (SVG + HTML + CSS + JavaScript all embedded within the HTML document), "jpg", "png", "webp", "ps" and "pdf" export.formats.fileprefix="AdhereR-plot", # the file name prefix for the exported formats export.formats.height=NA, export.formats.width=NA, # desired dimensions (in pixels) for the exported figure (defaults to sane values) export.formats.save.svg.placeholder=TRUE, export.formats.svg.placeholder.type=c("jpg", "png", "webp")[2], export.formats.svg.placeholder.embed=FALSE, # save a placeholder for the SVG image? export.formats.directory=NA, # if exporting, which directory to export to (if not give, creates files in the temporary directory) export.formats.html.template=NULL, export.formats.html.javascript=NULL, export.formats.html.css=NULL, # HTML, JavaScript and CSS templates for exporting HTML+SVG generate.R.plot=TRUE, # generate standard (base R) plot for plotting within R? do.not.draw.plot=FALSE # if TRUE, don't draw the actual plot, but only the legend (if required) ) { .plot.CMA1plus(cma=x, patients.to.plot=patients.to.plot, duration=duration, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, show.period=show.period, period.in.days=period.in.days, show.legend=show.legend, legend.x=legend.x, legend.y=legend.y, legend.bkg.opacity=legend.bkg.opacity, legend.cex=legend.cex, legend.cex.title=legend.cex.title, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, show.cma=show.cma, col.cats=col.cats, unspecified.category.label=unspecified.category.label, medication.groups.to.plot=medication.groups.to.plot, medication.groups.separator.show=medication.groups.separator.show, medication.groups.separator.lty=medication.groups.separator.lty, medication.groups.separator.lwd=medication.groups.separator.lwd, medication.groups.separator.color=medication.groups.separator.color, medication.groups.allother.label=medication.groups.allother.label, lty.event=lty.event, lwd.event=lwd.event, pch.start.event=pch.start.event, pch.end.event=pch.end.event, show.event.intervals=show.event.intervals, col.na=col.na, print.CMA=print.CMA, CMA.cex=CMA.cex, plot.CMA=plot.CMA, CMA.plot.ratio=CMA.plot.ratio, CMA.plot.col=CMA.plot.col, CMA.plot.border=CMA.plot.border, CMA.plot.bkg=CMA.plot.bkg, CMA.plot.text=CMA.plot.text, highlight.followup.window=highlight.followup.window, followup.window.col=followup.window.col, highlight.observation.window=highlight.observation.window, observation.window.col=observation.window.col, observation.window.density=observation.window.density, observation.window.angle=observation.window.angle, observation.window.opacity=observation.window.opacity, show.real.obs.window.start=show.real.obs.window.start, real.obs.window.density=real.obs.window.density, real.obs.window.angle=real.obs.window.angle, print.dose=print.dose, cex.dose=cex.dose, print.dose.outline.col=print.dose.outline.col, print.dose.centered=print.dose.centered, plot.dose=plot.dose, lwd.event.max.dose=lwd.event.max.dose, plot.dose.lwd.across.medication.classes=plot.dose.lwd.across.medication.classes, alternating.bands.cols=alternating.bands.cols, bw.plot=bw.plot, rotate.text=rotate.text, force.draw.text=force.draw.text, min.plot.size.in.characters.horiz=min.plot.size.in.characters.horiz, min.plot.size.in.characters.vert=min.plot.size.in.characters.vert, max.patients.to.plot=max.patients.to.plot, export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.height=export.formats.height, export.formats.width=export.formats.width, export.formats.save.svg.placeholder=export.formats.save.svg.placeholder, export.formats.svg.placeholder.type=export.formats.svg.placeholder.type, export.formats.svg.placeholder.embed=export.formats.svg.placeholder.embed, export.formats.html.template=export.formats.html.template, export.formats.html.javascript=export.formats.html.javascript, export.formats.html.css=export.formats.html.css, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot, do.not.draw.plot=do.not.draw.plot, ...) } #' CMA2 and CMA4 constructors. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 2 or type 4 object. #' #' \code{CMA2} considers the total number of days with medication supplied in #' all medication events in the observation window, including the last event. #' \code{CMA4} is identical to \code{CMA2} except that it is capped at 100\%. #' #' The formula is #' \deqn{(number of days supply including last event) / (first to last event)} #' Thus, the durations of all events are added up, possibly resulting in an CMA #' estimate (much) bigger than 1.0 (100\%) #' #' \code{CMA2} and \code{\link{CMA1}} differ in the inclusion or not of the last #' event. #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA2} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso CMAs 1 to 8 are defined in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' \dontrun{ #' cma2 <- CMA2(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' cma4 <- CMA4(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' );} #' @export CMA2 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=FALSE, "carryover.into.obs.window"=FALSE, "carry.only.for.same.medication"=FALSE, "consider.dosage.change"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the observation window including the last event; durations of all events added up and divided by number of days from first event to end of observation window, possibly resulting in a value >1.0"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA2", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { sel.data4ID <- data4ID[ !.EVENT.STARTS.BEFORE.OBS.WINDOW & !.EVENT.STARTS.AFTER.OBS.WINDOW, ]; # select the events within the observation window only n.events <- nrow(sel.data4ID); # cache number of events if( n.events < 1 || sel.data4ID$.DATE.as.Date[1] > sel.data4ID$.OBS.END.DATE[1] ) { # For less than one event or when the first event is on the last day of the observation window, CMA2 does not make sense return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Otherwise, the sum of durations of the events divided by the number of days between the first event and the end of the observation window return (list("CMA"=as.numeric(sum(sel.data4ID[, get(event.duration.colname)],na.rm=TRUE) / (as.numeric(difftime(sel.data4ID$.OBS.END.DATE[1], sel.data4ID$.DATE.as.Date[1], units="days")))), "included.events.original.row.order"=sel.data4ID$..ORIGINAL.ROW.ORDER..)); } } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA2","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=NA, # not relevant medication.class.colname=NA, # not relevant event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=FALSE, # if TRUE consider the carry-over within the observation window carryover.into.obs.window=FALSE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA2 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA2 <- function(...) .plot.CMA1plus(...) #' @rdname CMA1 #' @export CMA3 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=FALSE, "carryover.into.obs.window"=FALSE, "carry.only.for.same.medication"=FALSE, "consider.dosage.change"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the observation window including the last event; durations of all events added up and divided by number of days from first to last event, then capped at 1.0"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA3", "AdhereR"); } } } # Create the CMA1 object: ret.val <- CMA1(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, arguments.that.should.not.be.defined=arguments.that.should.not.be.defined); if( is.null(ret.val) ) return (NULL); # some error upstream # Cap the CMA at 1.0: if( !is.null(ret.val$CMA) ) { if( inherits(ret.val$CMA, "data.frame") ) { ret.val$CMA$CMA <- pmin(1, ret.val$CMA$CMA); } else if( is.list(ret.val$CMA) && length(ret.val$CMA) > 0 ) { for( i in 1:length(ret.val$CMA) ) if( !is.null(ret.val$CMA[[i]]) ) ret.val$CMA[[i]]$CMA <- pmin(1, ret.val$CMA[[i]]$CMA); } } # Convert to data.frame and return: class(ret.val) <- c("CMA3", class(ret.val)); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA3 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA3 <- function(...) .plot.CMA1plus(...) #' @rdname CMA2 #' @export CMA4 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=FALSE, "carryover.into.obs.window"=FALSE, "carry.only.for.same.medication"=FALSE, "consider.dosage.change"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the observation window including the last event; durations of all events added up and divided by number of days from first event to end of observation window, then capped at 1.0"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA4", "AdhereR"); } } } # Create the CMA2 object: ret.val <- CMA2(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, arguments.that.should.not.be.defined=arguments.that.should.not.be.defined); if( is.null(ret.val) ) return (NULL); # some error upstream # Cap the CMA at 1.0: if( !is.null(ret.val$CMA) ) { if( inherits(ret.val$CMA, "data.frame") ) { ret.val$CMA$CMA <- pmin(1, ret.val$CMA$CMA); } else if( is.list(ret.val$CMA) && length(ret.val$CMA) > 0 ) { for( i in 1:length(ret.val$CMA) ) if( !is.null(ret.val$CMA[[i]]) ) ret.val$CMA[[i]]$CMA <- pmin(1, ret.val$CMA[[i]]$CMA); } } # Convert to data.frame and return: class(ret.val) <- c("CMA4", class(ret.val)); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA4 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA4 <- function(...) .plot.CMA1plus(...) #' CMA5 constructor. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 5 object. #' #' \code{CMA5} assumes that, within the observation window, the medication is #' used as prescribed and new medication is "banked" until needed (oversupply #' from previous events is used first, followed new medication supply). #' It computes days of theoretical use by extracting the total number of gap #' days from the total time interval between the first and the last event, #' accounting for carry over for all medication events within the observation #' window. #' Thus, it accounts for timing within the observation window, and excludes the #' remaining supply at the start of the last event within the observation window. #' #' The formula is #' \deqn{(number of days of theoretical use) / (first to last event)} #' #' Observations: #' \itemize{ #' \item the \code{carry.only.for.same.medication} parameter controls the #' transmission of carry-over across medication changes, producing a "standard" #' \code{CMA5} (default value is FALSE), and an "alternative" \code{CMA5b}, #' respectively; #' \item the \code{consider.dosage.change} parameter controls if dosage changes #' are taken into account, i.e. if set as TRUE and a new medication event has a #' different daily dosage recommendation, carry-over is recomputed assuming #' medication use according to the new prescribed dosage (default value is FALSE). #' } #' #' @param data A \emph{\code{data.frame}} containing the medication events used #' to compute the CMA. Must contain, at a minimum, the patient unique ID, the #' event date and duration, and might also contain the daily dosage and #' medication type (the actual column names are defined in the following four #' parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider not #' covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA5} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso CMAs 1 to 8 are defined in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' cma5 <- CMA5(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA5 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=TRUE, "carryover.into.obs.window"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available from first to last event; total number of gap days extracted from this time interval, then divided by the time interval, accounting for carry-over within observation window and excluding remaining supply"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA5", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { sel.data4ID <- data4ID[ !.EVENT.STARTS.BEFORE.OBS.WINDOW & !.EVENT.STARTS.AFTER.OBS.WINDOW, ]; # select the events within the observation window only n.events <- nrow(sel.data4ID); # cache number of events if( n.events < 2 || sel.data4ID$.DATE.as.Date[1] == sel.data4ID$.DATE.as.Date[n.events] ) { # For less than two events or when the first and the last events are on the same day, CMA5 does not make sense return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Otherwise, the sum of durations of the events excluding the last divided by the number of days between the first and the last event return (list("CMA"=1 - as.numeric(sum(sel.data4ID[-n.events, get(gap.days.colname)],na.rm=TRUE) / (as.numeric(difftime(sel.data4ID$.DATE.as.Date[n.events], sel.data4ID$.DATE.as.Date[1], units="days")))), "included.events.original.row.order"=sel.data4ID$..ORIGINAL.ROW.ORDER..[-n.events])); } } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA5","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=FALSE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA5 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA5 <- function(...) .plot.CMA1plus(...) #' CMA6 constructor. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 6 object. #' #' \code{CMA6} assumes that, within the observation window, the medication is #' used as prescribed and new medication is "banked" until needed (oversupply #' from previous events is used first, followed new medication supply). #' It computes days of theoretical use by extracting the total number of gap #' days from the total time interval between the first event and the end of the #' observation window, accounting for carry over for all medication events #' within the observation window. #' Thus, it accounts for timing within the observation window, and excludes the #' remaining supply at the end of the observation window. #' #' The formula is #' \deqn{(number of days of theoretical use) / (first event to end of #' observation window)} #' #' Observations: #' \itemize{ #' \item the \code{carry.only.for.same.medication} parameter controls the #' transmission of carry-over across medication changes, producing a #' "standard" \code{CMA6} (default value is FALSE), and an "alternative" #' \code{CMA6b}, respectively; #' \item the \code{consider.dosage.change} parameter controls if dosage changes #' are taken into account, i.e. if set as TRUE and a new medication event has #' a different daily dosage recommendation, carry-over is recomputed assuming #' medication use according to the new prescribed dosage (default value is FALSE). #' } #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA6} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso CMAs 1 to 8 are defined in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' cma6 <- CMA6(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA6 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=TRUE, "carryover.into.obs.window"=FALSE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available from the first event to the end of the observation window; total number of gap days extracted from this time interval, then divided by the time interval, accounting for carry-over within observation window and excluding remaining supply"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA6", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { sel.data4ID <- data4ID[ !.EVENT.STARTS.BEFORE.OBS.WINDOW & !.EVENT.STARTS.AFTER.OBS.WINDOW, ]; # select the events within the observation window only n.events <- nrow(sel.data4ID); # cache number of events if( n.events < 1 || sel.data4ID$.DATE.as.Date[1] > sel.data4ID$.OBS.END.DATE[1] ) { # For less than one event or when the first event is on the last day of the observation window, CMA6 does not make sense return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Otherwise, 1 - (total gap days divided by the number of days between the first event and the end of the observation window) return (list("CMA"=1 - as.numeric(sum(sel.data4ID[, get(gap.days.colname)],na.rm=TRUE) / (as.numeric(sel.data4ID$.OBS.END.DATE[1] - sel.data4ID$.DATE.as.Date[1]))), "included.events.original.row.order"=sel.data4ID$..ORIGINAL.ROW.ORDER..)); } } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA6","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=FALSE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA6 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA6 <- function(...) .plot.CMA1plus(...) #' CMA7 constructor. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 7 object. #' #' \code{CMA7} assumes that, within and before the observation window, the #' medication is used as prescribed and new medication is "banked" until needed #' (oversupply from previous events is used first, followed new medication #' supply). #' It computes days of theoretical use by extracting the total number of gap #' days from the total time interval between the start and the end of the #' observation window, accounting for carry over for all medication events #' within and before the observation window. All medication events in the #' follow up window before observation window are considered for carry-over #' calculation. #' Thus, it accounts for timing within and before the observation window, and #' excludes the remaining supply at the end of the observation window. #' #' The formula is #' \deqn{(number of days of theoretical use) / (start to end of observation #' window)} #' #' Observations: #' \itemize{ #' \item the \code{carry.only.for.same.medication} parameter controls the #' transmission of carry-over across medication changes, producing a "standard" #' \code{CMA7} (default value is FALSE), and an "alternative" \code{CMA7b}, #' respectively; #' \item the \code{consider.dosage.change} parameter controls if dosage #' changes are taken into account, i.e. if set as TRUE and a new medication #' event has a different daily dosage recommendation, carry-over is recomputed #' assuming medication use according to the new prescribed dosage (default #' value is FALSE). #' } #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider not #' covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA7} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, #' as given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso CMAs 1 to 8 are defined in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' cma7 <- CMA7(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA7 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=TRUE, "carryover.into.obs.window"=TRUE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the whole observation window; total number of gap days extracted from this time interval, then divided by the time interval, accounting for carry-over both before and within observation window and excluding remaining supply"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA7", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { # Select the events within the observation window: s <- which(!data4ID$.EVENT.STARTS.BEFORE.OBS.WINDOW & !data4ID$.EVENT.STARTS.AFTER.OBS.WINDOW); # Cache used things: n.events <- nrow(data4ID); s1 <- s[1]; slen <- length(s); slast <- s[slen]; gap.days.column <- data4ID[, get(gap.days.colname)]; # For less than one event or when the first event is on the last day of the observation window, if( slen < 1 || (data4ID$.DATE.as.Date[s1] > data4ID$.OBS.END.DATE[s1]) ) { if ( sum(data4ID$.EVENT.STARTS.BEFORE.OBS.WINDOW)==0 ) { # If there are no prior events, CMA7 does not make sense: return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Select the events that start before the observation window begins but continue within the observation window: event.start.before.continue.in <- max(which(data4ID$.EVENT.STARTS.BEFORE.OBS.WINDOW)); if( data4ID$gap.days[event.start.before.continue.in] <= as.numeric(data4ID$.OBS.END.DATE[n.events] - data4ID$.OBS.START.DATE[n.events]) ) { # Otherwise, CMA7 is the gap of the last event entering the observation window minus any days between the end of observation window and date of next event or end of follow-up window, divided by the observation window: return (list("CMA"=1.0 - as.numeric(gap.days.column[event.start.before.continue.in] / (as.numeric(data4ID$.OBS.END.DATE[event.start.before.continue.in] - data4ID$.OBS.START.DATE[event.start.before.continue.in]))), "included.events.original.row.order"=data4ID$..ORIGINAL.ROW.ORDER..[s])); } else { # If there is no event before that enters into the observation window, CMA7 is 0: return (list("CMA"=0.0, "included.events.original.row.order"=NA_integer_)); } } } else { # for all other situations compute the gap days for the last event in the observation window event.after.obs.window <- which(data4ID$.EVENT.STARTS.AFTER.OBS.WINDOW); # the events after the observation window gap.days.obswin.last.event <- gap.days.column[slast]; # Compute the gap days within the observation window but before the first event: if( s1 == 1 ) { gap.days.obswin.before.first.event <- as.numeric(difftime(data4ID$.DATE.as.Date[s1], data4ID$.OBS.START.DATE[s1], units="days")); # if it is the first event, there are gap days from start of observation window to first event } else { gap.days.obswin.before.first.event <- min(gap.days.column[s1-1], as.numeric(difftime(data4ID$.DATE.as.Date[s1], data4ID$.OBS.START.DATE[s1], units="days"))); } # Return 1 - (total gap days in observation window divided by the number of days between the start and the end of the observation window) if( slen == 1 ) { # if there is only one event, there are no "gap.days" to consider return (list("CMA"=1 - as.numeric((gap.days.obswin.last.event + gap.days.obswin.before.first.event) / (as.numeric(difftime(data4ID$.OBS.END.DATE[s1], data4ID$.OBS.START.DATE[s1], units="days")))), "included.events.original.row.order"=data4ID$..ORIGINAL.ROW.ORDER..[s])); } else { # if there are more events, gap days are the ones from before, the ones for the last event, and the ones in between return (list("CMA"=1 - as.numeric((sum(gap.days.column[s[-slen]],na.rm=TRUE) + gap.days.obswin.last.event + gap.days.obswin.before.first.event) / (as.numeric(difftime(data4ID$.OBS.END.DATE[s1], data4ID$.OBS.START.DATE[s1], units="days")))), "included.events.original.row.order"=data4ID$..ORIGINAL.ROW.ORDER..[s])); } } } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA7","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=TRUE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA7 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA7 <- function(...) .plot.CMA1plus(...) #' CMA8 constructor. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 8 object. #' #' \code{CMA8} is similar to CMA6 in that it assumes that, within the #' observation window, the medication is used as prescribed and new medication #' is "banked" until needed (oversupply from previous events is used first, #' followed new medication supply). Unlike \code{CMA6} it accounts for #' carry-over from before the window - but in a different way from \code{CMA7}: #' by adding a time lag at the start of the observation window equal to the #' duration of carry-over from before. It is designed for situations when an #' event with a hypothesized causal effect on adherence happens at the start of #' the observation window (e.g. enrolment in an intervention study); in this #' case, it may be that the existing supply is not part of the relationship #' under study (e.g. it delays the actual start of the study for that #' participant) and needs to be excluded by shortening the time interval #' examined. The end of the observation window remains the same. #' Thus, \code{CMA8} computes days of theoretical use by extracting the total #' number of gap days from the total time interval between the lagged start and #' the end of the observation window, accounting for carry over for all #' medication events within the observation window. All medication events in the #' follow up window before observation window are considered for carry-over #' calculation. #' Thus, as \code{CMA7}, it accounts for timing within the observation window, #' as well as before (different adjustment than \code{CMA7}), and excludes the #' remaining supply at the end of the observation window. #' #' The formula is #' \deqn{(number of days of theoretical use) / (lagged start to end of #' observation window)} #' #' Observations: #' \itemize{ #' \item the \code{carry.only.for.same.medication} parameter controls the #' transmission of carry-over across medication changes, producing a "standard" #' \code{CMA8} (default value is FALSE), and an "alternative" \code{CMA8b}, #' respectively; #' \item the \code{consider.dosage.change} parameter controls if dosage changes #' are taken into account, i.e. if set as TRUE and a new medication event has #' a different daily dosage recommendation, carry-over is recomputed assuming #' medication use according to the new prescribed dosage (default value is #' FALSE). #' } #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA8} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso CMAs 1 to 8 are defined in: #' #' Vollmer, W. M., Xu, M., Feldstein, A., Smith, D., Waterbury, A., & Rand, C. #' (2012). Comparison of pharmacy-based measures of medication adherence. #' \emph{BMC Health Services Research}, \strong{12}, 155. #' \doi{10.1186/1472-6963-12-155}. #' #' @examples #' cma8 <- CMA8(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA8 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date plus number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=TRUE, "carryover.into.obs.window"=TRUE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the whole observation window, with lagged start until previous supply is finished; total number of gap days extracted from this time interval, then divided by the time interval, accounting for carry-over within lagged observation window and excluding remaining supply"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA8", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the new OW start date: .new.OW.start <- function(data4ID) { # Select the events that start before the observation window but end within it: s <- which(data4ID$.START.BEFORE.END.WITHIN.OBS.WND); if( length(s) > 0 ) return (max(data4ID$.END.EVENT.DATE[s])) else return (data4ID$.OBS.START.DATE[1]); # new (or old) OW start date } # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); # Add auxiliary columns to the event.info data.table: event.info[, .END.EVENT.DATE := (.DATE.as.Date + get(event.duration.colname) + .CARRY.OVER.FROM.BEFORE) ]; # compute the end date of the events event.info[, .START.BEFORE.END.WITHIN.OBS.WND := (.EVENT.STARTS.BEFORE.OBS.WINDOW & (.END.EVENT.DATE > .OBS.START.DATE)) ]; # events that start before the OW but end within it # Update the FU start, OW start and OW duration (make sure there is no naming conflict!): event.info[, .FU.START.DATE.UPDATED := .FU.START.DATE ]; # FU start date as Date object event.info[, .OBS.START.DATE.UPDATED := .new.OW.start(.SD), by=ID.colname ]; # OW start date as Date object event.info[, .OBS.DURATION.UPDATED := as.numeric(.OBS.END.DATE - .OBS.START.DATE.UPDATED) ]; # OW duration as number # Calling CMA7: include.columns <- which(!(names(event.info) %in% c(event.interval.colname, gap.days.colname))); # make sure we don't send these two columns as they'll produce an error in CMA7 CMA <- CMA7(data=as.data.frame(event.info[, include.columns, with=FALSE]), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=".FU.START.DATE.UPDATED", followup.window.start.unit="days", followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".OBS.START.DATE.UPDATED", observation.window.start.unit="days", observation.window.duration=".OBS.DURATION.UPDATED", observation.window.duration.unit="days", # fix it to days date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, # suppress warnings from CMA7 suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=FALSE # may enforce this afterwards... ); # Recover the rows in data: CMA$event.info$..ORIGINAL.ROW.ORDER.. -> event.info$..ORIGINAL.ROW.ORDER.. -> data: event.info$.EVENT.USED.IN.CMA <- NA; event.info$.EVENT.USED.IN.CMA[ CMA$event.info$..ORIGINAL.ROW.ORDER.. ] <- CMA$event.info$.EVENT.USED.IN.CMA; return (list("CMA"=CMA$CMA, "event.info"=event.info)); # make sure to return the non-adjusted event.info prior to computing CMA7! } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA8","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=TRUE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); # Save the real observation window as well: if( !is.null(ret.val$event.info) ) { if( inherits(ret.val$event.info, "data.frame") ) { ret.val[["real.obs.windows"]] <- unique(data.frame( ret.val$event.info[, ID.colname], "window.start"=ret.val$event.info$.OBS.START.DATE.UPDATED, "window.end"=NA)); setnames(ret.val$real.obs.windows, 1, ID.colname); } else if( is.list(ret.val$event.info) && length(ret.val$event.info) > 0 ) { ret.val[["real.obs.windows"]] <- lapply(ret.val$event.info, function(x) { if( is.null(x) ) return (NULL); tmp <- unique(data.frame( x[, ID.colname], "window.start"=x$.OBS.START.DATE.UPDATED, "window.end"=NA)); setnames(tmp, 1, ID.colname); return (tmp); }); names(ret.val[["real.obs.windows"]]) <- names(ret.val$event.info); } else { ret.val[["real.obs.windows"]] <- NULL; } } else { ret.val[["real.obs.windows"]] <- NULL; } return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA8 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA8 <- function(...) .plot.CMA1plus(...) #' CMA9 constructor. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) type 9 object. #' #' #' \code{CMA9} is similar to \code{CMA7} and \code{CMA8} in that it accounts for #' carry-over within and before the observation window assuming that new #' medication is "banked" until needed (oversupply from previous events is used #' first, followed new medication supply). Yet, unlike these previous CMAs, it #' does not assume the medication is used as prescribed; in longitudinal studies #' with multiple CMA measures, this assumption may introduce additional #' variation in CMA estimates depending on when the observation window starts #' in relation to the previous medication event. A shorter time distance from #' the previous event (and longer to the first event in the observation window) #' results in higher values even if the number of gap days is the same, and it #' may also be that the patient has had a similar use pattern for that time #' interval, rather than perfect adherence followed by no medication use. #' \code{CMA9} applies a different adjustment: it computes a ratio of days #' supply over each interval between two prescriptions and considers this #' applies for each day of that interval, up to 100\% (moving oversupply to the #' next event interval). All medication events in the follow up window before #' observation window are considered for carry-over calculation. The last #' interval ends at the end of the follow-up window. #' Thus, it accounts for timing within the observation window, as well as #' before (but differently from \code{CMA7} and \code{CMA8}), and excludes the #' remaining supply at the end of the observation window, if any. #' #' The formula is #' \deqn{(number of days in the observation window, each weighted by the ratio #' of days supply applicable to their event interval) / (start to end of #' observation window)} #' #' Observations: #' \itemize{ #' \item the \code{carry.only.for.same.medication} parameter controls the #' transmission of carry-over across medication changes, producing a "standard" #' \code{CMA7} (default value is FALSE), and an "alternative" \code{CMA7b}, #' respectively; #' \item the \code{consider.dosage.change} parameter controls if dosage changes #' are taken into account, i.e. if set as TRUE and a new medication event has a #' different daily dosage recommendation, carry-over is recomputed assuming #' medication use according to the new prescribed dosage (default value is #' FALSE). #' } #' #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider not #' covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param arguments.that.should.not.be.defined a \emph{list} of argument names #' and pre-defined valuesfor which a warning should be thrown if passed to the #' function. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA9} (derived from \code{CMA0}) #' with the following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, #' as given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column). #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @examples #' cma9 <- CMA9(data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=30, #' observation.window.start=30, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' @export CMA9 <- function( data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=FALSE, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=FALSE, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary=NA, # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names arguments.that.should.not.be.defined=c("carryover.within.obs.window"=TRUE, "carryover.into.obs.window"=TRUE), # the list of argument names and values for which a warning should be thrown if passed to the function ... ) { # The summary: if( is.na(summary) ) summary <- "The ratio of days with medication available in the observation window; the supply of each event is evenly spread until the next event (ratio days supply up to 1), then oversupply carried over to the next event; the each day in the observation window is weighted by its ratio of days supply, and the sum divided by the duration of the observation window"; # Arguments that should not have been passed: if( !suppress.warnings && !is.null(arguments.that.should.not.be.defined) ) { # Get the actual list of arguments (including in the ...); the first is the function's own name: args.list <- as.list(match.call(expand.dots = TRUE)); args.mathing <- (names(arguments.that.should.not.be.defined) %in% names(args.list)[-1]); if( any(args.mathing) ) { for( i in which(args.mathing) ) { .report.ewms(paste0("Please note that '",args.list[[1]],"' overrides argument '",names(arguments.that.should.not.be.defined)[i],"' with value '",arguments.that.should.not.be.defined[i],"'!\n"), "warning", "CMA9", "AdhereR"); } } } # Create the CMA0 object: ret.val <- CMA0(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, summary=summary, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(ret.val) ) return (NULL); # some error upstream # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { n.events <- nrow(data4ID); # cache number of events # Caching; .obs.start.actual <- data4ID$.OBS.START.DATE.ACTUAL[1]; .obs.end.actual <- data4ID$.OBS.END.DATE.ACTUAL[1]; # Select the events within the observation window: s <- which(data4ID$.DATE.as.Date <= .obs.end.actual); if( length(s) == 0 ) { return (list("CMA"=NA_real_, "included.events.original.row.order"=NA_integer_)); } else { # Compute the ratios of CMA within the FUW: .CMA.PER.INTERVAL <- (1 - data4ID[,get(gap.days.colname)] / data4ID[,get(event.interval.colname)]); event.start <- data4ID$.DATE.as.Date; event.end <- (event.start + data4ID[,get(event.interval.colname)]); int.start <- pmax(event.start, .obs.start.actual); int.end <- pmin(event.end, .obs.end.actual); .EVENT.INTERVAL.IN.OBS.WIN <- pmax(0, as.numeric(int.end - int.start)); # Weight the days by the ratio: return (list("CMA"=sum(.CMA.PER.INTERVAL * .EVENT.INTERVAL.IN.OBS.WIN, na.rm=TRUE) / as.numeric(.obs.end.actual - .obs.start.actual), "included.events.original.row.order"=data4ID$..ORIGINAL.ROW.ORDER..[s])); } } # ATTENTION: this is done for an observation window that is identical to the follow-up window to accommodate events that overshoot the observation window! event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=TRUE, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=0, # force follow-up window start at 0! observation.window.start.unit="days", observation.window.duration=followup.window.duration, observation.window.duration.unit=followup.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, keep.event.interval.for.all.events=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); # Also compute the actual observation window start and end: #patinfo.cols <- which(names(event.info) %in% c(ID.colname, event.date.colname, event.duration.colname, event.daily.dose.colname, medication.class.colname)); #tmp <- as.data.frame(data); tmp <- tmp[!duplicated(tmp[,ID.colname]),patinfo.cols]; # the reduced dataset for comuting the actual OW: tmp <- as.data.frame(data); tmp <- tmp[!duplicated(tmp[,ID.colname]),names(data)]; # the reduced dataset for comuting the actual OW: actual.obs.win <- compute.event.int.gaps(data=tmp, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(actual.obs.win) ) return (list("CMA"=NA, "event.info"=NULL)); # Add the actual OW dates to event.info: actual.obs.win <- actual.obs.win[,c(ID.colname,".OBS.START.DATE",".OBS.END.DATE"),with=FALSE] setkeyv(actual.obs.win, ID.colname); event.info <- merge(event.info, actual.obs.win, all.x=TRUE); setnames(event.info, ncol(event.info)-c(1,0), c(".OBS.START.DATE.ACTUAL", ".OBS.END.DATE.ACTUAL")); CMA <- event.info[, .process.patient(.SD), by=ID.colname]; # Make sure the information reflects the real observation window: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=TRUE, # if TRUE consider the carry-over from before the starting date of the observation window carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, keep.event.interval.for.all.events=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); event.info$.EVENT.USED.IN.CMA <- (event.info$..ORIGINAL.ROW.ORDER.. %in% CMA$included.events.original.row.order); # store if the event was used to compute the CMA or not return (list("CMA"=unique(CMA[,1:2]), "event.info"=event.info)); } ret.val <- .cma.skeleton(data=data, ret.val=ret.val, cma.class.name=c("CMA9","CMA1"), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=TRUE, carryover.into.obs.window=TRUE, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, flatten.medication.groups=flatten.medication.groups, followup.window.start.per.medication.group=followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, force.NA.CMA.for.failed.patients=force.NA.CMA.for.failed.patients, parallel.backend=parallel.backend, parallel.threads=parallel.threads, .workhorse.function=.workhorse.function); return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA9 <- function(...) print.CMA0(...) #' @rdname plot.CMA1 #' @export plot.CMA9 <- function(...) .plot.CMA1plus(...) #' CMA_per_episode constructor. #' #' Applies a given CMA to each treatment episode and constructs a #' CMA_per_episode object. #' #' \code{CMA_per_episode} first identifies the treatment episodes for the whole #' follo-up window (using the \code{\link{compute.treatment.episodes}} function), #' and then computes the given "simple" CMA for each treatment episode that #' intersects with the observation window. NB: the CMA is computed for the #' period of the episode that is part of the observations window; thus, if an #' episode starts earlier or ends later than the observation window, CMA will #' be computed for a section of that episode. #' Thus, as opposed to the "simple" CMAs 1 to 9, it returns a set of CMAs, with #' possibly more than one element. #' #' It is highly similar to \code{\link{CMA_sliding_window}} which computes a CMA #' for a set of sliding windows. #' #' @param CMA.to.apply A \emph{string} giving the name of the CMA function (1 to #' 9) that will be computed for each treatment episode. #' @param data A \emph{\code{data.frame}} containing the events (prescribing or #' dispensing) used to compute the CMA. Must contain, at a minimum, the patient #' unique ID, the event date and duration, and might also contain the daily #' dosage and medication type (the actual column names are defined in the #' following four parameters). #' @param treat.epi A \emph{\code{data.frame}} containing the treatment episodes. #' Must contain the patient ID (as given in \code{ID.colname}), the episode unique ID #' (increasing sequentially, \code{episode.ID}), the episode start date #' (\code{episode.start}), the episode duration in days (\code{episode.duration}), #' and the episode end date (\code{episode.end}). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type; valid only for #' CMAs 5 to 9, in which case it is coupled (i.e., the same value is used for #' computing the treatment episodes and the CMA on each treatment episode). #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage; valid only for CMAs 5 to 9, in #' which case it is coupled (i.e., the same value is used for computing the #' treatment episodes and the CMA on each treatment episode). #' @param medication.change.means.new.treatment.episode \emph{Logical}, should a #' change in medication automatically start a new treatment episode? #' @param dosage.change.means.new.treatment.episode \emph{Logical}, should a #' change in dosage automatically start a new treatment episode? #' @param maximum.permissible.gap The \emph{number} of units given by #' \code{maximum.permissible.gap.unit} representing the maximum duration of #' permissible gaps between treatment episodes (can also be a percent, see #' \code{maximum.permissible.gap.unit} for details). #' @param maximum.permissible.gap.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"}, \emph{"years"} or \emph{"percent"}, and #' represents the time units that \code{maximum.permissible.gap} refers to; #' if \emph{percent}, then \code{maximum.permissible.gap} is interpreted as a #' percent (can be greater than 100\%) of the duration of the current #' prescription. #' @param maximum.permissible.gap.append.to.episode a \emph{logical} value #' specifying of the \code{maximum.permissible.gap} should be append at the #' end of an episode with a gap larger than the \code{maximum.permissible.gap}; #' \code{FALSE} (the default) mean no addition, while \code{TRUE} mean that the #' full \code{maximum.permissible.gap} is added. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param return.inner.event.info \emph{Logical} specifying if the function #' should also return the event.info for all the individual events in each #' sliding window; by default it is \code{FALSE} as this information is useful #' only in very specific cases (e.g., plotting the event intervals) and adds a #' small but non-negligible computational overhead. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param return.mapping.events.episodes A \emph{Logical}, if \code{TRUE} then #' the mapping between events and episodes is returned as an extra component #' \code{mapping.episodes.to.events}, which is a \code{data.table} giving, for #' each episode, the events that belong to it (an event is given by its row #' number in the \code{data}). Please note that the episodes returned are #' specific to the particular simple CMA used, and should preferentially used #' over those returned by \code{compute.treatment.episodes()}. This component #' can also be accessed using the \code{getEventsToEpisodesMapping()} function. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA_per_episode} with the #' following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{computed.CMA} the class name of the computed CMA. #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column) and treatment #' episode, with columns: #' \itemize{ #' \item \code{ID.colname} the patient ID as given by the \code{ID.colname} #' parameter. #' \item \code{episode.ID} the unique treatment episode ID (within #' patients). #' \item \code{episode.start} the treatment episode's start date (as a #' \code{Date} object). #' \item \code{end.episode.gap.days} the corresponding gap days of the last #' event in this episode. #' \item \code{episode.duration} the treatment episode's duration in days. #' \item \code{episode.end} the treatment episode's end date (as a #' \code{Date} object). #' \item \code{CMA} the treatment episode's estimated CMA. #' } #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso \code{\link{CMA_sliding_window}} is very similar, computing a #' "simple" CMA for each of a set of same-size sliding windows. #' The "simple" CMAs that can be computed comprise \code{\link{CMA1}}, #' \code{\link{CMA2}}, \code{\link{CMA3}}, \code{\link{CMA4}}, #' \code{\link{CMA5}}, \code{\link{CMA6}}, \code{\link{CMA7}}, #' \code{\link{CMA8}}, \code{\link{CMA9}}, as well as user-defined classes #' derived from \code{\link{CMA0}} that have a \code{CMA} component giving the #' estimated CMA per patient as a \code{data.frame}. #' If \code{return.mapping.events.episodes} is \code{TRUE}, then this also has a #' component \code{mapping.episodes.to.events} that gives the mapping between #' episodes and events as a \code{data.table} with the following columns: #' \itemize{ #' \item \code{patid} the patient ID. #' \item \code{episode.ID} the episode unique ID (increasing sequentially). #' \item \code{event.index.in.data} the event given by its row number in the \code{data}. #' } #' @examples #' \dontrun{ #' cmaE <- CMA_per_episode(CMA="CMA1", #' data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=0, #' observation.window.start=0, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' );} #' @export CMA_per_episode <- function( CMA.to.apply, # the name of the CMA function (e.g., "CMA1") to be used data, # the data used to compute the CMA on treat.epi=NULL, # the treatment episodes, if available # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = use the CMA's values) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = use the CMA's values) # Treatment episodes: medication.change.means.new.treatment.episode=TRUE, # does a change in medication automatically start a new treatment episode? dosage.change.means.new.treatment.episode=FALSE, # does a change in dosage automatically start a new treatment episode? maximum.permissible.gap=180, # if a number, is the duration in units of max. permissible gaps between treatment episodes maximum.permissible.gap.unit=c("days", "weeks", "months", "years", "percent")[1], # time units; can be "days", "weeks" (fixed at 7 days), "months" (fixed at 30 days), "years" (fixed at 365 days), or "percent", in which case maximum.permissible.gap is interpreted as a percent (can be > 100%) of the duration of the current prescription maximum.permissible.gap.append.to.episode=FALSE, # should the maximum permissible gap be appended at the end of an episode with a gap larger than the maximum permissible gap? FALSE = no addition (the default), TRUE = the full maximum permissible gap is added # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1],# the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) return.inner.event.info=FALSE, # should we return the event.info for all the individual events in each sliding window? # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary="CMA per treatment episode", # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Return also the mapping between episodes and events? return.mapping.events.episodes=FALSE, # if TRUE, return the mapping # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names # extra parameters to be sent to the CMA function: ... ) { # Get the CMA function corresponding to the name: if( !(is.character(CMA.to.apply) || is.factor(CMA.to.apply)) ) { if( !suppress.warnings ) .report.ewms(paste0("'CMA.to.apply' must be a string contining the name of the simple CMA to apply!\n)"), "error", "CMA_per_episode", "AdhereR"); return (NULL); } CMA.FNC <- switch(as.character(CMA.to.apply), # if factor, force it to string "CMA1" = CMA1, "CMA2" = CMA2, "CMA3" = CMA3, "CMA4" = CMA4, "CMA5" = CMA5, "CMA6" = CMA6, "CMA7" = CMA7, "CMA8" = CMA8, "CMA9" = CMA9, {if( !suppress.warnings ) .report.ewms(paste0("Unknown 'CMA.to.apply' '",CMA.to.apply,"': defaulting to CMA0!\n)"), "warning", "CMA_per_episode", "AdhereR"); CMA0;}); # by default, fall back to CMA0 # Default argument values and overrides: def.vals <- formals(CMA.FNC); if( CMA.to.apply %in% c("CMA1", "CMA2", "CMA3", "CMA4") ) { carryover.into.obs.window <- carryover.within.obs.window <- FALSE; if( !is.na(carry.only.for.same.medication) && carry.only.for.same.medication && !suppress.warnings ) .report.ewms("'carry.only.for.same.medication' cannot be defined for CMAs 1-4!\n", "warning", "CMA_per_episode", "AdhereR"); carry.only.for.same.medication <- FALSE; if( !is.na(consider.dosage.change) && consider.dosage.change && !suppress.warnings ) .report.ewms("'consider.dosage.change' cannot be defined for CMAs 1-4!\n", "warning", "CMA_per_episode", "AdhereR"); consider.dosage.change <- FALSE; } else if( CMA.to.apply %in% c("CMA5", "CMA6") ) { carryover.into.obs.window <- FALSE; carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else if( CMA.to.apply %in% c("CMA7", "CMA8", "CMA9") ) { carryover.into.obs.window <- carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else { if( !suppress.warnings ) .report.ewms("I know how to do CMA per episodes only for CMAs 1 to 9!\n", "error", "CMA_per_episode", "AdhereR"); return (NULL); } ## Force data to data.table #if( !inherits(data,"data.table") ) data <- as.data.table(data); # Create the return value skeleton and check consistency: ret.val <- CMA0(data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, summary=NA); if( is.null(ret.val) ) return (NULL); # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; ## retain only necessary columns of data #data <- data[,c(ID.colname, # event.date.colname, # event.duration.colname, # event.daily.dose.colname, # medication.class.colname), # with=FALSE]; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { mapping.episodes.to.events <- NULL; # the mapping events <-> episodes, if any if(is.null(treat.epi)) { # Compute the treatment episodes: treat.epi <- compute.treatment.episodes(data=data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, medication.change.means.new.treatment.episode=medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=dosage.change.means.new.treatment.episode, maximum.permissible.gap=maximum.permissible.gap, maximum.permissible.gap.unit=maximum.permissible.gap.unit, maximum.permissible.gap.append.to.episode=maximum.permissible.gap.append.to.episode, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, return.mapping.events.episodes=TRUE, # map the events to episodes anyways date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if("mapping.episodes.to.events" %in% names(attributes(treat.epi))) mapping.episodes.to.events <- attr(treat.epi, "mapping.episodes.to.events"); # store the mapping events <-> episodes } else { # various checks # Convert treat.epi to data.table, cache event date as Date objects, and key by patient ID and event date treat.epi <- as.data.table(treat.epi); treat.epi[, `:=` (episode.start = as.Date(episode.start,format=date.format), episode.end = as.Date(episode.end,format=date.format) )]; # .DATE.as.Date: convert event.date.colname from formatted string to Date setkeyv(treat.epi, c(ID.colname, "episode.ID")); # key (and sorting) by patient and episode ID } if( is.null(treat.epi) || nrow(treat.epi) == 0 ) return (NULL); # Compute the real observation windows (might differ per patient) only once per patient (speed things up & the observation window is the same for all events within a patient): tmp <- as.data.frame(data); tmp <- tmp[!duplicated(tmp[,ID.colname]),]; # the reduced dataset for computing the actual OW: event.info2 <- compute.event.int.gaps(data=tmp, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info2) ) return (NULL); # Merge the observation window start and end dates back into the treatment episodes: treat.epi <- merge(treat.epi, event.info2[,c(ID.colname, ".OBS.START.DATE", ".OBS.END.DATE"),with=FALSE], all.x=TRUE, by = c(ID.colname)); setnames(treat.epi, ncol(treat.epi)-c(1,0), c(".OBS.START.DATE.PRECOMPUTED", ".OBS.END.DATE.PRECOMPUTED")); # Get the intersection between the episode and the observation window: treat.epi[, c(".INTERSECT.EPISODE.OBS.WIN.START", ".INTERSECT.EPISODE.OBS.WIN.END") := list(max(episode.start, .OBS.START.DATE.PRECOMPUTED), min(episode.end, .OBS.END.DATE.PRECOMPUTED)), by=c(ID.colname,"episode.ID")]; treat.epi <- treat.epi[ .INTERSECT.EPISODE.OBS.WIN.START < .INTERSECT.EPISODE.OBS.WIN.END, ]; # keep only the episodes which fall within the OW treat.epi[, c("episode.duration", ".INTERSECT.EPISODE.OBS.WIN.DURATION", ".PATIENT.EPISODE.ID") := list(as.numeric(episode.end - episode.start), as.numeric(.INTERSECT.EPISODE.OBS.WIN.END - .INTERSECT.EPISODE.OBS.WIN.START), paste(get(ID.colname),episode.ID,sep="*"))]; # Merge the data and the treatment episodes info: data.epi <- merge(treat.epi, data, allow.cartesian=TRUE); setkeyv(data.epi, c(".PATIENT.EPISODE.ID", ".DATE.as.Date")); # compute end.episode.gap.days, if treat.epi are supplied if(!"end.episode.gap.days" %in% colnames(treat.epi)) { data.epi2 <- compute.event.int.gaps(data=as.data.frame(data.epi), ID.colname=".PATIENT.EPISODE.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start="episode.start", followup.window.start.unit=followup.window.start.unit, followup.window.duration="episode.duration", followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".INTERSECT.EPISODE.OBS.WIN.START", observation.window.duration=".INTERSECT.EPISODE.OBS.WIN.DURATION", observation.window.duration.unit="days", date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); episode.gap.days <- data.epi2[which(.EVENT.WITHIN.FU.WINDOW), c(ID.colname, "episode.ID", gap.days.colname), by = c(ID.colname, "episode.ID"), with = FALSE]; # gap days during the follow-up window end.episode.gap.days <- episode.gap.days[,last(get(gap.days.colname)), by = c(ID.colname, "episode.ID")]; # gap days during the last event setnames(end.episode.gap.days, old = "V1", new = "end.episode.gap.days") treat.epi <- merge(treat.epi, end.episode.gap.days, all.x = TRUE, by = c(ID.colname, "episode.ID")); # merge end.episode.gap.days back to data.epi treat.epi[, episode.duration := as.numeric(.INTERSECT.EPISODE.OBS.WIN.END-.INTERSECT.EPISODE.OBS.WIN.START)]; } # Compute the required CMA on this new combined database: if(length(dot.args <- list(...)) > 0 && "arguments.that.should.not.be.defined" %in% names(dot.args)) # check if arguments.that.should.not.be.defined is passed in the ... argument { # Avoid passing again arguments.that.should.not.be.defined to the CMA function: cma <- CMA.FNC(data=as.data.frame(data.epi), ID.colname=".PATIENT.EPISODE.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start="episode.start", followup.window.start.unit=followup.window.start.unit, followup.window.duration="episode.duration", followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".INTERSECT.EPISODE.OBS.WIN.START", observation.window.duration=".INTERSECT.EPISODE.OBS.WIN.DURATION", observation.window.duration.unit="days", date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, # we know we're using special arguments, so don't do an extra check ...); } else { # Temporarily avoid warnings linked to rewriting some CMA arguments by passing it arguments.that.should.not.be.defined=NULL: cma <- CMA.FNC(data=as.data.frame(data.epi), ID.colname=".PATIENT.EPISODE.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start="episode.start", followup.window.start.unit=followup.window.start.unit, followup.window.duration="episode.duration", followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".INTERSECT.EPISODE.OBS.WIN.START", observation.window.duration=".INTERSECT.EPISODE.OBS.WIN.DURATION", observation.window.duration.unit="days", date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, # we know we're using special arguments, so don't do an extra check arguments.that.should.not.be.defined=NULL, ...); } # adjust episode start- and end dates treat.epi[, `:=` (episode.start = .INTERSECT.EPISODE.OBS.WIN.START, episode.end = .INTERSECT.EPISODE.OBS.WIN.END)] # Add back the patient and episode IDs: tmp <- as.data.table(merge(cma$CMA, treat.epi)[,c(ID.colname, "episode.ID", "episode.start", "end.episode.gap.days", "episode.duration", "episode.end", "CMA")]); setkeyv(tmp, c(ID.colname,"episode.ID")); # The return value: ret.val <- list("CMA"=as.data.frame(tmp), "event.info"=as.data.frame(event.info2)[,c(ID.colname, ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE")]); if( return.inner.event.info ) { ret.val[["inner.event.info"]] <- as.data.frame(event.info2); } if( return.mapping.events.episodes ) { events.actually.used <- cma$data$..ORIGINAL.ROW.ORDER..[ cma$event.info$..ORIGINAL.ROW.ORDER..[ cma$event.info$.EVENT.USED.IN.CMA ] ]; # translate back to the original data row numbers of the used events mapping.episodes.to.events <- mapping.episodes.to.events[ mapping.episodes.to.events$event.index.in.data %in% events.actually.used, ]; # keep only those events that are used in the episodes ret.val[["mapping.episodes.to.events"]] <- merge(mapping.episodes.to.events, tmp[,c(ID.colname, "episode.ID"), with=FALSE], by=c(ID.colname, "episode.ID"), all.x=FALSE, all.y=TRUE); } return (ret.val); } # Convert to data.table, cache event date as Date objects, and key by patient ID and event date # columns to keep: columns.to.keep <- c(); if( !is.null(ID.colname) && !is.na(ID.colname) && length(ID.colname) == 1 && ID.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, ID.colname); if( !is.null(event.date.colname) && !is.na(event.date.colname) && length(event.date.colname) == 1 && event.date.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, event.date.colname); if( !is.null(event.duration.colname) && !is.na(event.duration.colname) && length(event.duration.colname) == 1 && event.duration.colname %in% names(data)) columns.to.keep <- c(columns.to.keep, event.duration.colname); if( !is.null(event.daily.dose.colname) && !is.na(event.daily.dose.colname) && length(event.daily.dose.colname) == 1 && event.daily.dose.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, event.daily.dose.colname); if( !is.null(medication.class.colname) && !is.na(medication.class.colname) && length(medication.class.colname) == 1 && medication.class.colname %in% names(data) ) columns.to.keep <- c(columns.to.keep, medication.class.colname); if( !is.null(mg <- getMGs(ret.val)) && !is.null(medication.groups.colname) && !is.na(medication.groups.colname) && length(medication.groups.colname) == 1 && medication.groups.colname %in% names(data)) columns.to.keep <- c(columns.to.keep, medication.groups.colname); if( !is.null(followup.window.start) && !is.na(followup.window.start) && length(followup.window.start) == 1 && (is.character(followup.window.start) || (is.factor(followup.window.start) && is.character(followup.window.start <- as.character(followup.window.start)))) && followup.window.start %in% names(data) ) columns.to.keep <- c(columns.to.keep, followup.window.start); if( !is.null(followup.window.duration) && !is.na(followup.window.duration) && length(followup.window.duration) == 1 && (is.character(followup.window.duration) || (is.factor(followup.window.duration) && is.character(followup.window.duration <- as.character(followup.window.duration)))) && followup.window.duration %in% names(data) ) columns.to.keep <- c(columns.to.keep, followup.window.duration); if( !is.null(observation.window.start) && !is.na(observation.window.start) && length(observation.window.start) == 1 && (is.character(observation.window.start) || (is.factor(observation.window.start) && is.character(observation.window.start <- as.character(observation.window.start)))) && observation.window.start %in% names(data) ) columns.to.keep <- c(columns.to.keep, observation.window.start); if( !is.null(observation.window.duration) && !is.na(observation.window.duration) && length(observation.window.duration) == 1 && (is.character(observation.window.duration) || (is.factor(observation.window.duration) && is.character(observation.window.duration <- as.character(observation.window.duration)))) && observation.window.duration %in% names(data) ) columns.to.keep <- c(columns.to.keep, observation.window.duration); # special column names that should not be used: if( !suppress.special.argument.checks ) { ..special.colnames <- c(.special.colnames, event.interval.colname, gap.days.colname); # don't forget event.interval.colname and gap.days.colname! if( any(s <- ..special.colnames %in% columns.to.keep) ) { .report.ewms(paste0("Column name(s) ",paste0("'",..special.colnames[s],"'",collapse=", "),"' are reserved: please don't use them in your input data!\n"), "error", cma.class.name, "AdhereR"); return (NULL); } } # copy only the relevant bits of the data: data.copy <- data.table(data)[, columns.to.keep, with=FALSE]; data.copy[, .DATE.as.Date := as.Date(get(event.date.colname),format=date.format)]; # .DATE.as.Date: convert event.date.colname from formatted string to Date data.copy$..ORIGINAL.ROW.ORDER.. <- 1:nrow(data.copy); # preserve the original order of the rows (needed for medication groups) setkeyv(data.copy, c(ID.colname, ".DATE.as.Date")); # key (and sorting) by patient ID and event date # Are there medication groups? if( is.null(mg <- getMGs(ret.val)) ) { # Nope: do a single estimation on the whole dataset: # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || !inherits(tmp$CMA,"data.frame") || is.null(tmp$event.info) ) return (NULL); # Construct the return object: class(ret.val) <- "CMA_per_episode"; ret.val$event.info <- as.data.frame(tmp$event.info); ret.val$computed.CMA <- CMA.to.apply; ret.val$summary <- summary; ret.val$CMA <- as.data.frame(tmp$CMA); setnames(ret.val$CMA, 1, ID.colname); if( return.inner.event.info && !is.null(tmp$inner.event.info) ) ret.val$inner.event.info <- as.data.frame(tmp$inner.event.info); if( return.mapping.events.episodes && !is.null(tmp$mapping.episodes.to.events) ) ret.val$mapping.episodes.to.events <- as.data.frame(tmp$mapping.episodes.to.events); return (ret.val); } else { # Yes # Make sure the group's observations reflect the potentially new order of the observations in the data: mb.obs <- mg$obs[data.copy$..ORIGINAL.ROW.ORDER.., ]; # Focus only on the non-trivial ones: mg.to.eval <- (colSums(!is.na(mb.obs) & mb.obs) > 0); if( sum(mg.to.eval) == 0 ) { # None selects not even one observation! .report.ewms(paste0("None of the medication classes (included __ALL_OTHERS__) selects any observation!\n"), "warning", "CMA1", "AdhereR"); return (NULL); } mb.obs <- mb.obs[,mg.to.eval]; # keep only the non-trivial ones # Check if there are medication classes that refer to the same observations (they would result in the same estimates): mb.obs.dupl <- duplicated(mb.obs, MARGIN=2); # Estimate each separately: tmp <- lapply(1:nrow(mg$defs), function(i) { # Check if these are to be evaluated: if( !mg.to.eval[i] ) { return (list("CMA"=NULL, "event.info"=NULL)); } # Translate into the index of the classes to be evaluated: ii <- sum(mg.to.eval[1:i]); # Cache the selected observations: mg.sel.obs <- mb.obs[,ii]; # Check if this is a duplicated medication class: if( mb.obs.dupl[ii] ) { # Find which one is the original: for( j in 1:(ii-1) ) # ii=1 never should be TRUE { if( identical(mb.obs[,j], mg.sel.obs) ) { # This is the original: return it and stop return (c("identical.to"=j)); } } } # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy[mg.sel.obs,], # apply it on the subset of observations covered by this medication class ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || !inherits(tmp$CMA,"data.frame") || is.null(tmp$event.info) ) return (NULL); # Convert to data.frame and return: tmp$CMA <- as.data.frame(tmp$CMA); setnames(tmp$CMA, 1, ID.colname); tmp$event.info <- as.data.frame(tmp$event.info); if( return.inner.event.info && !is.null(tmp$inner.event.info) ) tmp$inner.event.info <- as.data.frame(tmp$inner.event.info); return (tmp); }); # Set the names: names(tmp) <- mg$defs$name; # Solve the duplicates: for( i in seq_along(tmp) ) { if( is.numeric(tmp[[i]]) && length(tmp[[i]]) == 1 && names(tmp[[i]]) == "identical.to" ) tmp[[i]] <- tmp[[ tmp[[i]] ]]; } # Rearrange these and return: ret.val[["CMA"]] <- lapply(tmp, function(x) x$CMA); ret.val[["event.info"]] <- lapply(tmp, function(x) x$event.info); if( return.inner.event.info && !is.null(tmp$inner.event.info) ) ret.val[["inner.event.info"]] <- lapply(tmp, function(x) x$inner.event.info); ret.val$computed.CMA <- CMA.to.apply; if( flatten.medication.groups && !is.na(medication.groups.colname) ) { # Flatten the CMA: tmp <- do.call(rbind, ret.val[["CMA"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["CMA"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["CMA"]]), function(i) if(!is.null(ret.val[["CMA"]][[i]])){rep(names(ret.val[["CMA"]])[i], nrow(ret.val[["CMA"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["CMA"]] <- tmp; } # ... and the event.info: tmp <- do.call(rbind, ret.val[["event.info"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["event.info"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["event.info"]]), function(i) if(!is.null(ret.val[["event.info"]][[i]])){rep(names(ret.val[["event.info"]])[i], nrow(ret.val[["event.info"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["event.info"]] <- tmp; } # ... and the inner.event.info: if( return.inner.event.info && !is.null(ret.val[["inner.event.info"]]) ) { tmp <- do.call(rbind, ret.val[["inner.event.info"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["inner.event.info"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["inner.event.info"]]), function(i) if(!is.null(ret.val[["inner.event.info"]][[i]])){rep(names(ret.val[["inner.event.info"]])[i], nrow(ret.val[["inner.event.info"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["inner.event.info"]] <- tmp; } } } class(ret.val) <- "CMA_per_episode"; ret.val$summary <- summary; return (ret.val); } } #' @export getMGs.CMA_per_episode <- function(x) { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_per_episode") || is.null(cma$medication.groups) ) return (NULL); return (cma$medication.groups); } #' getEventsToEpisodesMapping #' #' This function returns the event-to-episode mapping, if this information exists. #' #' There are cases where it is interesting to know which events belong to which #' episodes and which events have been actually used in computing the simple CMA #' for each episode. #' This information can be returned by \code{compute.treatment.episodes()} and #' \code{CMA_per_episode()} if the parameter \code{return.mapping.events.episodes} #' is set to \code{TRUE}. #' #' @param x Either a \code{data.frame} as returned by \code{compute.treatment.episodes()} #' or an \code{CMA_per_episode object}. #' @return The mapping between events and episodes, if it exists either as the #' attribute \code{mapping.episodes.to.events} of the \code{data.frame} or as the #' \code{mapping.episodes.to.events} component of the \code{CMA_per_episode object} #' object, or \code{NULL} otherwise. #' @export getEventsToEpisodesMapping <- function(x) { if( is.null(x) ) { return (NULL); } else if( inherits(x, "CMA_per_episode") && ("mapping.episodes.to.events" %in% names(x)) && !is.null(x$mapping.episodes.to.events) && inherits(x$mapping.episodes.to.events, "data.frame") ) { return (x$mapping.episodes.to.events); } else if( inherits(x, "data.frame") && ("mapping.episodes.to.events" %in% names(attributes(x))) && !is.null(attr(x,"mapping.episodes.to.events")) && inherits(attr(x,"mapping.episodes.to.events"), "data.frame") ) { return (attr(x,"mapping.episodes.to.events")); } else { return (NULL); } } #' @export getCMA.CMA_per_episode <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_per_episode") || !("CMA" %in% names(cma)) || is.null(cma$CMA) ) return (NULL); if( inherits(cma$CMA, "data.frame") || !flatten.medication.groups ) { return (cma$CMA); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$CMA); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$CMA), function(i) if(!is.null(cma$CMA[[i]])){rep(names(cma$CMA)[i], nrow(cma$CMA[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export getEventInfo.CMA_per_episode <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_per_episode") || !("event.info" %in% names(cma)) || is.null(cma$event.info) ) return (NULL); if( inherits(cma$event.info, "data.frame") || !flatten.medication.groups ) { return (cma$event.info); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$event.info); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$event.info), function(i) if(!is.null(cma$event.info[[i]])){rep(names(cma$event.info)[i], nrow(cma$event.info[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export getInnerEventInfo.CMA_per_episode <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_per_episode") || !("inner.event.info" %in% names(cma)) || is.null(cma$inner.event.info) ) return (NULL); if( inherits(cma$inner.event.info, "data.frame") || !flatten.medication.groups ) { return (cma$inner.event.info); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$inner.event.info); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$inner.event.info), function(i) if(!is.null(cma$inner.event.info[[i]])){rep(names(cma$inner.event.info)[i], nrow(cma$inner.event.info[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export subsetCMA.CMA_per_episode <- function(cma, patients, suppress.warnings=FALSE) { if( inherits(patients, "factor") ) patients <- as.character(patients); all.patients <- unique(cma$data[,cma$ID.colname]); patients.to.keep <- intersect(patients, all.patients); if( length(patients.to.keep) == length(all.patients) ) { # Keep all patients: return (cma); } if( length(patients.to.keep) == 0 ) { if( !suppress.warnings ) .report.ewms("No patients to subset on!\n", "error", "subsetCMA.CMA_per_episode", "AdhereR"); return (NULL); } if( length(patients.to.keep) < length(patients) && !suppress.warnings ) .report.ewms("Some patients in the subsetting set are not in the CMA itself and are ignored!\n", "warning", "subsetCMA.CMA_per_episode", "AdhereR"); ret.val <- cma; ret.val$data <- ret.val$data[ ret.val$data[,ret.val$ID.colname] %in% patients.to.keep, ]; if( !is.null(ret.val$event.info) ) { if( inherits(ret.val$event.info, "data.frame") ) { ret.val$event.info <- ret.val$event.info[ ret.val$event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( nrow(ret.val$event.info) == 0 ) ret.val$event.info <- NULL; } else if( is.list(ret.val$event.info) && length(ret.val$event.info) > 0 ) { ret.val$event.info <- lapply(ret.val$event.info, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } if( !is.null(ret.val$inner.event.info) ) { if( inherits(ret.val$inner.event.info, "data.frame") ) { ret.val$inner.event.info <- ret.val$inner.event.info[ ret.val$inner.event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( nrow(ret.val$inner.event.info) == 0 ) ret.val$inner.event.info <- NULL; } else if( is.list(ret.val$inner.event.info) && length(ret.val$inner.event.info) > 0 ) { ret.val$inner.event.info <- lapply(ret.val$inner.event.info, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } if( ("CMA" %in% names(ret.val)) && !is.null(ret.val$CMA) ) { if( inherits(ret.val$CMA, "data.frame") ) { ret.val$CMA <- ret.val$CMA[ ret.val$CMA[,ret.val$ID.colname] %in% patients.to.keep, ]; } else if( is.list(ret.val$CMA) && length(ret.val$CMA) > 0 ) { ret.val$CMA <- lapply(ret.val$CMA, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA_per_episode <- function(x, # the CMA_per_episode (or derived) object ..., # required for S3 consistency inline=FALSE, # print inside a line of text or as a separate, extended object? format=c("text", "latex", "markdown"), # the format to print to print.params=TRUE, # show the parameters? print.data=TRUE, # show the summary of the data? exclude.params=c("event.info", "inner.event.info", "mapping.episodes.to.events"), # if so, should I not print some? skip.header=FALSE, # should I print the generic header? cma.type=class(x)[1] ) { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) ) return (invisible(NULL)); if( format[1] == "text" ) { # Output text: if( !inline ) { # Extended print: if( !skip.header ) cat(paste0(cma.type,":\n")); if( print.params ) { params <- names(cma); params <- params[!(params %in% c("data",exclude.params))]; # exlude the 'data' (and any other requested) params from printing if( length(params) > 0 ) { if( "summary" %in% params ) { cat(paste0(" \"",cma$summary,"\"\n")); params <- params[!(params %in% "summary")]; } cat(" [\n"); for( p in params ) { if( p == "CMA" ) { cat(paste0(" ",p," = CMA results for ",nrow(cma[[p]])," patients\n")); } else if( p == "medication.groups" ) { if( !is.null(cma[[p]]) ) { cat(paste0(" ", p, " = ", nrow(cma[[p]]$defs), " [", ifelse(nrow(cma[[p]]$defs)<4, paste0("'",cma[[p]]$defs$name,"'", collapse=", "), paste0(paste0("'",cma[[p]]$defs$name[1:4],"'", collapse=", ")," ...")), "]\n")); } else { cat(paste0(" ", p, " = <NONE>\n")); } } else if( !is.null(cma[[p]]) && length(cma[[p]]) > 0 && !is.na(cma[[p]]) ) { cat(paste0(" ",p," = ",cma[[p]],"\n")); } } cat(" ]\n"); } if( print.data && !is.null(cma$data) ) { # Data summary: cat(paste0(" DATA: ",nrow(cma$data)," (rows) x ",ncol(cma$data)," (columns)"," [",length(unique(cma$data[,cma$ID.colname]))," patients]",".\n")); } } } else { # Inline print: cat(paste0(cma$summary,ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } } else if( format[1] == "latex" ) { # Output LaTeX: no difference between inline and not inline: cat(paste0("\\textbf{",cma$summary,"} (",cma.type,"):", ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } else if( format[1] == "markdown" ) { # Output Markdown: no difference between inline and not inline: cat(paste0("**",cma$summary,"** (",cma.type,"):", ifelse(print.data && !is.null(cma$data),paste0(" (on ",nrow(cma$data)," rows x ",ncol(cma$data)," columns",", ",length(unique(cma$data[,cma$ID.colname]))," patients",")"),""))); } else { .report.ewms("Unknown format for printing!\n", "error", "print.CMA_per_episode", "AdhereR"); return (invisible(NULL)); } } #' Plot CMA_per_episode and CMA_sliding_window objects. #' #' Plots the event data and the estimated CMA per treatment episode and sliding #' window, respectively. #' #' The x-axis represents time (either in days since the earliest date or as #' actual dates), with consecutive events represented as ascending on the y-axis. #' #' Each event is represented as a segment with style \code{lty.event} and line #' width \code{lwd.event} starting with a \code{pch.start.event} and ending with #' a \code{pch.end.event} character, coloured with a unique color as given by #' \code{col.cats}, extending from its start date until its end date. #' Consecutive events are thus represented on consecutive levels of the y-axis #' and are connected by a "continuation" line with \code{col.continuation} #' colour, \code{lty.continuation} style and \code{lwd.continuation} width; #' these continuation lines are purely visual guides helping to perceive the #' sequence of events, and carry no information about the avilability of #' medicine in this interval. #' #' Above these, the treatment episodes or the sliding windows are represented in #' a stacked manner from the earlieast (left, bottom of the stack) to the latest #' (right, top of the stack), each showing the CMA as percent fill (capped at #' 100\% even if CMA values may be higher) and also as text. #' #' The follow-up and the observation windows are plotted as empty an rectangle #' and as shaded rectangle, respectively (for some CMAs the observation window #' might be adjusted in which case the adjustment may also be plotted using a #' different shading). #' #' The kernel density ("smoothed histogram") of the CMA estimates across #' treatment episodes/sliding windows (if more than 2) can be visually #' represented as well in the left side of the figure (NB, their horizontal #' scales may be different across patients). #' #' When several patients are displayed on the same plot, they are organized #' vertically, and alternating bands (white and gray) help distinguish #' consecutive patients. #' Implicitely, all patients contained in the \code{cma} object will be plotted, #' but the \code{patients.to.plot} parameter allows the selection of a subset #' of patients. #' #' Finally, the y-axis shows the patient ID and possibly the CMA estimate as #' well. #' #' Any not explicitely defined arguments are passed to the simple CMA estimation #' and plotting function; therefore, for more info about possible estimation #' parameters plese see the help for the appropriate simple CMA, and for possible #' aesthetic tweaks, please see the help for their plotting. #' #' @param x A \emph{\code{CMA0}} or derived object, representing the CMA to #' plot #' @param patients.to.plot A vector of \emph{strings} containing the list of #' patient IDs to plot (a subset of those in the \code{cma} object), or #' \code{NULL} for all #' @param duration A \emph{number}, the total duration (in days) of the whole #' period to plot; in \code{NA} it is automatically determined from the event #' data such that the whole dataset fits. #' @param align.all.patients \emph{Logical}, should all patients be aligned #' (i.e., the actual dates are discarded and all plots are relative to the #' earliest date)? #' @param align.first.event.at.zero \emph{Logical}, should the first event be #' placed at the origin of the time axis (at 0)? #' @param show.period A \emph{string}, if "dates" show the actual dates at the #' regular grid intervals, while for "days" (the default) shows the days since #' the beginning; if \code{align.all.patients == TRUE}, \code{show.period} is #' taken as "days". #' @param period.in.days The \emph{number} of days at which the regular grid is #' drawn (or 0 for no grid). #' @param show.legend \emph{Logical}, should the legend be drawn? #' @param legend.x The position of the legend on the x axis; can be "left", #' "right" (default), or a \emph{numeric} value. #' @param legend.y The position of the legend on the y axis; can be "bottom" #' (default), "top", or a \emph{numeric} value. #' @param legend.bkg.opacity A \emph{number} between 0.0 and 1.0 specifying the #' opacity of the legend background. #' @param legend.cex,legend.cex.title The legend and legend title font sizes. #' @param cex,cex.axis,cex.lab \emph{numeric} values specifying the cex of the #' various types of text. #' @param show.cma \emph{Logical}, should the CMA type be shown in the title? #' @param xlab Named vector of x-axis labels to show for the two types of periods #' ("days" and "dates"), or a single value for both, or \code{NULL} for nothing. #' @param ylab Named vector of y-axis labels to show without and with CMA estimates, #' or a single value for both, or \code{NULL} for nonthing. #' @param title Named vector of titles to show for and without alignment, or a #' single value for both, or \code{NULL} for nonthing. #' @param col.cats A \emph{color} or a \emph{function} that specifies the single #' colour or the colour palette used to plot the different medication; by #' default \code{rainbow}, but we recommend, whenever possible, a #' colorblind-friendly palette such as \code{viridis} or \code{colorblind_pal}. #' @param unspecified.category.label A \emph{string} giving the name of the #' unspecified (generic) medication category. #' @param medication.groups.to.plot the names of the medication groups to plot or #' \code{NULL} (the default) for all. #' @param medication.groups.separator.show a \emph{boolean}, if \code{TRUE} (the #' default) visually mark the medication groups the belong to the same patient, #' using horizontal lines and alternating vertical lines. #' @param medication.groups.separator.lty,medication.groups.separator.lwd,medication.groups.separator.color #' graphical parameters (line type, line width and colour describing the visual #' marking og medication groups as beloning to the same patient. #' @param medication.groups.allother.label a \emph{string} giving the label to #' use for the implicit \code{__ALL_OTHERS__} medication group (defaults to "*"). #' @param lty.event,lwd.event,pch.start.event,pch.end.event The style of the #' event (line style, width, and start and end symbols). #' @param show.event.intervals \emph{Logical}, should the actual event intervals #' be shown? As per-episode and sliding windows might have overlapping intervals, #' it is better not to show them by default (\code{FALSE}). #' @param show.overlapping.event.intervals specifies how to plot the event #' intervals that appear in multiple sliding windows or episodes. We can plot #' how thye look in the \emph{first} sliding window or episode (the default), #' how they appear in the \emph{last}, pick the one that minimizes the gap #' (\emph{min gap}) or maximizes it (\emph{max gap}), or compute their #' \emph{average} across all sliding windows or episodes containing them. #' @param plot.events.vertically.displaced Should consecutive events be plotted #' on separate rows (i.e., separated vertically, the default) or on the same row? #' @param print.dose,cex.dose,print.dose.outline.col,print.dose.centered Print daily #' dose as a number and, if so, how (color, size, position...). #' @param plot.dose,lwd.event.max.dose,plot.dose.lwd.across.medication.classes #' Show dose through the width of the event lines and, if so, what the maximum #' width should be, and should this maximum be by medication class or overall. #' @param col.na The colour used for missing event data. #' @param col.continuation,lty.continuation,lwd.continuation The color, style #' and width of the contuniation lines connecting consecutive events. #' @param alternating.bands.cols The colors of the alternating vertical bands #' distinguishing the patients; can be \code{NULL} = don't draw the bandes; #' or a vector of colors. #' @param print.episode.or.sliding.window \emph{Logical}, should we show which #' events belong to which episode or sliding window? To work, the CMA must have #' been constructed with \code{return.mapping.events.episodes} or #' \code{return.mapping.events.sliding.window} set to \code{TRUE}, respectively. #' @param bw.plot \emph{Logical}, should the plot use grayscale only (i.e., the #' \code{\link[grDevices]{gray.colors}} function)? #' @param rotate.text \emph{Numeric}, the angle by which certain text elements #' (e.g., axis labels) should be rotated. #' @param force.draw.text \emph{Logical}, if \code{TRUE}, always draw text even #' if too big or too small #' @param print.CMA \emph{Logical}, should the CMA values be printed? #' @param CMA.cex ... and, if printed, what cex (\emph{numeric}) to use? #' @param plot.CMA \emph{Logical}, should the distribution of the CMA values #' across episodes/sliding windows be plotted? If \code{TRUE} (the default), the #' distribution is shown on the left-hand side of the plot, otherwise it is not. #' @param plot.CMA.as.histogram \emph{Logical}, should the CMA plot be a #' histogram or a (truncated) density plot? Please note that it is TRUE by #' deafult for CMA_per_episode and FALSE for CMA_sliding_window, because #' usually there are more sliding windows than episodes. Also, the density #' estimate cannot be estimated for less than three different values. #' @param plot.partial.CMAs.as Should the partial CMAs be plotted? Possible values #' are "stacked", "overlapping" or "timeseries", or \code{NULL} for no partial #' CMA plots. Please note that \code{plot.CMA} and \code{plot.partial.CMAs.as} #' are independent of each other. #' @param plot.partial.CMAs.as.stacked.col.bars,plot.partial.CMAs.as.stacked.col.border,plot.partial.CMAs.as.stacked.col.text #' If plotting the partial CMAs as stacked bars, define their graphical attributes. #' @param plot.partial.CMAs.as.timeseries.vspace,plot.partial.CMAs.as.timeseries.start.from.zero,plot.partial.CMAs.as.timeseries.col.dot,plot.partial.CMAs.as.timeseries.col.interval,plot.partial.CMAs.as.timeseries.col.text,plot.partial.CMAs.as.timeseries.interval.type,plot.partial.CMAs.as.timeseries.lwd.interval,plot.partial.CMAs.as.timeseries.alpha.interval,plot.partial.CMAs.as.timeseries.show.0perc,plot.partial.CMAs.as.timeseries.show.100perc #' If plotting the partial CMAs as imeseries, these are their graphical attributes. #' @param plot.partial.CMAs.as.overlapping.alternate,plot.partial.CMAs.as.overlapping.col.interval,plot.partial.CMAs.as.overlapping.col.text #' If plotting the partial CMAs as overlapping segments, these are their #' graphical attributes. #' @param CMA.plot.ratio A \emph{number}, the proportion of the total horizontal #' plot space to be allocated to the CMA plot. #' @param CMA.plot.col,CMA.plot.border,CMA.plot.bkg,CMA.plot.text \emph{Strings} #' giving the colours of the various components of the CMA plot. #' @param highlight.followup.window \emph{Logical}, should the follow-up window #' be plotted? #' @param followup.window.col The follow-up window colour. #' @param highlight.observation.window \emph{Logical}, should the observation #' window be plotted? #' @param observation.window.col,observation.window.opacity #' Attributes of the observation window (colour, transparency). #' @param min.plot.size.in.characters.horiz,min.plot.size.in.characters.vert #' \emph{Numeric}, the minimum size of the plotting surface in characters; #' horizontally (min.plot.size.in.characters.horiz) refers to the the whole #' duration of the events to plot; vertically (min.plot.size.in.characters.vert) #' refers to a single event. If the plotting is too small, possible solutions #' might be: if within \code{RStudio}, try to enlarge the "Plots" panel, or #' (also valid outside \code{RStudio} but not if using \code{RStudio server} #' start a new plotting device (e.g., using \code{X11()}, \code{quartz()} #' or \code{windows()}, depending on OS) or (works always) save to an image #' (e.g., \code{jpeg(...); ...; dev.off()}) and display it in a viewer. #' @param max.patients.to.plot \emph{Numeric}, the maximum patients to attempt #' to plot. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param export.formats a \emph{string} giving the formats to export the figure #' to (by default \code{NULL}, meaning no exporting); can be any combination of #' "svg" (just an \code{SVG} file), "html" (\code{SVG} + \code{HTML} + \code{CSS} #' + \code{JavaScript}, all embedded within one \code{HTML} document), "jpg", #' "png", "webp", "ps" or "pdf". #' @param export.formats.fileprefix a \emph{string} giving the file name prefix #' for the exported formats (defaults to "AdhereR-plot"). #' @param export.formats.height,export.formats.width \emph{numbers} giving the #' desired dimensions (in pixels) for the exported figure (defaults to sane #' values if \code{NA}). #' @param export.formats.save.svg.placeholder a \emph{logical}, if TRUE, save an #' image placeholder of type given by \code{export.formats.svg.placeholder.type} #'for the \code{SVG} image. #' @param export.formats.svg.placeholder.type a \emph{string}, giving the type of #' placeholder for the \code{SVG} image to save; can be "jpg", #' "png" (the default) or "webp". #' @param export.formats.svg.placeholder.embed a \emph{logical}, if \code{TRUE}, #' embed the placeholder image in the HTML document (if any) using \code{base64} #' encoding, otherwise (the default) leave it as an external image file (works #' only when an \code{HTML} document is exported and only for \code{JPEG} or #' \code{PNG} images. #' @param export.formats.html.template,export.formats.html.javascript,export.formats.html.css #' \emph{character strings} or \code{NULL} (the default) giving the path to the #' \code{HTML}, \code{JavaScript} and \code{CSS} templates, respectively, to be #' used when generating the HTML+CSS semi-interactive plots; when \code{NULL}, #' the default ones included with the package will be used. If you decide to define #' new templates please use the default ones for inspiration and note that future #' version are not guaranteed to be backwards compatible! #' @param export.formats.directory a \emph{string}; if exporting, which directory #' to export to; if \code{NA} (the default), creates the files in a temporary #' directory. #' @param generate.R.plot a \emph{logical}, if \code{TRUE} (the default), #' generate the standard (base \code{R}) plot for plotting within \code{R}. #' @param do.not.draw.plot a \emph{logical}, if \code{TRUE} (\emph{not} the default), #' does not draw the plot itself, but only the legend (if \code{show.legend} is #' \code{TRUE}) at coordinates (0,0) irrespective of the given legend coordinates. #' This is intended to allow (together with the \code{get.legend.plotting.area()} #' function) the separate plotting of the legend. #' @param ... other parameters (to be passed to the estimation and plotting of #' the simple CMA) #' #' @seealso See the simple CMA estimation \code{\link[AdhereR]{CMA1}} #' to \code{\link[AdhereR]{CMA9}} and plotting \code{\link[AdhereR]{plot.CMA1}} #' functions for extra parameters. #' #' @examples #' \dontrun{ #' cmaW <- CMA_sliding_window(CMA=CMA1, #' data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=0, #' observation.window.start=0, #' observation.window.duration=365, #' sliding.window.start=0, #' sliding.window.start.unit="days", #' sliding.window.duration=90, #' sliding.window.duration.unit="days", #' sliding.window.step.duration=7, #' sliding.window.step.unit="days", #' sliding.window.no.steps=NA, #' date.format="%m/%d/%Y" #' ); #' plot(cmaW, patients.to.plot=c("1","2")); #' cmaE <- CMA_per_episode(CMA=CMA1, #' data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=0, #' observation.window.start=0, #' observation.window.duration=365, #' date.format="%m/%d/%Y" #' ); #' plot(cmaE, patients.to.plot=c("1","2"));} #' @export plot.CMA_per_episode <- function(x, # the CMA_per_episode or CMA_sliding_window (or derived) object patients.to.plot=NULL, # list of patient IDs to plot or NULL for all duration=NA, # duration and end period to plot in days (if missing, determined from the data) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? and, if so, place the first event as the horizintal 0? show.period=c("dates","days")[2], # draw vertical bars at regular interval as dates or days? period.in.days=90, # the interval (in days) at which to draw veritcal lines show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend params and position cex=1.0, cex.axis=0.75, cex.lab=1.0, # various graphical params show.cma=TRUE, # show the CMA type xlab=c("dates"="Date", "days"="Days"), # Vector of x labels to show for the two types of periods, or a single value for both, or NULL for nothing ylab=c("withoutCMA"="patient", "withCMA"="patient (& CMA)"), # Vector of y labels to show without and with CMA estimates, or a single value for both, or NULL ofr nonthing title=c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns"), # Vector of titles to show for and without alignment, or a single value for both, or NULL for nonthing col.cats=rainbow, # single color or a function mapping the categories to colors unspecified.category.label="drug", # the label of the unspecified category of medication medication.groups.to.plot=NULL, # the names of the medication groups to plot (by default, all) medication.groups.separator.show=TRUE, medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", # group medication events by patient? medication.groups.allother.label="*", # the label to use for the __ALL_OTHERS__ medication class (defaults to *) lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, # event style show.event.intervals=FALSE, # per-episode and sliding windows might have overlapping intervals, so better not to show them by default show.overlapping.event.intervals=c("first", "last", "min gap", "max gap", "average")[1], # how to plot overlapping event intervals (relevant for sliding windows and per episode) plot.events.vertically.displaced=TRUE, # display the events on different lines (vertical displacement) or not (defaults to TRUE)? print.dose=FALSE, cex.dose=0.75, print.dose.outline.col="white", print.dose.centered=FALSE, # print daily dose plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # draw daily dose as line width col.na="lightgray", # color for mising data col.continuation="black", lty.continuation="dotted", lwd.continuation=1, # style of the contuniation lines connecting consecutive events print.CMA=TRUE, CMA.cex=0.50, # print CMA next to the participant's ID? plot.CMA=TRUE, # plot the CMA next to the participant ID? plot.CMA.as.histogram=TRUE, # plot CMA as a histogram or as a density plot? plot.partial.CMAs.as=c("stacked", "overlapping", "timeseries")[1], # how to plot the "partial" (i.e., intervals/episodes) CMAs (NULL for none)? plot.partial.CMAs.as.stacked.col.bars="gray90", plot.partial.CMAs.as.stacked.col.border="gray30", plot.partial.CMAs.as.stacked.col.text="black", plot.partial.CMAs.as.timeseries.vspace=7, # how much vertical space to reserve for the timeseries plot (in character lines) plot.partial.CMAs.as.timeseries.start.from.zero=TRUE, #show the vertical axis start at 0 or at the minimum actual value (if positive)? plot.partial.CMAs.as.timeseries.col.dot="darkblue", plot.partial.CMAs.as.timeseries.col.interval="gray70", plot.partial.CMAs.as.timeseries.col.text="firebrick", # setting any of these to NA results in them not being plotted plot.partial.CMAs.as.timeseries.interval.type=c("none", "segments", "arrows", "lines", "rectangles")[2], # how to show the covered intervals plot.partial.CMAs.as.timeseries.lwd.interval=1, # line width for some types of intervals plot.partial.CMAs.as.timeseries.alpha.interval=0.25, # the transparency of the intervales (when drawn as rectangles) plot.partial.CMAs.as.timeseries.show.0perc=TRUE, plot.partial.CMAs.as.timeseries.show.100perc=FALSE, #show the 0% and 100% lines? plot.partial.CMAs.as.overlapping.alternate=TRUE, # should successive intervals be plotted low/high? plot.partial.CMAs.as.overlapping.col.interval="gray70", plot.partial.CMAs.as.overlapping.col.text="firebrick", # setting any of these to NA results in them not being plotted CMA.plot.ratio=0.10, # the proportion of the total horizontal plot to be taken by the CMA plot CMA.plot.col="lightgreen", CMA.plot.border="darkgreen", CMA.plot.bkg="aquamarine", CMA.plot.text=CMA.plot.border, # attributes of the CMA plot highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.opacity=0.3, print.episode.or.sliding.window=FALSE, # should we print the episode or sliding window to which an event belongs? alternating.bands.cols=c("white", "gray95"), # the colors of the alternating vertical bands across patients (NULL=don't draw any; can be >= 1 color) bw.plot=FALSE, # if TRUE, override all user-given colors and replace them with a scheme suitable for grayscale plotting rotate.text=-60, # some text (e.g., axis labels) may be rotated by this much degrees force.draw.text=FALSE, # if true, always draw text even if too big or too small min.plot.size.in.characters.horiz=0, min.plot.size.in.characters.vert=0, # the minimum plot size (in characters: horizontally, for the whole duration, vertically, per event (and, if shown, per episode/sliding window)) max.patients.to.plot=100, # maximum number of patients to plot export.formats=NULL, # the formats to export the figure to (by default, none); can be any subset of "svg" (just SVG file), "html" (SVG + HTML + CSS + JavaScript all embedded within the HTML document), "jpg", "png", "webp", "ps" and "pdf" export.formats.fileprefix="AdhereR-plot", # the file name prefix for the exported formats export.formats.height=NA, export.formats.width=NA, # desired dimensions (in pixels) for the exported figure (defaults to sane values) export.formats.save.svg.placeholder=TRUE, export.formats.svg.placeholder.type=c("jpg", "png", "webp")[2], export.formats.svg.placeholder.embed=FALSE, # save a placeholder for the SVG image? export.formats.html.template=NULL, export.formats.html.javascript=NULL, export.formats.html.css=NULL, # HTML, JavaScript and CSS templates for exporting HTML+SVG export.formats.directory=NA, # if exporting, which directory to export to (if not give, creates files in the temporary directory) generate.R.plot=TRUE, # generate standard (base R) plot for plotting within R? do.not.draw.plot=FALSE, # if TRUE, don't draw the actual plot, but only the legend (if required) suppress.warnings=FALSE, # suppress warnings? ... ) { #if( show.event.intervals ) #{ # if( !suppress.warnings ) .report.ewms("show.event.intervals=TRUE is not yet implemented in plotting sliding windows and per episodes!\n", "message", "plot", "AdhereR"); # show.event.intervals <- FALSE; #} .plot.CMAs(x, patients.to.plot=patients.to.plot, duration=duration, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, show.period=show.period, period.in.days=period.in.days, show.legend=show.legend, legend.x=legend.x, legend.y=legend.y, legend.bkg.opacity=legend.bkg.opacity, legend.cex=legend.cex, legend.cex.title=legend.cex.title, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, show.cma=show.cma, xlab=xlab, ylab=ylab, title=title, col.cats=col.cats, unspecified.category.label=unspecified.category.label, medication.groups.to.plot=medication.groups.to.plot, medication.groups.separator.show=medication.groups.separator.show, medication.groups.separator.lty=medication.groups.separator.lty, medication.groups.separator.lwd=medication.groups.separator.lwd, medication.groups.separator.color=medication.groups.separator.color, medication.groups.allother.label=medication.groups.allother.label, lty.event=lty.event, lwd.event=lwd.event, show.event.intervals=show.event.intervals, show.overlapping.event.intervals=show.overlapping.event.intervals, plot.events.vertically.displaced=plot.events.vertically.displaced, pch.start.event=pch.start.event, pch.end.event=pch.end.event, print.dose=print.dose, cex.dose=cex.dose, print.dose.outline.col=print.dose.outline.col, print.dose.centered=print.dose.centered, plot.dose=plot.dose, lwd.event.max.dose=lwd.event.max.dose, plot.dose.lwd.across.medication.classes=plot.dose.lwd.across.medication.classes, col.na=col.na, print.CMA=print.CMA, CMA.cex=CMA.cex, plot.CMA=plot.CMA, plot.CMA.as.histogram=plot.CMA.as.histogram, CMA.plot.ratio=CMA.plot.ratio, CMA.plot.col=CMA.plot.col, CMA.plot.border=CMA.plot.border, CMA.plot.bkg=CMA.plot.bkg, CMA.plot.text=CMA.plot.text, plot.partial.CMAs.as=plot.partial.CMAs.as, plot.partial.CMAs.as.stacked.col.bars=plot.partial.CMAs.as.stacked.col.bars, plot.partial.CMAs.as.stacked.col.border=plot.partial.CMAs.as.stacked.col.border, plot.partial.CMAs.as.stacked.col.text=plot.partial.CMAs.as.stacked.col.text, plot.partial.CMAs.as.timeseries.vspace=plot.partial.CMAs.as.timeseries.vspace, plot.partial.CMAs.as.timeseries.start.from.zero=plot.partial.CMAs.as.timeseries.start.from.zero, plot.partial.CMAs.as.timeseries.col.dot=plot.partial.CMAs.as.timeseries.col.dot, plot.partial.CMAs.as.timeseries.col.interval=plot.partial.CMAs.as.timeseries.col.interval, plot.partial.CMAs.as.timeseries.col.text=plot.partial.CMAs.as.timeseries.col.text, plot.partial.CMAs.as.timeseries.interval.type=plot.partial.CMAs.as.timeseries.interval.type, plot.partial.CMAs.as.timeseries.lwd.interval=plot.partial.CMAs.as.timeseries.lwd.interval, plot.partial.CMAs.as.timeseries.alpha.interval=plot.partial.CMAs.as.timeseries.alpha.interval, plot.partial.CMAs.as.timeseries.show.0perc=plot.partial.CMAs.as.timeseries.show.0perc, plot.partial.CMAs.as.timeseries.show.100perc=plot.partial.CMAs.as.timeseries.show.100perc, plot.partial.CMAs.as.overlapping.alternate=plot.partial.CMAs.as.overlapping.alternate, plot.partial.CMAs.as.overlapping.col.interval=plot.partial.CMAs.as.overlapping.col.interval, plot.partial.CMAs.as.overlapping.col.text=plot.partial.CMAs.as.overlapping.col.text, highlight.followup.window=highlight.followup.window, followup.window.col=followup.window.col, highlight.observation.window=highlight.observation.window, observation.window.col=observation.window.col, observation.window.opacity=observation.window.opacity, print.episode.or.sliding.window=print.episode.or.sliding.window, alternating.bands.cols=alternating.bands.cols, bw.plot=bw.plot, rotate.text=rotate.text, force.draw.text=force.draw.text, min.plot.size.in.characters.horiz=min.plot.size.in.characters.horiz, min.plot.size.in.characters.vert=min.plot.size.in.characters.vert, max.patients.to.plot=max.patients.to.plot, export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.height=export.formats.height, export.formats.width=export.formats.width, export.formats.save.svg.placeholder=export.formats.save.svg.placeholder, export.formats.svg.placeholder.type=export.formats.svg.placeholder.type, export.formats.svg.placeholder.embed=export.formats.svg.placeholder.embed, export.formats.html.template=export.formats.html.template, export.formats.html.javascript=export.formats.html.javascript, export.formats.html.css=export.formats.html.css, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot, do.not.draw.plot=do.not.draw.plot, suppress.warnings=suppress.warnings); } #' CMA_sliding_window constructor. #' #' Applies a given CMA to each sliding window and constructs a #' CMA_sliding_window object. #' #' \code{CMA_sliding_window} first computes a set of fixed-size (possibly partly #' overlapping) sliding windows, #' each sliding to the right by a fixed timelag, #' and then, for each of them, it computes the given "simple" CMA. #' Thus, as opposed to the "simple" CMAs 1 to 9, it returns a set of CMAs, with #' possibly more than one element. #' #' It is highly similar to \code{\link{CMA_per_episode}} which computes a CMA #' for a set of treatment episodes. #' #' @param CMA.to.apply A \emph{string} giving the name of the CMA function (1 to #' 9) that will be computed for each treatment episode. #' @param data A \emph{\code{data.frame}} containing the events used to compute #' the CMA. Must contain, at a minimum, the patient unique ID, the event date #' and duration, and might also contain the daily dosage and medication type #' (the actual column names are defined in the following four parameters). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID; must be present. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param medication.groups A \emph{vector} of characters defining medication #' groups or the name of a column in \code{data} that defines such groups. #' The names of the vector are the medication group unique names, while #' the content defines them as logical expressions. While the names can be any #' string of characters except "\}", it is recommended to stick to the rules for #' defining vector names in \code{R}. For example, #' \code{c("A"="CATEGORY == 'medA'", "AA"="{A} & PERDAY < 4"} defines two #' medication groups: \emph{A} which selects all events of type "medA", and #' \emph{B} which selects all events already defined by "A" but with a daily #' dose lower than 4. If \code{NULL}, no medication groups are defined. If #' medication groups are defined, there is one CMA estimate for each group; #' moreover, there is a special group \emph{__ALL_OTHERS__} automatically defined #' containing all observations \emph{not} covered by any of the explicitly defined #' groups. #' @param flatten.medication.groups \emph{Logical}, if \code{FALSE} (the default) #' then the \code{CMA} and \code{event.info} components of the object are lists #' with one medication group per element; otherwise, they are \code{data.frame}s #' with an extra column containing the medication group (its name is given by #' \code{medication.groups.colname}). #' @param medication.groups.colname a \emph{string} (defaults to ".MED_GROUP_ID") #' giving the name of the column storing the group name when #' \code{flatten.medication.groups} is \code{TRUE}. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type. #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage. #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date} or a string #' that conforms to the format specified in \code{date.format}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.start.per.medication.group a \emph{logical}: if there are #' medication groups defined and this is \code{TRUE}, then the first event #' considered for the follow-up window start is relative to each medication group #' separately, otherwise (the default) it is relative to the patient. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider not #' covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). #' @param sliding.window.start,sliding.window.start.unit,sliding.window.duration,sliding.window.duration.unit the definition of the first sliding window #' (see the follow-up window parameters above for details). #' @param sliding.window.step.duration,sliding.window.step.unit if not missing #' (\code{NA}), these give the step (or "jump") to the right of the sliding #' window in time units. #' @param sliding.window.no.steps a \emph{integer} specifying the desired number #' of sliding windows to cover the observation window (if possible); trumps #' \code{sliding.window.step.duration} and \code{sliding.window.step.unit}. #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param event.interval.colname A \emph{string}, the name of a newly-created #' column storing the number of days between the start of the current event and #' the start of the next one; the default value "event.interval" should be #' changed only if there is a naming conflict with a pre-existing #' "event.interval" column in \code{event.info}. #' @param gap.days.colname A \emph{string}, the name of a newly-created column #' storing the number of days when medication was not available (i.e., the #' "gap days"); the default value "gap.days" should be changed only if there is #' a naming conflict with a pre-existing "gap.days" column in \code{event.info}. #' @param return.inner.event.info \emph{Logical} specifying if the function #' should also return the event.info for all the individual events in each #' sliding window; by default it is \code{FALSE} as this information is useful #' only in very specific cases (e.g., plotting the event intervals) and adds a #' small but non-negligible computational overhead. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param return.mapping.events.sliding.window A \emph{Logical}, if \code{TRUE} then #' the mapping between events and sliding windows is returned as the component #' \code{mapping.windows.to.events}, which is a \code{data.table} giving, for #' each sliding window, the events that belong to it (an event is given by its row #' number in the \code{data}). #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA_sliding_window} with the #' following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, #' as given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{computed.CMA} the class name of the computed CMA. #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column) and sliding #' window, with columns: #' \itemize{ #' \item \code{ID.colname} the patient ID as given by the \code{ID.colname} #' parameter. #' \item \code{window.ID} the unique window ID (within patients). #' \item \code{window.start} the window's start date (as a \code{Date} #' object). #' \item \code{window.end} the window's end date (as a \code{Date} object). #' \item \code{CMA} the window's estimated CMA. #' } #' } #' Please note that if \code{medication.groups} are defined, then the \code{CMA} #' and \code{event.info} are named lists, each element containing the CMA and #' event.info corresponding to a single medication group (the element's name). #' @seealso \code{\link{CMA_per_episode}} is very similar, computing a "simple" #' CMA for each of the treatment episodes. #' The "simple" CMAs that can be computed comprise \code{\link{CMA1}}, #' \code{\link{CMA2}}, \code{\link{CMA3}}, \code{\link{CMA4}}, #' \code{\link{CMA5}}, \code{\link{CMA6}}, \code{\link{CMA7}}, #' \code{\link{CMA8}}, \code{\link{CMA9}}, as well as user-defined classes #' derived from \code{\link{CMA0}} that have a \code{CMA} component giving the #' estimated CMA per patient as a \code{data.frame}. #' If \code{return.mapping.events.sliding.window} is \code{TRUE}, then this also has an #' attribute \code{mapping.windows.to.events} that gives the mapping between #' episodes and events as a \code{data.table} with the following columns: #' \itemize{ #' \item \code{patid} the patient ID. #' \item \code{window.ID} the episode unique ID (increasing sequentially). #' \item \code{event.index.in.data} the event given by its row number in the \code{data}. #' } #' @examples #' \dontrun{ #' cmaW <- CMA_sliding_window(CMA="CMA1", #' data=med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' carry.only.for.same.medication=FALSE, #' consider.dosage.change=FALSE, #' followup.window.start=0, #' observation.window.start=0, #' observation.window.duration=365, #' sliding.window.start=0, #' sliding.window.start.unit="days", #' sliding.window.duration=90, #' sliding.window.duration.unit="days", #' sliding.window.step.duration=7, #' sliding.window.step.unit="days", #' sliding.window.no.steps=NA, #' date.format="%m/%d/%Y" #' );} #' @export CMA_sliding_window <- function( CMA.to.apply, # the name of the CMA function (e.g., "CMA1") to be used data, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Groups of medication classes: medication.groups=NULL, # a named vector of medication group definitions, the name of a column in the data that defines the groups, or NULL flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID", # if medication.groups were defined, return CMAs and event.info as single data.frame? # Various types methods of computing gaps: carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.start.per.medication.group=FALSE, # if there are medication groups and this is TRUE, then the first event is relative to each medication group separately, otherwise is relative to the patient followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1],# the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Sliding window: sliding.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) sliding.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.duration=90, # the duration of the sliding window in time units (NA = undefined) sliding.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.step.duration=30, # the step ("jump") of the sliding window in time units (NA = undefined) sliding.window.step.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.no.steps=NA, # the number of steps to jump; has priority over setp specification return.inner.event.info=FALSE, # should we return the event.info for all the individual events in each sliding window? # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary="CMA per sliding window", # The description of the output (added) columns: event.interval.colname="event.interval", # contains number of days between the start of current event and the start of the next gap.days.colname="gap.days", # contains the number of days when medication was not available # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? return.mapping.events.sliding.window=FALSE, # return the mapping of events to sliding windows? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=FALSE, # used internally to suppress the check that we don't use special argument names # extra parameters to be sent to the CMA function: ... ) { # Preconditions: if( is.numeric(sliding.window.start) && sliding.window.start < 0 ) { if( !suppress.warnings ) .report.ewms("The sliding window must start a positive number of time units after the start of the observation window!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( !inherits(sliding.window.start,"Date") && !is.numeric(sliding.window.start) && !(sliding.window.start %in% names(data)) ) { if( !suppress.warnings ) .report.ewms("The sliding window start must be a valid column name!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( !(sliding.window.start.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The sliding window start unit is not recognized!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( !is.numeric(sliding.window.duration) || sliding.window.duration <= 0 ) { if( !suppress.warnings ) .report.ewms("The sliding window duration must be greater than 0!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( !(sliding.window.duration.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The sliding window duration unit is not recognized!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( is.numeric(sliding.window.step.duration) && sliding.window.step.duration < 1 ) { if( !suppress.warnings ) .report.ewms("The sliding window's step duration must be at least 1 unit!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( !(sliding.window.step.unit %in% c("days", "weeks", "months", "years") ) ) { if( !suppress.warnings ) .report.ewms("The sliding window's step duration unit is not recognized!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } if( is.numeric(sliding.window.no.steps) && sliding.window.no.steps < 1 ) { if( !suppress.warnings ) .report.ewms("The sliding window must move at least once!\n", "error", "CMA_sliding_window", "AdhereR") return (NULL); } # Get the CMA function corresponding to the name: if( !(is.character(CMA.to.apply) || is.factor(CMA.to.apply)) ) { if( !suppress.warnings ) .report.ewms(paste0("'CMA.to.apply' must be a string contining the name of the simple CMA to apply!\n)"), "error", "CMA_sliding_window", "AdhereR"); return (NULL); } CMA.FNC <- switch(as.character(CMA.to.apply), # if factor, force it to string "CMA1" = CMA1, "CMA2" = CMA2, "CMA3" = CMA3, "CMA4" = CMA4, "CMA5" = CMA5, "CMA6" = CMA6, "CMA7" = CMA7, "CMA8" = CMA8, "CMA9" = CMA9, {if( !suppress.warnings ) .report.ewms(paste0("Unknown 'CMA.to.apply' '",CMA.to.apply,"': defaulting to CMA0!\n)"), "warning", "CMA_sliding_window", "AdhereR"); CMA0;}); # by default, fall back to CMA0 # Default argument values and overrides: def.vals <- formals(CMA.FNC); if( CMA.to.apply %in% c("CMA1", "CMA2", "CMA3", "CMA4") ) { carryover.into.obs.window <- carryover.within.obs.window <- FALSE; if( !is.na(carry.only.for.same.medication) && carry.only.for.same.medication && !suppress.warnings ) .report.ewms("'carry.only.for.same.medication' cannot be defined for CMAs 1-4!\n", "warning", "CMA_sliding_window", "AdhereR"); carry.only.for.same.medication <- FALSE; if( !is.na(consider.dosage.change) && consider.dosage.change && !suppress.warnings ) .report.ewms("'consider.dosage.change' cannot be defined for CMAs 1-4!\n", "warning", "CMA_sliding_window", "AdhereR"); consider.dosage.change <- FALSE; } else if( CMA.to.apply %in% c("CMA5", "CMA6") ) { carryover.into.obs.window <- FALSE; carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else if( CMA.to.apply %in% c("CMA7", "CMA8", "CMA9") ) { carryover.into.obs.window <- carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else { if( !suppress.warnings ) .report.ewms("I know how to do CMA sliding windows only for CMAs 1 to 9!\n", "error", "CMA_sliding_window", "AdhereR"); return (NULL); } # Create the return value skeleton and check consistency: ret.val <- CMA0(data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, medication.groups=medication.groups, flatten.medication.groups=flatten.medication.groups, medication.groups.colname=medication.groups.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.start.per.medication.group=followup.window.start.per.medication.group, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, summary=NA); if( is.null(ret.val) ) return (NULL); # The followup.window.start and observation.window.start might have been converted to Date: followup.window.start <- ret.val$followup.window.start; observation.window.start <- ret.val$observation.window.start; # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Auxiliary internal function: Compute the CMA for a given patient: .process.patient <- function(data4ID) { n.events <- nrow(data4ID); # cache number of events if( n.events < 1 ) return (NULL); # Compute the sliding windows for this patient: start.date <- .add.time.interval.to.date(data4ID$.OBS.START.DATE[1], sliding.window.start, sliding.window.start.unit, suppress.warnings); # when do the windows start? sliding.duration <- as.numeric(data4ID$.OBS.END.DATE[1] - start.date) - sliding.window.duration.in.days; # the effective duration to be covered with sliding windows if( sliding.duration < 0) return (NULL); # the sliding window is longer than the available time in the observation window if( is.na(sliding.window.no.steps) ) { # Compute the number of steps required from the step size: sliding.window.no.steps <- (sliding.duration / sliding.window.step.duration.in.days) + 1; } else if( sliding.window.no.steps > 1 ) { # Compute the step size to optimally cover the duration (possibly adjust the number of steps, too): sliding.window.step.duration.in.days <- (sliding.duration / (sliding.window.no.steps - 1)); sliding.window.step.duration.in.days <- max(1, min(sliding.window.duration.in.days, sliding.window.step.duration.in.days)); # make sure we don't overdue it sliding.window.no.steps <- min(((sliding.duration / sliding.window.step.duration.in.days) + 1), sliding.duration); # adjust the number of steps just in case } else { # Only one sliding window: sliding.window.step.duration.in.days <- 0; } if( sliding.window.no.steps < 1 || sliding.window.step.duration.in.days < 0 ) return (NULL); # Expand the participant data by replicating it for each consecutive sliding window: data4ID.wnds <- cbind(".WND.ID" =rep(1:sliding.window.no.steps, each=n.events), data4ID, ".WND.START.DATE"=rep(as.Date(vapply(1:sliding.window.no.steps, function(i) .add.time.interval.to.date(start.date, (i-1)*sliding.window.step.duration.in.days, "days", suppress.warnings), numeric(1)), origin=lubridate::origin), each=n.events), ".WND.DURATION" =sliding.window.duration.in.days); setkeyv(data4ID.wnds, ".WND.ID"); # Apply the desired CMA to all the windows: if(length(dot.args <- list(...)) > 0 && "arguments.that.should.not.be.defined" %in% names(dot.args)) # check if arguments.that.should.not.be.defined is passed in the ... argument { # Avoid passing again arguments.that.should.not.be.defined to the CMA function: cma <- CMA.FNC(data=as.data.frame(data4ID.wnds), ID.colname=".WND.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".WND.START.DATE", observation.window.duration=".WND.DURATION", observation.window.duration.unit="days", date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, # we know we're using special columns, so supress this check ...); } else { # Temporarily avoid warnings linked to rewriting some CMA arguments by passing it arguments.that.should.not.be.defined=NULL: cma <- CMA.FNC(data=as.data.frame(data4ID.wnds), ID.colname=".WND.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".WND.START.DATE", observation.window.duration=".WND.DURATION", observation.window.duration.unit="days", date.format=date.format, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, # we know we're using special columns, so supress this check arguments.that.should.not.be.defined=NULL, ...); } if( is.null(cma) ) return (NULL); # Unpack the data fo returning: wnd.info <- data4ID.wnds[, list(".WND.START"=.WND.START.DATE[1], # the start ".WND.END"=.add.time.interval.to.date(.WND.START.DATE[1], sliding.window.duration.in.days, "days", suppress.warnings)), # and end by=.WND.ID]; # for each window wnd.info <- cbind(merge(wnd.info, cma$CMA, by=".WND.ID", all=TRUE), "CMA.to.apply"=class(cma)[1]); setnames(wnd.info, c("window.ID", "window.start", "window.end", "CMA", "CMA.to.apply")); cma$event.info$..ORIGINAL.ROW.ORDER.IN.DATA.. <- data4ID.wnds$..ORIGINAL.ROW.ORDER..[ cma$event.info$..ORIGINAL.ROW.ORDER.. ]; # restore the row numbers in the original data if( return.inner.event.info || return.mapping.events.sliding.window ) { # Add the event.info to also return it: wnd.info <- merge(wnd.info, cma$event.info, by.x="window.ID", by.y=".WND.ID", all=TRUE); } return (as.data.frame(wnd.info)); } # Compute the real observation windows (might differ per patient) only once per patient (speed things up & the observation window is the same for all events within a patient): #patinfo.cols <- which(names(data) %in% c(ID.colname, event.date.colname, event.duration.colname, event.daily.dose.colname, medication.class.colname)); #tmp <- as.data.frame(data); tmp <- tmp[!duplicated(tmp[,ID.colname]),patinfo.cols]; # the reduced dataset for computing the actual OW: tmp <- as.data.frame(data); tmp <- tmp[!duplicated(tmp[,ID.colname]),]; # the reduced dataset for computing the actual OW: event.info2 <- compute.event.int.gaps(data=tmp, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks, return.data.table=TRUE); if( is.null(event.info2) ) return (NULL); # Merge the observation window start and end dates back into the data: data <- merge(data, event.info2[,c(ID.colname, ".OBS.START.DATE", ".OBS.END.DATE"),with=FALSE], all.x=TRUE); setnames(data, ncol(data)-c(1,0), c(".OBS.START.DATE.PRECOMPUTED", ".OBS.END.DATE.PRECOMPUTED")); if( return.inner.event.info || return.mapping.events.sliding.window ) { CMA.and.event.info <- data[, .process.patient(.SD), by=ID.colname ]; # contains both the CMAs per sliding window and the event.info's for each event CMA <- unique(CMA.and.event.info[,1:6,with=FALSE]); # the per-window CMAs... inner.event.info <- CMA.and.event.info[,c(1,2,7:ncol(CMA.and.event.info)),with=FALSE]; # ...and the event info for each event within the sliding windows return (list("CMA"=CMA, "event.info"=event.info2[,c(ID.colname, ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE"), with=FALSE], "inner.event.info"=inner.event.info)); } else { CMA <- data[, .process.patient(.SD), by=ID.colname ]; # contains just the CMAs per sliding window return (list("CMA"=CMA, "event.info"=event.info2[,c(ID.colname, ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE"), with=FALSE])); } } # Convert the sliding window duration and step in days: sliding.window.duration.in.days <- switch(sliding.window.duration.unit, "days"=sliding.window.duration, "weeks"=sliding.window.duration * 7, "months"=sliding.window.duration * 30, "years"=sliding.window.duration * 365, sliding.window.duration); sliding.window.step.duration.in.days <- switch(sliding.window.step.unit, "days"=sliding.window.step.duration, "weeks"=sliding.window.step.duration * 7, "months"=sliding.window.step.duration * 30, "years"=sliding.window.step.duration * 365, sliding.window.step.duration); # Convert to data.table, cache event date as Date objects, and key by patient ID and event date data.copy <- data.table(data); data.copy[, .DATE.as.Date := as.Date(get(event.date.colname),format=date.format)]; # .DATE.as.Date: convert event.date.colname from formatted string to Date data.copy$..ORIGINAL.ROW.ORDER.. <- 1:nrow(data.copy); # preserve the original order of the rows (needed for medication groups) setkeyv(data.copy, c(ID.colname, ".DATE.as.Date")); # key (and sorting) by patient ID and event date ## Computing the inner.event.info makes sense only for non-overlapping sliding windows: #if( return.inner.event.info && (sliding.window.duration.in.days > sliding.window.step.duration.in.days) ) #{ # if( !suppress.warnings ) .report.ewms("Computing the inner.event.info makes sense only for non-overlapping sliding windows.\n", "warning", "CMA_sliding_windows", "AdhereR"); # return.inner.event.info <- FALSE; #} # Are there medication groups? if( is.null(mg <- getMGs(ret.val)) ) { # Nope: do a single estimation on the whole dataset: # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || !inherits(tmp$CMA,"data.frame") || is.null(tmp$event.info) ) return (NULL); # Construct the return object: class(ret.val) <- "CMA_sliding_window"; ret.val$event.info <- as.data.frame(tmp$event.info); ret.val$computed.CMA <- as.character(tmp$CMA$CMA.to.apply[1]); ret.val$sliding.window.start <- sliding.window.start; ret.val$sliding.window.start.unit <- sliding.window.start.unit; ret.val$sliding.window.duration <- sliding.window.duration; ret.val$sliding.window.duration.unit <- sliding.window.duration.unit; ret.val$sliding.window.step.duration <- sliding.window.step.duration; ret.val$sliding.window.step.unit <- sliding.window.step.unit; ret.val$sliding.window.no.steps <- sliding.window.no.steps; ret.val$summary <- summary; ret.val$CMA <- as.data.frame(tmp$CMA); setnames(ret.val$CMA, 1, ID.colname); ret.val$CMA <- ret.val$CMA[,-ncol(ret.val$CMA)]; if( return.inner.event.info && !is.null(tmp$inner.event.info) ) ret.val$inner.event.info <- as.data.frame(tmp$inner.event.info); if( return.mapping.events.sliding.window && !is.null(tmp$inner.event.info) && ".EVENT.USED.IN.CMA" %in% names(tmp$inner.event.info) ) { # Unpack the info in the needed format: ret.val$mapping.windows.to.events <- as.data.frame(tmp$inner.event.info)[ tmp$inner.event.info$.EVENT.USED.IN.CMA, c(ID.colname, "window.ID", "..ORIGINAL.ROW.ORDER.IN.DATA..") ]; names(ret.val$mapping.windows.to.events)[3] <- "event.index.in.data"; } return (ret.val); } else { # Yes # Make sure the group's observations reflect the potentially new order of the observations in the data: mb.obs <- mg$obs[data.copy$..ORIGINAL.ROW.ORDER.., ]; # Focus only on the non-trivial ones: mg.to.eval <- (colSums(!is.na(mb.obs) & mb.obs) > 0); if( sum(mg.to.eval) == 0 ) { # None selects not even one observation! .report.ewms(paste0("None of the medication classes (included __ALL_OTHERS__) selects any observation!\n"), "warning", "CMA1", "AdhereR"); return (NULL); } mb.obs <- mb.obs[,mg.to.eval]; # keep only the non-trivial ones # Check if there are medication classes that refer to the same observations (they would result in the same estimates): mb.obs.dupl <- duplicated(mb.obs, MARGIN=2); # Estimate each separately: tmp <- lapply(1:nrow(mg$defs), function(i) { # Check if these are to be evaluated: if( !mg.to.eval[i] ) { return (list("CMA"=NULL, "event.info"=NULL, "CMA.to.apply"=NA)); } # Translate into the index of the classes to be evaluated: ii <- sum(mg.to.eval[1:i]); # Cache the selected observations: mg.sel.obs <- mb.obs[,ii]; # Check if this is a duplicated medication class: if( mb.obs.dupl[ii] ) { # Find which one is the original: for( j in 1:(ii-1) ) # ii=1 never should be TRUE { if( identical(mb.obs[,j], mg.sel.obs) ) { # This is the original: return it and stop return (c("identical.to"=j)); } } } # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=2, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy[mg.sel.obs,], # apply it on the subset of observations covered by this medication class ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || !inherits(tmp$CMA,"data.frame") || is.null(tmp$event.info) ) return (NULL); # Convert to data.frame and return: tmp$CMA.to.apply <- tmp$CMA$CMA.to.apply[1]; tmp$CMA <- as.data.frame(tmp$CMA); setnames(tmp$CMA, 1, ID.colname); tmp$CMA <- tmp$CMA[,-ncol(tmp$CMA)]; tmp$event.info <- as.data.frame(tmp$event.info); if( return.inner.event.info && !is.null(tmp$inner.event.info) ) tmp$inner.event.info <- as.data.frame(tmp$inner.event.info); return (tmp); }); # Set the names: names(tmp) <- mg$defs$name; # Solve the duplicates: for( i in seq_along(tmp) ) { if( is.numeric(tmp[[i]]) && length(tmp[[i]]) == 1 && names(tmp[[i]]) == "identical.to" ) tmp[[i]] <- tmp[[ tmp[[i]] ]]; } # Rearrange these and return: ret.val[["CMA"]] <- lapply(tmp, function(x) x$CMA); ret.val[["event.info"]] <- lapply(tmp, function(x) x$event.info); if( return.inner.event.info && !is.null(tmp$inner.event.info) ) ret.val[["inner.event.info"]] <- lapply(tmp, function(x) x$inner.event.info); ret.val$computed.CMA <- unique(vapply(tmp, function(x) if(is.null(x) || is.na(x$CMA.to.apply)){return (NA_character_)}else{return(x$CMA.to.apply)}, character(1))); ret.val$computed.CMA <- ret.val$computed.CMA[ !is.na(ret.val$computed.CMA) ]; if( flatten.medication.groups && !is.na(medication.groups.colname) ) { # Flatten the CMA: tmp <- do.call(rbind, ret.val[["CMA"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["CMA"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["CMA"]]), function(i) if(!is.null(ret.val[["CMA"]][[i]])){rep(names(ret.val[["CMA"]])[i], nrow(ret.val[["CMA"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["CMA"]] <- tmp; } # ... and the event.info: tmp <- do.call(rbind, ret.val[["event.info"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["event.info"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["event.info"]]), function(i) if(!is.null(ret.val[["event.info"]][[i]])){rep(names(ret.val[["event.info"]])[i], nrow(ret.val[["event.info"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["event.info"]] <- tmp; } # ... and the inner.event.info: if( return.inner.event.info && !is.null(ret.val[["inner.event.info"]]) ) { tmp <- do.call(rbind, ret.val[["inner.event.info"]]); if( is.null(tmp) || nrow(tmp) == 0 ) { ret.val[["inner.event.info"]] <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(ret.val[["inner.event.info"]]), function(i) if(!is.null(ret.val[["inner.event.info"]][[i]])){rep(names(ret.val[["inner.event.info"]])[i], nrow(ret.val[["inner.event.info"]][[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- medication.groups.colname; rownames(tmp) <- NULL; ret.val[["inner.event.info"]] <- tmp; } } } class(ret.val) <- "CMA_sliding_window"; ret.val$sliding.window.start.unit <- sliding.window.start.unit; ret.val$sliding.window.duration <- sliding.window.duration; ret.val$sliding.window.duration.unit <- sliding.window.duration.unit; ret.val$sliding.window.step.duration <- sliding.window.step.duration; ret.val$sliding.window.step.unit <- sliding.window.step.unit; ret.val$sliding.window.no.steps <- sliding.window.no.steps; ret.val$summary <- summary; return (ret.val); } } #' @export getMGs.CMA_sliding_window <- function(x) { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_sliding_window") || is.null(cma$medication.groups) ) return (NULL); return (cma$medication.groups); } #' getEventsToSlidingWindowsMapping #' #' This function returns the event-to-sliding-window mapping, if this information exists. #' #' There are cases where it is interesting to know which events belong to which #' sliding windows and which events have been actually used in computing the simple CMA #' for each sliding window #' This information can be returned by \code{CMA_sliding_window()} if the #' parameter \code{return.mapping.events.episodes} is set to \code{TRUE}. #' #' @param x is an \code{CMA_sliding_window object}. #' @return The mapping between events and episodes, if it exists as the #' \code{mapping.windows.to.events} component of the \code{CMA_sliding_window object} #' object, or \code{NULL} otherwise. #' @export getEventsToSlidingWindowsMapping <- function(x) { if( is.null(x) ) { return (NULL); } else if( inherits(x, "CMA_sliding_window") && ("mapping.windows.to.events" %in% names(x)) && !is.null(x$mapping.windows.to.events) && inherits(x$mapping.windows.to.events, "data.frame") ) { return (x$mapping.windows.to.events); } else { return (NULL); } } #' @export getCMA.CMA_sliding_window <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_sliding_window") || !("CMA" %in% names(cma)) || is.null(cma$CMA) ) return (NULL); if( inherits(cma$CMA, "data.frame") || !flatten.medication.groups ) { return (cma$CMA); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$CMA); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$CMA), function(i) if(!is.null(cma$CMA[[i]])){rep(names(cma$CMA)[i], nrow(cma$CMA[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export getEventInfo.CMA_sliding_window <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_sliding_window") || !("event.info" %in% names(cma)) || is.null(cma$event.info) ) return (NULL); if( inherits(cma$event.info, "data.frame") || !flatten.medication.groups ) { return (cma$event.info); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$event.info); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$event.info), function(i) if(!is.null(cma$event.info[[i]])){rep(names(cma$event.info)[i], nrow(cma$event.info[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export getInnerEventInfo.CMA_sliding_window <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_sliding_window") || !("event.info" %in% names(cma)) || is.null(cma$inner.event.info) ) return (NULL); if( inherits(cma$inner.event.info, "data.frame") || !flatten.medication.groups ) { return (cma$inner.event.info); } else { # Flatten the medication groups into a single data.frame: ret.val <- do.call(rbind, cma$inner.event.info); if( is.null(ret.val) || nrow(ret.val) == 0 ) return (NULL); ret.val <- cbind(ret.val, unlist(lapply(1:length(cma$inner.event.info), function(i) if(!is.null(cma$inner.event.info[[i]])){rep(names(cma$inner.event.info)[i], nrow(cma$inner.event.info[[i]]))}else{NULL}))); names(ret.val)[ncol(ret.val)] <- medication.groups.colname; rownames(ret.val) <- NULL; return (ret.val); } } #' @export subsetCMA.CMA_sliding_window <- function(cma, patients, suppress.warnings=FALSE) { if( inherits(patients, "factor") ) patients <- as.character(patients); patients.to.keep <- intersect(patients, unique(cma$data[,cma$ID.colname])); if( length(patients.to.keep) == 0 ) { if( !suppress.warnings ) .report.ewms("No patients to subset on!\n", "error", "subsetCMA.CMA_sliding_window", "AdhereR"); return (NULL); } if( length(patients.to.keep) < length(patients) && !suppress.warnings ) .report.ewms("Some patients in the subsetting set are not in the CMA itsefl and are ignored!\n", "warning", "subsetCMA.CMA_sliding_window", "AdhereR"); ret.val <- cma; ret.val$data <- ret.val$data[ ret.val$data[,ret.val$ID.colname] %in% patients.to.keep, ]; if( !is.null(ret.val$event.info) ) { if( inherits(ret.val$event.info, "data.frame") ) { ret.val$event.info <- ret.val$event.info[ ret.val$event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( nrow(ret.val$event.info) == 0 ) ret.val$event.info <- NULL; } else if( is.list(ret.val$event.info) && length(ret.val$event.info) > 0 ) { ret.val$event.info <- lapply(ret.val$event.info, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } if( !is.null(ret.val$inner.event.info) ) { if( inherits(ret.val$inner.event.info, "data.frame") ) { ret.val$inner.event.info <- ret.val$inner.event.info[ ret.val$inner.event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( nrow(ret.val$inner.event.info) == 0 ) ret.val$inner.event.info <- NULL; } else if( is.list(ret.val$inner.event.info) && length(ret.val$inner.event.info) > 0 ) { ret.val$inner.event.info <- lapply(ret.val$inner.event.info, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } if( ("CMA" %in% names(ret.val)) && !is.null(ret.val$CMA) ) { if( inherits(ret.val$CMA, "data.frame") ) { ret.val$CMA <- ret.val$CMA[ ret.val$CMA[,ret.val$ID.colname] %in% patients.to.keep, ]; } else if( is.list(ret.val$CMA) && length(ret.val$CMA) > 0 ) { ret.val$CMA <- lapply(ret.val$CMA, function(x){tmp <- x[ x[,ret.val$ID.colname] %in% patients.to.keep, ]; if(!is.null(tmp) && nrow(tmp) > 0){tmp}else{NULL}}); } } return (ret.val); } #' @rdname print.CMA0 #' @export print.CMA_sliding_window <- function(...) print.CMA_per_episode(...) #' @rdname plot.CMA_per_episode #' @export plot.CMA_sliding_window <- plot.CMA_per_episode; #' Interactive exploration and CMA computation. #' #' Interactively plot a given patient's data, allowing the real-time exploration #' of the various CMAs and their parameters. #' It can use \code{Rstudio}'s \code{manipulate} library or \code{Shiny}. #' #' This is merely a stub for the actual implementation in package #' \code{AdhereRViz}: it just checks if this package is installed and functional, #' in which case it calls the actual implementation, otherwise warns the user that #' \code{AdhereRViz} must be instaled. #' #' @seealso Function \code{\link[AdhereR]{plot_interactive_cma}} in package #' \code{AdhereRViz}. #' #' @param ... Parameters to be passed to \code{plot_interactive_cma()} in package #' \code{AdhereRViz}. #' #' @return Nothing #' @examples #' \dontrun{ #' plot_interactive_cma(med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY");} #' @export plot_interactive_cma <- function(...) { if( requireNamespace("AdhereRViz", quietly=TRUE) ) { # Pass the parameters to AdhereRViz: AdhereRViz::plot_interactive_cma(...); } else { .report.ewms("Package 'AdhereRViz' must be installed for the interactive plotting to work! Please either install it or use the 'normal' plotting functions provided by 'AdhereR'...\n", "error", "plot_interactive_cma", "AdhereR"); if( interactive() ) { if( menu(c("Yes", "No"), graphics=FALSE, title="Do you want to install 'AdhereRViz' now?") == 1 ) { # Try to install AdhereRViz: install.packages("AdhereRViz", dependencies=TRUE); if( requireNamespace("AdhereRViz", quietly=TRUE) ) { # Pass the parameters to AdhereRViz: AdhereRViz::plot_interactive_cma(...); } else { .report.ewms("Failed to install 'AdhereRViz'!\n", "error", "plot_interactive_cma", "AdhereR"); return (invisible(NULL)); } } else { return (invisible(NULL)); } } } } # # Create the medication groups example dataset med.groups from the drcomp dataset: # # DON'T RUN! # event_durations <- compute_event_durations(disp.data = durcomp.dispensing, # presc.data = durcomp.prescribing, # special.periods.data = durcomp.hospitalisation, # ID.colname = "ID", # presc.date.colname = "DATE.PRESC", # disp.date.colname = "DATE.DISP", # medication.class.colnames = c("ATC.CODE", "UNIT", "FORM"), # total.dose.colname = "TOTAL.DOSE", # presc.daily.dose.colname = "DAILY.DOSE", # presc.duration.colname = "PRESC.DURATION", # visit.colname = "VISIT", # split.on.dosage.change = TRUE, # force.init.presc = TRUE, # force.presc.renew = TRUE, # trt.interruption = "continue", # special.periods.method = "continue", # date.format = "%Y-%m-%d", # suppress.warnings = FALSE, # return.data.table = FALSE); # med.events.ATC <- event_durations$event_durations[ !is.na(event_durations$event_durations$DURATION) & event_durations$event_durations$DURATION > 0, # c("ID", "DISP.START", "DURATION", "DAILY.DOSE", "ATC.CODE")]; # names(med.events.ATC) <- c("PATIENT_ID", "DATE", "DURATION", "PERDAY", "CATEGORY"); # # Groups from the ATC codes: # sort(unique(med.events.ATC$CATEGORY)); # all the ATC codes in the data # # Level 1: # med.events.ATC$CATEGORY_L1 <- vapply(substr(med.events.ATC$CATEGORY,1,1), switch, character(1), # "A"="ALIMENTARY TRACT AND METABOLISM", # "B"="BLOOD AND BLOOD FORMING ORGANS", # "J"="ANTIINFECTIVES FOR SYSTEMIC USE", # "R"="RESPIRATORY SYSTEM", # "OTHER"); # # Level 2: # med.events.ATC$CATEGORY_L2 <- vapply(substr(med.events.ATC$CATEGORY,1,3), switch, character(1), # "A02"="DRUGS FOR ACID RELATED DISORDERS", # "A05"="BILE AND LIVER THERAPY", # "A09"="DIGESTIVES, INCL. ENZYMES", # "A10"="DRUGS USED IN DIABETES", # "A11"="VITAMINS", # "A12"="MINERAL SUPPLEMENTS", # "B02"="ANTIHEMORRHAGICS", # "J01"="ANTIBACTERIALS FOR SYSTEMIC USE", # "J02"="ANTIMYCOTICS FOR SYSTEMIC USE", # "R03"="DRUGS FOR OBSTRUCTIVE AIRWAY DISEASES", # "R05"="COUGH AND COLD PREPARATIONS", # "OTHER"); # # # Define groups of medications: # med.groups <- c("Vitamins" = "(CATEGORY_L2 == 'VITAMINS')", # "VitaResp" = "({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')", # "VitaShort" = "({Vitamins} & DURATION <= 30)", # "VitELow" = "(CATEGORY == 'A11HA03' & PERDAY <= 500)", # "VitaComb" = "({VitaShort} | {VitELow})", # "NotVita" = "(!{Vitamins})"); # save(med.events.ATC, med.groups, file="./data/medgroups.rda", version=2); # save it backwards compatible with R >= 1.4.0 #' Example of medication events with ATC codes. #' #' An artificial dataset containing medication events (one per row) for 16 #' patients (1564 events in total), containing ATC codes. This dataset is #' derived from the \code{durcomp} datasets using the \code{compute_event_durations} #' function. See @med.events for more details. #' #' @format A data frame with 1564 rows and 7 variables: #' \describe{ #' \item{PATIENT_ID}{the patient unique identifier.} #' \item{DATE}{the medication event date.} #' \item{DURATION}{the duration in days.} #' \item{PERDAY}{the daily dosage.} #' \item{CATEGORY}{the ATC code.} #' \item{CATEGORY_L1}{explicitation of the first field of the ATC code (e.g., #' "A"="ALIMENTARY TRACT AND METABOLISM").} #' \item{CATEGORY_L2}{explicitation of the first and second fields of the ATC #' code (e.g., "A02"="DRUGS FOR ACID RELATED DISORDERS").} #' } "med.events.ATC" #' Example of medication groups. #' #' An example defining 6 medication groups for \code{med.events.ATC}. #' It is a \emph{named character vector}, where the names are the medication #' group unique \emph{names} (e.g., "Vitamines") and the elements are the medication #' group \emph{definitions} (e.g., "(CATEGORY_L2 == 'VITAMINS')"). #' The definitions are \code{R} logical expressions using \emph{column names} and #' \emph{values} that appear in the dataset, as well as references to other #' medication groups using the construction \emph{"{NAME}"}. #' #' In the above example, "CATEGORY_L2" is a column name in the \code{med.events.ATC} #' dataset, and 'VITAMINS' one of its possible values, and which selects all events #' that have prescribed ATC codes "A11" (aka "VITAMINS"). #' Another example is "NotVita" defined as "(!{Vitamines})", which selects all #' events that do not have Vitamines prescribed. #' #' For more details, please see the acompanying vignette. "med.groups"
/scratch/gouwar.j/cran-all/cranData/AdhereR/R/adherer.R
############################################################################################### # # This allows AdhereR to be called from outside R using a generic `shell` + # shared files mechanism. # Copyright (C) 2015-2018 Dan Dediu & Alexandra Dima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### #' callAdhereR. #' #' The function encapsulating all the logics that allows AdhereR to be called #' from any platform using the generic \code{shell} mechanism. #' #' In most cases this should not be done directly by the user, #' but instead used by an appropriate \code{wrapper} on the client platform. #' It allows transparent use of \code{AdhereR} from virtually any platform or #' programming language for which an appropriate wrapper is provided. #' For more details see the vignette describing the included reference #' \code{Python 3} wrapper. #' #' @param shared.data.directory A \emph{string} containing the path to the #' directory where all the exchanged (shared) data (both input and output) is. #' \code{AdhereR} needs read and write access to this directory. #' @return This function displays any messages to the console, tries to also #' write them to the \code{Adherer-results.txt} file in the #' \code{shared.data.directory} directory, and, when finished, forces \code{R} #' to quit with a given shell error code: #' \itemize{ #' \item \code{0} The processing ended without major errors; #' \item \code{1} General error (hopefully there are messages in the #' \code{Adherer-results.txt} file; #' \item \code{10} The directory \code{shared.data.directory} does not exit; #' \item \code{11} \code{AdhereR} does not have read access to the #' \code{shared.data.directory} directory; #' \item \code{12} \code{AdhereR} does not have write access to the #' \code{shared.data.directory} directory; #' \item \code{13} issues with the parameters file \code{parameters.log}; #' \item \code{14} issues with the data file \code{dataset.csv}; #' \item \code{15} plotting issues; #' \item \code{16} interactive plotting issues; #' \item \code{17} issues exporting the results. #' } #' @export callAdhereR <- function(shared.data.directory) # the directory where the shared data (input and output) is found { # Auxiliary function: Interactive plotting: .do.interactive.plotting <- function(params.as.list) { # pre-process the parameters: if( length(s <- which("patient_to_plot" == names(params.as.list))) > 0 ) { names(params.as.list)[s] <- "ID"; params.as.list[[s]] <- .get.param.value("patient_to_plot", type="character", default.value=NULL, required=FALSE); } # Interactive plotting: do.call("plot_interactive_cma", c(list("print.full.params"=FALSE), # DEBUG list("backend"="shiny"), list("use.system.browser"=TRUE), # force using shiny in the system browser params.as.list)); return (NULL); # all ok } # Check to see if the folder exists: if( !file.exists(shared.data.directory) ) { msg <- paste0("AdhereR: The given directory '",shared.data.directory,"' does not seem to exist: ABORTING...\n"); cat(msg); quit(save="no", status=10, runLast=FALSE); } # Check to see if we have read and write access to the folder: if( file.access(shared.data.directory, 4) != 0 ) { msg <- paste0("AdhereR: I don't have read access to given directory '",shared.data.directory,"': ABORTING...\n"); cat(msg); quit(save="no", status=11, runLast=FALSE); } if( file.access(shared.data.directory, 2) != 0 ) { msg <- paste0("AdhereR: I don't have write access to given directory '",shared.data.directory,"': ABORTING...\n"); cat(msg); quit(save="no", status=12, runLast=FALSE); } # The errors/warnings/messages file: msg.file <- file(paste0(shared.data.directory,"/Adherer-results.txt"), "wt"); cat(paste0("AdhereR ",packageVersion("AdhereR")," on R ",getRversion()," started at ",Sys.time(),":\n"), file=msg.file, append=FALSE); # initial message # Check to see if the directory contains the "parameters.log" file: parameters.file <- paste0(shared.data.directory,"/parameters.log"); if( !file.exists(parameters.file) ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' does not seem to exist in the given folder '",shared.data.directory,"': ABORTING...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } # Try to parse it: parameters <- readLines(parameters.file); if( parameters[1] != "Parameters" ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' should start with a 'Parameters' line: ABORTING...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } if( parameters[length(parameters)] != "end_parameters" ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' should end with a 'end_parameters' line: ABORTING...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } if( length(parameters) < 3 ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' should at least some parameters...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } # get the parameters block nicely parsed: .remove.spaces.and.quotes <- function(s) { if( is.null(s) || is.na(s) || !is.character(s) || nchar(s)==0 ) return (""); # not a proper string value s <- trimws(s); # get rid of the trailing spaces if( substr(s,1,1) == "\"" || substr(s,1,1) == "'" ) s <- substr(s,2,nchar(s)); if( substr(s,nchar(s),nchar(s)) == "\"" || substr(s,nchar(s),nchar(s)) == "'" ) s <- substr(s,1,nchar(s)-1); return (s); } parameters.block <- do.call(rbind, lapply( 2:(length(parameters)-1), function(i) { # quick and dirty parser (it does not catch all possible cases but should generally work): s <- parameters[i]; # get rid of any comments (preceded by # or ///): s <- strsplit(s,"#",fixed=TRUE)[[1]][1]; s <- strsplit(s,"///",fixed=TRUE)[[1]][1]; # get the param name and possible value: s <- strsplit(s,"=",fixed=TRUE)[[1]]; if( length(s) == 1 ) { return (data.frame("param"=.remove.spaces.and.quotes(s[1]), "value"=NA)); } else { return (data.frame("param"=.remove.spaces.and.quotes(s[1]), "value"=.remove.spaces.and.quotes(paste(s[-1],collapse="=")))); # put back the '=' signs in the value } })); parameters.block$param <- as.character(parameters.block$param); parameters.block$value <- as.character(parameters.block$value); # make sure these are strings! # Check the input data: data.file <- paste0(shared.data.directory,"/dataset.csv"); if( !file.exists(data.file) ) { msg <- paste0("AdhereR: The data file 'dataset.csv' does not seem to exist in the given folder '",shared.data.directory,"': ABORTING...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=14, runLast=FALSE); } # try to load the data: data <- NULL; try(data <- read.table(data.file, header=TRUE, sep="\t", quote="", stringsAsFactors=FALSE)); if( is.null(data) || nrow(data)==0 || ncol(data)==0 ) { msg <- paste0("AdhereR: Cannot load the data file 'dataset.csv' or it is empty: ABORTING...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=14, runLast=FALSE); } # try to get the value of a given parameter: .get.param.value <- function(param.name, # the parameter's name type=c("character","numeric","logical","Date","character.vector")[1], # the expected type (vector = list of values of given type separated by ";") default.value=NA, # the default value (if not defined) date.format="%d/%m/%y", # the format of the Date (if so requested) required=TRUE # is the param required (i.e., stop everything if not defined)? ) { if( is.na(param.name) || is.null(param.name) || !is.character(param.name) || length(param.name) != 1 ) return (NA); s <- which(parameters.block$param == param.name); if( length(s) == 0 ) { if( required ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' must contain a single value for required parameter '",param.name,"': ABORTING...\n"); #cat(msg); sink(); stop(msg, call.=FALSE); } else { return (default.value); # otherwise return the default value } } s <- s[1]; # use the first defined value... if( is.na(parameters.block$value[s]) || parameters.block$value[s] == "" ) { # empty string "" also means *not given* -> use the default value: return (default.value); } else { # return the value (with conversion to requested type): return (switch(type, "character"=parameters.block$value[s], "numeric"=as.numeric(parameters.block$value[s]), "logical"=as.logical(parameters.block$value[s]), "Date"=as.Date(parameters.block$value[s], format=date.format), "character.vector"=vapply(strsplit(parameters.block$value[s],";",fixed=TRUE)[[1]], function(s) .remove.spaces.and.quotes(s), character(1)))); } } # try to call the appropriate AdhereR function: if( sum(parameters.block$param == "function", na.rm=TRUE) != 1 ) { msg <- paste0("AdhereR: The parameters file 'parameters.log' should contain a single 'function=' line...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } # collect the parameters in a list: NON_CMA_PARAMS <- c("NA.SYMBOL.NUMERIC", "NA.SYMBOL.STRING", "LOGICAL.SYMBOL.TRUE", "LOGICAL.SYMBOL.FALSE", "COLNAMES.DOT.SYMBOL", "COLNAMES.START.DOT", "function"); PARAMS <- setdiff(unique(parameters.block$param), NON_CMA_PARAMS); params.as.list <- lapply(PARAMS, function(s){ x <- .get.param.value(s, type="character", default.value=NA, required=FALSE); if( is.na(x) ) return (NULL) else return (x); }); names(params.as.list) <- PARAMS; params.as.list <- Filter(Negate(is.null), params.as.list); # get rid of the NULL ("default") elemens # some params have special meaning and should be processed as such: .cast.param.to.type <- function(value.param, type.param, is.type.param.fixed=FALSE) { if( !is.null(params.as.list[[value.param]]) ) { # set its type appropriately: tmp <- switch(ifelse(is.type.param.fixed, type.param, .get.param.value(type.param, type="character", default.value="numeric", required=FALSE)), "character"=params.as.list[[value.param]], # nothing to covert to "numeric"=as.numeric(params.as.list[[value.param]]), # try to make it a number "logical"=as.logical(params.as.list[[value.param]]), # try to make it a boolean "date"=as.Date(params.as.list[[value.param]], format=.get.param.value("date.format", type="character", default.value="%m/%d/%Y", required=FALSE)), # try to make it a Date NA); if( is.na(tmp) ) { msg <- paste0("AdhereR: Cannot convert '",value.param,"' to the desired type '",type.param,"'...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } else { params.as.list[[value.param]] <<- tmp; # write it back directly! } } } # Force type for params with known type: .cast.param.to.type("followup.window.start", "followup.window.start.type"); .cast.param.to.type("followup.window.duration", "followup.window.duration.type"); .cast.param.to.type("observation.window.start", "observation.window.start.type"); .cast.param.to.type("observation.window.duration", "observation.window.duration.type"); .cast.param.to.type("sliding.window.start", "sliding.window.start.type"); .cast.param.to.type("sliding.window.duration", "sliding.window.duration.type"); .cast.param.to.type("sliding.window.step.duration", "sliding.window.step.duration.type"); if( .get.param.value("sliding.window.no.steps", type="numeric", default.value=-1, required=FALSE) == -1 ) params.as.list[["sliding.window.no.steps"]] <- NA; .cast.param.to.type("plot.show", "logical", TRUE); .cast.param.to.type("plot.align.all.patients", "logical", TRUE); .cast.param.to.type("plot.align.first.event.at.zero", "logical", TRUE); .cast.param.to.type("plot.show.legend", "logical", TRUE); .cast.param.to.type("plot.show.cma", "logical", TRUE); .cast.param.to.type("plot.show.event.intervals", "logical", TRUE); .cast.param.to.type("plot.print.CMA", "logical", TRUE); .cast.param.to.type("plot.plot.CMA", "logical", TRUE); .cast.param.to.type("plot.plot.CMA.as.histogram", "logical", TRUE); .cast.param.to.type("plot.highlight.followup.window", "logical", TRUE); .cast.param.to.type("plot.highlight.observation.window", "logical", TRUE); .cast.param.to.type("plot.show.real.obs.window.start", "logical", TRUE); .cast.param.to.type("plot.bw.plot", "logical", TRUE); .cast.param.to.type("force.NA.CMA.for.failed.patients", "logical", TRUE); .cast.param.to.type("suppress.warnings", "logical", TRUE); .cast.param.to.type("save.event.info", "logical", TRUE); .cast.param.to.type("keep.event.interval.for.all.events","logical", TRUE); .cast.param.to.type("keep.window.start.end.dates", "logical", TRUE); .cast.param.to.type("plot.width", "numeric", TRUE); .cast.param.to.type("plot.height", "numeric", TRUE); .cast.param.to.type("plot.quality", "numeric", TRUE); .cast.param.to.type("plot.dpi", "numeric", TRUE); .cast.param.to.type("plot.period.in.days", "numeric", TRUE); .cast.param.to.type("plot.legend.bkg.opacity", "numeric", TRUE); .cast.param.to.type("plot.legend.cex", "numeric", TRUE); .cast.param.to.type("plot.legend.cex.title", "numeric", TRUE); .cast.param.to.type("plot.cex", "numeric", TRUE); .cast.param.to.type("plot.cex.axis", "numeric", TRUE); .cast.param.to.type("plot.cex.lab", "numeric", TRUE); .cast.param.to.type("plot.cex.title", "numeric", TRUE); .cast.param.to.type("plot.lwd.event", "numeric", TRUE); .cast.param.to.type("plot.pch.start.event", "numeric", TRUE); .cast.param.to.type("plot.pch.end.event", "numeric", TRUE); .cast.param.to.type("plot.lwd.continuation", "numeric", TRUE); .cast.param.to.type("plot.CMA.plot.ratio", "numeric", TRUE); .cast.param.to.type("plot.observation.window.density", "numeric", TRUE); .cast.param.to.type("plot.observation.window.angle", "numeric", TRUE); .cast.param.to.type("plot.real.obs.window.density", "numeric", TRUE); .cast.param.to.type("plot.real.obs.window.angle", "numeric", TRUE); .cast.param.to.type("carryover.within.obs.window", "logical", TRUE); .cast.param.to.type("carryover.into.obs.window", "logical", TRUE); .cast.param.to.type("carry.only.for.same.medication", "logical", TRUE); .cast.param.to.type("consider.dosage.change", "logical", TRUE); .cast.param.to.type("medication.change.means.new.treatment.episode", "logical", TRUE); .cast.param.to.type("dosage_change_means_new_treatment_episode", "logical", TRUE); .cast.param.to.type("plot.medication.groups.separator.show", "logical", TRUE); .cast.param.to.type("plot.medication.groups.separator.lwd", "numeric", TRUE); .cast.param.to.type("plot.plot.events.vertically.displaced", "logical", TRUE); .cast.param.to.type("plot.print.dose", "logical", TRUE); .cast.param.to.type("plot.cex.dose", "numeric", TRUE); .cast.param.to.type("plot.print.dose.centered", "logical", TRUE); .cast.param.to.type("plot.plot.dose", "logical", TRUE); .cast.param.to.type("plot.lwd.event.max.dose", "numeric", TRUE); .cast.param.to.type("plot.plot.dose.lwd.across.medication.classes", "logical", TRUE); .cast.param.to.type("plot.cma.cex", "numeric", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.vspace", "numeric", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.start.from.zero", "logical", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.lwd.interval", "numeric", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.alpha.interval", "numeric", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.show.0perc", "logical", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.timeseries.show.100perc", "logical", TRUE); .cast.param.to.type("plot.plot.partial.CMAs.as.overlapping.alternate", "logical", TRUE); .cast.param.to.type("plot.observation.window.opacity", "numeric", TRUE); .cast.param.to.type("plot.rotate.text", "numeric", TRUE); .cast.param.to.type("plot.force.draw.text", "logical", TRUE); .cast.param.to.type("plot.min.plot.size.in.characters.horiz", "numeric", TRUE); .cast.param.to.type("plot.min.plot.size.in.characters.vert", "numeric", TRUE); .cast.param.to.type("plot.max.patients.to.plot", "numeric", TRUE); .cast.param.to.type("plot.do.not.draw.plot", "logical", TRUE); .cast.param.to.type("return.inner.event.info", "logical", TRUE); # col.cats is special in that it can be a function name or a color name: col.cats <- trimws(.get.param.value("plot.col.cats", type="character", required=FALSE)); if( substring(col.cats, nchar(col.cats)-1, nchar(col.cats)) == "()" ) { # it seems to be a function name, so match it to the ones we currently support: col.cats <- switch(col.cats, "rainbow()"=rainbow, "heat.colors()"=heat.colors, "terrain.colors()"=terrain.colors, "topo.colors()"=topo.colors, "cm.colors()"=cm.colors, "viridis()"=viridisLite::viridis, "magma()"=viridisLite::magma, "inferno()"=viridisLite::inferno, "plasma()"=viridisLite::plasma, "cividis()"=viridisLite::cividis, "rocket()"=viridisLite::rocket, "mako"=viridisLite::mako, "turbo"=viridisLite::turbo, rainbow); # defaults to rainbow } # otherwise it is a color name, so use it as such # xlab.* are special in that they need assembly into a single named vector: xlab.dates <- trimws(.get.param.value("plot.xlab.dates", type="character", required=FALSE)); xlab.days <- trimws(.get.param.value("plot.xlab.days", type="character", required=FALSE)); xlab <- c("dates"=xlab.dates, "days"=xlab.days); # ylab.* are special in that they need assembly into a single named vector: ylab.withoutcma <- trimws(.get.param.value("plot.ylab.withoutcma", type="character", required=FALSE)); ylab.withcma <- trimws(.get.param.value("plot.ylab.withcma", type="character", required=FALSE)); ylab <- c("withoutCMA"=ylab.withoutcma, "withCMA"=ylab.withcma); # title.* are special in that they need assembly into a single named vector: title.aligned <- trimws(.get.param.value("plot.title.aligned", type="character", required=FALSE)); title.notaligned <- trimws(.get.param.value("plot.title.notaligned", type="character", required=FALSE)); title.main <- c("aligned"=title.aligned, "notaligned"=title.notaligned); # medication.groups.to.plot is a bit special: if( (medication.groups.to.plot <- trimws(.get.param.value("plot.medication.groups.to.plot", type="character", default.value="", required=FALSE))) == "" ) medication.groups.to.plot <- NA; # NA and NULL are equivalent # plot.partial.CMAs.as is a bit special: if( (plot.partial.CMAs.as <- trimws(.get.param.value("plot.plot.partial.CMAs.as", type="character", default.value="", required=FALSE))) == "" ) plot.partial.CMAs.as <- NULL; # plot.partial.CMAs.as is special in that it might be a vector of strings: alternating.bands.cols <- trimws(.get.param.value("plot.alternating.bands.cols", type="character", default.value="", required=FALSE)); if( alternating.bands.cols == "" ) { alternating.bands.cols <- NA; } else { # see if it is a list of strings: alternating.bands.cols <- strsplit(alternating.bands.cols, ",", fixed=TRUE)[[1]]; if( length(alternating.bands.cols) == 1 ) { alternating.bands.cols <- .remove.spaces.and.quotes(alternating.bands.cols); } else { alternating.bands.cols <- vapply(alternating.bands.cols, .remove.spaces.and.quotes, character(1)); } } # medication.groups is a bit special: if( (medication.groups <- trimws(.get.param.value("medication.groups", type="character", default.value="", required=FALSE))) == "" ) params.as.list[["medication.groups"]] <- NULL; if( suppressWarnings(!is.na(as.numeric(params.as.list[["parallel.threads"]]))) ) { params.as.list[["parallel.threads"]] <- as.numeric(params.as.list[["parallel.threads"]]); } else if( is.character(params.as.list[["parallel.threads"]]) && params.as.list[["parallel.threads"]] == "auto" ) { # nothing to pre-process } else { # try to eval it: tmp <- NULL; tmp <- try(eval(parse(text=as.character(params.as.list[["parallel.threads"]]))), silent=FALSE); if( is.null(tmp) ) { msg <- paste0("AdhereR: I don't understand parallel.threads=\"",as.character(params.as.list[["parallel.threads"]]),"\"!\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=13, runLast=FALSE); } else { params.as.list[["parallel.threads"]] <- tmp; } } # special case for plotting: don't compute the CMA for all patients but only for those to be plotted: if( .get.param.value("plot.show", type="logical", default.value=FALSE, required=FALSE) && !is.null(patients.to.plot <- .get.param.value("plot.patients.to.plot", type="character.vector", default.value=NULL, required=FALSE)) ) { data <- data[ data[,.get.param.value("ID.colname", type="character", required=TRUE)] %in% patients.to.plot, ]; if( is.null(data) || nrow(data) == 0 ) { msg <- paste0("AdhereR: No patients to plot!...\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=15, runLast=FALSE); } } # add the data to the list of params as well: params.as.list <- c(list("data"=data), params.as.list); # medication groups: always flatten them: params.as.list[["flatten.medication.groups"]] <- TRUE; params.as.list[["medication.groups.colname"]] <- "__MED_GROUP_ID"; # call the appropriate function: function.to.call <- .get.param.value("function", type="character", required=TRUE); # avoid warnings about the arguments.that.should.not.be.defined: if(function.to.call %in% c("CMA0", "CMA1", "CMA2", "CMA3", "CMA4", "CMA5", "CMA6", "CMA7", "CMA8", "CMA9", "CMA_per_episode", "CMA_sliding_window") ) { # get the arguments.that.should.not.be.defined directly from the function definition: arguments.to.undefine <- names(formals(function.to.call)[["arguments.that.should.not.be.defined"]]); if( !is.null(arguments.to.undefine) && length(arguments.to.undefine) > 0 ) { arguments.to.undefine <- arguments.to.undefine[ arguments.to.undefine != "" ]; # keep only the named arguments params.as.list <- params.as.list[!(names(params.as.list) %in% arguments.to.undefine)]; # simply remove these arguments from the list (if already there) } } # call the function: results <- switch(function.to.call, "CMA0"=, "CMA1"=, "CMA2"=, "CMA3"=, "CMA4"=, "CMA5"=, "CMA6"=, "CMA7"=, "CMA8"=, "CMA9"=, "CMA_per_episode"=, "CMA_sliding_window"=do.call(function.to.call, params.as.list), # call a CMA function "compute_event_int_gaps"=do.call("compute.event.int.gaps", params.as.list), # call compute.event.int.gaps() "compute_treatment_episodes"= do.call("compute.treatment.episodes", params.as.list), # call compute.treatment.episodes() "plot_interactive_cma"=.do.interactive.plotting(params.as.list), # call the interactive plotting function NULL # oops! ); if( is.null(results) ) # OOPS! some error occurred: make it known and quit! { if( function.to.call == "plot_interactive_cma" ) { # interactive plotting is a special case where NULL is just a sign of ending the call... cat("OK: interactive plotting is over (but still, there might be warnings and messages above worth paying attention to)!\n", file=stderr()); } else { msg <- "\nSOME ERROR HAS OCCURED (maybe there's some helpful messages above?)\n"; cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=16, runLast=FALSE); } } else { # Otherwise, continue.... # Save the results (possibly applying conversions): .apply.export.conversions <- function(df) { # logical symbols (may require converssion to numeric or string): LOGICAL.SYMBOL.TRUE <- .get.param.value("LOGICAL.SYMBOL.TRUE", type="character", default.value=NA, required=FALSE); LOGICAL.SYMBOL.FALSE <- .get.param.value("LOGICAL.SYMBOL.FALSE", type="character", default.value=NA, required=FALSE); if( !is.na(LOGICAL.SYMBOL.TRUE) || !is.na(LOGICAL.SYMBOL.FALSE) ) { for( i in 1:ncol(df) ) if( is.logical(df[,i]) ) { tmp <- as.character(df[,i]); if( !is.na(LOGICAL.SYMBOL.TRUE) ) tmp[tmp=="TRUE"] <- LOGICAL.SYMBOL.TRUE; if( !is.na(LOGICAL.SYMBOL.FALSE) ) tmp[tmp=="FALSE"] <- LOGICAL.SYMBOL.FALSE; df[,i] <- tmp; } } # NA.SYMBOL.NUMERIC (applies to numeric columns): NA.SYMBOL.NUMERIC <- .get.param.value("NA.SYMBOL.NUMERIC", type="character", default.value=NA, required=FALSE); if( !is.na(NA.SYMBOL.NUMERIC) ) { for( i in 1:ncol(df) ) if( is.numeric(df[,i]) ){ tmp <- as.character(df[,i]); tmp[is.na(tmp)] <- NA.SYMBOL.NUMERIC; df[,i] <- tmp; } } # NA.SYMBOL.STRING (applies to character and Date columns): NA.SYMBOL.STRING <- .get.param.value("NA.SYMBOL.STRING", type="character", default.value=NA, required=FALSE); if( !is.na(NA.SYMBOL.STRING) ) { for( i in 1:ncol(df) ) { if( is.character(df[,i]) || is.factor(df[,i]) ){ tmp <- as.character(df[,i]); tmp[is.na(tmp)] <- NA.SYMBOL.STRING; df[,i] <- tmp; } if( inherits(df[,i],"Date") ){ tmp <- as.character(df[,i], format=.get.param.value("date.format", type="character", default.value="%m/%d/%Y", required=FALSE)); tmp[is.na(tmp)] <- NA.SYMBOL.STRING; df[,i] <- tmp; } } } # column name stuff: COLNAMES.START.DOT <- .get.param.value("COLNAMES.START.DOT", type="character", default.value=NA, required=FALSE); if( !is.na(COLNAMES.START.DOT) ) names(df) <- sub("^\\.", COLNAMES.START.DOT, names(df)); COLNAMES.DOT.SYMBOL <- .get.param.value("COLNAMES.DOT.SYMBOL", type="character", default.value=NA, required=FALSE); if( !is.na(COLNAMES.DOT.SYMBOL) ) names(df) <- gsub(".", COLNAMES.DOT.SYMBOL, names(df), fixed=TRUE); # return the new df for exporting: return (df); } # Depending on the computation, we may export different things: if( length(cl_res <- class(results)) == 1 && cl_res == "CMA0" ) { # Nothing to export.... } else if( inherits(results, "CMA0") || inherits(results, "CMA_per_episode") || inherits(results, "CMA_sliding_window") ) { # Special case: for plot.show == TRUE, add the "-plotted" suffix to the saved files! file.name.suffix <- ifelse(.get.param.value("plot.show", type="character", default.value="FALSE", required=FALSE) == "TRUE", "-plotted", "" ); # CMAs: write.table(.apply.export.conversions(results$CMA), paste0(shared.data.directory,"/CMA",file.name.suffix,".csv"), row.names=FALSE, col.names=TRUE, sep="\t", quote=FALSE); # event info: if( !is.na(save.event.info <- .get.param.value("save.event.info", type="character", default.value=NA, required=FALSE)) && save.event.info=="TRUE" ) { write.table(.apply.export.conversions(results$event.info), paste0(shared.data.directory,"/EVENTINFO",file.name.suffix,".csv"), row.names=FALSE, col.names=TRUE, sep="\t", quote=FALSE); } # inner event info: if( !is.na(return.inner.event.info <- .get.param.value("return.inner.event.info", type="character", default.value=NA, required=FALSE)) && return.inner.event.info=="TRUE" && (inherits(results, "CMA_per_episode") || inherits(results, "CMA_sliding_window")) ) { write.table(.apply.export.conversions(results$inner.event.info), paste0(shared.data.directory,"/INNEREVENTINFO",file.name.suffix,".csv"), row.names=FALSE, col.names=TRUE, sep="\t", quote=FALSE); } } else if( function.to.call == "compute_event_int_gaps" && inherits(results, "data.frame") && nrow(results) > 0 && ncol(results) > 0 ) { # event info: write.table(.apply.export.conversions(results), paste0(shared.data.directory,"/EVENTINFO.csv"), row.names=FALSE, col.names=TRUE, sep="\t", quote=FALSE); } else if( function.to.call == "compute_treatment_episodes" && inherits(results, "data.frame") && nrow(results) > 0 && ncol(results) > 0 ) { # treatment episodes: write.table(.apply.export.conversions(results), paste0(shared.data.directory,"/TREATMENTEPISODES.csv"), row.names=FALSE, col.names=TRUE, sep="\t", quote=FALSE); } else { # how did we get here? msg <- "\nDon't know how to export this type of results!\n"; cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=17, runLast=FALSE); } # Plotting might have been required: if( .get.param.value("plot.show", type="logical", default.value="FALSE", required=FALSE) ) { # OK, plotting it too! # Get the list of relevant parameters: plotting.params <- params.as.list[grep("^plot\\.", names(params.as.list))]; names(plotting.params) <- substring(names(plotting.params), nchar("plot.")+1); # patients.to.plot has already been parsed: if( "patients.to.plot" %in% names(plotting.params) ) plotting.params[["patients.to.plot"]] <- patients.to.plot; # col.cats has already been parsed: if( "col.cats" %in% names(plotting.params) ) plotting.params[["col.cats"]] <- col.cats; # xlab has already been parsed: if( "xlab.dates" %in% names(plotting.params) && "xlab.days" %in% names(plotting.params) ){ plotting.params[["xlab"]] <- xlab; plotting.params["xlab.dates"] <- NULL; plotting.params["xlab.days"] <- NULL; } # ylab has already been parsed: if( "ylab.withoutcma" %in% names(plotting.params) && "ylab.withcma" %in% names(plotting.params) ){ plotting.params[["ylab"]] <- ylab; plotting.params["ylab.withoutcma"] <- NULL; plotting.params["ylab.withcma"] <- NULL; } # title has already been parsed: if( "title.aligned" %in% names(plotting.params) && "title.notaligned" %in% names(plotting.params) ){ plotting.params[["title"]] <- title.main; plotting.params["title.aligned"] <- NULL; plotting.params["title.notaligned"] <- NULL; } # medication.groups.to.plot has already been parsed: if( "medication.groups.to.plot" %in% names(plotting.params) ) plotting.params[["medication.groups.to.plot"]] <- medication.groups.to.plot; # plot.partial.CMAs.as has already been parsed: if( "plot.partial.CMAs.as" %in% names(plotting.params) ) plotting.params[["plot.partial.CMAs.as"]] <- plot.partial.CMAs.as; # alternating.bands.cols has already been parsed: plotting.params[["alternating.bands.cols"]] <- alternating.bands.cols; # Get the info about the plot exporting process: plot.file.dir <- .get.param.value("plot.save.to", type="character", default.value=shared.data.directory, required=FALSE); # Check if the directory exists and is writtable: if( !file.exists(plot.file.dir) || file.access(plot.file.dir, 2) != 0 ) { msg <- paste0("\nThe destination directory for plots '",plot.file.dir,"' does not exist or does not have write access!\n"); cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=15, runLast=FALSE); } plot.file.name <- paste0(plot.file.dir,"/adherer-plot."); plot.file.type <- .get.param.value("plot.save.as", type="character", default.value="jpg", required=FALSE); if( plot.file.type %in% c("jpg", "jpeg") ) { jpeg(paste0(plot.file.name,"jpg"), width=.get.param.value("plot.width", type="numeric", default.value=7, required=FALSE), height=.get.param.value("plot.height", type="numeric", default.value=7, required=FALSE), units="in", quality=.get.param.value("plot.quality", type="numeric", default.value=90, required=FALSE), res=.get.param.value("plot.dpi", type="numeric", default.value=150, required=FALSE)); } else if( plot.file.type %in% c("png") ) { png(paste0(plot.file.name,"png"), width=.get.param.value("plot.width", type="numeric", default.value=7, required=FALSE), height=.get.param.value("plot.height", type="numeric", default.value=7, required=FALSE), units="in", res=.get.param.value("plot.dpi", type="numeric", default.value=150, required=FALSE)); } else if( plot.file.type %in% c("tif", "tiff") ) { tiff(paste0(plot.file.name,"tiff"), width=.get.param.value("plot.width", type="numeric", default.value=7, required=FALSE), height=.get.param.value("plot.height", type="numeric", default.value=7, required=FALSE), units="in", compression="lzw", res=.get.param.value("plot.dpi", type="numeric", default.value=150, required=FALSE)); } else if( plot.file.type %in% c("eps") ) { postscript(paste0(plot.file.name,"eps"), width=.get.param.value("plot.width", type="numeric", default.value=7, required=FALSE), height=.get.param.value("plot.height", type="numeric", default.value=7, required=FALSE), horizontal=FALSE, onefile=FALSE, paper="special"); # make sure the output is EPS } else if( plot.file.type %in% c("pdf") ) { pdf(paste0(plot.file.name,"pdf"), width=.get.param.value("plot.width", type="numeric", default.value=7, required=FALSE), height=.get.param.value("plot.height", type="numeric", default.value=7, required=FALSE), onefile=FALSE, paper="special"); } # attempt to plot: msg <- capture.output(do.call("plot", c(list(results), plotting.params)), file=NULL, type="output"); if( length(msg) > 0 ) { dev.off(); # close the plotting device anyway cat(msg); cat(paste0(msg,"\n"), file=msg.file, append=TRUE); quit(save="no", status=0, runLast=FALSE); # Some plotting error seems to have occurred } # close the plotting device: dev.off(); } } msg <- "OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n"; cat(msg); cat(msg, file=msg.file, append=TRUE); quit(save="no", status=0, runLast=FALSE); # everything seems OK } #' getCallerWrapperLocation. #' #' This function returns the full path to where the various \code{wrappers} that #' can call \code{AdhereR} are installed. #' #' In most cases, these wrappers are one or more files in the calling language #' that may be directly used as such. #' For more details see the vignette describing the included reference #' \code{Python 3} wrapper. #' #' @param callig.platform A \emph{string} specifying the desired wrapper. #' Currently it can be "python3". #' @param full.path A \emph{logical} specifying if the returned path should #' also include the wrapper's main file name. #' @return The full path to the requested wrapper or NULL if none exists. #' @export getCallerWrapperLocation <- function(callig.platform=c("python3")[1], full.path=FALSE) { switch(tolower(callig.platform), "python3" = file.path(system.file(package="AdhereR"), "wrappers", "python3", ifelse(full.path,"adherer.py","")), NULL); }
/scratch/gouwar.j/cran-all/cranData/AdhereR/R/call-adherer-external.R
############################################################################################### # # This file is part of AdhereR. # Copyright (C) 2018 Samuel Allemann, Dan Dediu & Alexandra Dima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### # Declare some variables as global to avoid NOTEs during package building: globalVariables(c("ID", "DATE.IN", "DATE.OUT", "DISP.DATE", "PRESC.DATE", "episode.start", "episode.end", "VISIT", "DURATION", "SPECIAL.DURATION", ".PRESC.DURATION", "DAILY.DOSE", "TOTAL.DOSE", "DISP.START", "DISP.END", "DISP.EVENT", "CARRYOVER.DURATION", "INT.DURATION", "CUSTOM", "DATE", "active.episode", ".drop", ".interval", "SPECIAL.PERIOD", "POS.DOSE", "join_date", ".prune.event", ".from.carryover", ".new.events", "EVENT", "cum.duration", ".episode", ".out", ".special.periods", "time.to.initiation", "first.disp", "episode.start", "debug.mode")); #' Example prescription events for 16 patients. #' #' A sample dataset containing prescription events (one per row) for 16 patients #' over a period of roughly 15 months (1502 events in total). #' This is the appropriate format to compute event durations with the #' \code{compute_event_durations} function. Each row represents an individual prescription #' record for a specific dose of a specific medication for a patient at a given date. #' Visit number and Duration are optional, and more than one column to group medications #' can be supplied (such as ATC Code, Form or Unit). #' #' @format A data table with 1502 rows and 8 variables: #' \describe{ #' \item{ID}{\emph{integer} here; patient unique identifier. Can also #' be \emph{string}.} #' \item{DATE.PRESC}{\emph{Date} here;the prescription event date, by default in the #' yyyy-mm-dd format. Can also be \emph{string}.} #' \item{VISIT}{\emph{integer}; the consecutive number of the prescription instances. #' This column is optional and will be generated internally when not supplied. It is #' used to identify treatment interruptions.} #' \item{ATC.CODE}{\emph{character}; the medication type, according to the WHO ATC #' classification system. This can be a researcher-defined classification #' depending on study aims (e.g., based on therapeutic use, mechanism of #' action, chemical molecule, or pharmaceutical formulation). The \code{compute_event_durations} #' function will match prescribed medication to dispensed medications based on this variable.} #' \item{FORM}{\emph{character}; the galenic form of the prescribed preparation. #' This is optional and can be used as a separate variable to match between prescription and #' dispensing events.} #' \item{UNIT}{\emph{integer}; the unit of the prescribed dose. This is optional and can be used #' as a separate variable to match between prescription and dispensing events.} #' \item{PRESC.DURATION}{\emph{numeric}; the duration (in days) for which the prescription #' is intended. Can be \code{NA} if the prescription is continuous without a fixed end date.} #' \item{DAILY.DOSE}{\emph{numeric}; the daily dose prescribed during this event (e.g., \code{50} for 1 tablet #' of 50 mg per day or \code{25} for 1 tablet of 50 mg every two days).} #' } "durcomp.prescribing" #' Example dispensing events for 16 patients. #' #' A sample dataset containing dispensing events (one per row) for 16 patients #' over a period of roughly 24 months (1794 events in total). #' This is the appropriate format to compute event durations with the #' \code{compute_event_durations} function. Each row represents an individual dispensing #' record for a specific dose of a specific medication for a patient at a given date. #' More than one column to group medications can be supplied (such as ATC code, Form and Unit). #' #' @format A data frame with 1794 rows and 6 variables: #' \describe{ #' \item{ID}{\emph{integer} here; patient unique identifier. Can also #' be \emph{string}.} #' \item{DATE.DISP}{\emph{Date} here;the dispensing event date, by default in the #' yyyy-mm-dd format. Can also be \emph{string}.} #' \item{ATC.CODE}{\emph{character}; the medication type, according to the WHO ATC #' classification system. This can be a researcher-defined classification #' depending on study aims (e.g., based on therapeutic use, mechanism of #' action, chemical molecule, or pharmaceutical formulation). The \code{compute_event_durations} #' function will match prescribed medication to dispensed medications based on this variable.} #' \item{UNIT}{\emph{integer}; the unit of the dispensed dose. This is optional and can be used #' as a separate variable to match between prescription and dispensing events.} #' \item{FORM}{\emph{character}; the galenic form of the dispensed preparation. #' This is optional and can be used as a separate variable to match between prescription and #' dispensing events.} #' \item{TOTAL.DOSE}{\emph{numeric}; the total dispensed dose supplied at this #' medication event (e.g., \code{5000} for 10 tables of 500 mg).} #' } "durcomp.dispensing" #' Example special periods for 10 patients. #' #' A sample dataset containing special periods (one per row) for 10 patients #' over a period of roughly 18 months (28 events in total). #' This is the appropriate format to compute event durations with the #' \code{compute_event_durations} function. Each row represents an individual special period of type #' "hospitalization" of a patient for whom event durations should be calculated. #' Besides hospitalizations, this could cover other situations #' where medication use may differ, e.g. during incarcerations or holidays. #' All column names must match the format provided in this example. #' #' @format A data frame with 28 rows and 3 variables: #' \describe{ #' \item{ID}{\emph{Integer} here; patient unique identifier. Can also #' be \emph{string}.} #' \item{DATE.IN}{\emph{Date} here;the start of the hospitalization period, by default in the #' yyyy-mm-dd format.Can also be \emph{string}.} #' \item{DATE.OUT}{\emph{Date};the end of the hospitalization period, by default in the #' yyyy-mm-dd format. Can also be \emph{string}.} #' } "durcomp.hospitalisation" ################ function to construct treatment episodes from dispensing and prescription databases #' Computation of event durations. #' #' Computes event durations based on dispensing, prescription, and other data (e.g. #' hospitalization data) and returns a \code{data.frame} which can be used with the #' CMA constructors in \code{AdhereR}. #' #' Computation of CMAs requires a supply duration for medications dispensed to #' patients. If medications are not supplied for fixed durations but as a quantity #' that may last for various durations based on the prescribed dose, the supply #' duration has to be calculated based on dispensed and prescribed doses. Treatments #' may be interrupted and resumed at later times, for which existing supplies may #' or may not be taken into account. Patients may be hospitalized or incarcerated, #' and may not use their own supplies during these periods. This function calculates #' supply durations, taking into account the aforementioned situations and providing #' various parameters for flexible adjustments. #' #' @param disp.data A \emph{\code{data.frame}} or \emph{\code{data.table}} containing #' the dispensing events. Must contain, at a minimum, the patient unique ID, one #' medication identifier, the dispensing date, and total dispensed dose, and might #' also contain additional columns to identify and group medications (the actual #' column names are defined in the \emph{\code{medication.class.colnames}} parameter). #' @param presc.data A \emph{\code{data.frame}} containing the prescribing events. #' Must contain, at a minimum, the same unique patient ID and medication identifier(s) #' as the dispensing data, the prescription date, the daily prescribed dose, and the #' prescription duration. Optionally, it might also contain a visit number. #' @param special.periods.data Optional, \emph{\code{NULL}} or a \emph{\code{data.frame}} #' containing the information about special periods (e.g., hospitalizations or other situations #' where medication use may differ, e.g. during incarcerations or holidays). Must contain the same unique #' patient ID as dispensing and prescription data, the start and end dates of the special #' periods with the exact column names \emph{\code{DATE.IN}} and \emph{\code{DATE.OUT}}. #' Optional columns are \emph{\code{TYPE}} (indicating the type of special situation), #' customized instructions how to handle a specific period (see #' \code{special.periods.method}), and any of those specified in \code{medication.class.colnames}. #' @param ID.colname A \emph{string}, the name of the column in \code{disp.data}, #' \code{presc.data}, and \code{special.periods.data} containing the unique patient ID. #' @param medication.class.colnames A \emph{\code{Vector}} of \emph{strings}, the #' name(s) of the column(s) in \code{disp.data} and \code{presc.data} containing #' the classes/types/groups of medication. #' @param disp.date.colname A \emph{string}, the name of the column in #' \code{disp.data} containing the dispensing date (in the format given in #' the \code{date.format} parameter). #' @param total.dose.colname A \emph{string}, the name of the column in #' \code{disp.data} containing the total dispensed dose as \code{numeric} (e.g. #' \code{500} for 10 tablets of 50 mg). #' @param presc.date.colname A \emph{string}, the name of the column in #' \code{presc.data} containing the prescription date (in the format given in #' the \code{date.format} parameter). #' @param presc.daily.dose.colname A \emph{string}, the name of the column in #' \code{presc.data} containing the daily prescribed dose as \code{numeric} (e.g. #' \code{50} for 50 mg once per day, or 25 for 50 mg once ever 2 days). #' @param presc.duration.colname A \emph{string}, the name of the column in #' \code{presc.data} containing the duration of the prescription as \code{numeric} #' or \code{NA} if duration is unknown. #' @param visit.colname A \emph{string}, the name of the column in #' \code{presc.data} containing the number of the visit or a new column name if the #' prescribing data does not contain such a column. #' @param split.on.dosage.change \emph{Logical} or \emph{string}. If \code{TRUE} #' split the dispensing event on days with dosage change and create a new event with #' the new dosage for the remaining supply. If \emph{string}, the name of the column #' containing the \code{Logical} in \emph{disp.data} for each medication class separatly. #' Important if carryover should be considered later on. #' @param force.init.presc \emph{Logical}. If \code{TRUE} advance the date of the #' first prescription event to the date of the first dispensing event, if the first #' prescription event is after the first dispensing event for a specific medication. #' Only if the first prescription event is not limited in duration (as indicated in #' the \code{presc.duration.colname}). #' @param force.presc.renew \emph{Logical} or \emph{string}. If \code{TRUE} require #' a new prescription for all medications for every prescription event (visit), #' otherwise prescriptions end on the first visit without renewal. If \emph{string}, #' the name of the column in \emph{disp.data} containing the \code{Logical} for each #' medication class separatly. #' @param trt.interruption can be either of \emph{"continue"}, \emph{"discard"}, #' \emph{"carryover"}, or a \emph{string}. It indicates how to handle durations during #' treatment interruptions (see \code{special.periods.method}). #' If \emph{string}, the name of the (\emph{character}) column in \emph{disp.data} #' containing the information (\emph{"continue"}, \emph{"discard"}, or \emph{"carryover"}) #' for each medication class separatly. #' @param special.periods.method can be either of \emph{continue}, \emph{discard}, #' \emph{carryover}, or \emph{custom}. It indicates how to handle durations during special periods. #' With \emph{continue}, special periods have no effect on durations and event start dates. #' With \emph{discard}, durations are truncated at the beginning of special periods and the #' remaining quantity is discarded. With \emph{carryover}, durations are truncated #' at the beginning of a special period and a new event with the remaining duration #' is created after the end of the end of the special period. With \emph{custom}, the #' mapping has to be included in \emph{\code{special.periods.data}}. #' @param carryover \emph{Logical}, if \code{TRUE} apply carry-over to medications of the #' same type (according to \code{medication.class.colnames}). Can only be used together with #' CMA7 and above in combination with \code{carry.only.for.same.medication = TRUE}. #' @param date.format A \emph{string} giving the format of the dates used in #' the \code{data} and the other parameters; see the \code{format} parameters #' of the \code{\link[base]{as.Date}} function for details (NB, this concerns #' only the dates given as strings and not as \code{Date} objects). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any warnings. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param progress.bar \emph{Logical}, if \code{TRUE} show a progress bar. #' @param ... other possible parameters. #' @return A \code{list} with the following elements: #' \itemize{ #' \item \code{event_durations}: A \code{data.table} or \code{data.frame} with the following columns: #' \itemize{ #' \item \code{ID.colname} the unique patient ID, as given by the \code{ID.colname} #' parameter. #' \item \code{medication.class.colnames} the column(s) with classes/types/groups #' of medication, as given by the \code{medication.class.colnames} parameter. #' \item \code{disp.date.colname} the date of the dispensing event, as given by #' the \code{disp.date.colnema} parameter. #' \item \code{total.dose.colname} the total dispensed dose, as given by the #' \code{total.dose.colname} parameter. #' \item \code{presc.daily.dose.colname} the prescribed daily dose, as given by #' the \code{presc.daily.dose.colname} parameter. #' \item \code{DISP.START} the start date of the dispensing event, either the #' same as in \code{disp.date.colname} or a later date in case of dosage changes #' or treatment interruptions/hospitalizations. #' \item \code{DURATION} the calculated duration of the supply, based on the total #' dispensed dose and the prescribed daily dose, starting from the \code{DISP.START} #' date. #' \item \code{episode.start}: the start date of the current prescription episode. #' \item \code{episode.end}: the end date of the current prescription episode. #' Can be before the start date of the dispensing event if dispensed during a treatment interruption. #' \item \code{SPECIAL.DURATION} the number of days \emph{during} the current duration affected #' by special durations or treatment interruptions of type "continue". #' \item \code{CARRYOVER.DURATION} the number of days \emph{after} the current duration affected #' by special durations or treatment interruptions of type "carryover". #' \item \code{EVENT.ID}: in case of multiple events with the same dispensing date #' (e.g. for dosage changes or interruptions); a unique ID starting at 1 for the first event #' \item \code{tot.presc.interruptions} the total number of prescription interruptions #' per patient for a specific medication. #' \item \code{tot.dosage.changes} the total number of dosage changes per patient #' for a specific medication. #' } #' \item \code{prescription_episodes}: A \code{data.table} or \code{data.frame} with the following columns: #' \itemize{ #' \item \code{ID.colname}: the unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{medication.class.colnames}: the column(s) with classes/types/groups of medication, #' as given by the \code{medication.class.colnames} parameter. #' \item \code{presc.daily.dose.colname}: the prescribed daily dose, as given by the #' \code{presc.daily.dose.colname} parameter. #' \item \code{episode.start}: the start date of the prescription episode. #' \item \code{episode.duration}: the duration of the prescription episode in days. #' \item \code{episode.end}: the end date of the prescription episode. #' } #' \item \code{special_periods}: A \code{data.table} or \code{data.frame}, the \code{special.periods.data} #' with an additional column \code{SPECIAL.DURATION}: the number of days #' between \code{DATE.IN} and \code{DATE.OUT} #' \item \code{ID.colname} the name of the columns containing #' the unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{medication.class.colnames} the name(s) of the column(s) in \code{disp.data} #' and \code{presc.data} containing the classes/types/groups of medication, as given by the #' \code{medication.class.colnames} parameter. #' \item \code{disp.date.colname} the name of the column in #' \code{disp.data} containing the dispensing date, as given in the \code{disp.date.colname} #' parameter. #' \item \code{total.dose.colname} the name of the column in #' \code{disp.data} containing the total dispensed dose, as given by the #' \code{total.dose.colname} parameter. #' \item \code{presc.date.colname} the name of the column in #' \code{presc.data} containing the prescription date, as given in the \code{presc.date.colname} #' parameter. #' \item \code{presc.daily.dose.colname} the name of the column in #' \code{presc.data} containing the daily prescribed dose, as given by the #' \code{presc.daily.dose.colname} parameter. #' \item \code{presc.duration.colname} the name of the column in #' \code{presc.data} containing the duration of the prescription, as given by the #' \code{presc.duration.colname} parameter. #' \item \code{visit.colname} the name of the column containing the number of the visit, #' as given by the \code{visit.colname} parameter #' \item \code{split.on.dosage.change} whether to split the dispensing event on days with dosage changes #' and create a new event with the new dosage for the remaining supply, as given by the #' \code{split.on.dosage.change} parameter. #' \item \code{force.init.presc} whether the date of the first prescription event was set back #' to the date of the first dispensing event, when the first prescription event was after the #' first dispensing event for a specific medication, as given by the \code{force.init.presc} parameter. #' \item \code{force.presc.renew} whether a new prescription was required for all medications for every #' prescription event (visit), as given by the \code{force.presc.renew} parameter. #' \item \code{trt.interruption} how durations during treatment interruptions were handled, as given #' by the \code{trt.interruption} parameter. #' \item \code{special.periods.method} as given by the \code{special.periods.method} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' } #' @examples #' \dontrun{ #' event_durations <- compute_event_durations(disp.data = durcomp.dispensing, #' presc.data = durcomp.prescribing, #' special.periods.data = durcomp.hospitalisation, #' ID.colname = "ID", #' presc.date.colname = "DATE.PRESC", #' disp.date.colname = "DATE.DISP", #' medication.class.colnames = c("ATC.CODE", #' "UNIT", "FORM"), #' total.dose.colname = "TOTAL.DOSE", #' presc.daily.dose.colname = "DAILY.DOSE", #' presc.duration.colname = "PRESC.DURATION", #' visit.colname = "VISIT", #' split.on.dosage.change = TRUE, #' force.init.presc = TRUE, #' force.presc.renew = TRUE, #' trt.interruption = "continue", #' special.periods.method = "continue", #' date.format = "%Y-%m-%d", #' suppress.warnings = FALSE, #' return.data.table = TRUE); #' } #' @export compute_event_durations <- function(disp.data = NULL, presc.data = NULL, special.periods.data = NULL, ID.colname, medication.class.colnames, disp.date.colname, total.dose.colname, presc.date.colname, presc.daily.dose.colname, presc.duration.colname, visit.colname, split.on.dosage.change = TRUE, force.init.presc = FALSE, force.presc.renew = FALSE, trt.interruption = c("continue", "discard", "carryover")[1], special.periods.method = trt.interruption, carryover = FALSE, date.format = "%d.%m.%Y", suppress.warnings = FALSE, return.data.table = FALSE, progress.bar = TRUE, ...) { # set carryover to false # carryover <- FALSE # remove when carryover argument is properly implemented # Preconditions: { # dispensing data class and dimensions: if( inherits(disp.data, "matrix") ) disp.data <- as.data.table(disp.data); # convert matrix to data.table if( !inherits(disp.data, "data.frame") ) { if( !suppress.warnings ) warning("The dispensing data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(disp.data) < 1 ) { if( !suppress.warnings ) warning("The dispensing data must have at least one row!\n"); return (NULL); } # prescribing data class and dimensions: if( inherits(presc.data, "matrix") ) presc.data <- as.data.table(presc.data); # convert matrix to data.table if( !inherits(presc.data, "data.frame") ) { if( !suppress.warnings ) warning("The prescribing data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(presc.data) < 1 ) { if( !suppress.warnings ) warning("The prescribing data must have at least one row!\n"); return (NULL); } # special period data class and dimensions: if(!is.null(special.periods.data)) { special.periods.data <- copy(special.periods.data) if( inherits(special.periods.data, "matrix") ) special.periods.data <- as.data.table(special.periods.data); # convert matrix to data.table if( !inherits(special.periods.data, "data.frame") ) { if( !suppress.warnings ) warning("The special periods data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(special.periods.data) < 1 ) { if( !suppress.warnings ) warning("The special periods data must have at least one row!\n"); return (NULL); } if(!all(c(ID.colname, "DATE.IN", "DATE.OUT") %in% colnames(special.periods.data))) { if( !suppress.warnings ) warning(paste0("The special periods data must contain at least all columns with the names '", ID.colname, "', 'DATE.IN', and 'DATE.OUT'.\n Please refer to the documentation for more information.\n")); return (NULL); } # if(!all(colnames(special.periods.data) %in% c(ID.colname, "DATE.IN", "DATE.OUT", "TYPE", special.periods.method, medication.class.colnames))) # { # if( !suppress.warnings ) warning(paste0("The special periods data can only contain columns # with the names \"", ID.colname, "\", \"DATE.IN\", \"DATE.OUT\", \"TYPE\", ", # paste(shQuote(medication.class.colnames), collapse = ", "), ", and a column with # customized instructions how to handle a specific period.\n # Please refer to the documentation for more information.\n")); # return (NULL); # } if( !special.periods.method %in% c("continue", "discard", "carryover") && !special.periods.method %in% names(special.periods.data)) { if( !suppress.warnings ) warning(paste0("special.periods.method must be either of 'continue', 'discard', 'carryover', or a column name in the special periods data!\n")); return (NULL); } if(special.periods.method %in% names(special.periods.data) && any(!unique(special.periods.data[[special.periods.method]] %in% c("continue", "discard", "carryover")))) { unexpected.values <- unique(special.periods.data[[special.periods.method]][!special.periods.data[[special.periods.method]] %in% c("continue", "discard", "carryover")]) if( !suppress.warnings ) warning(paste0("Column special.periods.method='",special.periods.method, "' in special periods data contains unexpected values: ", unexpected.values,"\n")); return (NULL); } } # the column names must exist in dispensing and prescription data: if( !is.na(ID.colname) && !(ID.colname %in% names(disp.data)) && !(ID.colname %in% names(presc.data))) { if( !suppress.warnings ) warning(paste0("Column ID.colname='",ID.colname,"' must appear in the dispensing and prescribing data!\n")); return (NULL); } if( !is.na(presc.date.colname) && !(presc.date.colname %in% names(presc.data)) ) { if( !suppress.warnings ) warning(paste0("Column presc.date.colname='",presc.date.colname,"' must appear in the prescribing data!\n")); return (NULL); } if(anyNA(presc.data[[presc.date.colname]])){ if( !suppress.warnings ) warning(paste0("Column presc.date.colname='",presc.date.colname,"' cannot contain missing values!\n")); return (NULL); } if( !is.na(disp.date.colname) && !(disp.date.colname %in% names(disp.data)) ) { if( !suppress.warnings ) warning(paste0("Column disp.date.colname='",disp.date.colname,"' must appear in the dispensing data!\n")); return (NULL); } if(anyNA(disp.data[[disp.date.colname]])){ if( !suppress.warnings ) warning(paste0("Column disp.date.colname='",disp.date.colname,"' cannot contain missing values!\n")); return (NULL); } if( any(!is.na(medication.class.colnames) & !(medication.class.colnames %in% names(disp.data)) & !(medication.class.colnames %in% names(presc.data))) ) # deal with the possibility of multiple column names { if( !suppress.warnings ) warning(paste0("Column(s) medication.class.colnames=",paste0("'",medication.class.colnames,"'",collapse=",")," must appear in the dispensing and prescribing data!\n")); return (NULL); } if( !is.na(total.dose.colname) && !(total.dose.colname %in% names(disp.data)) ) { if( !suppress.warnings ) warning(paste0("Column total.dose.colname='",total.dose.colname,"' must appear in the dispensing data!\n")); return (NULL); } if(anyNA(disp.data[[total.dose.colname]])){ if( !suppress.warnings ) warning(paste0("Column total.dose.colname='",total.dose.colname,"' cannot contain missing values!\n")); return (NULL); } if( !is.na(presc.daily.dose.colname) && !(presc.daily.dose.colname %in% names(presc.data)) ) { if( !suppress.warnings ) warning(paste0("Column presc.daily.dose.colname='",presc.daily.dose.colname,"' must appear in the prescribing data!\n")); return (NULL); } if(anyNA(presc.data[[presc.daily.dose.colname]])){ if( !suppress.warnings ) warning(paste0("Column presc.daily.dose.colname='",presc.daily.dose.colname,"' cannot contain missing values!\n")); return (NULL); } if( !is.na(presc.duration.colname) && !(presc.duration.colname %in% names(presc.data)) ) { if( !suppress.warnings ) warning(paste0("Column presc.duration.colname='",presc.duration.colname,"' must appear in the prescribing data!\n")); return (NULL); } if( visit.colname %in% colnames(presc.data) ) { if(anyNA(presc.data[[visit.colname]])){ if( !suppress.warnings ) warning(paste0("Column visit.colname='",visit.colname,"' cannot contain missing values!\n")); return (NULL); } } if( !is.logical(force.presc.renew) && !force.presc.renew %in% names(disp.data) ) { if( !suppress.warnings ) warning(paste0("Column force.presc.renew='",force.presc.renew,"' must appear in the dispensing data!\n")); return (NULL); } if( !is.logical(split.on.dosage.change) && !split.on.dosage.change %in% names(disp.data) ) { if( !suppress.warnings ) warning(paste0("Column split.on.dosage.change='",split.on.dosage.change,"' must appear in the dispensing data!\n")); return (NULL); } if( !trt.interruption %in% c("continue", "discard", "carryover") && !trt.interruption %in% names(disp.data)) { if( !suppress.warnings ) warning(paste0("trt.interruption must be either of 'continue', 'discard', 'carryover', or a column name in the dispensing data!\n")); return (NULL); } if(trt.interruption %in% names(disp.data) && any(!unique(disp.data[[trt.interruption]]) %in% c("continue", "discard", "carryover"))) { unexpected.values <- unique(disp.data[[trt.interruption]][disp.data[[trt.interruption]] %in% c("continue", "discard", "carryover")]) if( !suppress.warnings ) warning(paste0("Column trt.interruption='",trt.interruption, "' contains unexpected values: ", unexpected.values,"\n")); return (NULL); } if(".episode" %in% colnames(presc.data)){ { if( !suppress.warnings ) warning("The column name \'.episode\' is used internally, please use another column name."); return (NULL); } } if( is.na(date.format) || is.null(date.format) || length(date.format) != 1 || !is.character(date.format) ) { if( !suppress.warnings ) warning(paste0("The date format must be a single string!\n")); return (NULL); } } ## Force data to data.table if( !inherits(disp.data,"data.table") ) disp.data <- as.data.table(disp.data); if( !inherits(presc.data,"data.table") ) presc.data <- as.data.table(presc.data); # copy datasets disp.data.copy <- copy(disp.data) presc.data.copy <- copy(presc.data) # convert column names setnames(presc.data.copy, old = c(ID.colname, presc.date.colname, presc.daily.dose.colname, presc.duration.colname), new = c("ID", "PRESC.DATE", "DAILY.DOSE", "episode.duration")) setnames(disp.data.copy, old = c(ID.colname, disp.date.colname, total.dose.colname), new = c("ID", "DISP.DATE", "TOTAL.DOSE")) # convert dates disp.data.copy[,DISP.DATE := as.Date(DISP.DATE, format = date.format)]; presc.data.copy[,PRESC.DATE := as.Date(PRESC.DATE, format = date.format)]; if(!is.null(special.periods.data)) { ## Force data to data.table if( !inherits(special.periods.data,"data.table") ) special.periods.data <- as.data.table(special.periods.data); # copy datasets special.periods.data.copy <- copy(special.periods.data) setnames(special.periods.data.copy, old = c(ID.colname), new = c("ID")) special.periods.data.copy[,`:=` (DATE.IN = as.Date(DATE.IN, format = date.format), DATE.OUT = as.Date(DATE.OUT, format = date.format))]; special.periods.data.copy[,SPECIAL.DURATION := as.numeric(DATE.OUT-DATE.IN)]; } else {special.periods.data.copy <- NULL} # force medication class to character for(class.colname in medication.class.colnames) { if(inherits(disp.data.copy[[class.colname]], "factor")) { disp.data.copy[,(class.colname) := as.character(get(class.colname))]; } if(inherits(presc.data.copy[[class.colname]], "factor")) { presc.data.copy[,(class.colname) := as.character(get(class.colname))]; } } # add prescription duration column if NA is provided if( is.na(presc.duration.colname) ) { presc.data.copy[,.PRESC.DURATION := NA] presc.duration.colname <- ".PRESC.DURATION" } # add event ID disp.data.copy[,EVENT.ID := 1] # helper function to process each patient process_patient <- function(pat) { # helper function to process each medication process_medication <- function(med) { # helper function to process each dispensing event process_dispensing_events <- function(event) { # helper function to compute special intervals compute.special.intervals <- function(data, DATE.IN.colname = "DATE.IN", DATE.OUT.colname = "DATE.OUT", TYPE.colname = "TYPE", CUSTOM.colname = special.periods.method) { if(CUSTOM.colname %in% colnames(data)){ setnames(data, old = CUSTOM.colname, new = "CUSTOM") } else { data[,CUSTOM := special.periods.method]} # convert dates data[, (DATE.IN.colname) := as.Date(get(DATE.IN.colname), format = date.format)] data[, (DATE.OUT.colname) := as.Date(get(DATE.OUT.colname), format = date.format)] # add durations data[,DURATION := as.numeric(get(DATE.OUT.colname) - get(DATE.IN.colname))] # add episodes data[,.episode := seq_len(.N)] # melt special episodes data.melt <- melt(data, measure.vars = c(DATE.IN.colname, DATE.OUT.colname), variable.name = "EVENT", value.name = "DATE") # sort by DATE.IN setkeyv(data.melt, cols = c("DATE", ".episode")) # add dispensing event data.melt <- rbind(data.melt, data.table(ID = pat, DATE = disp.start.date.i, EVENT = "DISP.DATE", .episode = 0), fill = TRUE) # find row with end of episode data.melt <- rbind(data.melt, data.table(ID = pat, DATE = end.episode, EVENT = "episode.end", .episode = -1), fill = TRUE) data.melt[, EVENT := factor(EVENT, levels = c("DATE.OUT", "DISP.DATE", "DATE.IN", "episode.end"))] setorderv(data.melt, cols = c("DATE", "EVENT", ".episode"), na.last = TRUE) # calculate durations of intersections data.melt[,`:=` (DISP.EVENT = 0, CARRYOVER.DURATION = 0, INT.DURATION = as.numeric(shift(DATE, n = 1, type = "lead")-DATE))] # find active period data.melt[,active.episode := sapply(seq(nrow(data.melt)), function(x) { dt <- data.melt[seq(x)] closed.episodes <- dt[duplicated(dt[,.episode]),.episode] active.episode <- dt[!.episode %in% closed.episodes, suppressWarnings(max(.episode))] })] # indicate intersections that should be counted data.melt[active.episode %in% unique(data.melt[CUSTOM == "continue", .episode]), `:=` (SPECIAL.PERIOD = 1, DISP.EVENT = 1)] data.melt[active.episode == 0, DISP.EVENT := 1] # calculat durations during carryover if( "carryover" %in% unique(data.melt$CUSTOM) ){ data.melt[active.episode %in% unique(data.melt[CUSTOM == "carryover", .episode]), CARRYOVER.DURATION := INT.DURATION] # remove duration during carryover data.melt[CARRYOVER.DURATION != 0, INT.DURATION := 0] } # remove events before dispensing date and after end date first.row <- data.melt[EVENT == "DISP.DATE", which = TRUE] last.row <- data.melt[EVENT == "episode.end", which = TRUE] data.melt <- data.melt[first.row:last.row] # identify rows after discard data.melt[, .drop := 0] if("discard" %in% data$CUSTOM){ data.melt[,DISP.EVENT := 0] data.melt[CUSTOM == "discard", DISP.EVENT := 1] data.melt[,.drop := cumsum(DISP.EVENT)] data.melt[CUSTOM == "discard" & EVENT == DATE.IN.colname, .drop := .drop-1] # remove durations after discard data.melt[CUSTOM == "discard", `:=` (DISP.EVENT = 0, INT.DURATION = 0)] } # drop rows after discard data.melt.drop <- data.melt[.drop == 0] # create intervals of continuous use data.melt.drop[,.interval := rleidv(data.melt.drop, cols = "DISP.EVENT")] data.melt.drop[DISP.EVENT == 1,.interval := as.integer(.interval+1)] # calculate sum of all durations sum.duration <- sum(data.melt.drop$INT.DURATION, na.rm = TRUE); # if the supply duration is shorter than the sum of the duration if(duration.i <= sum.duration) { # calculate cumulative sum of durations data.melt.drop[,cum.duration := cumsum(INT.DURATION)]; # subset to all rows until supply is exhaused and add 1 .rows <- data.melt.drop[cum.duration <= duration.i,which=TRUE]; if( length(.rows) == 0 ) {.rows <- 0}; data.melt.drop <- data.melt.drop[c(.rows, tail(.rows,1)+1)]; # calculate remaining duration for last row sum.duration <- sum(head(data.melt.drop,-1)$INT.DURATION); data.melt.drop[nrow(data.melt.drop), INT.DURATION := duration.i-sum.duration]; } # calculate total duration data.melt.drop[,DURATION := sum(INT.DURATION, na.rm = TRUE), by = .interval] # calculate duration covered during special intervals data.melt.drop[,SPECIAL.DURATION := 0] data.melt.drop[SPECIAL.PERIOD == 1, SPECIAL.DURATION := sum(INT.DURATION, na.rm = TRUE), by = .interval] # data.melt.drop[(CUSTOM == "continue" & EVENT == DATE.IN.colname) | (shift(CUSTOM, n = 1, type = "lead") == "continue" & shift(EVENT, n = 1, type = "lead") == DATE.OUT.colname), # | (shift(CUSTOM, n = 1, type = "lag") == "continue" & shift(EVENT, n = 1, type = "lag") == DATE.IN.colname), # SPECIAL.DURATION := sum(INT.DURATION, na.rm = TRUE), by = .interval] data.melt.drop[,SPECIAL.DURATION := max(SPECIAL.DURATION, na.rm = TRUE), by = .interval] # calculate duration NOT covered during special intervals data.melt.drop[,CARRYOVER.DURATION := sum(CARRYOVER.DURATION, na.rm = TRUE), by = .interval] # subset to first and last row of interval events <- data.melt.drop[ data.melt.drop[, .I[c(1L,.N)], by=.interval]$V1 ] events[,CUSTOM := last(CUSTOM), by = .interval] # convert to wide format with start and end date of intervals events[,EVENT := rep(c("DISP.START", "DISP.END"), nrow(events)/2)] all.events <- dcast(events, ID + CUSTOM + DURATION + SPECIAL.DURATION + CARRYOVER.DURATION + .interval ~ EVENT, value.var = "DATE") setorderv(all.events, cols = ".interval") # create event IDs all.events[,EVENT.ID := seq(from = event_id, length.out = nrow(all.events), by = 1)] # create all events table all.events <- cbind(all.events[,c("ID", "CUSTOM", "EVENT.ID", "DISP.START", "DURATION", "SPECIAL.DURATION", "CARRYOVER.DURATION"), with = FALSE], data.table(DAILY.DOSE = as.numeric(presc.dose.i), episode.start = start.episode, episode.end = end.episode)) return(all.events) } if(exists("debug.mode") && debug.mode==TRUE) print(paste("Event:", event)); ## !Important: We assume that the prescribed dose can be accomodated with the dispensed medication #subset data to event curr_disp <- med_disp[event]; orig.disp.date <- curr_disp[["DISP.DATE"]] # if current dispensing event is before first prescription date, don't calculate a duration if(orig.disp.date < first_presc[["PRESC.DATE"]]) { med_event <- cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], DISP.START = orig.disp.date, DURATION = 0, DAILY.DOSE = NA, SPECIAL.DURATION = NA); # if current dispensing event is after end of last prescription episode, don't calculate a duration (only when last prescription indicates termination) } else { #select prescription episodes ending after the original dispensing date episodes <- med_presc[orig.disp.date < episode.end | is.na(episode.end), which = TRUE]; ## for each prescription episode, calculate the duration with the current dose total.dose.i <- curr_disp[["TOTAL.DOSE"]]; #dispensed dose presc.dose.i <- 0; # initialize prescibed dose as 0 disp.start.date.i <- orig.disp.date; #start date of dispensing event ## check for carry-over status and adjust start date in case of carry-over from last event if( carryover == TRUE){ if(length(last.disp.end.date) > 0 && !is.na(last.disp.end.date) && last.disp.end.date > disp.start.date.i ) { disp.start.date.i <- last.disp.end.date #select prescription episodes ending after the original dispensing date episodes <- med_presc[disp.start.date.i < episode.end | is.na(episode.end), which = TRUE]; } } # if the current dispensing event is after the last prescription episode, don't calculate a duration if(length(episodes) == 0 | out.of.presc == TRUE) { med_event <- cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], DISP.START = orig.disp.date, DURATION = NA, DAILY.DOSE = NA, SPECIAL.DURATION = NA); } else { #select prescription episodes ending after the original dispensing date and add the one immediately before curr_med_presc <- copy(med_presc) # if supply should be finished with original dose, collapse consecutive episodes with dosage > 0 if(split.on.dosage.change == FALSE){ curr_med_presc[(orig.disp.date < episode.end | is.na(episode.end)) & DAILY.DOSE > 0,POS.DOSE := 1] curr_med_presc[,.episode := rleidv(.SD, cols = "POS.DOSE")] curr_med_presc[POS.DOSE == 1,episode.start := head(episode.start,1), by = .episode]; # first start date per episode curr_med_presc[POS.DOSE == 1,episode.end:= tail(episode.end,1), by = .episode]; # last end date per episode curr_med_presc[POS.DOSE == 1,DAILY.DOSE:= head(DAILY.DOSE,1), by = .episode]; # first dosage per episode curr_med_presc <- unique(curr_med_presc, by = c("episode.start", "episode.end"), fromLast = TRUE); curr_med_presc[,.episode := rleidv(curr_med_presc, cols = c("episode.start", "episode.end"))]; #select prescription episodes ending after the original dispensing date episodes <- curr_med_presc[orig.disp.date < episode.end | is.na(episode.end), which = TRUE]; } # rm.trt.episode <- FALSE; # will be set to TRUE in case of calculations during treatment interruptions stop <- 0; med_event <- NULL; event_id <- 0 for(episode in episodes) {event_id <- event_id + 1 presc.dose.i <- curr_med_presc[[episode,"DAILY.DOSE"]]; # prescribed daily dose start.episode <- curr_med_presc[episode,episode.start]; end.episode <- curr_med_presc[episode,episode.end]; if(presc.dose.i == 0) # if event happens during treatment interruption (prescribed dose = 0), check what to do { if(trt.interruption == "continue") # if trt.interruption is set to continue, continue with last prescribed dose { presc.dose.i <- curr_med_presc[[episode-1,"DAILY.DOSE"]]; # adjust prescription episode to previous episode start.episode <- curr_med_presc[episode-1,episode.start]; end.episode <- curr_med_presc[episode-1,episode.end]; stop <- 1; # rm.trt.episode <- TRUE; # make sure that prescription start- and end date are removed at the end } else if(trt.interruption == "discard") # if trt.interruption is set to discard, don't calculate anything { if(is.null(med_event)) { med_event <- cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], EVENT.ID = event_id, DISP.START = disp.start.date.i, DURATION = 0, DAILY.DOSE = NA, SPECIAL.DURATION = NA); } break } else { episode <- episode + 1; # else skip to next episode next; } } # if disp.start.date.i is after end.episode date, go to next episode. if( !is.na(curr_med_presc[episode,episode.end]) & disp.start.date.i >= curr_med_presc[episode,episode.end] ) { next; } # if it is not the first episode, adjust supply start date to prescription start date if(episode != episodes[1]) disp.start.date.i <- curr_med_presc[episode,episode.start]; duration.i <- total.dose.i/presc.dose.i; # calculate duration disp.end.date.i <- disp.start.date.i + duration.i; # calculate end date of supply # add special durations during the supply period special.periods.duration.i <- 0; if(nrow(med_special.periods_events) != 0 & !is.na(duration.i)) { # check for special durations within the episode med_special.periods_events_i <- med_special.periods_events[(DATE.IN <= end.episode|is.na(end.episode)) & DATE.OUT > start.episode]; if(nrow(med_special.periods_events_i) > 0) { all.events <- compute.special.intervals(med_special.periods_events_i); event_id <- last(all.events$EVENT.ID) sum.duration <- sum(all.events$DURATION, na.rm = TRUE) # if last line is "discard", create med_event if(!is.na(last(all.events$CUSTOM)) && last(all.events$CUSTOM) == "discard") { med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], all.events[,3:10]), fill = TRUE); break; } else if( duration.i == sum.duration ) # if supply is equal to the sum of durations { med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], all.events[,3:10]), fill = TRUE); break; } else if(is.na(last(all.events$episode.end))) # if last event is not terminated { all.events[nrow(all.events), DURATION := DURATION + (duration.i-sum.duration)]; med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], all.events[,3:10]), fill = TRUE); break; } else # if supply duration is longer than the sum of the durations { # calculate the carryover dose oversupply <- duration.i-sum.duration; # calculate remaining days of oversupply total.dose.i <- presc.dose.i*oversupply; # calculate remaining total dose med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], all.events[,3:10]), fill = TRUE); next; } } } # check various parameters to decide wheter to stop or continue # check if end of supply is before end of episode OR last row of prescription episodes is reached if( disp.end.date.i < curr_med_presc[episode,episode.end] | episode == last(episodes) ) { stop <- 1; } else { episode <- episode + 1; # get next prescription episode next.presc.dose <- curr_med_presc[[episode,"DAILY.DOSE"]]; # get next episode's dosage # if there is a treatment interruption and trt.interruption is set to continue, stop if( next.presc.dose == 0 & trt.interruption == "continue" ) stop <- 1; # if there is no treatment interruption, but a dosage change and split.on.dosage.change is set FALSE, stop if( next.presc.dose != 0 & next.presc.dose != presc.dose.i & split.on.dosage.change == FALSE ) stop <- 1; } if( stop == 1 ) { # if( rm.trt.episode == TRUE ) # { # start.episode <- as.Date(NA, format = date.format); # end.episode <- as.Date(NA, format = date.format); # } med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], data.table(EVENT.ID = event_id, DISP.START = disp.start.date.i, DURATION = as.numeric(duration.i), episode.start = start.episode, episode.end = end.episode, DAILY.DOSE = as.numeric(presc.dose.i), SPECIAL.DURATION = as.numeric(special.periods.duration.i))), fill = TRUE); break; } else { duration.i <- end.episode - disp.start.date.i; # calculate duration until end of episode oversupply <- disp.end.date.i - end.episode; # calculate remaining days of oversupply total.dose.i <- presc.dose.i*oversupply; # calculate remaining total dose # if( rm.trt.episode == TRUE ) # { # start.episode <- as.Date(NA, format = date.format); # end.episode <- as.Date(NA, format = date.format); # } #create medication event med_event <- rbind(med_event, cbind(curr_disp[,c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE"), with = FALSE], data.table(EVENT.ID = event_id, DISP.START = disp.start.date.i, DURATION = as.numeric(duration.i), episode.start = start.episode, episode.end = end.episode, DAILY.DOSE = as.numeric(presc.dose.i), SPECIAL.DURATION = as.numeric(special.periods.duration.i))), fill = TRUE); } } med_event; } } } if(exists("debug.mode") && debug.mode==TRUE) print(paste("Medication:", med)); ## subset data to medication setkeyv(pat_disp, medication.class.colnames); setkeyv(pat_presc, medication.class.colnames); med_disp <- pat_disp[list(disp_presc[med, medication.class.colnames, with = FALSE])]; med_presc <- pat_presc[list(disp_presc[med, medication.class.colnames, with = FALSE])]; setkeyv(med_disp, cols = "DISP.DATE"); setkeyv(med_presc, cols = "PRESC.DATE"); med_special.periods_events <- copy(special.periods_events) if( !is.null(special.periods.data) ) { special.colnames <- intersect(medication.class.colnames, colnames(special.periods.data.copy)) if( length(special.colnames) > 0 ) { setkeyv(special.periods_events, special.colnames); med_special.periods_events <- special.periods_events[list(disp_presc[med, special.colnames, with = FALSE])]; } setkeyv(med_special.periods_events, cols = "DATE.IN") } # determine date of initial prescription first_presc <- med_presc[1]; # determine date of initial dispense first_disp <- med_disp[["DISP.DATE"]][1]; #if force.presc.renew, trt.interruption, and split.on.dosage.change are not set globally, set for medication based on first dispensing event if( !is.logical(force.presc.renew) ) { force.presc.renew <- as.logical(first_disp[[force.presc.renew]]); } if( !trt.interruption %in% c("continue", "discard", "carryover") ) { trt.interruption <- as.logical(first_disp[[trt.interruption]]); } if( !is.logical(split.on.dosage.change) ) { split.on.dosage.change <- as.logical(first_disp[[split.on.dosage.change]]); } ## calculate treatment interruptions and end of prescription date ## determine end of prescription and prescription interruptions if prescription reneval is enforced for each subsequent prescription event (requires the "visit" column) presc_interruptions <- data.table(NULL); if( force.presc.renew == TRUE ) { presc_visit <- presc_events[[visit.colname]] %in% unique(med_presc[[visit.colname]]); # determine for each visit if medication was prescribed first_presc_event <- head(which(presc_visit),1); # extract first prescription event last_presc_event <- tail(which(presc_visit),1); # extract last prescription event presc_omit <- which(!presc_visit)[which(!presc_visit) > first_presc_event & which(!presc_visit) < last_presc_event]; # identify visits between first and last prescription with missing prescriptions interruption_dates <- presc_events[["PRESC.DATE"]][presc_omit]; # determine dates of treatment interruptions presc_interruptions <- med_presc[rep(1, length(presc_omit))]; # create table with one row for each interruption presc_interruptions[, c(visit.colname, "PRESC.DATE", "DAILY.DOSE", "episode.duration") := list(presc_events[[visit.colname]][presc_omit], interruption_dates, 0, NA)]; # adjust variables med_presc <- rbind(med_presc, presc_interruptions); # bind to existing prescriptions setkeyv(med_presc, cols = "PRESC.DATE"); # order by date med_presc[,.episode := rleidv(med_presc, cols = "DAILY.DOSE")]; # add counter for treatment episodes } setorder(med_presc); ## construct treatment episodes # create new .episode counter med_presc[,.episode := rleidv(med_presc, cols = c("DAILY.DOSE", "episode.duration"))]; # if consecutive episodes with set end date, increase .episode counter if( nrow(med_presc) > 2 ) { for( n in 2:(nrow(med_presc))) { if( !is.na(med_presc[n,"episode.duration", with = FALSE]) & !is.na(med_presc[n-1,"episode.duration", with = FALSE]) ) { med_presc[n:nrow(med_presc), .episode := as.integer(.episode + 1)]; } } } else if( nrow(med_presc) == 2 ) { med_presc[!is.na(shift(episode.duration, type = "lag")) & !is.na(episode.duration), .episode := as.integer(.episode + 1)]; } # add episodes with same dose but set end date to last episode .row <- med_presc[is.na(shift(episode.duration, type = "lag")) & shift(DAILY.DOSE, type = "lag") == DAILY.DOSE & !is.na(episode.duration), which = TRUE]; if( length(.row)>0 ) { med_presc[.row:nrow(med_presc),.episode := as.integer(.episode-1)]; } ## set start and end of prescription dates per group med_presc[, `:=` (episode.start = PRESC.DATE, # set prescription date as start date episode.end = PRESC.DATE)]; # set end date to prescription date ... med_presc[,episode.end := shift(episode.end, type = "lead")]; # ... and shift end dates up by one # adjust end date if prescription duration is provided and change start date of following prescriptions med_presc[!is.na(episode.duration) & ((PRESC.DATE + episode.duration) <= episode.end | is.na(episode.end)), episode.end := PRESC.DATE + episode.duration]; # only if prescription ends before the current end prescription date! end.limited.presc <- head(med_presc,-1)[!is.na(episode.duration) & ((PRESC.DATE + episode.duration) <= episode.end | is.na(episode.end))]$episode.end; #don't include last prescription episode med_presc[shift(!is.na(episode.duration), type = "lag") & shift((PRESC.DATE + episode.duration) <= episode.end, type = "lag"), episode.start := end.limited.presc]; med_presc[PRESC.DATE>episode.start & DAILY.DOSE != 0,episode.start:=PRESC.DATE]; # combine episodes with set durations with previous episodes of same dosage but unrestricted duration med_presc[shift(DAILY.DOSE,type="lag")==DAILY.DOSE & !is.na(shift(episode.duration,type="lag")) & shift(episode.end, type = "lag") == episode.start, .episode := as.integer(.episode-1)]; # fill in start and end dates by group med_presc[,episode.start := head(episode.start,1), by = .episode]; # first start date per episode med_presc[,episode.end:= tail(episode.end,1), by = .episode]; # last end date per episode med_presc[,PRESC.DATE := min(PRESC.DATE), by = .episode]; # set PRESC.DATE to first start date # collapse episodes med_presc <- unique(med_presc, by = ".episode", fromLast = TRUE); med_presc[,.episode := rleidv(med_presc, cols = c("episode.start", "episode.end"))]; # remove episodes where end date is before start date rm.episode <- med_presc[episode.end <= episode.start, which = TRUE]; if( length(rm.episode) > 0 ) { med_presc <- med_presc[-rm.episode]; } med_presc[,.episode := rleidv(med_presc)]; # collapse consecutive episodes where end date of the former is before start date of the latter med_presc[shift(episode.end,type = "lag") > episode.start & shift(DAILY.DOSE,type = "lag") == DAILY.DOSE, .episode := as.integer(.episode-1)]; med_presc[,episode.start := head(episode.start,1), by = .episode]; # first start date per episode med_presc[,episode.end:= tail(episode.end,1), by = .episode]; # last end date per episode med_presc <- unique(med_presc, by = ".episode"); med_presc[,.episode := rleidv(med_presc, cols = c("episode.start", "episode.end"))]; # add treatment interruptions med_presc <- rbind(med_presc,med_presc[shift(episode.start,type = "lead")!=episode.end][,c("DAILY.DOSE", "episode.start", ".episode") := list(0, episode.end, 0)]); setorder(med_presc, episode.start, episode.end); end.trt.interruptions <- med_presc[shift(episode.end,type = "lag")!=episode.start]$episode.start; med_presc[.episode == 0, episode.end := end.trt.interruptions]; if( force.init.presc == TRUE ) { # if initial dispense is before initial prescription, adjust date of initial prescription to match initial dispense # but only if first prescription is unlimited if( first_disp < first(med_presc[["episode.start"]]) & is.na(head(med_presc[["episode.duration"]],1)) ) { # adjust first prescription date first_presc[1, PRESC.DATE := first_disp]; med_presc[1, episode.start := first_disp]; } } ## calculate medication events for "simple" events not extending over multiple episodes or affected by special periods # add prescription events to dispensing events for( i in 1:nrow(med_presc) ) { med_disp[DISP.DATE >= med_presc[i,episode.start] & (DISP.DATE < med_presc[i,episode.end] | is.na(med_presc[i,episode.end])), c("episode.start", "episode.end", "DAILY.DOSE") := list(med_presc[i,episode.start], med_presc[i,episode.end],med_presc[i,DAILY.DOSE])]; } med_disp[,DURATION := (TOTAL.DOSE)/(DAILY.DOSE)]; med_disp[,`:=` (DISP.START = DISP.DATE, DISP.END = DISP.DATE+DURATION)]; med_disp[DISP.END > episode.end, .out := 1]; # add special periods to dispensing events med_disp[,.special.periods := as.numeric(NA)]; if( nrow(med_special.periods_events) != 0 ){ for( i in 1:nrow(med_special.periods_events) ) { med_disp[(DISP.END >= med_special.periods_events[i,DATE.IN] & DISP.START < med_special.periods_events[i,DATE.OUT])|(DISP.START >= med_special.periods_events[i,DATE.IN] & DISP.START < med_special.periods_events[i,DATE.OUT]), .special.periods := 1]; } } med_disp[DURATION == Inf | .out == 1 | .special.periods == 1, process.seq := 1] med_disp[,process.seq.num := rleidv(process.seq)] medication_events_rest <- NULL; out.of.presc <- FALSE # set flag for carryover processing if(carryover == TRUE){ # compute carryover med_disp[,carryover.from.last := as.numeric(shift(DISP.START+DURATION, type = "lag")-DISP.START)] med_disp[1,carryover.from.last := 0] med_disp[,carryover.total := cumsum(carryover.from.last)] # get first row with carryover index <- suppressWarnings(min(which(med_disp$carryover.total > 0))) if(index <= nrow(med_disp)){ med_disp[index:nrow(med_disp), process.seq := 1] } # create medication events before first carryover event medication_events <- med_disp[is.na(process.seq) & process.seq.num == 1, c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE", "EVENT.ID", "DISP.START", "DURATION", "DAILY.DOSE", "episode.start", "episode.end"), with = FALSE]; medication_events[,SPECIAL.DURATION := 0]; # subset to events with carryover or special periods med_disp <- med_disp[process.seq == 1 | process.seq.num > 1]; ## apply process_dispensing_events to each dispensing event last.disp.end.date <- last(medication_events[,DISP.START + DURATION]) #carryover.total <- 0#ifelse(nrow(medication_events) > 0, last(medication_events$carryover.total), 0) if( nrow(med_disp) > 0 ) {for(i in 1:nrow(med_disp)){ medication_events_i <- process_dispensing_events(event = i) medication_events_rest <- rbind(medication_events_rest, medication_events_i, fill = TRUE) # if DURATION is NA, set flag for all future events if(is.na(last(medication_events_i[,DURATION]))) { out.of.presc <- TRUE } else { # cache last dispensing end date last.disp.end.date <- last(medication_events_i[, DISP.START + DURATION]) } } } } else { medication_events <- med_disp[is.na(process.seq), c("ID", medication.class.colnames, "TOTAL.DOSE", "DISP.DATE", "EVENT.ID", "DISP.START", "DURATION", "DAILY.DOSE", "episode.start", "episode.end"), with = FALSE]; medication_events[,SPECIAL.DURATION := 0]; med_disp <- med_disp[process.seq == 1]; if( nrow(med_disp) > 0 ) { medication_events_rest <- do.call(rbindlist, list(l = lapply(1:nrow(med_disp), FUN = function(i) process_dispensing_events(event = i)), fill = TRUE)); } } medication_events <- rbind(medication_events, medication_events_rest, fill = TRUE); setorderv(medication_events,cols=c("DISP.DATE", "DISP.START")); if( force.presc.renew == TRUE ) # add number of prescription interruptions { tot.presc.interruptions <- nrow(med_presc[DAILY.DOSE==0]); medication_events[,tot.presc.interruptions := tot.presc.interruptions]; } if( split.on.dosage.change == TRUE ) # add number of dosage changes { tot.dosage.changes <- (nrow(med_presc) - 1 - 2*nrow(med_presc[DAILY.DOSE==0])); medication_events[,tot.dosage.changes := tot.dosage.changes]; } # presc_episode_no_dispense <- med_presc[!medication_events[,c("DAILY.DOSE","episode.start","episode.end")], # on = c("DAILY.DOSE","episode.start", "episode.end")]; # # presc_episode_no_dispense[,c(".episode","VISIT", "episode.duration", "PRESC.DATE") := NULL]; # # medication_events <- rbind(medication_events, presc_episode_no_dispense, fill = TRUE); # add episode number med_presc <- med_presc[DAILY.DOSE != 0, episode.ID := seq(.N)]; # calculate duration med_presc[,episode.duration := as.numeric(episode.end-episode.start)]; # compute prescription events prescription_events <- med_presc[DAILY.DOSE != 0, c("ID", medication.class.colnames, "DAILY.DOSE", "episode.ID", "episode.start", "episode.duration", "episode.end"), with = FALSE] return(list(DURATIONS = medication_events, PRESCRIPTION_EPISODES = prescription_events)); ################### end of process_medication ################### } if(exists("debug.mode") && debug.mode==TRUE) print(paste("Patient:",pat)); # subset data to patient pat_disp <- disp.data.copy[ID == pat, c("ID", "DISP.DATE", "EVENT.ID", medication.class.colnames, "TOTAL.DOSE"), with = FALSE]; pat_presc <- presc.data.copy[ID == pat, c("ID", "PRESC.DATE", medication.class.colnames, "DAILY.DOSE", "episode.duration"), with = FALSE]; if(visit.colname %in% colnames(presc.data.copy)){ pat_presc <- cbind(presc.data.copy[ID == pat, visit.colname, with = FALSE], pat_presc); }; # sort by DCI setkeyv(pat_disp, cols = medication.class.colnames); setkeyv(pat_presc, cols = medication.class.colnames); # extract unique dispensed/prescribed DCIs disp_unique <- unique(pat_disp[,c(medication.class.colnames), with = FALSE]); presc_unique <- unique(pat_presc[,c(medication.class.colnames), with = FALSE]); # extract medications present in both dispensing and prescription database (by DCI, Unit, and Form) disp_presc <- merge(disp_unique, presc_unique, by = c(medication.class.colnames), all=FALSE); # extract unique dispensed/prescribed DCIs not present in both databases disp_no_presc <- disp_unique[!presc_unique]; presc_no_disp <- presc_unique[!disp_unique]; #create visits if not supplied if( !visit.colname %in% colnames(presc.data.copy) ) { presc_events <- unique(pat_presc[,"PRESC.DATE"]); presc_events[,(visit.colname) := 0:(nrow(presc_events)-1)]; pat_presc <- merge(pat_presc, presc_events, by = "PRESC.DATE"); setorderv(pat_presc, medication.class.colnames); } else { presc_events <- unique(pat_presc[,c("PRESC.DATE", visit.colname), with = FALSE]); # extract prescription instances } # if duplicate visit numbers for different dates or vice versa, throw an error if( length(unique(presc_events[["PRESC.DATE"]])) != nrow(presc_events) ) { { if( !suppress.warnings ) warning("Prescription dates and visit number don't match for patient Nr.", pat); return (NULL); } } # extract special periods if( !is.null(special.periods.data) ) { special.periods_events <- special.periods.data.copy[ID == pat]; } else { special.periods_events <- data.table(NULL); } setkeyv(presc_events, cols = "PRESC.DATE"); # apply process_medication() function to each medication present in both databses patient_events <- NULL; if( nrow(disp_presc) != 0 ) { patient_events <- lapply(1:nrow(disp_presc), FUN = function(i) process_medication(med = i)); # patient_events <- do.call(rbindlist, list(l = lapply(1:nrow(disp_presc), FUN = function(i) process_medication(med = i)), # fill = TRUE)); } setkeyv(pat_disp, cols = medication.class.colnames); setkeyv(pat_presc, cols = medication.class.colnames); # patient_events[[1]][[1]] <- rbind(pat_disp[list(disp_no_presc[,medication.class.colnames, with = FALSE]), c("ID", "DISP.DATE", medication.class.colnames, "TOTAL.DOSE"), with = FALSE], pat_presc[list(presc_no_disp[,medication.class.colnames, with = FALSE]), c("ID", medication.class.colnames, "DAILY.DOSE"), with = FALSE], patient_events[[1]][[1]], fill = TRUE); # update progress bar if(progress.bar == TRUE) { setTxtProgressBar(pb, getTxtProgressBar(pb)+1) }; patient_events; } # extract IDs of all patients present in dispensing and prescription database disp_presc_IDs <- sort(intersect(disp.data.copy[["ID"]], presc.data.copy[["ID"]])); # progress bar if(progress.bar == TRUE) { pb <- txtProgressBar(min = 0, max = length(disp_presc_IDs), style = 3); } # apply process_patient function setkeyv(disp.data.copy, cols = "ID"); setkeyv(presc.data.copy, cols = "ID"); events_output_list <- lapply(disp_presc_IDs, FUN = function(i) process_patient(pat = i)); events_output_durations <- do.call(rbindlist, list(l = lapply(events_output_list, FUN = function(i) { do.call(rbindlist, list(l = lapply(i, FUN = function(j) { j[[1]] }), fill = TRUE)) }), fill = TRUE)); events_output_prescriptions <- do.call(rbindlist, list(l = lapply(events_output_list, FUN = function(i) { do.call(rbindlist, list(l = lapply(i, FUN = function(j) { j[[2]] }), fill = TRUE)) }), fill = TRUE)); # events_output <- do.call(rbindlist, list(l = lapply(disp_presc_IDs, FUN = function(i) process_patient(pat = i)), # fill = TRUE)); # key by ID, medication class, and dispensing date setkeyv(events_output_durations, cols = c("ID", medication.class.colnames, "DISP.DATE")); setkeyv(events_output_prescriptions, cols = c("ID", medication.class.colnames)); # convert column names setnames(events_output_durations, old = c("ID", "DISP.DATE", "DAILY.DOSE", "TOTAL.DOSE"), new = c(ID.colname, disp.date.colname, presc.daily.dose.colname, total.dose.colname) ) setnames(events_output_prescriptions, old = c("ID", "DAILY.DOSE"), new = c(ID.colname, presc.daily.dose.colname) ) # only return special periods for selected patients if(!is.null(special.periods.data)) { special.periods.data.copy <- special.periods.data.copy[ID %in% disp_presc_IDs] } else {special.periods.data.copy <- NULL} if(!is.null(special.periods.data.copy)) { setnames(special.periods.data.copy, old = c("ID"), new = c(ID.colname)) } if(progress.bar == TRUE) { close(pb) } attributes(events_output_durations)$carryover <- carryover if( !return.data.table ) { events_output_durations <- as.data.frame(events_output_durations); events_output_prescriptions <- as.data.frame(events_output_prescriptions) } # set order of column names opt_cols <- c("SPECIAL.DURATION","tot.presc.interruptions","tot.dosage.changes","CARRYOVER.DURATION") opt_cols <- opt_cols[opt_cols %in% names(events_output_durations)] colorder <- c(ID.colname, medication.class.colnames, disp.date.colname, total.dose.colname, presc.daily.dose.colname, "EVENT.ID", "DISP.START", "DURATION", "episode.start", "episode.end", opt_cols) setcolorder(events_output_durations, colorder) summary <- "Event durations based on dispensing, prescription, and other data, which can be used with the CMA constructors in AdhereR." structure(list("event_durations" = events_output_durations, "prescription_episodes" = events_output_prescriptions, "special_periods" = special.periods.data, "ID.colname" = ID.colname, "medication.class.colnames" = medication.class.colnames, "disp.date.colname" = disp.date.colname, "total.dose.colname" = total.dose.colname, "presc.date.colname" = presc.date.colname, "presc.daily.dose.colname" = presc.daily.dose.colname, "presc.duration.colname" = presc.duration.colname, "visit.colname" = visit.colname, "split.on.dosage.change" = split.on.dosage.change, "force.init.presc" = force.init.presc, "force.presc.renew" = force.presc.renew, "trt.interruption" = trt.interruption, "special.periods.method" = special.periods.method, "date.format" = date.format), class = "event_durations"); } ############ function to prune event durations #' Prune event durations. #' #' Flags or removes leftover supply durations after dosage changes, the end of a special period, #' or treatment interruption. #' The function accepts the raw list output of \code{compute_event_durations} and additional arguments #' to specify event durations that need to be removed. #' #' Dosage changes, special periods, and treatment interruptions may lead to overestimation of #' implementation, e.g. if patients get a refill after discharge from hospital and don't continue to use #' their previous supply. Likewise, it may also lead to overestimation of persistence, e.g. when #' patients discontinue treatments after the end of a special period or treatment interruption. #' #' @param data A \emph{\code{list}}, the output of \code{compute_event_durations}. #' @param include A \emph{\code{Vector}} of \emph{strings} indicating whether to include #' dosage changes, special periods, and/or treatment interruptions. #' @param medication.class.colnames A \emph{\code{Vector}} of \emph{strings}, the #' name(s) of the column(s) in the \code{event_durations} element of \code{data} to #' identify medication classes. Defaults to the columns used in \code{compute_event_durations}. #' @param days.within.out.date.1 event durations from before the dosage change, special period, or #' treatment interruptions are removed if there is a new dispensing event within the #' number of days specified as \emph{integer} after the dosage change or end of the special #' period/treatment interruption. #' @param days.within.out.date.2 event durations from before dosage change, special period, #' or treatment interruption are removed if there is \emph{NO} new dispensing event within the #' number of days specified as \emph{integer} after the dosage change or end of the special #' period/treatment interruption. #' @param keep.all \emph{Logical}, should events be kept and marked for removal? #' If \code{TRUE}, a new column \code{.prune.event} will be added to \code{event_durations}, #' if \code{FALSE} the events will be removed from the output. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param ... other possible parameters. #' @return A \code{data.frame} or \code{data.table}, the pruned event_durations. #' @examples #' \dontrun{ #' # select medication class of interest and compute event durations #' #' disp_data <- durcomp.dispensing[ID == 3 & grepl("J01EE01", ATC.CODE)] #' presc_data <- durcomp.prescribing[ID == 3 & grepl("J01EE01", ATC.CODE)] #' #' # compute event durations #' event_durations_list <- compute_event_durations(disp.data = disp_data, #' presc.data = presc_data, #' special.periods.data = durcomp.hospitalisation, #' ID.colname = "ID", #' presc.date.colname = "DATE.PRESC", #' disp.date.colname = "DATE.DISP", #' date.format = "%Y-%m-%d", #' medication.class.colnames = c("ATC.CODE", #' "UNIT", #' "FORM"), #' total.dose.colname = "TOTAL.DOSE", #' presc.daily.dose.colname = "DAILY.DOSE", #' presc.duration.colname = "PRESC.DURATION", #' visit.colname = "VISIT", #' force.init.presc = TRUE, #' force.presc.renew = TRUE, #' split.on.dosage.change = TRUE, #' trt.interruption = "carryover", #' special.periods.method = "carryover", #' suppress.warnings = FALSE, #' return.data.table = TRUE, #' progress.bar = FALSE) #' #' # prune event durations #' event_durations <- prune_event_durations(event_durations_list, #' include = c("special periods"), #' medication.class.colnames = "ATC.CODE", #' days.within.out.date.1 = 7, #' days.within.out.date.2 = 30, #' keep.all = FALSE) #' } #' @export prune_event_durations <- function(data, include = c("special periods", "treatment interruptions", "dosage changes"), medication.class.colnames = data$medication.class.colnames, days.within.out.date.1, days.within.out.date.2, keep.all = TRUE, suppress.warnings = FALSE, return.data.table = FALSE, ...){ ## Preconditions { # data class and dimensions if( !inherits(data, c("event_durations", "list")) ) { if( !suppress.warnings ) warning("The data must be a of type 'list'!\n"); return (NULL); } if( !inherits(data$event_durations, "data.frame") ) { if( !suppress.warnings ) warning("The event_durations element in data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(data$event_durations) < 1 ) { if( !suppress.warnings ) warning("The event_durations element in data must have at least one row!\n"); return (NULL); } if( !inherits(data$prescription_episodes, "data.frame") ) { if( !suppress.warnings ) warning("The prescription_episodes element in data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(data$prescription_episodes) < 1 ) { if( !suppress.warnings ) warning("The prescription_episodes element in data must have at least one row!\n"); return (NULL); } if( !inherits(data$special_periods, "data.frame") ) { if( !suppress.warnings ) warning("The special_periods element in data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(data$special_periods) < 1 ) { if( !suppress.warnings ) warning("The special_periods element in data must have at least one row!\n"); return (NULL); } if(!all(c(data$ID.colname, "DATE.IN", "DATE.OUT") %in% colnames(data$special_periods))) { if( !suppress.warnings ) warning(paste0("The special_periods element in data must contain at least all columns with the names '", data$ID.colname, "', 'DATE.IN', and 'DATE.OUT'.\n Please refer to the documentation for more information.\n")); return (NULL); } # include parameter valid if(any(!include %in% c("special periods", "treatment interruptions", "dosage changes"))) { if( !suppress.warnings ) warning("The included elements in include = '", include, "' can only be 'special periods', 'treatment interruptions', and/or 'dosage changes'\n"); return (NULL); } # days.within.out.date parameters valid if( is.na(days.within.out.date.1) || is.null(days.within.out.date.1) || length(days.within.out.date.1) != 1 || !is.numeric(days.within.out.date.1) || days.within.out.date.1 < 0 ) { if( !suppress.warnings ) warning("The 'days.within.out.date.1' argument must be a positive number of days after a special period!\n") return (NULL); } if( is.na(days.within.out.date.2) || is.null(days.within.out.date.2) || length(days.within.out.date.2) != 1 || !is.numeric(days.within.out.date.2) || days.within.out.date.2 < 0 ) { if( !suppress.warnings ) warning("The 'days.within.out.date.2' argument must be a positive number of days after a special period!\n") return (NULL); } } # extract data from output list event_durations <- copy(data$event_durations) ## Force data to data.table if( !inherits(event_durations,"data.table") ) { event_durations <- as.data.table(event_durations); } # medication class colnames in dataset if( any(!is.na(medication.class.colnames) & !(medication.class.colnames %in% names(event_durations))) ) # deal with the possibility of multiple column names { if( !suppress.warnings ) warning(paste0("Column(s) medication.class.colnames=",paste0("'",medication.class.colnames,"'",collapse=",")," must appear in the event_durations data!\n")); return (NULL); } if(".prune.event" %in% colnames(event_durations)) { event_durations[,.prune.event := NULL] } end_dates <- NULL if("special periods" %in% include){ special_periods <- data$special_periods # extract end dates end_dates <- unique(special_periods[,c(data$ID.colname, "DATE.OUT"), with = FALSE]) # add medication classes unique_med <- unique(event_durations[,c(data$ID.colname, medication.class.colnames), with = FALSE]) end_dates <- merge(end_dates, unique_med, by = data$ID.colname, allow.cartesian = TRUE) } if("treatment interruptions" %in% include){ presc_episodes <- data$prescription_episodes trt_interruptions <- presc_episodes[shift(episode.end, n = 1, type = "lag") < episode.start, .SD, by = c(data$ID.colname, medication.class.colnames)] trt_interruptions <- trt_interruptions[,c(data$ID.colname, "episode.start", medication.class.colnames), with = FALSE] setnames(trt_interruptions, old = "episode.start", new = "DATE.OUT") # extract end dates end_dates <- unique(rbind(end_dates, trt_interruptions)) } if("dosage changes" %in% include) { presc_episodes <- data$prescription_episodes dosage_changes <- presc_episodes[shift(episode.start, n = 1, type = "lead") == episode.end, .SD, by = c(data$ID.colname, medication.class.colnames)] dosage_changes <- dosage_changes[,c(data$ID.colname, "episode.start", medication.class.colnames), with = FALSE] setnames(dosage_changes, old = "episode.start", new = "DATE.OUT") # extract end dates end_dates <- unique(rbind(end_dates, dosage_changes)) } # create new variable for join date event_durations[, join_date := DISP.START] end_dates[, join_date := DATE.OUT] # key by ID, medication class, and join date setkeyv(event_durations, cols = c(data$ID.colname, medication.class.colnames, "join_date")) setkeyv(end_dates, cols = c(data$ID.colname, medication.class.colnames, "join_date")) # identify events to remove from the event_durations dataset disp.remove.1 <- NULL if(!is.na(days.within.out.date.1)) { # rolling join to select events starting within the specified number of days after the end date of special periods #if(is.numeric(days.within.out.date.1)){ disp.within.1 <- na.omit(end_dates[event_durations, roll = days.within.out.date.1], cols = c(#"DURATION", "DATE.OUT", data$disp.date.colname)) # } else { # # disp.within.1 <- na.omit(end_dates[event_durations, roll = get(days.within.out.date.1)], cols = c("DURATION", "DATE.OUT", data$disp.date.colname)) # # } # identify durations from previous events #disp.within.1[get(data$disp.date.colname) < DATE.OUT & get(data$disp.date.colname) < DISP.START, .from.carryover := 1] disp.within.1[EVENT.ID != 1, .from.carryover := 1] # identify new events disp.within.1[, .new.events := .N - sum(.from.carryover, na.rm = TRUE), by = c(data$ID.colname, medication.class.colnames, "DATE.OUT")] # mark events for removal if they are from previous events and at least one new event is present within the specified period disp.remove.1 <- disp.within.1[.from.carryover == 1 & .new.events > 0, .prune.event := 1] disp.remove.1 <- disp.remove.1[.prune.event == 1] } # create new variable for join date event_durations[!is.na(DURATION), join_date := DISP.START+DURATION] # key by ID, medication class, and join date setkeyv(event_durations, cols = c(data$ID.colname, medication.class.colnames, "join_date")) disp.remove.2 <- NULL if(!is.na(days.within.out.date.2)) { # rolling join to select events starting within the specified number of days after the end date of special periods #if(is.numeric(days.within.out.date.2)){ disp.within.2 <- na.omit(end_dates[event_durations, roll = days.within.out.date.2], cols = c(# "DURATION", "DATE.OUT", data$disp.date.colname)) # } else { # # disp.within.2 <- na.omit(end_dates[event_durations, roll = get(days.within.out.date.2)], cols = c("DURATION", # "DATE.OUT", # data$disp.date.colname)) # } # identify durations from previous events #disp.within.2[get(data$disp.date.colname) < DATE.OUT & get(data$disp.date.colname) < DISP.START, .from.carryover := 1] disp.within.2[EVENT.ID != 1, .from.carryover := 1] # identify new events disp.within.2[, .new.events := .N - sum(.from.carryover, na.rm = TRUE), by = c(data$ID.colname, medication.class.colnames, "DATE.OUT")] # mark events for removal if they are from previous and no new events are present disp.remove.2 <- disp.within.2[.from.carryover == 1 & .new.events == 0, .prune.event := 1] # in case of multiple new durations from the same dispensing event, mark previous new durations according to last new duration disp.remove.2[.from.carryover == 1,.prune.event := last(.prune.event), by = c(data$disp.date.colname)] disp.remove.2 <- disp.remove.2[.prune.event == 1] } # compine events to remove disp.remove <- rbind(disp.remove.1, disp.remove.2) # merge with event_durations event_durations_prune <- merge(event_durations[, join_date := NULL], disp.remove[, c(data$ID.colname, medication.class.colnames, data$disp.date.colname, "DISP.START", "DURATION", ".prune.event"), with = FALSE], by = c(data$ID.colname, medication.class.colnames, data$disp.date.colname, "DISP.START", "DURATION"), all.x = TRUE) # set order of column names opt_cols <- c("SPECIAL.DURATION", "tot.presc.interruptions", "tot.dosage.changes", "CARRYOVER.DURATION", ".prune.event") opt_cols <- opt_cols[opt_cols %in% names(event_durations_prune)] colorder <- c(data$ID.colname, data$disp.date.colname, data$medication.class.colnames, data$total.dose.colname, data$presc.daily.dose.colname, "DISP.START", "DURATION", "episode.start", "episode.end", opt_cols) setcolorder(event_durations_prune, colorder) if(keep.all == FALSE) { output <- event_durations_prune[is.na(.prune.event)] output[, .prune.event := NULL] } else { output <- event_durations_prune } if( !return.data.table ) { output <- as.data.frame(output); } return(output) } ############ function to consider special periods as covered #' Cover special periods. #' #' Identifies special periods that are in proximity to already covered durations and adds additional #' events for these durations. #' #' Special periods may appear as gaps, possibly leading to underestimation of implementation or even #' assumption of discontinuation and non-persistence. To consider such periods as covered, this function #' adds additional durations, for example when it is assumed that hospitalized patients are adherent #' during the hospitalization period. This function should be used after pruning with #' \code{prune_event_durations}. #' #' @param events.data A \emph{\code{data.frame}} or \emph{\code{data.table}} with the event durations. #' @param special.periods.data a \emph{\code{data.frame}} or or \emph{\code{data.table}} #' containing the information about special periods (e.g., hospitalizations or other situations #' where medication use may differ, e.g. during incarcerations or holidays). Must contain the same unique #' patient ID as dispensing and prescription data, the start and end dates of the special #' periods with the exact column names \emph{\code{DATE.IN}} and \emph{\code{DATE.OUT}}. #' @param ID.colname A \emph{string}, the name of the column in \code{events.data} and #' \code{special.periods.data} containing the unique patient ID. #' @param medication.class.colnames A \emph{\code{Vector}} of \emph{strings}, the #' name(s) of the column(s) in the \code{events.data} identify medication classes. #' @param disp.date.colname A \emph{string}, the name of the column in #' \code{events.data} containing the dispensation start date (in the format given in #' the \code{date.format} parameter). #' @param disp.start.colname,episode.start.colname,episode.end.colname column names in #' \code{events.data}. #' @param duration.colname A \emph{string}, the name of the column in #' \code{events.data} containing the duration of the medication event. #' @param days.before an \emph{integer}, the number of days before the start of a special period #' within which an event duration must end to consider the special period as covered. #' @param days.after an \emph{integer}, the number of days after a special period within #' which an event duration must start to consider the special period as covered. #' @param date.format A \emph{string} giving the format of the dates used in #' the \code{data} and the other parameters; see the \code{format} parameters #' of the \code{\link[base]{as.Date}} function for details (NB, this concerns #' only the dates given as strings and not as \code{Date} objects). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param ... other possible parameters. #' @return A \code{data.frame} or \code{data.table}, the \code{events.data} with the additional #' durations for special periods covered. #' @examples #' \dontrun{ #' # select medication class of interest and compute event durations #' disp_data <- durcomp.dispensing[ID == 3 & grepl("J01EE01", ATC.CODE)] #' presc_data <- durcomp.prescribing[ID == 3 & grepl("J01EE01", ATC.CODE)] #' #' event_durations_list <- compute_event_durations(disp.data = disp_data, #' presc.data = presc_data, #' special.periods.data = durcomp.hospitalisation, #' special.periods.method = "carryover", #' ID.colname = "ID", #' presc.date.colname = "DATE.PRESC", #' disp.date.colname = "DATE.DISP", #' date.format = "%Y-%m-%d", #' medication.class.colnames = c("ATC.CODE", #' "UNIT", #' "FORM"), #' total.dose.colname = "TOTAL.DOSE", #' presc.daily.dose.colname = "DAILY.DOSE", #' presc.duration.colname = "PRESC.DURATION", #' visit.colname = "VISIT", #' force.init.presc = TRUE, #' force.presc.renew = TRUE, #' split.on.dosage.change = TRUE, #' trt.interruption = "carryover", #' suppress.warnings = FALSE, #' return.data.table = TRUE, #' progress.bar = FALSE) #' #' event_durations <- prune_event_durations(event_durations_list, #' include = c("special periods"), #' medication.class.colnames = "ATC.CODE", #' days.within.out.date.1 = 7, #' days.within.out.date.2 = 30, #' keep.all = TRUE) #' #' # cover special periods #' special_periods <- event_durations_list$special_periods #' event_durations_covered <- cover_special_periods(events.data = event_durations, #' special.periods.data = special_periods, #' ID.colname = "ID", #' medication.class.colnames = "ATC.CODE", #' disp.start.colname = "DISP.START", #' duration.colname = "DURATION", #' days.before = 7, #' days.after = 7, #' date.format = "%Y-%m-%d") #' } #' @export cover_special_periods <- function(events.data, special.periods.data, ID.colname, medication.class.colnames, disp.date.colname, disp.start.colname, episode.start.colname, episode.end.colname, duration.colname, days.before, days.after, date.format, suppress.warnings = FALSE, return.data.table = FALSE, ...){ # Preconditions { # events.data class and dimensions: if( inherits(events.data, "matrix") ) events.data <- as.data.table(events.data); # convert matrix to data.table if( !inherits(events.data, "data.frame") ) { if( !suppress.warnings ) warning("The events data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(events.data) < 1 ) { if( !suppress.warnings ) warning("The events data must have at least one row!\n"); return (NULL); } # special period data class and dimensions: if( inherits(special.periods.data, "matrix") ) special.periods.data <- as.data.table(special.periods.data); # convert matrix to data.table if( !inherits(special.periods.data, "data.frame") ) { if( !suppress.warnings ) warning("The special periods data must be of type 'data.frame'!\n"); return (NULL); } if( nrow(special.periods.data) < 1 ) { if( !suppress.warnings ) warning("The special periods data must have at least one row!\n"); return (NULL); } if(!all(c(ID.colname, "DATE.IN", "DATE.OUT") %in% colnames(special.periods.data))) { if( !suppress.warnings ) warning(paste0("The special periods data must contain at least all columns with the names '", ID.colname, "', 'DATE.IN', and 'DATE.OUT'.\n Please refer to the documentation for more information.\n")); return (NULL); } # the column names must exist in dispensing and prescription data: if( !is.na(ID.colname) && !(ID.colname %in% names(events.data)) ) { if( !suppress.warnings ) warning(paste0("Column ID.colname='",ID.colname,"' must appear in the events data!\n")); return (NULL); } if( !is.na(disp.start.colname) && !(disp.start.colname %in% names(events.data)) ) { if( !suppress.warnings ) warning(paste0("Column disp.start.colname='",disp.start.colname,"' must appear in the events data!\n")); return (NULL); } if(anyNA(events.data[[disp.start.colname]])){ if( !suppress.warnings ) warning(paste0("Column disp.start.colname='",disp.start.colname,"' cannot contain missing values!\n")); return (NULL); } if( any(!is.na(medication.class.colnames) & !(medication.class.colnames %in% names(events.data)) ) ) # deal with the possibility of multiple column names { if( !suppress.warnings ) warning(paste0("Column(s) medication.class.colnames=",paste0("'",medication.class.colnames,"'",collapse=",")," must appear in the events data!\n")); return (NULL); } if( !is.na(duration.colname) && !(duration.colname %in% names(events.data)) ) { if( !suppress.warnings ) warning(paste0("Column duration.colname='",duration.colname,"' must appear in the events data!\n")); return (NULL); } # days before and after if( is.na(days.before) || is.null(days.before) || length(days.before) != 1 || !is.numeric(days.before) || days.before < 0 ) { if( !suppress.warnings ) warning("The 'days.before' argument must be a positive number of days before a special period!\n") return (NULL); } if( is.na(days.after) || is.null(days.after) || length(days.after) != 1 || !is.numeric(days.after) || days.after < 0 ) { if( !suppress.warnings ) warning("The 'days.after' argument must be a positive number of days after a special period!\n") return (NULL); } if( is.na(date.format) || is.null(date.format) || length(date.format) != 1 || !is.character(date.format) ) { if( !suppress.warnings ) warning(paste0("The date format must be a single string!\n")); return (NULL); } } events.data.copy <- copy(events.data) special.periods.data.copy <- copy(special.periods.data) ## Force data to data.table if( !inherits(events.data.copy,"data.table") ) { events.data.copy <- as.data.table(events.data.copy); } if( !inherits(special.periods.data.copy,"data.table") ) { special.periods.data.copy <- as.data.table(special.periods.data.copy); } setnames(events.data.copy, old = c(ID.colname, disp.date.colname, disp.start.colname, duration.colname, episode.start.colname, episode.end.colname), new = c("ID", "DISP.DATE", "DISP.START", "DURATION", "episode.start", "episode.end")) setnames(special.periods.data.copy, old = c(ID.colname), new = c("ID")) # set join date to the beginning of special durations events.data.copy[, join_date := DISP.START+DURATION] special.periods.data.copy[, join_date := DATE.IN] # key by ID and join date setkeyv(events.data.copy, cols = c("ID", "join_date")) setkeyv(special.periods.data.copy, cols = c("ID", "join_date")) # select special periods with event durations ending within x days before the start of a special period dt1 <- na.omit(special.periods.data.copy[events.data.copy, roll = -days.before], cols = "DATE.IN") dt1 <- dt1[,c("ID", "DATE.IN", "DATE.OUT", "DISP.DATE", medication.class.colnames, "SPECIAL.DURATION", "episode.start", "episode.end" #, events.data.copy_list$presc.daily.dose.colname ), with = FALSE] # only keep necessary columns # set join date to the end of special durations events.data.copy[, join_date := DISP.START] special.periods.data.copy[, join_date := DATE.OUT] # key by ID and join date setkeyv(events.data.copy, cols = c("ID", "join_date")) setkeyv(special.periods.data.copy, cols = c("ID", "join_date")) # select special periods with event durations beginning within x days after the end of a special period dt2 <- na.omit(special.periods.data.copy[events.data.copy, roll = days.after], cols = "DATE.OUT") dt2 <- dt2[,c("ID", "DATE.IN", "DATE.OUT", "DISP.DATE", medication.class.colnames, "SPECIAL.DURATION", "episode.start", "episode.end"), with = FALSE] # only keep necessary columns # combine dt1 and dt2 and select unique rows dt_all <- unique(rbind(dt1, dt2)) if( sum(dt_all$SPECIAL.DURATION, na.rm = TRUE) != 0 ) { if( !suppress.warnings ) warning(paste0("The events data contains already (partially) covered special periods ('SPECIAL.DURATION' > 0)! This function should be used together with special.periods.method = 'carryover'. Please refer to the documentation for more information. \n")); return (NULL); } dt_all[,SPECIAL.DURATION := as.numeric(DATE.OUT-DATE.IN)] # change column names setnames(dt_all, old = c("DATE.IN", "SPECIAL.DURATION"), new = c("DISP.START", "DURATION")) output <- rbind(events.data.copy, dt_all, fill = TRUE) output[,`:=`(join_date = NULL, DATE.OUT = NULL)] setorderv(output, cols = c("ID", medication.class.colnames, "DISP.DATE")) # change back to original column names setnames(output, old = c("ID", "DISP.DATE", "DISP.START", "DURATION", "episode.start", "episode.end"), new = c(ID.colname, disp.date.colname, disp.start.colname, duration.colname, episode.start.colname, episode.end.colname)) if( !return.data.table ) { output <- as.data.frame(output); } return(output) } ############ function to compute time to initiation #' Computation of initiation times. #' #' Computes the time between the start of a prescription episode and the first dispensing #' event for each medication class. #' #' The period between the start of a prescription episode and the first dose administration #' may impact health outcomes differently than omitting doses once on treatment or #' interrupting medication for longer periods of time. Primary non-adherence (not #' acquiring the first prescription) or delayed initiation may have a negative #' impact on health outcomes. The function \code{time_to_initiation} calculates #' the time between the start of a prescription episode and the first dispensing event, taking #' into account multiple variables to differentiate between treatments. #' #' @param presc.data A \emph{\code{data.frame}} or \emph{\code{data.table}} containing #' the prescription episodes. Must contain, at a minimum, the patient unique ID, #' one medication identifier, and the start date of the prescription episode, and might #' also contain additional columns to identify and group medications (the actual #' column names are defined in the \emph{\code{medication.class.colnames}} parameter). #' @param disp.data A \emph{\code{data.frame}} or \emph{\code{data.table}} containing #' the dispensing events. Must contain, at a minimum, the patient unique ID, one #' medication identifier, the dispensing date, and might also contain additional #' columns to identify and group medications (the actual column names are defined #' in the \emph{\code{medication.class.colnames}} parameter). #' @param ID.colname A \emph{string}, the name of the column in \code{presc.data} #' and \code{disp.data} containing the unique patient ID, or \code{NA} if not defined. #' @param medication.class.colnames A \emph{\code{Vector}} of \emph{strings}, the #' name(s) of the column(s) in \code{data} containing the classes/types/groups of #' medication, or \code{NA} if not defined. #' @param presc.start.colname A \emph{string}, the name of the column in #' \code{presc.data} containing the prescription date (in the format given in #' the \code{date.format} parameter), or \code{NA} if not defined. #' @param disp.date.colname A \emph{string}, the name of the column in #' \code{disp.data} containing the dispensing date (in the format given in #' the \code{date.format} parameter), or \code{NA} if not defined. #' @param date.format A \emph{string} giving the format of the dates used in #' the \code{data} and the other parameters; see the \code{format} parameters #' of the \code{\link[base]{as.Date}} function for details (NB, this concerns #' only the dates given as strings and not as \code{Date} objects). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param return.data.table \emph{Logical}, if \code{TRUE} return a #' \code{data.table} object, otherwise a \code{data.frame}. #' @param ... other possible parameters #' @return A \code{data.frame} or \code{data.table} with the following columns: #' \itemize{ #' \item \code{ID.colname} the unique patient ID, as given by the \code{ID.colname} #' parameter. #' \item \code{medication.class.colnames} the column(s) with classes/types/groups #' of medication, as given by the \code{medication.class.colnames} parameter. #' \item \code{episode.start} the date of the first prescription event. #' \item \code{first.disp} the date of the first dispensing event. #' \item \code{time.to.initiation} the difference in days between the first #' dispensing date and the first prescription date. #' } #' @examples #' time_init <- time_to_initiation(presc.data = durcomp.prescribing, #' disp.data = durcomp.dispensing, #' ID.colname = "ID", #' medication.class.colnames = c("ATC.CODE", "FORM", "UNIT"), #' presc.start.colname = "DATE.PRESC", #' disp.date.colname = "DATE.DISP", #' date.format = "%Y-%m-%d", #' suppress.warnings = FALSE, #' return.data.table = TRUE); #' @export time_to_initiation <- function(presc.data = NULL, disp.data = NULL, ID.colname = NA, medication.class.colnames = NA, presc.start.colname = NA, disp.date.colname = NA, date.format = "%d.%m.%Y", suppress.warnings = FALSE, return.data.table = FALSE, ...) { # Preconditions { # data class and dimensions: if( inherits(presc.data, "matrix") ) presc.data <- as.data.table(presc.data); # convert matrix to data.table if( !inherits(presc.data, "data.frame") ) { if( !suppress.warnings ) warning("The presc.data must be of type 'data.frame'!\n"); return (NULL); } if( inherits(disp.data, "matrix") ) disp.data <- as.data.table(disp.data); # convert matrix to data.table if( !inherits(disp.data, "data.frame") ) { if( !suppress.warnings ) warning("The presc.data must be of type 'data.frame'!\n"); return (NULL); } if( !is.na(ID.colname) && !(ID.colname %in% names(disp.data)) && !(ID.colname %in% names(presc.data))) { if( !suppress.warnings ) warning(paste0("Column ID.colname='",ID.colname,"' must appear in the data!\n")); return (NULL); } if( any(!is.na(medication.class.colnames) & !(medication.class.colnames %in% names(disp.data)) & !(medication.class.colnames %in% names(presc.data))) ) # deal with the possibility of multiple column names { if( !suppress.warnings ) warning(paste0("Column(s) medication.class.colnames=",paste0("'",medication.class.colnames,"'",collapse=",")," must appear in the dispensing and prescribing data!\n")); return (NULL); } if( !is.na(disp.date.colname) && !(disp.date.colname %in% names(disp.data)) ) { if( !suppress.warnings ) warning(paste0("Column disp.date.colname='",disp.date.colname,"' must appear in the data!\n")); return (NULL); } if( !is.na(presc.start.colname) && !(presc.start.colname %in% names(presc.data)) ) { if( !suppress.warnings ) warning(paste0("Column presc.start.colname='",presc.start.colname,"' must appear in the data!\n")); return (NULL); } if( sum(is.na(disp.data[[disp.date.colname]])) > 0 ) { if( !suppress.warnings ) warning(paste0("Dispensing dates in disp.date.colname='",disp.date.colname,"' cannot contain NAs!\n")); return (NULL); } } presc.data <- presc.data[,c(ID.colname, presc.start.colname, medication.class.colnames), with = FALSE] # only first dispensing events with a duration disp.data <- disp.data[,c(ID.colname, disp.date.colname, medication.class.colnames), with = FALSE] # convert dates presc.data[,(presc.start.colname) := as.Date(get(presc.start.colname), format = date.format)]; disp.data[,(disp.date.colname) := as.Date(get(disp.date.colname), format = date.format)]; # set join date to the beginning of prescription episodes presc.data[, join_date := get(presc.start.colname)] disp.data[, join_date := get(disp.date.colname)] # key by ID and join date setkeyv(presc.data, cols = c(ID.colname, medication.class.colnames, "join_date")) setkeyv(disp.data, cols = c(ID.colname, medication.class.colnames, "join_date")) # rolling join first dispensing event for each prescription episode dt_t2i <- disp.data[presc.data, roll = -Inf] setnames(dt_t2i, old = c(disp.date.colname, presc.start.colname), new = c("first.disp", "episode.start")) dt_t2i <- dt_t2i[,c(ID.colname, medication.class.colnames, "episode.start", "first.disp"), with = FALSE] # calculate time to initiation dt_t2i[,time.to.initiation := as.numeric(first.disp-episode.start)]; # key by ID, medication class, and dispensing date setkeyv(dt_t2i, cols = c(ID.colname, medication.class.colnames, "first.disp")); if( !return.data.table ) { return (as.data.frame(dt_t2i)); } else { return(dt_t2i); } }
/scratch/gouwar.j/cran-all/cranData/AdhereR/R/matching_function.R
################################################################################ # # Plotting: # # Plotting is handled by a single function that can manage CMA0, CMA1+ as well # as per-episodes and sliding-windows. # It can handle 1 or more patients. # # For a given case, it produces an intermediate format that can be used to # generate either a static plot (using R base graphics) or various degrees of # interactivity (using HTML5/CSS/JavaScript). # # In principle, this should ensure the "future-proffing" of the plotting system # as well as make its maintenance and development easier by providing a unified # codebase. # # This is part of AdhereR. # # Copyright (C) 2015-2018 Dan Dediu & Alexandra Dima # Copyright (C) 2018-2019 Dan Dediu, Alexandra Dima & Samuel Allemann # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ ## TODO #### # # string height & width in SVG # make sure the image resizes well # check colors, etc, consistency # image dimensions (also for export) # # HTML + CSS + JavaScript # # test # profile & optimise # # Grayscale colors palette: .bw.colors <- function(n) { gray.colors(n, start=0, end=0.5); } ## SVG special functions and constants #### .SVG.number <- function(n, prec=3) { # if( is.numeric(n) ) as.character(round(n,prec)) else n; if( is.numeric(n) ) sprintf("%.3f",n) else n; } # Replace special characters with XML/HTML entities # Inspired by htmlspecialchars() in package "fun" # and HTMLdecode()/HTMLencode() in package "textutils" .SVG.specialchars.2.XMLentities <- function(s) { s <- as.character(s); # make sure s is a string spec.chars <- c("&amp;"="&", "&quot;"='"', "&#039;"="'", "&lt;"="<", "&gt;"=">"); if( length(grep("[&\\+\"'<>]", s, fixed=FALSE)) == 0 ) return (s); # none found # Replace them with the corresponding HTML entities: for (i in seq_along(spec.chars)) { s <- gsub(spec.chars[i], names(spec.chars)[i], s, fixed = TRUE); } return (s); } .SVG.comment <- function(s, newpara=FALSE, # should there be a newline before the comment? newline=TRUE, # should a newline be added at the end? return_string=FALSE # return a singe string or a vector of strings to be concatenated later? ) { r <- c(if(newpara) '\n', '<!-- ',s,' -->', if(newline) '\n'); if( return_string ) return (paste0(r,collapse="")) else return (r); } .SVG.color <- function(col, return_string=FALSE) { if( col == "none" ) { return ('none'); } else { if( return_string ) { return (paste0("rgb(",paste0(col2rgb(col),collapse=","),")")); } else { x <- col2rgb(col); return (list('rgb(', x[1], ',', x[2], ',', x[3], ')')); } } } # Stroke dash-arrays for line types (lty): .SVG.lty <- data.frame("lty"=0:6, "names"=c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash"), "stroke"=c("none", NA, NA, NA, NA, NA, NA), "stroke-dasharray"=c(NA, NA, "3,3", "1,2", "1,2,3,2", "5,2", "2,2,4,2"), stringsAsFactors=FALSE); .SVG.rect <- function(x=NA, y=NA, width=NA, height=NA, xend=NA, yend=NA, # can accomodate both (wdith,height) and (xend,yend) stroke=NA, stroke_width=NA, lty=NA, stroke_dasharray=NA, fill="white", fill_opacity=NA, other_params=NA, # styling attributes id=NA, class=NA, comment=NA, tooltip=NA, # ID, comment and tooltip newline=TRUE, # should a newline be added at the end? return_string=FALSE # return a singe string or a vector of strings to be concatenated later? ) { # Check for missing data: if( is.na(x) || is.na(y) || (is.na(width) && is.na(xend)) || (is.na(height) && is.na(yend)) ) { # Nothing to plot! if( return_string ) return ("") else return (NULL); } if(!is.na(tooltip)) tooltip <- .SVG.specialchars.2.XMLentities(tooltip); # make sure special chars in tooltip are treated correctly # Process lty first: if( !is.na(lty) ) { if( is.numeric(lty) ) s <- which(.SVG.lty$lty == lty) else s <- which(.SVG.lty$names == as.character(lty)); if( length(s) == 1 ) { if( !is.na(.SVG.lty$stroke[s]) ) stroke <- .SVG.lty$stroke[s]; stroke_dasharray <- .SVG.lty$stroke.dasharray[s]; } } r <- list(# The initial comment (if any): if(!is.na(comment)) .SVG.comment(comment), # The rect element: '<rect ', # The id and class (if any): if(!is.na(id)) c('id="',id,'" '), if(!is.na(class)) c('class="',class,'" '), # The x and y coordinates of the bottom-left corner: if(!is.na(x)) c('x="',.SVG.number(x),'" '), if(!is.na(y)) c('y="',.SVG.number(y),'" '), # The width and height of the rectangle (either given directly or computed from the top-right corner coordinates): if(!is.na(width)) c('width="', .SVG.number(width), '" ') else if(!is.na(xend)) c('width="',.SVG.number(xend-x),'" '), if(!is.na(height)) c('height="',.SVG.number(height),'" ') else if(!is.na(yend)) c('height="',.SVG.number(yend-y),'" '), # Aesthetics: if(!is.na(stroke)) c('stroke="', .SVG.color(stroke), '" '), if(!is.na(stroke_width)) c('stroke-width="',stroke_width,'" '), if(!is.na(stroke_dasharray)) c('stroke-dasharray="',stroke_dasharray,'" '), if(!is.na(fill)) c('fill="', .SVG.color(fill), '" '), if(!is.na(fill_opacity)) c('fill-opacity="',fill_opacity,'" '), # Other parameters: if(!is.na(other_params)) other_params, # Close the element (and add optional tooltip): if(!is.na(tooltip)) c('>',' <title>', tooltip, '</title>', '</rect>') else '></rect>', # the tooltip title must be first child # Add ending newline (if so required): if(newline) '\n' ); if( return_string ) return (paste0(unlist(r),collapse="")) else return (r); } .SVG.lines <- function(x, y, # the coordinates of the points (at least 2) connected=FALSE, # are the lines connected or not? stroke=NA, stroke_width=NA, lty=NA, stroke_dasharray=NA, other_params=NA, # styling attributes (may be one per line for connected==FALSE) id=NA, class=NA, comment=NA, tooltip=NA, # ID, comment and tooltip newline=TRUE, # should a newline be added at the end? return_string=FALSE, # return a singe string or a vector of strings to be concatenated later? suppress.warnings=FALSE ) { # Preconditions: if( length(x) != length(y) || length(x) < 2 || length(y) < 2 ) { if( !suppress.warnings ) .report.ewms("The line point coodinates must be of the same length >= 2.\n", "error", ".SVG.lines", "AdhereR"); if( return_string ) return ("") else return (NULL); } if(!is.na(tooltip)) tooltip <- .SVG.specialchars.2.XMLentities(tooltip); # make sure special chars in tooltip are treated correctly if(connected) { # One 'polyline' elememet: # Process lty: if( length(lty) > 0 && !is.na(lty) ) { lty.cur <- lty[1]; # consider only the first one if( is.numeric(lty.cur) ) s <- which(.SVG.lty$lty == lty.cur) else s <- which(.SVG.lty$names == as.character(lty.cur)); if( length(s) == 1 ) { if( !is.na(.SVG.lty$stroke[s]) ) stroke <- .SVG.lty$stroke[s]; stroke_dasharray <- .SVG.lty$stroke.dasharray[s]; } } # Remove any points with NA coordinates: s <- (!is.na(x) & !is.na(y)); if( !any(s) ) { # Nothing to plot: if( return_string ) return ("") else return (NULL); } x <- x[s]; y <- y[s]; # Keep only the non-missing points # Pre-process stroke: if(!is.na(stroke)) stroke2col <- .SVG.color(stroke); r <- list(# The initial comment (if any): if(!is.na(comment)) .SVG.comment(comment), '<polyline ', # The id and class (if any): if(!is.na(id)) c('id="',id,'" '), if(!is.na(class)) c('class="',class,'" '), # The coordinates of the points as pairs separated by ',': 'points="', unlist(lapply(seq_along(x), function(i) c(.SVG.number(x[i]),",",.SVG.number(y[i])," "))),'" ', # Aesthetics: 'fill="none" ', if(!is.na(stroke)) c('stroke="', stroke2col, '" '), if(!is.na(stroke_width)) c('stroke-width="',stroke_width,'" '), if(!is.na(stroke_dasharray)) c('stroke-dasharray="',stroke_dasharray,'" '), # Other parameters: if(!is.na(other_params)) other_params, # Close the element (and add optional tooltip): if(!is.na(tooltip)) c('>',' <title>', tooltip, '</title>', '</polyline>') else '></polyline>', # the tooltip title must be first child # Add ending newline (if so required): if(newline) '\n' ); } else { # Multiple 'line' elements: if( length(x) %% 2 != 0 ) { if( !suppress.warnings ) .report.ewms("For unconnected lines there must an even number of point coordinates.\n", "error", ".SVG.lines", "AdhereR"); return (NULL); } r <- list(# The initial comment (if any): if(!is.na(comment)) .SVG.comment(comment), lapply(seq(1,length(x),by=2), function(i) { # Check for missing coordinates: if( is.na(x[i]) || is.na(x[i+1]) || is.na(y[i]) || is.na(y[i+1]) ) return(NULL); # cannot draw this line # Process lty: if( length(lty) > 0 && all(!is.na(lty)) ) { if( length(lty) == length(x)/2 ) lty.cur <- lty[(i+1)/2] else lty.cur <- lty[1]; # consider the corresponding lty or only first one if( is.numeric(lty.cur) ) s <- which(.SVG.lty$lty == lty.cur) else s <- which(.SVG.lty$names == as.character(lty.cur)); if( length(s) == 1 ) { if( !is.na(.SVG.lty$stroke[s]) ) stroke <- .SVG.lty$stroke[s]; stroke_dasharray <- .SVG.lty$stroke.dasharray[s]; } } list('<line ', # The id and class (if any): if(!is.na(id)) c('id="',id,'" '), if(!is.na(class)) c('class="',class,'" '), # The coordinates of the points: 'x1="', .SVG.number(x[i]), '" ', 'y1="', .SVG.number(y[i]), '" ', 'x2="', .SVG.number(x[i+1]), '" ', 'y2="', .SVG.number(y[i+1]), '" ', # Aesthetics: if(!is.na(stroke)) c('stroke="', .SVG.color(stroke), '" '), if(!is.na(stroke_width)) c('stroke-width="',stroke_width,'" '), if(!is.na(stroke_dasharray)) c('stroke-dasharray="',stroke_dasharray,'" '), # Other parameters: if(!is.na(other_params)) other_params, # Close the element (and add optional tooltip): if(!is.na(tooltip)) c('>',' <title>', tooltip, '</title>', '</line>') else '></line>', # the tooltip title must be first child # Add ending newline (if so required): if(newline) '\n' ); })); } if( return_string ) return (paste0(unlist(r),collapse="")) else return (r); } .SVG.points <- function(x, y, pch=0, col="black", cex=1.0, other_params=NA, # styling attributes id=NA, class=NA, comment=NA, tooltip=NA, # ID, comment and tooltip newline=TRUE, # should a newline be added at the end? return_string=FALSE, # return a singe string or a vector of strings to be concatenated later? suppress.warnings=FALSE ) { # Preconditions: if( length(x) != length(y) || length(x) == 0 ) { if( !suppress.warnings ) .report.ewms("There must be at least on point.\n", "error", ".SVG.points", "AdhereR"); return (NULL); } if(!is.na(tooltip)) tooltip <- .SVG.specialchars.2.XMLentities(tooltip); # make sure special chars in tooltip are treated correctly # Make sure the point attributes are correctly distributed: if( length(pch) != length(x) ) pch <- rep(pch[1], length(x)); if( length(col) != length(x) ) { col <- rep(col[1], length(x)); col_cache <- rep(.SVG.color(col[1]), length(x)); } else { col_cache <- lapply(col, function(z) .SVG.color(z)); } if( length(cex) != length(x) ) cex <- rep(cex[1], length(x)); # Remove any points with NA coordinates: s <- (!is.na(x) & !is.na(y) & !is.na(pch)); if( !any(s) ) { # Nothing to plot: if( return_string ) return ("") else return (NULL); } x <- x[s]; y <- y[s]; pch <- pch[s]; col <- col[s]; cex <- cex[s]; # Keep only the non-missing points r <- list(# The initial comment (if any): if(!is.na(comment)) .SVG.comment(comment), lapply(seq_along(x), function(i) { list(# The element: '<g ', # The id and class (if any): if(!is.na(id)) c('id="',id,'" '), if(!is.na(class)) c('class="',class,'" '), '>', # Add optional tooltip: if(!is.na(tooltip)) c(' <title>', tooltip, '</title>'), # the tooltip title must be first child # Reuse the predefined symbol: '<use xlink:href="#pch',pch[i],'" ', # The coordinates and size: 'transform="translate(',.SVG.number(x[i]),' ',.SVG.number(y[i]),') scale(',cex[i],')" ', # Aesthetics: if(!is.na(col[i])) list('stroke="', col_cache[[i]], '" ', 'fill="', col_cache[[i]], '" '), # Other parameters: if(!is.na(other_params)) other_params, # Close the element: '></use></g>', # Add ending newline (if so required): if(newline) '\n' ); })); if( return_string ) return (paste0(unlist(r),collapse="")) else return (r); } .SVG.text <- function(x, y, text, col="black", font="Arial", font_size=16, h.align=c(NA,"left","center","right")[1], v.align=c(NA,"top","center","bottom")[1], # alignment rotate=NA, # rotation in degrees other_params=NA, # styling attributes id=NA, class=NA, comment=NA, tooltip=NA, # ID, comment and tooltip newline=TRUE, # should a newline be added at the end? return_string=FALSE, # return a singe string or a vector of strings to be concatenated later? suppress.warnings=FALSE ) { # Preconditions: if( length(x) != length(y) || length(x) != length(text) || length(x) == 0 ) { if( !suppress.warnings ) .report.ewms("There must be at least one text and the number of texts should matche the number of coordinates.\n", "error", ".SVG.text", "AdhereR"); return (NULL); } if(!is.na(tooltip)) tooltip <- .SVG.specialchars.2.XMLentities(tooltip); # make sure special chars in tooltip are treated correctly # Make sure the attributes are correctly distributed: if( length(col) != length(x) ) col <- rep(col[1], length(x)); if( length(font) != length(x) ) font <- rep(font[1], length(x)); if( length(font_size) != length(x) ) font_size <- rep(font_size[1], length(x)); if( length(h.align) != length(x) ) h.align <- rep(h.align[1], length(x)); if( length(v.align) != length(x) ) v.align <- rep(v.align[1], length(x)); if( length(rotate) != length(x) ) rotate <- rep(rotate[1], length(x)); # Remove any points with NA coordinates: s <- (!is.na(x) & !is.na(y) & !is.na(text)); if( !any(s) ) { # Nothing to plot: if( return_string ) return ("") else return (NULL); } x <- x[s]; y <- y[s]; col <- col[s]; font <- font[s]; font_size <- font_size[s]; h.align <- h.align[s]; v.align <- v.align[s]; rotate <- rotate[s]; # Keep only the non-missing points r <- list(# The initial comment (if any): if(!is.na(comment)) .SVG.comment(comment), lapply(seq_along(x), function(i) { list(# The element: '<text ', # The id and class (if any): if(!is.na(id)) c('id="',id,'" '), if(!is.na(class)) c('class="',class,'" '), # The coordinates: 'x="',.SVG.number(x[i]),'" y="',.SVG.number(y[i]),'" ', # The font: 'font-family="',font[i],'" font-size="',font_size[i],'" ', # The alignment: if(!is.na(h.align[i])) c('text-anchor="',switch(h.align[i], "left"="start", "center"="middle", "right"="end"),'" '), #if(!is.na(v.align[i])) c('alignment-baseline="',switch(v.align[i], "top"="auto", "center"="central", "bottom"="baseline"),'" '), if(!is.na(v.align[i]) && v.align[i]!="top") c('dominant-baseline="',switch(v.align[i], "center"="central", "bottom"="text-before-edge"),'" '), # Rotation: if(!is.na(rotate[i])) c('transform="rotate(',rotate[i],' ',.SVG.number(x[i]),' ',.SVG.number(y[i]),')" '), # Aesthetics: if(!is.na(col[i])) c('fill="', .SVG.color(col[i]), '" '), # Other parameters: if(!is.na(other_params)) other_params, # Close the tag: '> ', # The text: .SVG.specialchars.2.XMLentities(text[i]), # Add optional tooltip: if(!is.na(tooltip)) c(' <title>', tooltip, '</title>'), # the tooltip title must be first child # Close it: '</text>', # Add ending newline (if so required): if(newline) '\n' ); })); if( return_string ) return (paste0(unlist(r),collapse="")) else return (r); } # For a given font, style, font size and cex, compute the string's width and height in pixels # family cam be "serif", "sans" or "mono"; font can be 1 = plain text, 2 = bold face, 3 = italic and 4 = bold italic; font_size in pixels; cex as for points .SVG.string.dims <- function(s, family="sans", font=1, font_size=10, cex=1.0) { # Actual font size: font_size_cex <- (font_size * cex); # The number of lines of text: no.lines <- length(grep("\n",s,fixed=TRUE)) + 1; ## The stupid way: #return (c("width"=(nchar(s) - no.lines + 1) * font_size_cex, # "height"=no.lines * font_size_cex)); # Slightly better way: use "M" as the reference and compute everything relative to it (use the ): M.h <- strheight("M",units="inches"); M.w <- strwidth("M",units="inches"); s.h <- strheight(s,units="inches"); s.w <- strwidth(s,units="inches"); return (c("width"=(s.w / M.w) * font_size_cex, "height"=(s.h / M.h) * font_size_cex)); } #' Access last adherence plot info. #' #' Returns the full info the last adherence plot, to be used to modify and/or to #' add new elements to this plot. #' #' This is intended for advanced users only. #' It may return \code{NULL} if no plotting was generated yet, but if one was, a #' list contaning one named element for each type of plot produced (currently only #' \emph{baseR} and \emph{SVG} are used). #' For all types of plots there are a set of \emph{mapping} functions useful for #' transforming events in plotting coordinates: \code{.map.event.x(x)} takes a #' number of days \code{x}, \code{.map.event.date(d, adjust.for.earliest.date=TRUE)} #' takes a \code{Date} \code{d} (and implictely adjusts for the earilerst date #' plotted), and \code{.map.event.y(y)} takes a row ("event" number) \code{y}. #' Besides the shared elements (see the returned value), there are specific ones #' as well. #' For \emph{baseR}, the members \emph{old.par} and \emph{used.par} contain the #' original (pre-plot) \code{par()} environment and the one used within #' \code{plot()}, respectively, in case these need restoring. #' #' @return A \code{list} (possibly empty) contaning one named element for each type #' of plot produced (currently only \emph{baseR} and \emph{SVG}). Each may contain #' shared and specific fields concerning: #' \itemize{ #' \item the values of the parameters with which \code{plot()} was invoked. #' \item actual plot size and other characteristics. #' \item actual title, axis names and labels and their position and size. #' \item legend size, position and size and position of its components. #' \item expanded \code{cma$data} contaning, for each event, info about its #' plotting, including the corresponding fullow-uo and observation windows, #' event start and end, dose text (if any) and other graphical elements. #' \item position, size of the partial CMAs (if any) and of their components. #' \item position, size of the plotted CMAs (if any) and of their components. #' \item rescaling function(s) useful for mapping events to plotting coordinates. #' } #' @examples #' cma7 <- CMA7(data=med.events[med.events$PATIENT_ID %in% c(1,2),], #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' plot(cma7); #' tmp <- last.plot.get.info(); #' names(tmp); #' tmp$baseR$legend$box; # legend position and size #' head(tmp$baseR$cma$data); # events + plotting info #' # Add a transparent blue rect between days 270 and 900: #' rect(tmp$baseR$.map.event.x(270), tmp$baseR$.map.event.y(1-0.5), #' tmp$baseR$.map.event.x(900), tmp$baseR$.map.event.y(nrow(tmp$baseR$cma$data)+0.5), #' col=adjustcolor("blue",alpha.f=0.5), border="blue"); #' # Add a transparent rect rect between dates 03/15/2036 and 03/15/2037: #' rect(tmp$baseR$.map.event.date(as.Date("03/15/2036", format="%m/%d/%Y")), #' tmp$baseR$.map.event.y(1-0.5), #' tmp$baseR$.map.event.date(as.Date("03/15/2037", format="%m/%d/%Y")), #' tmp$baseR$.map.event.y(nrow(tmp$baseR$cma$data)+0.5), #' col=adjustcolor("red",alpha.f=0.5), border="blue"); #' @export last.plot.get.info <- function() { return (get(".last.cma.plot.info", envir=.adherer.env)); } #' Map from event to plot coordinates. #' #' Maps the (x,y) coordinates in the event space to the plotting space. #' #' This is intended for advanced users only. #' In the event space, the \emph{x} coordinate can be either given as the number of #' days since the first plotted event, or as an actual calendar date (either as a #' \code{Date} object or a string with a given format; a date may or may not be corrected #' relative to the first displayed date). On the \emph{y} coordinate, the plotting is #' divided in equally spaced rows, each row corresponding to a single event or an element #' of a partial CMA plot (one can specify in between rows using fractions). Any or both of #' \emph{x} and \emph{y} can be missing. #' #' @param x The \emph{x} coordinate in the event space, either a \code{number} giving the #' number of days since the earliest plotted date, or a \code{Date} or a \code{string} in #' the format given by the \emph{x.date.format} parameter giving the actual calendar date. #' @param y The \emph{y} coordinate in the event space, thus a \code{number} giving the #' plot row. #' @param x.is.Date A \code{logical}, being \code{TRUE} if \emph{x} is a string giving the #' date in the \emph{x.date.format} format. #' @param x.date.format A \code{string} giving the format of the \emph{x} date, if #' \emph{x.is.Date} id \code{TRUE}. #' @param adjust.for.earliest.date A \code{logical} which is \code{TRUE} if \emph{x} is a #' calendar date that must be adjusted for the earliest plotted date (by default #' \code{TRUE}). #' @param plot.type Can be either "baseR" or "SVG" and specifies to which type of plotting #' the mapping applies. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' #' @return A numeric vector with \emph{x} and \emph{y} components giving the plotting #' coordinates, or \code{NULL} in case of error. #' #' @examples #' cma7 <- CMA7(data=med.events[med.events$PATIENT_ID %in% c(1,2),], #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' plot(cma7); #' # Add a transparent blue rect: #' rect(map.event.coords.to.plot(x=270), #' get.event.plotting.area()["y.min"]-1, #' map.event.coords.to.plot(x="03/15/2037", x.is.Date=TRUE, x.date.format="%m/%d/%Y"), #' get.event.plotting.area()["y.max"]+1, #' col=adjustcolor("blue",alpha.f=0.5), border="blue"); #' @export map.event.coords.to.plot <- function(x=NA, y=NA, x.is.Date=FALSE, x.date.format="%m/%d/%Y", adjust.for.earliest.date=TRUE, plot.type=c("baseR", "SVG")[1], suppress.warnings=FALSE) { lcpi <- last.plot.get.info(); if( plot.type[1] == "baseR" ) { if( is.null(lcpi) || is.null(lcpi$baseR) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no base R plot were generated!\n", "error", "map.event.coords.to.plot", "AdhereR"); return (NULL); } else { # x: if( is.na(x) ) { x1 <- NA; } else if( inherits(x, "Date") ) { x1 <- lcpi$baseR$.map.event.date(x, adjust.for.earliest.date=adjust.for.earliest.date); } else if( x.is.Date ) { x1 <- lcpi$baseR$.map.event.date(as.Date(as.character(x), format=x.date.format), adjust.for.earliest.date=adjust.for.earliest.date); } else { x1 <- lcpi$baseR$.map.event.x(x); } # y: if( is.na(y) ) { y1 <- NA; } else { y1 <- lcpi$baseR$.map.event.y(y); } # Return value: return (c("x"=x1, "y"=y1)); } } else if( plot.type[1] == "SVG" ) { if( is.null(lcpi) || is.null(lcpi$SVG) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no SVG was generated!\n", "error", "map.event.coords.to.plot", "AdhereR"); return (NULL); } else { # x: if( inherits(x, "Date") || x.is.Date ) { x1 <- lcpi$SVG$.map.event.date(ifelse(inherits(x, "Date"), x, as.Date(x, format=x.date.format)), adjust.for.earliest.date=adjust.for.earliest.date); } else { x1 <- lcpi$SVG$.map.event.x(x); } # y: y1 <- lcpi$SVG$.map.event.y(y); # Return value: return (c("x"=x1, "y"=y1)); } } else { if( !suppress.warnings ) .report.ewms("Unknown plot type!\n", "error", "map.event.coords.to.plot", "AdhereR"); return (NULL); } } #' Get the actual plotting area. #' #' Returns the actual plotting area rectangle in plotting coordinates. #' #' This is intended for advanced users only. #' #' @param plot.type Can be either "baseR" or "SVG" and specifies to which type of plotting #' the mapping applies. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' #' @return A numeric vector with components \emph{x.min}, \emph{x.max}, #' \emph{y.min} and \emph{y.max}, or \code{NULL} in case of error. #' @export get.event.plotting.area <- function(plot.type=c("baseR", "SVG")[1], suppress.warnings=FALSE) { lcpi <- last.plot.get.info(); if( plot.type[1] == "baseR" ) { if( is.null(lcpi) || is.null(lcpi$baseR) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no base R was generated!\n", "error", "get.event.plotting.area", "AdhereR"); return (NULL); } else { return (c("x.min"=lcpi$baseR$x.min, "x.max"=lcpi$baseR$x.max, "y.min"=lcpi$baseR$y.min, "y.max"=lcpi$baseR$y.max)); } } else if( plot.type[1] == "SVG" ) { if( is.null(lcpi) || is.null(lcpi$SVG) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no SVG was generated!\n", "error", "get.event.plotting.area", "AdhereR"); return (NULL); } else { return (c("x.min"=lcpi$SVG$x.min, "x.max"=lcpi$SVG$x.max, "y.min"=lcpi$SVG$y.min, "y.max"=lcpi$SVG$y.max)); } } else { if( !suppress.warnings ) .report.ewms("Unknown plot type!\n", "error", "get.event.plotting.area", "AdhereR"); return (NULL); } } #' Get the legend plotting area. #' #' Returns the legend plotting area rectangle in plotting coordinates #' (if any). #' #' This is intended for advanced users only. #' #' @param plot.type Can be either "baseR" or "SVG" and specifies to which type of plotting #' the mapping applies. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' #' @return A numeric vector with components \emph{x.min}, \emph{x.max}, #' \emph{y.min} and \emph{y.max}, or \code{NULL} in case of error or no #' legend being shown. #' @export get.legend.plotting.area <- function(plot.type=c("baseR", "SVG")[1], suppress.warnings=FALSE) { lcpi <- last.plot.get.info(); if( plot.type[1] == "baseR" ) { if( is.null(lcpi) || is.null(lcpi$baseR) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no base R was generated!\n", "error", "get.legend.plotting.area", "AdhereR"); return (NULL); } else { if( is.null(lcpi$baseR$legend$box) ) { return (NULL); # no legend being shown } else { return (c("x.min"=lcpi$baseR$legend$box$x.start, "x.max"=lcpi$baseR$legend$box$x.end, "y.min"=lcpi$baseR$legend$box$y.start, "y.max"=lcpi$baseR$legend$box$y.end)); } } } else if( plot.type[1] == "SVG" ) { if( is.null(lcpi) || is.null(lcpi$SVG) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no SVG was generated!\n", "error", "get.legend.plotting.area", "AdhereR"); return (NULL); } else { if( is.null(lcpi$SVG$legend$box) ) { return (NULL); # no legend being shown } else { return (c("x.min"=lcpi$SVG$legend$box$x.start, "x.max"=lcpi$SVG$legend$box$x.end, "y.min"=lcpi$SVG$legend$box$y.start, "y.max"=lcpi$SVG$legend$box$y.end)); } } } else { if( !suppress.warnings ) .report.ewms("Unknown plot type!\n", "error", "get.legend.plotting.area", "AdhereR"); return (NULL); } } #' Get info about the plotted events. #' #' Returns a \code{data.frame} where each row contains info about one plotted event; #' the order of the rows reflects the y-axis (first row on bottom). #' #' This is intended for advanced users only. #' #' @param plot.type Can be either "baseR" or "SVG" and specifies to which type of plotting #' the mapping applies. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' #' @return A \code{data.frame} that, besides the info about each event, also #' contains info about: #' \itemize{ #' \item the corresponding follow-up and observation windows (and, for #' \code{CMA8}, the "real" observation window), given as the corners of the area #' \emph{.X...START}, \emph{.X...END}, \emph{.Y...START} and \emph{.Y...END} #' (where the mid dot stands for FUW, OW and ROW, respectively). #' \item the area occupied by the graphic representation of the event given by #' its four corners \emph{.X.START}, \emph{.X.END}, \emph{.Y.START} and #' \emph{.Y.END}, as well as the line width \emph{.EV.LWD}. #' \item the dose text's (if any) position (\emph{.X.DOSE}, \emph{.Y.DOSE}) and #' font size \emph{.FONT.SIZE.DOSE}. #' \item if event corvered and not covered are plotted, also give their areas as #' \emph{.X.EVC.START}, \emph{.X.EVC.END}, \emph{.Y.EVC.START}, \emph{.Y.EVC.END}, #' \emph{.X.EVNC.START}, \emph{.X.EVNC.END}, \emph{.Y.EVNC.START} and #' \emph{.Y.EVNC.END}. #' \item the continuation lines area as \emph{.X.CNT.START}, \emph{.X.CNT.END}, #' \emph{.Y.CNT.START} and \emph{.Y.CNT.END}. #' \item and the corresponding summary CMA (if any) given as the area #' \emph{.X.SCMA.START}, \emph{.X.SCMA.END}, \emph{.Y.SCMA.START} and #' \emph{.Y.SCMA.END}. #' } #' Please note that even if with follow-up and ("real") observation window, and #' the summary CMA info is repeated for each event, they really make sense at #' the level of the patient. #' @examples #' cma7 <- CMA7(data=med.events[med.events$PATIENT_ID %in% c(1,2),], #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' followup.window.start.unit="days", #' followup.window.duration=2*365, #' followup.window.duration.unit="days", #' observation.window.start=30, #' observation.window.start.unit="days", #' observation.window.duration=365, #' observation.window.duration.unit="days", #' date.format="%m/%d/%Y", #' summary="Base CMA"); #' plot(cma7); #' tmp <- get.plotted.events(); #' head(tmp); #' # "Mask" the first event: #' rect(tmp$.X.START[1], tmp$.Y.START[1]-0.5, tmp$.X.END[1], tmp$.Y.END[1]+0.5, #' col=adjustcolor("white",alpha.f=0.75), border="black"); #' # "Mask" the first patient's summary CMA: #' rect(tmp$.X.SCMA.START[1], tmp$.Y.SCMA.START[1], #' tmp$.X.SCMA.END[1], tmp$.Y.SCMA.END[1], #' col=adjustcolor("white",alpha.f=0.75), border="black"); #' @export get.plotted.events <- function(plot.type=c("baseR", "SVG")[1], suppress.warnings=FALSE) { lcpi <- last.plot.get.info(); if( plot.type[1] == "baseR" ) { if( is.null(lcpi) || is.null(lcpi$baseR) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no base R was generated!\n", "error", "get.plotted.events", "AdhereR"); return (NULL); } else { if( is.null(lcpi$baseR$cma) || is.null(lcpi$baseR$cma$data) ) { if( !suppress.warnings ) .report.ewms("No info about the plotted CMA!\n", "error", "get.plotted.events", "AdhereR"); return (NULL); } else { return (lcpi$baseR$cma$data); } } } else if( plot.type[1] == "SVG" ) { if( is.null(lcpi) || is.null(lcpi$SVG) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no SVG was generated!\n", "error", "get.plotted.events", "AdhereR"); return (NULL); } else { if( is.null(lcpi$SVG$cma) || is.null(lcpi$SVG$cma$data) ) { if( !suppress.warnings ) .report.ewms("No info about the plotted CMA!\n", "error", "get.plotted.events", "AdhereR"); return (NULL); } else { return (lcpi$SVG$cma$data); } } } else { if( !suppress.warnings ) .report.ewms("Unknown plot type!\n", "error", "get.plotted.events", "AdhereR"); return (NULL); } } #' Get info about the plotted partial CMAs. #' #' Returns a \code{data.frame} where each row contains info about one plotted #' partial CMA (partial CMAs make sense only for "complex" CMAs, i.e., per #' episode and sliding windows). #' #' This is intended for advanced users only. #' #' @param plot.type Can be either "baseR" or "SVG" and specifies to which type of plotting #' the mapping applies. #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' #' @return A \code{data.frame} that contains info about: #' \itemize{ #' \item the patient ID (\emph{pid}) to which the partial CMA belongs. #' \item the \emph{type} of partial CMA (see the help for plotting "complex" #' CMAs). #' \item the corners of the whole area covered by the partial CMA plot given as #' \emph{x.region.start}, \emph{y.region.start}, \emph{x.region.end} and #' \emph{y.region.end}. #' \item for each element of the partial CMA plot, its area as #' \emph{x.partial.start}, \emph{y.partial.start}, \emph{x.partial.end} and #' \emph{y.partial.end}. #' } #' Please note that this contains one row per partial CMA element (e.g., if #' plotting stacked, one row for each rectangle). #' @export get.plotted.partial.cmas <- function(plot.type=c("baseR", "SVG")[1], suppress.warnings=FALSE) { lcpi <- last.plot.get.info(); if( plot.type[1] == "baseR" ) { if( is.null(lcpi) || is.null(lcpi$baseR) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no base R was generated!\n", "error", "get.plotted.partial.cmas", "AdhereR"); return (NULL); } else { if( is.null(lcpi$baseR$partialCMAs) ) { if( !suppress.warnings ) .report.ewms("No partial CMAs: are you sur this is the right type of CMA and that the partial CMAs were actually plotted?\n", "error", "get.plotted.partial.cmas", "AdhereR"); return (NULL); } else { return (lcpi$baseR$partialCMAs); } } } else if( plot.type[1] == "SVG" ) { if( is.null(lcpi) || is.null(lcpi$SVG) ) { if( !suppress.warnings ) .report.ewms("No CMA plot or no SVG was generated!\n", "error", "get.plotted.partial.cmas", "AdhereR"); return (NULL); } else { if( is.null(lcpi$SVG$partialCMAs) ) { if( !suppress.warnings ) .report.ewms("No partial CMAs: are you sur this is the right type of CMA and that the partial CMAs were actually plotted?\n", "error", "get.plotted.partial.cmas", "AdhereR"); return (NULL); } else { return (lcpi$SVG$partialCMAs); } } } else { if( !suppress.warnings ) .report.ewms("Unknown plot type!\n", "error", "get.plotted.partial.cmas", "AdhereR"); return (NULL); } } ## The plotting function #### .plot.CMAs <- function(cma, # the CMA_per_episode or CMA_sliding_window (or derived) object patients.to.plot=NULL, # list of patient IDs to plot or NULL for all duration=NA, # duration and end period to plot in days (if missing, determined from the data) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? and, if so, place the first event as the horizontal 0? show.period=c("dates","days")[2], # draw vertical bars at regular interval as dates or days? period.in.days=90, # the interval (in days) at which to draw vertical lines show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend params and position cex=1.0, cex.axis=0.75, cex.lab=1.0, cex.title=1.5, # various graphical params show.cma=TRUE, # show the CMA type xlab=c("dates"="Date", "days"="Days"), # Vector of x labels to show for the two types of periods, or a single value for both, or NULL for nothing ylab=c("withoutCMA"="patient", "withCMA"="patient (& CMA)"), # Vector of y labels to show without and with CMA estimates, or a single value for both, or NULL for nothing title=c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns"), # Vector of titles to show for and without alignment, or a single value for both, or NULL for nothing col.cats=rainbow, # single color or a function mapping the categories to colors unspecified.category.label="drug", # the label of the unspecified category of medication medication.groups.to.plot=NULL, # the names of the medication groups to plot (by default, all) medication.groups.separator.show=TRUE, medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", # group medication events by patient? medication.groups.allother.label="*", # the label to use for the __ALL_OTHERS__ medication class (defaults to *) lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, # event style show.event.intervals=TRUE, # show the actual prescription intervals show.overlapping.event.intervals=c("first", "last", "min gap", "max gap", "average")[1], # how to plot overlapping event intervals (relevant for sliding windows and per episode) plot.events.vertically.displaced=TRUE, # display the events on different lines (vertical displacement) or not (defaults to TRUE)? print.dose=FALSE, cex.dose=0.75, print.dose.col="black", print.dose.outline.col="white", print.dose.centered=FALSE, # print daily dose plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # draw daily dose as line width col.na="lightgray", # color for missing data col.continuation="black", lty.continuation="dotted", lwd.continuation=1, # style of the continuation lines connecting consecutive events print.CMA=TRUE, CMA.cex=0.50, # print CMA next to the participant's ID? plot.CMA=TRUE, # plot the CMA next to the participant ID? plot.CMA.as.histogram=TRUE, # plot CMA as a histogram or as a density plot? plot.partial.CMAs.as=c("stacked", "overlapping", "timeseries")[1], # how to plot the "partial" (i.e., intervals/episodes) CMAs (NULL for none)? plot.partial.CMAs.as.stacked.col.bars="gray90", plot.partial.CMAs.as.stacked.col.border="gray30", plot.partial.CMAs.as.stacked.col.text="black", plot.partial.CMAs.as.timeseries.vspace=7, # how much vertical space to reserve for the timeseries plot (in character lines) plot.partial.CMAs.as.timeseries.start.from.zero=TRUE, #show the vertical axis start at 0 or at the minimum actual value (if positive)? plot.partial.CMAs.as.timeseries.col.dot="darkblue", plot.partial.CMAs.as.timeseries.col.interval="gray70", plot.partial.CMAs.as.timeseries.col.text="firebrick", # setting any of these to NA results in them not being plotted plot.partial.CMAs.as.timeseries.interval.type=c("none", "segments", "arrows", "lines", "rectangles")[2], # how to show the covered intervals plot.partial.CMAs.as.timeseries.lwd.interval=1, # line width for some types of intervals plot.partial.CMAs.as.timeseries.alpha.interval=0.25, # the transparency of the intervals (when drawn as rectangles) plot.partial.CMAs.as.timeseries.show.0perc=TRUE, plot.partial.CMAs.as.timeseries.show.100perc=FALSE, #show the 0% and 100% lines? plot.partial.CMAs.as.overlapping.alternate=TRUE, # should successive intervals be plotted low/high? plot.partial.CMAs.as.overlapping.col.interval="gray70", plot.partial.CMAs.as.overlapping.col.text="firebrick", # setting any of these to NA results in them not being plotted CMA.plot.ratio=0.10, # the proportion of the total horizontal plot to be taken by the CMA plot CMA.plot.col="lightgreen", CMA.plot.border="darkgreen", CMA.plot.bkg="aquamarine", CMA.plot.text=CMA.plot.border, # attributes of the CMA plot highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, # for CMA8, the real observation window starts at a different date print.episode.or.sliding.window=FALSE, # should we print the episode or sliding window to which an event belongs? alternating.bands.cols=c("white", "gray95"), # the colors of the alternating vertical bands across patients (NULL or NA=don't draw any; can be >= 1 color) rotate.text=-60, # some text (e.g., axis labels) may be rotated by this much degrees force.draw.text=FALSE, # if true, always draw text even if too big or too small bw.plot=FALSE, # if TRUE, override all user-given colors and replace them with a scheme suitable for grayscale plotting min.plot.size.in.characters.horiz=0, min.plot.size.in.characters.vert=0, # the minimum plot size (in characters: horizontally, for the whole duration, vertically, per event (and, if shown, per episode/sliding window)) max.patients.to.plot=100, # maximum number of patients to plot suppress.warnings=FALSE, # suppress warnings? export.formats=NULL, # the formats to export the figure to (by default, none); can be any subset of "svg" (just SVG file), "html" (SVG + HTML + CSS + JavaScript all embedded within the HTML document), "jpg", "png", "webp", "ps" and "pdf" export.formats.fileprefix="AdhereR-plot", # the file name prefix for the exported formats export.formats.height=NA, export.formats.width=NA, # desired dimensions (in pixels) for the exported figure (defaults to sane values) export.formats.save.svg.placeholder=TRUE, export.formats.svg.placeholder.type=c("jpg", "png", "webp")[2], export.formats.svg.placeholder.embed=FALSE, # save a placeholder for the SVG image? export.formats.html.template=NULL, export.formats.html.javascript=NULL, export.formats.html.css=NULL, # HTML, JavaScript and CSS templates for exporting HTML+SVG export.formats.directory=NA, # if exporting, which directory to export to (if not give, creates files in the temporary directory) generate.R.plot=TRUE, # generate standard (base R) plot for plotting within R? do.not.draw.plot=FALSE, # if TRUE, don't draw the actual plot, but only the legend (if required) ... ) { # What sorts of plots to generate (use short names for short if statements): .do.R <- generate.R.plot; .do.SVG <- (!is.null(export.formats) && any(c("svg", "html", "jpg", "png", "webp", "ps", "pdf") %in% export.formats)); if( !.do.R && !.do.SVG ) { # Nothing to plot! return (invisible(NULL)); } # There is a confusion in the help concerning align.first.event.at.zero, so negate it: align.first.event.at.zero <- !align.first.event.at.zero; if( !is.null(medication.groups.to.plot) && length(medication.groups.to.plot) == 1 && is.na(medication.groups.to.plot) ) medication.groups.to.plot <- NULL; # NA has the same effect as NULL # # Initialize the SVG file content #### # # Things to remember about SVGs: # - coordinates start top-left and go right and bottom # - font size is relative to the viewBox # if( .do.SVG ) { # The SVG header and string (body): svg.header <- c('<?xml version="1.0" standalone="no"?>\n', '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'); } svg.str <- list(); #svg.str <- NULL; # some cases need (even an empty) svg.str... # # Set-up, checks and local functions #### # # Preconditions: if( is.null(cma) || # must be: non-null !(inherits(cma, "CMA_per_episode") || inherits(cma, "CMA_sliding_window") || inherits(cma, "CMA0")) || # a proper CMA object is.null(cma$data) || nrow(cma$data) < 1 || !inherits(cma$data, "data.frame") || # that contains non-null data derived from data.frame is.na(cma$ID.colname) || !(cma$ID.colname %in% names(cma$data)) || # has a valid patient ID column is.na(cma$event.date.colname) || !(cma$event.date.colname %in% names(cma$data)) || # has a valid event date column is.na(cma$event.duration.colname) || !(cma$event.duration.colname %in% names(cma$data)) # has a valid event duration column ) { if( !suppress.warnings ) .report.ewms("Can only plot a correctly specified CMA object (i.e., with valid data and column names)!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Overriding dangerous or aesthetic defaults: if( force.draw.text && !suppress.warnings ) .report.ewms("Forcing drawing of text elements even if too big or ugly!\n", "warning", ".plot.CMAs", "AdhereR"); # SVG placeholder: if( export.formats.save.svg.placeholder && (length(export.formats.svg.placeholder.type) != 1 || !export.formats.svg.placeholder.type %in% c("jpg", "png", "webp")) ) { if( !suppress.warnings ) .report.ewms("The SVG place holder can only be a jpg, png or webp!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Local functions for the various types of summary CMA plots: .plot.summary.CMA.as.histogram <- function(adh, svg.str) { adh.hist <- hist(adh, plot=FALSE); adh.x <- adh.hist$breaks[-1]; adh.x.0 <- min(adh.x,0); adh.x.1 <- max(adh.x,1); adh.x <- (adh.x - adh.x.0) / (adh.x.1 - adh.x.0); adh.y <- adh.hist$counts; adh.y <- adh.y / max(adh.y); adh.x.max <- adh.x[which.max(adh.hist$counts)]; if( .do.R ) # Rplot { segments(.rescale.xcoord.for.CMA.plot(adh.x), y.mean - 2, .rescale.xcoord.for.CMA.plot(adh.x), y.mean - 2 + 4*adh.y, lty="solid", lwd=1, col=CMA.plot.border); if( force.draw.text || char.height.CMA <= abs(.rescale.xcoord.for.CMA.plot(1.0) - .rescale.xcoord.for.CMA.plot(0.0)) ) { # There's enough space for vertically writing all three of them: text(x=.rescale.xcoord.for.CMA.plot(0.0), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*min(adh.x.0,na.rm=TRUE)), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); text(x=.rescale.xcoord.for.CMA.plot(1.0), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*max(adh.x.1,na.rm=TRUE)), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); text(x=.rescale.xcoord.for.CMA.plot(adh.x.max), y.mean + 2 + char.height.CMA/2, sprintf("%d",max(adh.hist$counts,an.rm=TRUE)), srt=90, pos=3, cex=CMA.cex, col=CMA.plot.text); } } if( .do.SVG ) # SVG { svg.str[[length(svg.str)+1]] <- .SVG.comment("The CMA summary as histogram", newpara=TRUE) svg.str[[length(svg.str)+1]] <- lapply(seq_along(adh.x), function(j) { # The CMA as histogram: .SVG.lines(x=rep(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x[j])),2), y=c(.scale.y.to.SVG.plot(y.mean - 2), .scale.y.to.SVG.plot(y.mean - 2 + 4*adh.y[j])), connected=FALSE, stroke=CMA.plot.border, stroke_width=1, class="cma-summary-plot", suppress.warnings=suppress.warnings); }); if( force.draw.text || 3*dims.chr.cma <= abs(.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0) - .rescale.xcoord.for.CMA.plot(0.0))) ) { # There's enough space for vertically writing all three of them: svg.str[[length(svg.str)+1]] <- # The CMA as histogram: .SVG.text(x=c(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0)), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x.max))), y=c(.scale.y.to.SVG.plot(y.mean - 2 - 0.25), .scale.y.to.SVG.plot(y.mean - 2 - 0.25), .scale.y.to.SVG.plot(y.mean + 2 + 0.25)), text=c(sprintf("%.1f%%",100*min(adh.x.0,na.rm=TRUE)), sprintf("%.1f%%",100*max(adh.x.1,na.rm=TRUE)), sprintf("%d",max(adh.hist$counts,an.rm=TRUE))), col=CMA.plot.text, font_size=dims.chr.cma, h.align=c("right","right","left"), v.align="center", rotate=c(-(90+rotate.text),-(90+rotate.text),-90), class="cma-summary-text", suppress.warnings=suppress.warnings); } } return (svg.str); } .plot.summary.CMA.as.density <- function(adh.x, adh.y, svg.str) { adh.x.0 <- min(adh.x,0); adh.x.1 <- max(adh.x,1); adh.x <- (adh.x - adh.x.0) / (adh.x.1 - adh.x.0); adh.y <- (adh.y - min(adh.y)) / (max(adh.y) - min(adh.y)); if( .do.R ) # Rplot: { points(.rescale.xcoord.for.CMA.plot(adh.x), y.mean - 2 + 4*adh.y, type="l", col=CMA.plot.border); if( force.draw.text || char.height.CMA <= abs(.rescale.xcoord.for.CMA.plot(1) - .rescale.xcoord.for.CMA.plot(0)) ) { # There's enough space for vertical writing: text(x=.rescale.xcoord.for.CMA.plot(0.0), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*adh.x.0), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); text(x=.rescale.xcoord.for.CMA.plot(1.0), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*adh.x.1), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); } } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.comment("The CMA summary as density", newpara=TRUE); svg.str[[length(svg.str)+1]] <- # The individual lines: .SVG.lines(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x)), y=.scale.y.to.SVG.plot(y.mean - 2 + 4*adh.y), connected=TRUE, stroke=CMA.plot.border, stroke_width=1, class="cma-summary-plot", suppress.warnings=suppress.warnings); if( force.draw.text || 2*dims.chr.cma <= abs(.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0) - .rescale.xcoord.for.CMA.plot(0.0))) ) { # There's enough space for vertical writing: svg.str[[length(svg.str)+1]] <- # The actual values as text: .SVG.text(x=c(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0))), y=c(.scale.y.to.SVG.plot(y.mean - 2 - 0.25), .scale.y.to.SVG.plot(y.mean - 2 - 0.25)), text=c(sprintf("%.1f%%",100*adh.x.0), sprintf("%.1f%%",100*adh.x.1)), col=CMA.plot.text, font_size=dims.chr.cma, h.align=c("right","right"), v.align="center", rotate=rotate.text, class="cma-summary-text", suppress.warnings=suppress.warnings); } } return (svg.str); } .plot.summary.CMA.as.lines <- function(adh, svg.str) { adh.x.0 <- min(adh,0); adh.x.1 <- max(adh,1); adh.x <- (adh - adh.x.0) / (adh.x.1 - adh.x.0); if( .do.R ) # Rplot: { segments(.rescale.xcoord.for.CMA.plot(adh.x), y.mean - 2, .rescale.xcoord.for.CMA.plot(adh.x), y.mean - 2 + 4, lty="solid", lwd=2, col=CMA.plot.border); if( char.height.CMA*length(adh) <= abs(.rescale.xcoord.for.CMA.plot(1) - .rescale.xcoord.for.CMA.plot(0)) ) { # There's enough space for vertical writing all of them (alternated): for( j in 1:length(adh) ) { text(x=.rescale.xcoord.for.CMA.plot(adh.x[j]), y.mean + ifelse(j %% 2==0, 2 + char.height.CMA/2, -2 - char.height.CMA/2), sprintf("%.1f%%",100*adh[j]), srt=90, pos=ifelse(j %% 2==0, 3, 1), cex=CMA.cex, col=CMA.plot.text); } } else if( force.draw.text || char.height.CMA <= abs(.rescale.xcoord.for.CMA.plot(1) - .rescale.xcoord.for.CMA.plot(0)) ) { # There's enough space for vertical writing only the extremes: text(x=.rescale.xcoord.for.CMA.plot(adh.x[1]), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*adh[1]), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); text(x=.rescale.xcoord.for.CMA.plot(adh.x[length(adh)]), y.mean - 2 - char.height.CMA/2, sprintf("%.1f%%",100*adh[length(adh)]), srt=90, pos=1, cex=CMA.cex, col=CMA.plot.text); } } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.comment("The CMA summary as barplot", newpara=TRUE); svg.str[[length(svg.str)+1]] <- lapply(seq_along(adh.x), function(j) { # The individual lines: .SVG.lines(x=rep(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x[j])),2), y=c(.scale.y.to.SVG.plot(y.mean - 2), .scale.y.to.SVG.plot(y.mean - 2 + 4)), connected=FALSE, stroke=CMA.plot.border, stroke_width=2, class="cma-summary-plot", suppress.warnings=suppress.warnings); }); if( length(adh)*dims.chr.cma <= abs(.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0) - .rescale.xcoord.for.CMA.plot(0.0))) ) { # There's enough space for vertical writing all of them (alternated): svg.str[[length(svg.str)+1]] <- # The actual values as text: .SVG.text(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x)), y=.scale.y.to.SVG.plot(y.mean + rep(c(-2 - 0.25, 2 + 0.25),times=length(adh))[1:length(adh)]), text=sprintf("%.1f%%",100*adh), col=CMA.plot.text, font_size=dims.chr.cma, h.align=rep(c("right", "left"),times=length(adh))[1:length(adh)], v.align="center", rotate=rotate.text, class="cma-summary-text", suppress.warnings=suppress.warnings); } else if( force.draw.text || 2*dims.chr.cma <= abs(.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0) - .rescale.xcoord.for.CMA.plot(0.0))) ) { # There's enough space for vertical writing only the extremes: svg.str[[length(svg.str)+1]] <- # The actual values as text: .SVG.text(x=c(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x[1])), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.x[length(adh)]))), y=c(.scale.y.to.SVG.plot(y.mean - 2 - 0.25), .scale.y.to.SVG.plot(y.mean - 2 - 0.25)), text=c(sprintf("%.1f%%",100*adh[1]), sprintf("%.1f%%",100*adh[length(adh)])), col=CMA.plot.text, font_size=dims.chr.cma, h.align=c("right","right"), v.align="center", rotate=c(-90,-90), class="cma-summary-text", suppress.warnings=suppress.warnings); } } return (svg.str); } # Legend plotting auxiliary functions #### if( show.legend ) { if( .do.R ) { .legend.R <- function(x=0, y=0, width=1, height=1, do.plot=TRUE) { # Legend rectangle: if( do.plot ) { rect(x, y, x + width, y + height, border=gray(0.6), lwd=2, col=rgb(0.99,0.99,0.99,legend.bkg.opacity)); # Save the info: .last.cma.plot.info$baseR$legend <<- list("box"=data.frame("x.start"=x, "y.start"=y, "x.end"=x+width, "y.end"=y+height)); .last.cma.plot.info$baseR$legend$components <<- NULL; } cur.y <- y + height; # current y max.width <- width; # maximum width # Legend title: if( do.plot ) { text(x + width/2, cur.y, "Legend", pos=1, col=gray(0.3), cex=legend.cex.title); # Save the info: .last.cma.plot.info$baseR$legend$title <<- data.frame("string"="Legend", "x"=x+width/2, "y"=cur.y, "cex"=legend.cex.title); } cur.y <- cur.y - strheight("Legend", cex=legend.cex.title) - 3*legend.char.height; max.width <- max(max.width, strwidth("Legend", cex=legend.cex.title)); # Event: if( do.plot ) { segments(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y, lty=lty.event, lwd=lwd.event, col="black"); points(x + 1.0*legend.char.width, cur.y, pch=pch.start.event, cex=legend.cex, col="black"); points(x + 4.0*legend.char.width, cur.y, pch=pch.end.event, cex=legend.cex, col="black"); } if( !plot.dose ) { if( do.plot ) { text(x + 5.0*legend.char.width, cur.y, "duration", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="duration", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y, "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("duration", cex=legend.cex)); } else { if( do.plot ) { text(x + 5.0*legend.char.width, cur.y, "duration (min. dose)", col="black", cex=legend.cex, pos=4); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("duration (min. dose)", cex=legend.cex)); if( do.plot ) { segments(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y, lty=lty.event, lwd=lwd.event.max.dose, col="black"); points(x + 1.0*legend.char.width, cur.y, pch=pch.start.event, cex=legend.cex, col="black"); points(x + 4.0*legend.char.width, cur.y, pch=pch.end.event, cex=legend.cex, col="black"); text(x + 5.0*legend.char.width, cur.y, "duration (max. dose)", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"=c("duration (min. dose)", "duration (max. dose)"), "x.start"=rep(x + 1.0*legend.char.width,2), "y.start"=c(cur.y + 1.5*legend.char.height, cur.y), "x.end"=rep(x + 4.0*legend.char.width,2), "y.end"=c(cur.y + 1.5*legend.char.height, cur.y), "x.string"=rep(x + 5.0*legend.char.width,2), "y.string"=c(cur.y + 1.5*legend.char.height, cur.y), "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("duration (max. dose)", cex=legend.cex)); } # No event: if( do.plot ) { segments(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y, lty=lty.continuation, lwd=lwd.continuation, col=col.continuation); text(x + 5.0*legend.char.width, cur.y, "no event/connector", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="no event/connector", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y, "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("no event/connector", cex=legend.cex)); # Event intervals: if( show.event.intervals ) { if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border="black", col=adjustcolor("black",alpha.f=0.5)); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "days covered", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="days covered", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("days covered", cex=legend.cex)); if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border="black", col=NA); #, col="black", density=25); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "gap days", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="gap days", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 2.0*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("gap days", cex=legend.cex)); } # medication classes: for( i in 1:length(cols) ) { med.class.name <- names(cols)[i]; med.class.name <- ifelse(is.na(med.class.name),"<missing>",med.class.name); if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border="black", col=adjustcolor(cols[i],alpha.f=0.5)); med.class.name <- names(cols)[i]; med.class.name <- ifelse(is.na(med.class.name),"<missing>",med.class.name); if( print.dose || plot.dose ) { dose.for.cat <- (dose.range$category == med.class.name); if( sum(dose.for.cat,na.rm=TRUE) == 1 ) { med.class.name <- paste0(med.class.name," (",dose.range$min[dose.for.cat]," - ",dose.range$max[dose.for.cat],")"); } } text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, med.class.name, col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"=med.class.name, "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth(names(cols)[i], cex=legend.cex)); } cur.y <- cur.y - 0.5*legend.char.height; # Follow-up window: if( highlight.followup.window ) { if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border=followup.window.col, lty="dotted", lwd=2, col=rgb(1,1,1,0.0)); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "follow-up wnd.", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="follow-up wnd.", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 2.0*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("follow-up wnd.", cex=legend.cex)); } # Observation window: if( highlight.observation.window ) { if( !is.null(cma.realOW) ) { # CMA8 also has a "real" OW: if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border=rgb(1,1,1,0.0), col=adjustcolor(observation.window.col,alpha.f=observation.window.opacity)); #, density=observation.window.density, angle=observation.window.angle); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "theor. obs. wnd.", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="theor. obs. wnd.", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 1.5*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("theor. obs. wnd.", cex=legend.cex)); if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border=rgb(1,1,1,0.0), col=adjustcolor(observation.window.col,alpha.f=observation.window.opacity)); #, density=real.obs.window.density, angle=real.obs.window.angle); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "real obs. wnd.", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="real obs. wnd.", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 2.0*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("real obs.wnd.", cex=legend.cex)); } else { if( do.plot ) { rect(x + 1.0*legend.char.width, cur.y, x + 4.0*legend.char.width, cur.y - 1.0*legend.char.height, border=rgb(1,1,1,0.0), col=adjustcolor(observation.window.col,alpha.f=observation.window.opacity)) #, density=observation.window.density, angle=observation.window.angle); text(x + 5.0*legend.char.width, cur.y - 0.5*legend.char.height, "observation wnd.", col="black", cex=legend.cex, pos=4); # Save the info: .last.cma.plot.info$baseR$legend$components <<- rbind(.last.cma.plot.info$baseR$legend$components, data.frame("string"="observation wnd.", "x.start"=x + 1.0*legend.char.width, "y.start"=cur.y, "x.end"=x + 4.0*legend.char.width, "y.end"=cur.y - 1.0*legend.char.height, "x.string"=x + 5.0*legend.char.width, "y.string"=cur.y - 0.5*legend.char.height, "cex"=legend.cex)); } cur.y <- cur.y - 2.0*legend.char.height; max.width <- max(max.width, 5.0*legend.char.width + strwidth("observation wnd.", cex=legend.cex)); } } # Required size: return (c("width" =max.width + 5.0*legend.char.width, "height"=(y + height - cur.y) + 1.0*legend.char.height)); } } if( .do.SVG ) { .legend.SVG <- function(x=0, y=0, do.plot=TRUE) { if( do.plot ) { # The legend is an object that we can move around, scale, etc: l1 <- c(.SVG.comment("The legend", newpara=TRUE, newline=TRUE), '<g id="legend">\n'); } # The legend origins: x.origin <- ifelse(!do.plot || is.numeric(x), x, 0.0); y.origin <- ifelse(!do.plot || is.numeric(y), y, 0.0); # Save the info: .last.cma.plot.info$SVG$legend <<- list(); .last.cma.plot.info$SVG$legend$components <<- NULL; # The legend dimensions and other aesthetics: lw <- lh <- 0; # width and height lmx <- dims.chr.legend; lmy <- 2 # margins lnl <- 1.25; lnp <- 0.25; # the vertical size of a newline and newpara (in dims.chr.legend) # The actual legend content: # The legend title: if( do.plot ) { l2 <- c(.SVG.text(x=x.origin + lmx, y=y.origin + lmy+lh+dims.chr.legend.title*2/3, text="Legend", font_size=dims.chr.legend.title, font="Arial", h.align="left", v.align="center", col="gray30", class="legend-title", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$title <<- data.frame("string"="Legend", "x"=x.origin + lmx, "y"=y.origin + lmy+lh+dims.chr.legend.title*2/3, "font.size"=dims.chr.legend.title); } lh <- lh + dims.chr.legend.title + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("Legend", font_size=dims.chr.legend.title)["width"]); lh <- lh + lnp*dims.chr.legend.title; # new para # The event: if( do.plot ) { l2 <- c(l2, .SVG.lines(x=x.origin + c(lmx, lmx + 3*dims.chr.legend), y=y.origin + c(lmy+lh, lmy+lh), connected=FALSE, stroke="black", stroke_width=lwd.event, lty=lty.event, class="legend-events", suppress.warnings=suppress.warnings), .SVG.points(x=x.origin + c(lmx, lmx + 3*dims.chr.legend), y=y.origin + c(lmy+lh, lmy+lh), pch=c(pch.start.event, pch.end.event), col="black", cex=legend.cex, class="legend-events", suppress.warnings=suppress.warnings)); } if( !plot.dose ) { if( do.plot ) { l2 <- c(l2, .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="duration", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-events", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="duration", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("duration", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } else { # Min dose: if( do.plot ) { l2 <- c(l2, .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="duration (min. dose)", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-events", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="duration (min. dose)", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("duration (min. dose)", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); # Max dose: if( do.plot ) { l2 <- c(l2, .SVG.lines(x=x.origin + c(lmx, lmx + 3*dims.chr.legend), y=y.origin + c(lmy+lh, lmy+lh), connected=FALSE, stroke="black", stroke_width=lwd.event.max.dose, lty=lty.event, class="legend-events", suppress.warnings=suppress.warnings), .SVG.points(x=x.origin + c(lmx, lmx + 3*dims.chr.legend), y=y.origin + c(lmy+lh, lmy+lh), pch=c(pch.start.event, pch.end.event),col="black", cex=legend.cex, class="legend-events", suppress.warnings=suppress.warnings), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="duration (max. dose)", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-events", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="duration (max. dose)", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("duration (max. dose)", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } # No event: if( do.plot ) { l2 <- c(l2, .SVG.lines(x=x.origin + c(lmx, lmx + 3*dims.chr.legend), y=y.origin + c(lmy+lh, lmy+lh), connected=FALSE, stroke=col.continuation, stroke_width=lwd.continuation, lty=lty.continuation, class="legend-no-event", suppress.warnings=suppress.warnings), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="no event/connector", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-no-event", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="no event/connector", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("no event/connector", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); lh <- lh + lnp*dims.chr.legend.title; # new para # Event intervals: if( show.event.intervals ) { if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="black", fill="black", fill_opacity=0.5, class="legend-interval"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="days covered", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-interval", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="days covered", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("days covered", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="black", fill="none", class="legend-interval"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="gap days", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-interval", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="gap days", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("gap days", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); lh <- lh + lnp*dims.chr.legend.title; # new para } # Medication classes: for( i in 1:length(cols) ) { med.class.name <- names(cols)[i]; med.class.name <- ifelse(is.na(med.class.name),"<missing>",med.class.name); if( (is.na(cma$medication.class.colname) || !(cma$medication.class.colname %in% names(cma$data))) && length(cols) == 1 ) { med.class.name.svg <- NA; } else { med.class.name.svg <- .map.category.to.class(med.class.name); } if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="black", fill=cols[i], fill_opacity=0.5, class=paste0("legend-medication-class-rect", if(med.class.name != "<missing>" && !is.na(med.class.name.svg)) paste0("-",med.class.name.svg) ))); } #med.class.name <- names(cols)[i]; med.class.name <- ifelse(is.na(med.class.name),"<missing>",med.class.name); if( print.dose || plot.dose ) { dose.for.cat <- (dose.range$category == med.class.name); if( sum(dose.for.cat,na.rm=TRUE) == 1 ) { med.class.name <- paste0(med.class.name," (",dose.range$min[dose.for.cat]," - ",dose.range$max[dose.for.cat],")"); } } if( do.plot ) { l2 <- c(l2, .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text=med.class.name, col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class=paste0("legend-medication-class-label", if(med.class.name != "<missing>" && !is.na(med.class.name.svg)) paste0("-",med.class.name.svg) ), suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"=med.class.name, "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh-dims.chr.legend/2, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh-dims.chr.legend/2+1*dims.chr.legend, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims(med.class.name, font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } lh <- lh + lnp*dims.chr.legend.title; # new para # Follow-up window: if( highlight.followup.window ) { if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke=followup.window.col, fill="none", stroke_width=2, lty="dashed", class="legend-fuw-rect"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="follow-up wnd.", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-fuw-label", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="follow-up wnd.", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh-dims.chr.legend/2, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh-dims.chr.legend/2+1*dims.chr.legend, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("follow-up wnd", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } # Observation window: if( highlight.observation.window ) { if( !is.null(cma.realOW) ) { # CMA8 also has a "real" OW: if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="none", fill=observation.window.col, fill_opacity=observation.window.opacity, class="legend-ow-rect"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="theor. obs. wnd.", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-ow-label", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="theor. obs. wnd.", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh-dims.chr.legend/2, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh-dims.chr.legend/2+1*dims.chr.legend, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("theor. obs. wnd", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="none", fill=observation.window.col, fill_opacity=observation.window.opacity, class="legend-ow-real"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="real obs. wnd.", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-ow-real", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="real obs. wnd.", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh-dims.chr.legend/2, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh-dims.chr.legend/2+1*dims.chr.legend, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("real obs. wnd.", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } else { if( do.plot ) { l2 <- c(l2, .SVG.rect(x=x.origin + lmx, y=y.origin + lmy+lh-dims.chr.legend/2, width=3*dims.chr.legend, height=1*dims.chr.legend, stroke="none", fill=observation.window.col, fill_opacity=observation.window.opacity, class="legend-ow-rect"), .SVG.text(x=x.origin + lmx + 4*dims.chr.legend, y=y.origin + lmy+lh, text="observation wnd.", col="black", font_size=dims.chr.legend, h.align="left", v.align="center", class="legend-ow-label", suppress.warnings=suppress.warnings)); # Save the info: .last.cma.plot.info$SVG$legend$components <<- rbind(.last.cma.plot.info$SVG$legend$components, data.frame("string"="observation wnd.", "x.start"=x.origin + lmx, "y.start"=y.origin + lmy+lh-dims.chr.legend/2, "x.end"=x.origin + lmx + 3*dims.chr.legend, "y.end"=y.origin + lmy+lh-dims.chr.legend/2+1*dims.chr.legend, "x.string"=lmx + 4*dims.chr.legend, "y.string"=lmy+lh, "font.size"=dims.chr.legend)); } lh <- lh + lnl*dims.chr.legend; lw <- max(lw, .SVG.string.dims("duration", font_size=dims.chr.legend)["width"] + 4*dims.chr.legend); } } # The legend background: lbox <- .SVG.rect(x=x.origin, y=y.origin, width=lw+2*lmx, height=lh+2*lmy, stroke="gray60", stroke_width=2, fill="gray99", fill_opacity=legend.bkg.opacity, class="legend-background"); if( !do.plot ) { # The legend position: if( is.null(x) || length(x) > 1 || is.na(x) || !(x %in% c("left", "center", "right") || is.numeric(x)) ) x <- "right"; if( is.na(x) || x == "right" ) { x <- (dims.plot.x + dims.plot.width - lw - 3*lmx); } else if( x == "center" ) { x <- (dims.plot.x + lmx + (dims.plot.width - lmx - lw)/2); } else if( x == "left" ) { x <- (dims.plot.x + lmx); } else { x <- .scale.x.to.SVG.plot(x); } if( is.null(y) || length(y) > 1 || is.na(y) || !(y %in% c("top", "center", "bottom") || is.numeric(y)) ) y <- "bottom"; if( is.na(y) || y == "bottom" ) { y <- (dims.plot.y + dims.plot.height - lh - 3*lmy); } else if( y == "center" ) { y <- (dims.plot.y + (dims.plot.height - lh - 2*lmy)/2); } else if( y == "top" ) { y <- (dims.plot.y + lmy); } else { y <- .scale.y.to.SVG.plot(y); } } if( do.plot ) { # Close the legend: l2 <- c(l2, '</g>\n'); } # Save the info: .last.cma.plot.info$SVG$legend$box <<- data.frame("x.start"=x, "y.start"=y, "x.end"=x+lw+2*lmx, "y.end"=y+lh+2*lmy); if( do.plot ) { # Insert the legend background where it should be: return (c(l1, lbox, l2)); } else { return (NULL); } } } } # Is the cma a time series or per episodes? is.cma.TS.or.SW <- (inherits(cma, "CMA_per_episode") || inherits(cma, "CMA_sliding_window")); # Does the cma contains estimated CMAs? has.estimated.CMA <- !is.null(getCMA(cma)); # Convert data.table to data.frame (basically, to guard against inconsistencies between data.table and data.frame in how they handle d[,i]): if( inherits(cma$data, "data.table") ) cma$data <- as.data.frame(cma$data); # Check compatibility between subtypes of plots: if( align.all.patients && show.period != "days" ){ show.period <- "days"; if( !suppress.warnings ) .report.ewms("When aligning all patients, cannot show actual dates: showing days instead!\n", "warning", ".plot.CMAs", "AdhereR"); } # # Cache useful column names #### # cma.mg <- !is.null(cma$medication.groups); # are there medication groups? col.patid <- cma$ID.colname; # patient ID if( !cma.mg ) { col.plotid <- col.patid; # when no medication groups, the plotting ID is the same the patient ID } else { col.mg <- cma$medication.groups.colname; col.plotid <- paste0("__",col.patid, ":", col.mg,"__"); # when there are medication groups, the plotting ID is patient ID concatenated with the medication group } cma.data <- cma$data; # the original data # Given a patient ID and medication group name, form the display label: if( cma.mg ) { .mg.label <- function(patients, medication.groups) { paste0(patients," [",ifelse(medication.groups=="__ALL_OTHERS__", medication.groups.allother.label, medication.groups),"]"); } } # # If CMA8, cache the real observation windows if it is to be plotted #### # if( inherits(cma,"CMA8") && !is.null(cma$real.obs.window) && show.real.obs.window.start ) { cma.realOW <- cma$real.obs.window; } else { cma.realOW <- NULL; } # # Medication groups: expand the data and keep only those patient x group that contain events #### # if( cma.mg ) { # Expand the data to contain all the patient x groups: cma$data <- do.call(rbind, lapply(1:ncol(cma$medication.groups$obs), function(i) { if( !is.null(medication.groups.to.plot) && length(medication.groups.to.plot) > 0 && !(colnames(cma$medication.groups$obs)[i] %in% medication.groups.to.plot) ) { # Not all medication groups should be plotted and this is one of them! return (NULL); } tmp <- cma$data[cma$medication.groups$obs[,i],]; if( is.null(tmp) || nrow(tmp) == 0 ) { return (NULL); } else { tmp <- cbind(tmp, colnames(cma$medication.groups$obs)[i]); names(tmp)[ncol(tmp)] <- col.mg; return (tmp); } })); # Keep only those that actually have events and that should be plotted: patmgids <- unique(cma$data[,c(col.patid, col.mg)]); if( is.null(patmgids) || nrow(patmgids) == 0 ) { # Nothing to plot! if( !suppress.warnings ) .report.ewms("No patients to plot!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Add the new column containing the patient ID and the medication group for plotting: cma$data <- cbind(cma$data, .mg.label(cma$data[,col.patid], cma$data[,col.mg])); names(cma$data)[ncol(cma$data)] <- col.plotid; patmgids <- cbind(patmgids, .mg.label(patmgids[,col.patid], patmgids[,col.mg])); names(patmgids)[ncol(patmgids)] <- col.plotid; # The data should be already fine: focus on the CMA estimates: if( !is.null(cma$CMA) ) { if( cma$flatten.medication.groups ) { cma$CMA <- cma$CMA[ vapply(1:nrow(cma$CMA), function(i) any(cma$CMA[i,col.patid] == patmgids[,col.patid] & cma$CMA[i,col.mg] == patmgids[,col.mg]), logical(1)), ]; } else { tmp <- lapply(1:length(cma$CMA), function(i) { tmp <- cma$CMA[[i]]; if( is.null(tmp) ) return (NULL); tmp <- tmp[ tmp[,col.patid] %in% patmgids[patmgids[,col.mg] == names(cma$CMA)[i], col.patid], ]; if( is.null(tmp) || nrow(tmp) == 0 ) return (NULL) else return (tmp); }); names(tmp) <- names(cma$CMA); cma$CMA <- tmp; } } if( !is.null(cma.realOW) ) { if( cma$flatten.medication.groups ) { # Nothing to do, the real OW is already a data.frame! } else { # Flatten the OW: tmp <- do.call(rbind, cma.realOW); if( is.null(tmp) || nrow(tmp) == 0 ) { cma.realOW <- NULL; } else { tmp <- cbind(tmp, unlist(lapply(1:length(cma.realOW), function(i) if(!is.null(cma.realOW[[i]])){rep(names(cma.realOW)[i], nrow(cma.realOW[[i]]))}else{NULL}))); names(tmp)[ncol(tmp)] <- cma$medication.groups.colname; rownames(tmp) <- NULL; cma.realOW <- tmp; } } # Add the new column containing the patient ID and the medication group for plotting: cma.realOW <- cbind(cma.realOW, .mg.label(cma.realOW[,col.patid], cma.realOW[,col.mg])); names(cma.realOW)[ncol(cma.realOW)] <- col.plotid; } } # # Select patients #### # # The patients: patients.to.plot <- patients.to.plot[ !duplicated(patients.to.plot) ]; # remove duplicates keeping the order patids <- unique(as.character(cma$data[,col.patid])); patids <- patids[!is.na(patids)]; if( !is.null(patients.to.plot) ) patids <- intersect(patids, as.character(patients.to.plot)); if( length(patids) == 0 ) { if( !suppress.warnings ) .report.ewms("No patients to plot!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } else if( length(patids) > max.patients.to.plot ) { if( !suppress.warnings ) .report.ewms(paste0("Too many patients to plot (",length(patids), ")! If this is the desired outcome, please change the 'max.patients.to.plot' parameter value (now set at ", max.patients.to.plot,") to at least ',length(patids),'!\n"), "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Select only the patients to display: cma <- subsetCMA(cma, patids); if( cma.mg ) { patmgids <- patmgids[ patmgids[,col.patid] %in% patids, ]; } ## ## Checks and conversions of various column types ## # Patient IDs and medical class better be characters: cma$data[, col.patid] <- as.character(cma$data[, col.patid]); if(!is.na(cma$medication.class.colname) && cma$medication.class.colname %in% names(cma$data)) { cma$data[, cma$medication.class.colname] <- as.character(cma$data[, cma$medication.class.colname]); } # # Cache, consolidate and homogenise the needed info (events, CMAs, FUW an OW) #### # # Cache the CMA estimates (if any): if( !cma.mg ) { # No medication groups: cmas <- getCMA(cma); } else { # There are medication groups: if( cma$flatten.medication.groups ) { cmas <- getCMA(cma); cma.mg.colname <- col.mg; } else { cmas <- getCMA(cma, flatten.medication.groups=TRUE); cma.mg.colname <- names(cmas)[ncol(cmas)]; } # Add the new column containing the patient ID and the medication group for plotting: if( !is.null(cmas) ) { cmas <- cbind(cmas, .mg.label(cmas[,col.patid], cmas[,col.mg])); names(cmas)[ncol(cmas)] <- col.plotid; } } # Keep only those patients with non-missing CMA estimates: if( !is.null(cmas) ) { if( inherits(cmas, "data.table") ) cmas <- as.data.frame(cmas); # same conversion to data.frame as above non_missing_cmas <- cmas[ !is.na(cmas[,"CMA"]), ]; non_missing_cma_patids <- unique(as.character(non_missing_cmas[,col.patid])); if( is.null(non_missing_cma_patids) || length(non_missing_cma_patids) == 0 ) { if( !suppress.warnings ) .report.ewms("No patients with CMA estimates: nothing to plot!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } } # The patients that have no events to plot: patids.no.events.to.plot <- NULL; # Depending on the cma's exact type, the relevant columns might be different or even absent: homogenize them for later use if( inherits(cma, "CMA_per_episode") ) { names(cmas)[2:7] <- c("WND.ID", "start", "gap.days", "duration", "end", "CMA"); # avoid possible conflict with patients being called "ID" # Remove the participants without CMA estimates: patids.no.events.to.plot <- setdiff(unique(cma$data[,col.patid]), unique(cmas[,col.patid])); if( length(patids.no.events.to.plot) > 0 ) { cma$data <- cma$data[ !(cma$data[,col.patid] %in% patids.no.events.to.plot), ]; cma$event.info <- cma$event.info[ !(cma$event.info[,col.patid] %in% patids.no.events.to.plot), ]; #cma$data[ nrow(cma$data) + 1:length(patids.no.events.to.plot), col.patid ] <- patids.no.events.to.plot; # everything ese is NA except for the patient id if( !suppress.warnings ) .report.ewms(paste0("Patient", ifelse(length(patids.no.events.to.plot) > 1, "s ", " "), paste0("'",patids.no.events.to.plot, "'", collapse=", "), ifelse(length(patids.no.events.to.plot) > 1, " have ", " has "), " no events to plot!\n"), "warning", ".plot.CMAs", "AdhereR"); } } else if( inherits(cma, "CMA_sliding_window") ) { cmas <- cbind(cmas[,1:3], "gap.days"=NA, "duration"=cma$sliding.window.duration, cmas[,4:ncol(cmas)]); names(cmas)[2:7] <- c("WND.ID", "start", "gap.days", "duration", "end", "CMA"); # avoid possible conflict with patients being called "ID" # Remove the participants without CMA estimates: patids.no.events.to.plot <- setdiff(unique(cma$data[,col.patid]), unique(cmas[,col.patid])); if( length(patids.no.events.to.plot) > 0 ) { cma$data <- cma$data[ !(cma$data[,col.patid] %in% patids.no.events.to.plot), ]; cma$event.info <- cma$event.info[ !(cma$event.info[,col.patid] %in% patids.no.events.to.plot), ]; #cma$data[ nrow(cma$data) + 1:length(patids.no.events.to.plot), col.patid ] <- patids.no.events.to.plot; # everything ese is NA except for the patient id if( !suppress.warnings ) .report.ewms(paste0("Patient", ifelse(length(patids.no.events.to.plot) > 1, "s ", " "), paste0("'",patids.no.events.to.plot, "'", collapse=", "), ifelse(length(patids.no.events.to.plot) > 1, " have ", " has "), " no events to plot!\n"), "warning", ".plot.CMAs", "AdhereR"); } } else if( inherits(cma, "CMA0") && is.null(cma$event.info) ) { # Try to compute the event.info: if( !cma.mg ) { # No medication groups: event.info <- compute.event.int.gaps(data=cma$data, ID.colname=col.patid, event.date.colname=cma$event.date.colname, event.duration.colname=cma$event.duration.colname, event.daily.dose.colname=cma$event.daily.dose.colname, medication.class.colname=cma$medication.class.colname, event.interval.colname="event.interval", gap.days.colname="gap.days", carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=cma$followup.window.start, followup.window.start.unit=cma$followup.window.start.unit, followup.window.duration=cma$followup.window.duration, followup.window.duration.unit=cma$followup.window.duration.unit, observation.window.start=cma$observation.window.start, observation.window.start.unit=cma$observation.window.start.unit, observation.window.duration=cma$observation.window.duration, observation.window.duration.unit=cma$observation.window.duration.unit, date.format=cma$date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, keep.event.interval.for.all.events=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=FALSE, return.data.table=FALSE); if( !is.null(event.info) ) { # Keep only those events that intersect with the observation window (and keep only the part that is within the intersection): # Compute end prescription date as well: event.info$.DATE.as.Date.end <- .add.time.interval.to.date(event.info$.DATE.as.Date, event.info[,cma$event.duration.colname], "days"); # Remove all treatments that end before FUW starts and those that start after FUW ends: patids.all <- unique(event.info[,col.patid]); event.info <- event.info[ !(event.info$.DATE.as.Date.end < event.info$.FU.START.DATE | event.info$.DATE.as.Date > event.info$.FU.END.DATE), ]; if( is.null(event.info) || nrow(event.info) == 0 ) { if( !suppress.warnings ) .report.ewms("No events in the follow-up window: nothing to plot!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } patids.no.events.to.plot <- setdiff(patids.all, unique(event.info[,col.patid])); # Find all prescriptions that start before the follow-up window and truncate them: s <- (event.info$.DATE.as.Date < event.info$.FU.START.DATE); if( length(s) > 0 ) { event.info$.DATE.as.Date[s] <- event.info$.FU.START.DATE[s]; } # Find all prescriptions that end after the follow-up window and truncate them: s <- (event.info$.DATE.as.Date.end > event.info$.FU.END.DATE); if( length(s) > 0 ) { event.info[s,cma$event.duration.colname] <- .difftime.Dates.as.days(event.info$.FU.END.DATE[s], event.info$.DATE.as.Date[s]); } # Store the event.info data: cma$event.info <- event.info; # For the patients without stuff to plot, replace their events by a fake single event: if( length(patids.no.events.to.plot) > 0 ) { cma$data <- cma$data[ !(cma$data[,col.patid] %in% patids.no.events.to.plot), ]; cma$event.info <- cma$event.info[ !(cma$event.info[,col.patid] %in% patids.no.events.to.plot), ]; #cma$data[ nrow(cma$data) + 1:length(patids.no.events.to.plot), col.patid ] <- patids.no.events.to.plot; # everything ese is NA except for the patient id if( !suppress.warnings ) .report.ewms(paste0("Patient", ifelse(length(patids.no.events.to.plot) > 1, "s ", " "), paste0("'",patids.no.events.to.plot, "'", collapse=", "), ifelse(length(patids.no.events.to.plot) > 1, " have ", " has "), " no events to plot!\n"), "warning", ".plot.CMAs", "AdhereR"); } } else { if( !suppress.warnings ) .report.ewms("Error(s) concerning the follow-up and observation windows!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } } else { # There are medication groups: # Do what the simple CMAs do: compute the event.info! # The workhorse auxiliary function: For a given (subset) of data, compute the event intervals and gaps: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # Call the compute.event.int.gaps() function and use the results: event.info <- compute.event.int.gaps(data=as.data.frame(data), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, return.data.table=TRUE); if( is.null(event.info) ) return (list("CMA"=NA, "event.info"=NULL)); return (list("CMA"=NULL, "event.info"=event.info)); } tmp <- .cma.skeleton(data=cma.data, ret.val=cma, cma.class.name=c("CMA0"), ID.colname=col.patid, event.date.colname=cma$event.date.colname, event.duration.colname=cma$event.duration.colname, event.daily.dose.colname=cma$event.daily.dose.colname, medication.class.colname=cma$medication.class.colname, event.interval.colname="event.interval", gap.days.colname="gap.days", carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=cma$followup.window.start, followup.window.start.unit=cma$followup.window.start.unit, followup.window.duration=cma$followup.window.duration, followup.window.duration.unit=cma$followup.window.duration.unit, observation.window.start=cma$observation.window.start, observation.window.start.unit=cma$observation.window.start.unit, observation.window.duration=cma$observation.window.duration, observation.window.duration.unit=cma$observation.window.duration.unit, date.format=cma$date.format, flatten.medication.groups=cma$flatten.medication.groups, followup.window.start.per.medication.group=cma$followup.window.start.per.medication.group, suppress.warnings=suppress.warnings, suppress.special.argument.checks=TRUE, force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CMA estimates parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, .workhorse.function=.workhorse.function); cma$event.info <- tmp$event.info; } } else { # Remove the participants without CMA estimates: patids.no.events.to.plot <- setdiff(unique(cmas[, col.patid ]), unique(cmas[ !is.na(cmas$CMA), col.patid ])); if( length(patids.no.events.to.plot) > 0 ) { cma$data <- cma$data[ !(cma$data[,col.patid] %in% patids.no.events.to.plot), ]; cma$event.info <- cma$event.info[ !(cma$event.info[,col.patid] %in% patids.no.events.to.plot), ]; #cma$data[ nrow(cma$data) + 1:length(patids.no.events.to.plot), col.patid ] <- patids.no.events.to.plot; # everything else is NA except for the patient id cmas <- cmas[ !(cmas[,col.patid] %in% patids.no.events.to.plot), ] if( !suppress.warnings ) .report.ewms(paste0("Patient", ifelse(length(patids.no.events.to.plot) > 1, "s ", " "), paste0("'",patids.no.events.to.plot, "'", collapse=", "), ifelse(length(patids.no.events.to.plot) > 1, " have ", " has "), " no events to plot!\n"), "warning", ".plot.CMAs", "AdhereR"); } } # Cache the event.info: if( !cma.mg ) { # No medication groups: evinfo <- getEventInfo(cma); } else { # There are medication groups: if( cma$flatten.medication.groups ) { evinfo <- getEventInfo(cma); evinfo.mg.colname <- col.mg; } else { evinfo <- getEventInfo(cma, flatten.medication.groups=TRUE); evinfo.mg.colname <- names(evinfo)[ncol(evinfo)]; } } # Add the follow-up and observation window info as well, to have everything in one place: if( !is.null(cmas) ) { cmas <- cbind(cmas, do.call(rbind, lapply(1:nrow(cmas), function(i) { if( !cma.mg ) { s <- which(evinfo[,col.patid] == cmas[i,col.patid]); } else { s <- which(evinfo[,col.patid] == cmas[i,col.patid] & evinfo[,evinfo.mg.colname] == cmas[i,cma.mg.colname]); } if( length(s) == 0 ) return(data.frame(".FU.START.DATE"=NA, ".FU.END.DATE"=NA, ".OBS.START.DATE"=NA, ".OBS.END.DATE"=NA)); #return (NULL); evinfo[s[1],c(".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE")]; }))); } else { # Create a fake one, containing but the follow-up and observation window info: if( !cma.mg ) { # No medication grops: cmas <- data.frame("..patid.."=unique(cma$data[,col.patid]), "CMA"=NA); names(cmas)[1] <- col.patid; if( !is.null(evinfo) ) { cmas <- merge(cmas, unique(evinfo[,c(col.patid, ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE")]), by=c(col.patid), all.x=TRUE); } else { cmas <- cbind(cmas, ".FU.START.DATE"=NA, ".FU.END.DATE"=NA, ".OBS.START.DATE"=NA, ".OBS.END.DATE"=NA); } } else { # There are medication groups: cmas <- cbind(unique(cma$data[,c(col.patid, col.mg)]), "CMA"=NA); if( !is.null(evinfo) ) { cmas <- merge(cmas, unique(evinfo[,c(col.patid, col.mg, ".FU.START.DATE", ".FU.END.DATE", ".OBS.START.DATE", ".OBS.END.DATE")]), by=c(col.patid, col.mg), all.x=TRUE); } else { cmas <- cbind(cmas, ".FU.START.DATE"=NA, ".FU.END.DATE"=NA, ".OBS.START.DATE"=NA, ".OBS.END.DATE"=NA); } # Add the new column containing the patient ID and the medication group for plotting: cmas <- cbind(cmas, .mg.label(cmas[,col.patid], cmas[,col.mg])); names(cmas)[ncol(cmas)] <- col.plotid; } } # Make sure the dates are cached as `Date` objects: if( !inherits(cma$data[,cma$event.date.colname], "Date") ) { if( is.na(cma$date.format) || is.null(cma$date.format) || length(cma$date.format) != 1 || !is.character(cma$date.format) ) { if( !suppress.warnings ) .report.ewms("The date format must be a single string: cannot continue plotting!\n", "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Convert them to Date: cma$data$.DATE.as.Date <- as.Date(cma$data[,cma$event.date.colname], format=cma$date.format); if( anyNA(cma$data$.DATE.as.Date) ) { if( !suppress.warnings ) .report.ewms(paste0("Not all entries in the event date \"",cma$event.date.colname,"\" column are valid dates or conform to the date format \"",cma$date.format,"\"; first issue occurs on row ",min(which(is.na(cma$data$.DATE.as.Date))),": cannot continue plotting!\n"), "error", ".plot.CMAs", "AdhereR"); plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } } else { # Just make a copy: cma$data$.DATE.as.Date <- cma$data[,cma$event.date.colname]; } # Make sure the patients are ordered by ID, medication group (if the case), and date: if( !is.null(patients.to.plot) && any(patients.to.plot %in% patids) ) { # Respect the order given in patients.to.plot by converting everything to factor with a given levels order: patids.ordered <- factor(patids, levels=patients.to.plot[patients.to.plot %in% patids]); cma$data[,col.patid] <- factor(cma$data[,col.patid], levels=patients.to.plot[patients.to.plot %in% cma$data[,col.patid]]); if( cma.mg ) patmgids[,col.patid] <- factor(patmgids[,col.patid], levels=patients.to.plot[patients.to.plot %in% patmgids[,col.patid]]); cmas[,col.patid] <- factor(cmas[,col.patid], levels=patients.to.plot[patients.to.plot %in% cmas[,col.patid]]); } patids <- patids[ order(patids) ]; if( !cma.mg ) { cma$data <- cma$data[ order(cma$data[,col.patid], cma$data$.DATE.as.Date), ]; } else { cma$data <- cma$data[ order(cma$data[,col.patid], cma$data[,col.mg], cma$data$.DATE.as.Date), ]; patmgids <- patmgids[ order(patmgids[,col.patid], patmgids[,col.mg]), ]; } if( all(c("WND.ID","start") %in% names(cmas)) ) { cmas <- cmas[ order(cmas[,col.patid], cmas$WND.ID, cmas$start), ]; } else { cmas <- cmas[ order(cmas[,col.patid]), ]; } # # Colors for plotting #### # # Grayscale plotting: if( bw.plot ) { if( is.function(col.cats) ) col.cats <- .bw.colors else col.cats <- gray(0.1); followup.window.col <- "black"; observation.window.col <- gray(0.3); CMA.plot.col <- gray(0.8); CMA.plot.border <- gray(0.2); CMA.plot.bkg <- gray(0.5); CMA.plot.text <- CMA.plot.border; col.na <- "lightgray"; col.continuation <- "black"; print.dose.outline.col <- "white"; plot.partial.CMAs.as.stacked.col.bars <- "gray90"; plot.partial.CMAs.as.stacked.col.border <- "gray30"; plot.partial.CMAs.as.stacked.col.text <- "black"; plot.partial.CMAs.as.timeseries.col.dot <- "black"; plot.partial.CMAs.as.timeseries.col.interval <- "gray70"; plot.partial.CMAs.as.timeseries.col.text <- "black"; plot.partial.CMAs.as.overlapping.col.interval <- "gray70"; plot.partial.CMAs.as.overlapping.col.text <- "black"; } # The colors for the categories: if( is.na(cma$medication.class.colname) || !(cma$medication.class.colname %in% names(cma$data)) ) { categories <- unspecified.category.label; } else { categories <- sort(unique(as.character(cma$data[,cma$medication.class.colname])), na.last=FALSE); # all categories making sure NA is first } if( is.na(categories[1]) ) { if( is.function(col.cats) ) cols <- c(col.na, col.cats(length(categories)-1)) else cols <- c(col.na, rep(col.cats,length(categories)-1)); } else { if( is.function(col.cats) ) cols <- col.cats(length(categories)) else cols <- rep(col.cats,length(categories)); } names(cols) <- categories; # .map.category.to.color <- function(category, cols.array=cols) ifelse( is.na(category), cols.array[1], ifelse( category %in% names(cols.array), cols.array[category], "black") ); .map.category.to.color <- function(category, cols.array=cols) { if( is.na(category) ) { return (cols.array[1]); } else { if( category %in% names(cols.array) ) { return (cols.array[category]); } else { return ("black"); } } } if( .do.SVG ) { # Map category names to standardized category ids to be stored as class attributes; this mapping will be exported as a JavaScript dictionary in the HTML container(if any): categories.to.classes <- paste0("med-class-",1:length(categories)); names(categories.to.classes) <- categories; # .map.category.to.class <- function(category, cat2class=categories.to.classes) ifelse( is.na(category), cat2class[1], # ifelse( category %in% names(cat2class), cat2class[category], # cat2class[1]) ); .map.category.to.class <- function(category, cat2class=categories.to.classes) { if( is.na(category) ) { return (cat2class[1]); } else { if( category %in% names(cat2class) ) { return (cat2class[category]); } else { return (cat2class[1]); } } } } # # Doses #### # # Daily dose: if( is.na(cma$event.daily.dose.colname) || !(cma$event.daily.dose.colname %in% names(cma$data)) ) { print.dose <- plot.dose <- FALSE; # can't show daily dose if column is not defined } if( plot.dose || print.dose ) # consistency checks: { if( lwd.event.max.dose < lwd.event ) lwd.event.max.dose <- lwd.event; } if( plot.dose || print.dose ) { if( length(categories) == 1 && categories == unspecified.category.label ) { # Really, no category: dose.range <- data.frame("category"=categories, "min"=min(cma$data[,cma$event.daily.dose.colname], na.rm=TRUE), "max"=max(cma$data[,cma$event.daily.dose.colname], na.rm=TRUE)); } else { # Range per category: tmp <- aggregate(cma$data[,cma$event.daily.dose.colname], by=list("category"=cma$data[,cma$medication.class.colname]), FUN=function(x) range(x,na.rm=TRUE)); dose.range <- data.frame("category"=tmp$category, "min"=tmp$x[,1], "max"=tmp$x[,2]); if( plot.dose.lwd.across.medication.classes ) { dose.range.global <- data.frame("category"="ALL", "min"=min(cma$data[,cma$event.daily.dose.colname], na.rm=TRUE), "max"=max(cma$data[,cma$event.daily.dose.colname], na.rm=TRUE)); } } # Function for the linear interpolation of dose between lwd.min and lwd.max: adjust.dose.lwd <- function(dose, lwd.min=lwd.event, lwd.max=lwd.event.max.dose, dose.min=dose.range$min[1], dose.max=dose.range$max[1]) { delta <- ifelse(dose.max == dose.min, 1.0, (dose.max - dose.min)); # avoid dividing by zero when there's only one dose return (lwd.min + (lwd.max - lwd.min)*(dose - dose.min) / delta); } } # # Episode or sliding window to which an event belongs #### # if( !(inherits(cma, "CMA_per_episode") && "mapping.episodes.to.events" %in% names(cma) && !is.null(cma$mapping.episodes.to.events)) && # for per episodes !(inherits(cma, "CMA_sliding_window") && "mapping.windows.to.events" %in% names(cma) && !is.null(cma$mapping.windows.to.events)) ) # for sliding windows { print.episode.or.sliding.window <- FALSE; # can't show this info } # # Event dates and durations #### # # Find the earliest date: earliest.date <- min(cma$data$.DATE.as.Date, if( "start" %in% names(cmas) ) cmas$start, cmas$.OBS.START.DATE, cmas$.FU.START.DATE, na.rm=TRUE); # If aligning all participants to the same date, simply relocate all dates relative to the earliest date: if( align.all.patients ) { # ASSUMPTIONS: the data is sorted by patient ID and (ascending) by event date for( i in 1:nrow(cma$data) ) { # For each event in the dataset: if( i == 1 || cma$data[i,col.patid] != cma$data[i-1,col.patid] ) { # It's a new patient (or the first one): # We will align to the patient's first event: align.to <- cma$data$.DATE.as.Date[i]; # Adjust the dates in the cmas as well: for( j in which(cmas[,col.patid] == cma$data[i,col.patid]) ) { if( "start" %in% names(cmas) ) cmas$start[j] <- earliest.date + (cmas$start[j] - align.to); if( "end" %in% names(cmas) ) cmas$end[j] <- earliest.date + (cmas$end[j] - align.to); cmas$.FU.START.DATE[j] <- earliest.date + (cmas$.FU.START.DATE[j] - align.to); cmas$.FU.END.DATE[j] <- earliest.date + (cmas$.FU.END.DATE[j] - align.to); cmas$.OBS.START.DATE[j] <- earliest.date + (cmas$.OBS.START.DATE[j] - align.to); cmas$.OBS.END.DATE[j] <- earliest.date + (cmas$.OBS.END.DATE[j] - align.to); } } # Move the event so that it is properly aligned: cma$data$.DATE.as.Date[i] <- (earliest.date + (cma$data$.DATE.as.Date[i] - align.to)); } # The corrected earliest follow-up window date: correct.earliest.followup.window <- as.numeric(min(cma$data$.DATE.as.Date - min(cmas$.FU.START.DATE,na.rm=TRUE),na.rm=TRUE)); } else { # There is no correction to the earliest follow-up window date: correct.earliest.followup.window <- 0; } # Compute the duration if not given: if( is.na(duration) ) { latest.date <- max(cma$data$.DATE.as.Date + cma$data[,cma$event.duration.colname], cmas$.FU.END.DATE, cmas$.OBS.END.DATE, na.rm=TRUE); if( "end" %in% names(cmas) ) latest.date <- max(cmas$end, latest.date, na.rm=TRUE); duration <- as.numeric(latest.date - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0); } endperiod <- duration; # # Reserve plotting space for various components #### # # There may be a difference between patids and plotids, depending on the medication groups being defined or not: if( !cma.mg ) { plotids <- patids; } else { plotids <- unique(patmgids[, col.plotid]); } # Reserve space for the CMA plotting: adh.plot.space <- c(0, ifelse( plot.CMA && has.estimated.CMA, duration*CMA.plot.ratio, 0) ); duration.total <- duration + adh.plot.space[2]; # Make sure there's enough space to actually plot the plot IDs on the y-axis: id.labels <- do.call(rbind,lapply(as.character(plotids), # for each plot ID, compute the string dimensions in inches function(p) { # The participant axis text: pid <- ifelse( print.CMA && !is.cma.TS.or.SW && has.estimated.CMA && length(x <- which(cmas[col.plotid] == p))==1, paste0(p,"\n",sprintf("%.1f%%",cmas[x,"CMA"]*100)), p); data.frame("ID"=p, "string"=pid, "width"=strwidth(pid, units="inches", cex=cex.axis), "height"=strheight(pid, units="inches", cex=cex.axis)); })); y.label <- data.frame("string"=(tmp <- ifelse(is.null(ylab),"", ifelse(length(ylab)==1, ylab, ifelse((print.CMA || plot.CMA) && has.estimated.CMA, ylab["withCMA"], ylab["withoutCMA"])))), # space needed for the label (in inches) "width"=strwidth(tmp, units="inches", cex=cex.lab), "height"=strheight(tmp, units="inches", cex=cex.lab)); left.margin <- (cur.mai <- par("mai"))[2]; # left margin in inches (and cache the current margins too) if( .do.R ) # Rplot: { # Save the graphical params and restore them later: old.par <- par(no.readonly=TRUE); # Rotate the ID labels: new.left.margin <- (y.label$height + (cos(-rotate.text*pi/180) * max(id.labels$width,na.rm=TRUE)) + strwidth("0000", units="inches", cex=cex.axis)); # ask for enough space par(mai=c(cur.mai[1], new.left.margin, cur.mai[3], cur.mai[4])); } ## Vertical space needed by the events #### vert.space.events <- ifelse(plot.events.vertically.displaced, # are the events for the same patient displayed on different rows? nrow(cma$data), # if yes, we need space for all individual events length(unique(cma$data[,col.plotid]))); # otherwise, we only needs space for each patient # Vertical space needed for showing the partial CMAs: vert.space.cmas <- 0; if( is.cma.TS.or.SW ) { # There actually is a partial CMA to be potentially plotted: if( ("timeseries" %in% plot.partial.CMAs.as) && (plot.partial.CMAs.as.timeseries.vspace < 5) ) { if( !suppress.warnings ) .report.ewms(paste0("The minimum vertical space for the timeseries plots (plot.partial.CMAs.as.timeseries.vspace) is 5 lines, but it currently is only ", plot.partial.CMAs.as.timeseries.vspace, ": skipping timeseries plots...\n"), "warning", ".plot.CMAs", "AdhereR"); plot.partial.CMAs.as <- plot.partial.CMAs.as[ plot.partial.CMAs.as != "timeseries" ]; } vert.space.cmas <- vert.space.cmas + ifelse(has.estimated.CMA, (nrow(cmas)+length(plotids)) * as.numeric("stacked" %in% plot.partial.CMAs.as) + 3 * length(plotids) * as.numeric("overlapping" %in% plot.partial.CMAs.as) + plot.partial.CMAs.as.timeseries.vspace * length(plotids) * as.numeric("timeseries" %in% plot.partial.CMAs.as), 0); } # Vertical space needed for the x axis: x.label <- ifelse(is.null(xlab), # x axis label "", ifelse(length(xlab)==1, xlab, xlab[show.period])); date.labels <- NULL; if( period.in.days > 0 ) { xpos <- seq(0, as.numeric(endperiod), by=period.in.days); # where to put lables and guidelines if( show.period=="dates" ) { axis.labels <- as.character(earliest.date + round(xpos, 1), format=cma$date.format); } else { axis.labels <- as.character(round(xpos - ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0), 1)); } date.labels <- data.frame("position"=adh.plot.space[2] + xpos, "string"=axis.labels); } # # SVG definitions and setup #### # if( .do.SVG ) # SVG: { # Compute the needed size: # the idea is to assume 1 standard character (chr) == 16 user units, and 1 month (x axis) == 1 event (y axis) == 1 chr # for the title, axis ticks and labels: 1 title == 1.5 chr, 1 axis tick == 0.75 chr, 1 axis label = 1.0 chr # plus spacing of about 0.5 chr around elements dims.chr.std <- 10; # the "standard" character size (SVG defaults to 16) dims.chr.event <- dims.chr.std / 2; dims.chr.title <- (cex.title * dims.chr.std); dims.chr.axis <- (cex.axis * dims.chr.std); dims.chr.lab <- (cex.lab * dims.chr.std); dims.chr.cma <- (CMA.cex * dims.chr.std); dims.chr.legend <- (legend.cex * dims.chr.std); dims.chr.legend.title <- (legend.cex.title * dims.chr.std); dims.event.x <- dims.chr.std*2; # the horizontal size of an event dims.event.y <- (cex * dims.chr.std); # the vertical size of an event dims.day <- ifelse(duration.total <= 90, 1, ifelse(duration.total <= 365, 7, ifelse(duration.total <= 3*365, 30, ifelse(duration.total <= 10*365, 90, 180)))); # how many days correspond to one horizontal user unit (depends on how many days there are in total) dims.axis.x <- dims.chr.std + dims.chr.lab + (cos(-rotate.text*pi/180) * max(vapply(as.character(date.labels$string), function(s) .SVG.string.dims(s, font_size=dims.chr.axis)["width"], numeric(1)),na.rm=TRUE)); dims.axis.y <- dims.chr.std + dims.chr.lab + (sin(-rotate.text*pi/180) * max(vapply(as.character(id.labels$string), function(s) .SVG.string.dims(s, font_size=dims.chr.axis)["width"], numeric(1)),na.rm=TRUE)); dims.plot.x <- (dims.axis.y + dims.chr.std); dims.plot.y <- (dims.chr.title + dims.chr.std); dims.plot.width <- (dims.event.x * (duration.total + 10)/dims.day); dims.plot.height <- (dims.event.y * (vert.space.events+vert.space.cmas+1)); # For the legend, we force a call to the .legend.SVG() to get the legend needed size: if( !show.legend ) { dims.legend.width <- 0; # no legend to show dims.legend.height <- 0; } else { .last.cma.plot.info <- list(); # create a fake .last.cma.plot.info because .legend.SVG() stores the results in it (it will be re-created later) .legend.SVG(legend.x, legend.y, do.plot=FALSE); # estimate the needed spaces dims.legend.width <- (.last.cma.plot.info$SVG$legend$box$x.end + dims.chr.std); # retrieve the right-most and top-most corner of the legend dims.legend.height <- (.last.cma.plot.info$SVG$legend$box$y.end - .last.cma.plot.info$SVG$legend$box$y.start + dims.chr.std); } # Total size needed: dims.total.width <- (dims.plot.x + max(dims.plot.width, dims.legend.width)); dims.total.height <- (dims.plot.y + max(dims.plot.height, dims.legend.height) + dims.axis.x); # Do we need to adjust for an extra large legend? dims.adjust.for.tall.legend <- max(0, dims.legend.height - dims.plot.height); # Scaling functions for plotting within the SVG: # Cache stuff: dims.event.x.2.dims.day <- (dims.event.x / dims.day); dims.plot.y.dims.plot.height.dims.adjust.for.tall.legend <- (dims.plot.y + dims.plot.height + dims.adjust.for.tall.legend); .scale.width.to.SVG.plot <- function(w) { return (dims.event.x.2.dims.day * w); } .scale.x.to.SVG.plot <- function(x) { return (dims.plot.x + .scale.width.to.SVG.plot(x)); } .scale.height.to.SVG.plot <- function(h) { return (h * dims.event.y); } .scale.y.to.SVG.plot <- function(y) { return (dims.plot.y.dims.plot.height.dims.adjust.for.tall.legend - .scale.height.to.SVG.plot(y)); } # Stroke dash-arrays for line types (lty): svg.stroke.dasharrays <- data.frame("lty"=0:6, "names"=c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash"), "svg"=c(' fill="none" stroke="none" ', ' fill="none" ', ' fill="none" stroke-dasharray="3,3" ', ' fill="none" stroke-dasharray="1,2" ', ' fill="none" stroke-dasharray="1,2,3,2" ', ' fill="none" stroke-dasharray="5,2" ', ' fill="none" stroke-dasharray="2,2,4,2" '), stringsAsFactors=FALSE); # SVG header: svg.str[[length(svg.str)+1]] <- c('<svg ', 'viewBox="0 0 ',dims.total.width,' ',dims.total.height,'" ', ' version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n'); # the plotting surface # Comments, notes and clarifications: svg.str[[length(svg.str)+1]] <- c(.SVG.comment("This is the self-contained SVG plot.", newpara=TRUE), .SVG.comment("NOTE: due to compatibility issues with Internet Explorer, we use explicit closing tags.")); # Reusable bits: dce1 <- .SVG.number(dims.chr.event); dce2 <- .SVG.number(dims.chr.event/2); ndce2 <- .SVG.number(-dims.chr.event/2); dce3 <- .SVG.number(dims.chr.event/3); dce4 <- .SVG.number(dims.chr.event/4); # cache the various relative sizes used to draw the pch symbols svg.str[[length(svg.str)+1]] <- list( # Predefined things to be used in the drawing: '<defs>\n', # The point symbols (pch) used for events etc: # (we use explicit tag closing as otherwise Internet Explorer generates warning HTML1500) # pch 0: '<g id="pch0" fill="none" stroke-width="1"> <rect x="',ndce2,'" y="',ndce2,'" width="',dce1,'" height="',dce1,'"></rect> </g>\n', # pch 1: '<g id="pch1" fill="none" stroke-width="1"> <circle cx="0" cy="0" r="',dce2,'"></circle> </g>\n', # pch 2: '<g id="pch2" fill="none" stroke-width="1"> <polyline points="',ndce2,',',dce2,' 0,',ndce2,' ',dce2,',',dce2,' ',ndce2,',',dce2,'"></polyline> </g>\n', # pch 3: '<g id="pch3" fill="none" stroke-width="1"> <line x1="',ndce2,'" y1="0" x2="',dce2,'" y2="0"></line> <line x1="0" y1="',ndce2,'" x2="0" y2="',dce2,'"></line> </g>\n', # pch 4: '<g id="pch4" fill="none" stroke-width="1"> <line x1="',ndce2,'" y1="',dce2,'" x2="',dce2,'" y2="',ndce2,'"></line> <line x1="',ndce2,'" y1="',ndce2,'" x2="',dce2,'" y2="',dce2,'"></line> </g>\n', # pch 5: '<g id="pch5" fill="none" stroke-width="1"> <polyline points="',ndce2,',0 0,',ndce2,' ',dce2,',0 0,',dce2,' ',ndce2,',0"></polyline> </g>\n', # pch 6: '<g id="pch6" fill="none" stroke-width="1"> <polyline points="',ndce2,',',ndce2,' 0,',dce2,' ',dce2,',',ndce2,' ',ndce2,',',ndce2,'"></polyline> </g>\n', # pch 7: '<g id="pch7" fill="none" stroke-width="1"> <use xlink:href="#pch0"></use> <use xlink:href="#pch4"></use> </g>\n', # pch 8: '<g id="pch8" fill="none" stroke-width="1"> <use xlink:href="#pch3"></use> <use xlink:href="#pch4"></use> </g>\n', # pch 9: '<g id="pch9" fill="none" stroke-width="1"> <use xlink:href="#pch3"></use> <use xlink:href="#pch5"></use> </g>\n', # pch 10: '<g id="pch10" fill="none" stroke-width="1"> <use xlink:href="#pch3"></use> <use xlink:href="#pch1"></use> </g>\n', # pch 11: '<g id="pch11" fill="none" stroke-width="1"> <use xlink:href="#pch2"></use> <use xlink:href="#pch6"></use> </g>\n', # pch 12: '<g id="pch12" fill="none" stroke-width="1"> <use xlink:href="#pch0"></use> <use xlink:href="#pch3"></use> </g>\n', # pch 13: '<g id="pch13" fill="none" stroke-width="1"> <use xlink:href="#pch1"></use> <use xlink:href="#pch4"></use> </g>\n', # pch 14: '<g id="pch14" fill="none" stroke-width="1"> <use xlink:href="#pch0"></use> <use xlink:href="#pch2"></use> </g>\n', # pch 15: '<g id="pch15" stroke-width="1"> <rect x="',ndce2,'" y="',ndce2,'" width="',dce1,'" height="',dce1,'"></rect> </g>\n', # pch 16: '<g id="pch16" stroke-width="1"> <circle cx="0" cy="0" r="',dce3,'"></circle> </g>\n', # pch 17: '<g id="pch17" stroke-width="1"> <polyline points="',ndce2,',',dce2,' 0,',ndce2,' ',dce2,',',dce2,' ',ndce2,',',dce2,'"></polyline> </g>\n', # pch 18: '<g id="pch18" stroke-width="1"> <polyline points="',ndce2,',0 0,',ndce2,' ',dce2,',0 0,',dce2,' ',ndce2,',0"></polyline> </g>\n', # pch 19: '<g id="pch19" stroke-width="1"> <circle cx="0" cy="0" r="',dce2,'"></circle> </g>\n', # pch 20: '<g id="pch20" stroke-width="1"> <circle cx="0" cy="0" r="',dce4,'"></circle> </g>\n', # pch 26 ( < ): '<g id="pch26" fill="none" stroke-width="1"> <polyline points="0,',dce2,' ',ndce2,',0 0,',ndce2,' "></polyline> </g>\n', # pch 27 ( > ): '<g id="pch27" fill="none" stroke-width="1"> <polyline points="0,',dce2,' ',dce2,',0 0,',ndce2,' "></polyline> </g>\n', # pch 28 ( | ): '<g id="pch28" fill="none" stroke-width="1"> <line x1="0" y1="',dce2,'" x2="0" y2="',ndce2,'"></line> </g>\n', '</defs>\n', '\n'); } # # The actual plotting #### # # For speed and clarity, we use an internal version of .last.cma.plot.info, which we save into the external environment on exit... .last.cma.plot.info <- list("baseR"=NULL, "SVG"=NULL); # delete the previous plot info and replace it with empty info... if( .do.R ) # Rplot: { # The plotting area: if(inherits(msg <- try(plot( 0, 1, xlim=c(0-5,duration.total+5), # pad left and right by 5 days to improve plotting xaxs="i", ylim=c(0,vert.space.events+vert.space.cmas+1), yaxs="i", type="n", axes=FALSE, xlab="", ylab="" ), silent=TRUE), "try-error")) { # Some error occurred when creating the plot... if( !suppress.warnings ) .report.ewms(msg, "error", ".plot.CMAs", "AdhereR"); try(par(old.par), silent=TRUE); # restore graphical params #assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } # Make sure we're initially plotting on white: par(bg="white"); # Character width and height in the current plotting system: if( print.dose ) dose.text.height <- strheight("0",cex=cex.dose); if( print.episode.or.sliding.window ) epiwnd.text.height <- strheight("0",cex=cex.dose); char.width <- strwidth("O",cex=cex); char.height <- strheight("O",cex=cex); char.height.CMA <- strheight("0",cex=CMA.cex); # Minimum plot dimensions: if( abs(par("usr")[2] - par("usr")[1]) <= char.width * min.plot.size.in.characters.horiz || abs(par("usr")[4] - par("usr")[3]) <= char.height * min.plot.size.in.characters.vert * (vert.space.events + ifelse(is.cma.TS.or.SW && has.estimated.CMA, nrow(cmas), 0)) ) { if( !suppress.warnings ) .report.ewms(paste0("Plotting area is too small (it must be at least ", min.plot.size.in.characters.horiz, " x ", min.plot.size.in.characters.vert, " characters per patient, but now it is only ", round(abs(par("usr")[2] - par("usr")[1]) / char.width,1), " x ", round(abs(par("usr")[4] - par("usr")[3]) / (char.height * (vert.space.events + ifelse(is.cma.TS.or.SW && has.estimated.CMA, nrow(cmas), 0))),1), ")!\n"), "error", ".plot.CMAs", "AdhereR"); par(old.par); # restore graphical params #assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=generate.R.plot); return (invisible(NULL)); } if( abs(par("usr")[2] - par("usr")[1]) / duration.total < 1.0 && !suppress.warnings ) .report.ewms("The horizontal plotting space might be too small!", "warning", ".plot.CMAs", "AdhereR"); if( abs(par("usr")[4] - par("usr")[3]) / (vert.space.events + ifelse(is.cma.TS.or.SW && has.estimated.CMA, nrow(cmas), 0)) < 1.0 && !suppress.warnings ) .report.ewms("The vertical plotting space might be too small!", "warning", ".plot.CMAs", "AdhereR"); # Save plot info: .last.cma.plot.info$baseR <- list( # Function params: "patients.to.plot"=patients.to.plot, "align.all.patients"=align.all.patients, "align.first.event.at.zero"=align.first.event.at.zero, "show.period"=show.period, "period.in.days"=period.in.days, "show.legend"=show.legend, "legend.x"=legend.x, "legend.y"=legend.y, "legend.bkg.opacity"=legend.bkg.opacity, "legend.cex"=legend.cex, "legend.cex.title"=legend.cex.title, "cex"=cex, "cex.axis"=cex.axis, "cex.lab"=cex.lab, "cex.title"=cex.title, "show.cma"=show.cma, "xlab"=xlab, "ylab"=ylab, "title"=title, "col.cats"=col.cats, "unspecified.category.label"=unspecified.category.label, "medication.groups.to.plot"=medication.groups.to.plot, "lty.event"=lty.event, "lwd.event"=lwd.event, "pch.start.event"=pch.start.event, "pch.end.event"=pch.end.event, "show.event.intervals"=show.event.intervals, "print.dose"=print.dose, "cex.dose"=cex.dose, "print.dose.col"=print.dose.col, "print.dose.centered"=print.dose.centered, "print.episode.or.sliding.window"=print.episode.or.sliding.window, "plot.dose"=plot.dose, "lwd.event.max.dose"=lwd.event.max.dose, "plot.dose.lwd.across.medication.classes"=plot.dose.lwd.across.medication.classes, "col.na"=col.na, "col.continuation"=col.continuation, "lty.continuation"=lty.continuation, "lwd.continuation"=lwd.continuation, "print.CMA"=print.CMA, "CMA.cex"=CMA.cex, "plot.CMA"=plot.CMA, "plot.CMA.as.histogram"=plot.CMA.as.histogram, "plot.partial.CMAs.as"=plot.partial.CMAs.as, "plot.partial.CMAs.as.stacked.col.bars"=plot.partial.CMAs.as.stacked.col.bars, "plot.partial.CMAs.as.stacked.col.border"=plot.partial.CMAs.as.stacked.col.border, "plot.partial.CMAs.as.stacked.col.text"=plot.partial.CMAs.as.stacked.col.text, "plot.partial.CMAs.as.timeseries.vspace"=plot.partial.CMAs.as.timeseries.vspace, "plot.partial.CMAs.as.timeseries.start.from.zero"=plot.partial.CMAs.as.timeseries.start.from.zero, "plot.partial.CMAs.as.timeseries.col.dot"=plot.partial.CMAs.as.timeseries.col.dot, "plot.partial.CMAs.as.timeseries.col.interval"=plot.partial.CMAs.as.timeseries.col.interval, "plot.partial.CMAs.as.timeseries.col.text"=plot.partial.CMAs.as.timeseries.col.text, "plot.partial.CMAs.as.timeseries.interval.type"=plot.partial.CMAs.as.timeseries.interval.type, "plot.partial.CMAs.as.timeseries.lwd.interval"=plot.partial.CMAs.as.timeseries.lwd.interval, "plot.partial.CMAs.as.timeseries.alpha.interval"=plot.partial.CMAs.as.timeseries.alpha.interval, "plot.partial.CMAs.as.timeseries.show.0perc"=plot.partial.CMAs.as.timeseries.show.0perc, "plot.partial.CMAs.as.timeseries.show.100perc"=plot.partial.CMAs.as.timeseries.show.100perc, "plot.partial.CMAs.as.overlapping.alternate"=plot.partial.CMAs.as.overlapping.alternate, "plot.partial.CMAs.as.overlapping.col.interval"=plot.partial.CMAs.as.overlapping.col.interval, "plot.partial.CMAs.as.overlapping.col.text"=plot.partial.CMAs.as.overlapping.col.text, "CMA.plot.ratio"=CMA.plot.ratio, "CMA.plot.col"=CMA.plot.col, "CMA.plot.border"=CMA.plot.border, "CMA.plot.bkg"=CMA.plot.bkg, "CMA.plot.text"=CMA.plot.text, "highlight.followup.window"=highlight.followup.window, "followup.window.col"=followup.window.col, "highlight.observation.window"=highlight.observation.window, "observation.window.col"=observation.window.col, "observation.window.opacity"=observation.window.opacity, "show.real.obs.window.start"=show.real.obs.window.start, "alternating.bands.cols"=alternating.bands.cols, "rotate.text"=rotate.text, "bw.plot"=bw.plot, "min.plot.size.in.characters.horiz"=min.plot.size.in.characters.horiz, "min.plot.size.in.characters.vert"=min.plot.size.in.characters.vert, "export.formats"=export.formats, "export.formats.fileprefix"=export.formats.fileprefix, "export.formats.directory"=export.formats.directory, "generate.R.plot"=generate.R.plot, # Computed things: "old.par"=old.par, "used.par"=par(no.readonly=TRUE), "xlim"=c(0-5,duration.total+5), "ylim"=c(0,vert.space.events+vert.space.cmas+1), "x.min"=0, "x.max"=duration.total, "y.min"=1, "y.max"=vert.space.events+vert.space.cmas, "dose.text.height"=ifelse(print.dose, dose.text.height, NA), "epiwnd.text.height"=ifelse(print.episode.or.sliding.window, epiwnd.text.height, NA), "char.width"=char.width, "char.height"=char.height, "char.height.CMA"=char.height.CMA, "is.cma.TS.or.SW"=is.cma.TS.or.SW, "has.estimated.CMA"=has.estimated.CMA, "cma"=cma, "cmas"=cmas, "categories"=categories, "cols"=cols, ".map.category.to.color"=.map.category.to.color, "earliest.date"=earliest.date, "correct.earliest.followup.window"=correct.earliest.followup.window, "endperiod"=endperiod, "adh.plot.space"=adh.plot.space, "duration.total"=duration.total, "id.labels"=id.labels, "date.labels"=date.labels, "x.label"=x.label, "y.label"=y.label, "vert.space.cmas"=vert.space.cmas ); if(plot.dose || print.dose) { .last.cma.plot.info$baseR$dose.range <- dose.range; if( plot.dose.lwd.across.medication.classes ) .last.cma.plot.info$baseR$dose.range.global <- dose.range.global; .last.cma.plot.info$baseR$adjust.dose.lwd <- adjust.dose.lwd; } } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- list( # Clear the area: .SVG.rect(comment="Clear the whole plotting area", class="plotting-area-background", x=0, y=0, width=dims.total.width, height=dims.total.height, fill="white", stroke="none"), '\n' # one empty line ); # Save plot info: .last.cma.plot.info$SVG <- list( # Function params: "patients.to.plot"=patients.to.plot, "align.all.patients"=align.all.patients, "align.first.event.at.zero"=align.first.event.at.zero, "show.period"=show.period, "period.in.days"=period.in.days, "show.legend"=show.legend, "legend.x"=legend.x, "legend.y"=legend.y, "legend.bkg.opacity"=legend.bkg.opacity, "legend.cex"=legend.cex, "legend.cex.title"=legend.cex.title, "cex"=cex, "cex.axis"=cex.axis, "cex.lab"=cex.lab, "cex.title"=cex.title, "show.cma"=show.cma, "xlab"=xlab, "ylab"=ylab, "title"=title, "col.cats"=col.cats, "unspecified.category.label"=unspecified.category.label, "medication.groups.to.plot"=medication.groups.to.plot, "lty.event"=lty.event, "lwd.event"=lwd.event, "pch.start.event"=pch.start.event, "pch.end.event"=pch.end.event, "show.event.intervals"=show.event.intervals, "print.dose"=print.dose, "cex.dose"=cex.dose, "print.dose.col"=print.dose.col, "print.dose.centered"=print.dose.centered, "print.episode.or.sliding.window"=print.episode.or.sliding.window, "plot.dose"=plot.dose, "lwd.event.max.dose"=lwd.event.max.dose, "plot.dose.lwd.across.medication.classes"=plot.dose.lwd.across.medication.classes, "col.na"=col.na, "col.continuation"=col.continuation, "lty.continuation"=lty.continuation, "lwd.continuation"=lwd.continuation, "print.CMA"=print.CMA, "CMA.cex"=CMA.cex, "plot.CMA"=plot.CMA, "plot.CMA.as.histogram"=plot.CMA.as.histogram, "plot.partial.CMAs.as"=plot.partial.CMAs.as, "plot.partial.CMAs.as.stacked.col.bars"=plot.partial.CMAs.as.stacked.col.bars, "plot.partial.CMAs.as.stacked.col.border"=plot.partial.CMAs.as.stacked.col.border, "plot.partial.CMAs.as.stacked.col.text"=plot.partial.CMAs.as.stacked.col.text, "plot.partial.CMAs.as.timeseries.vspace"=plot.partial.CMAs.as.timeseries.vspace, "plot.partial.CMAs.as.timeseries.start.from.zero"=plot.partial.CMAs.as.timeseries.start.from.zero, "plot.partial.CMAs.as.timeseries.col.dot"=plot.partial.CMAs.as.timeseries.col.dot, "plot.partial.CMAs.as.timeseries.col.interval"=plot.partial.CMAs.as.timeseries.col.interval, "plot.partial.CMAs.as.timeseries.col.text"=plot.partial.CMAs.as.timeseries.col.text, "plot.partial.CMAs.as.timeseries.interval.type"=plot.partial.CMAs.as.timeseries.interval.type, "plot.partial.CMAs.as.timeseries.lwd.interval"=plot.partial.CMAs.as.timeseries.lwd.interval, "plot.partial.CMAs.as.timeseries.alpha.interval"=plot.partial.CMAs.as.timeseries.alpha.interval, "plot.partial.CMAs.as.timeseries.show.0perc"=plot.partial.CMAs.as.timeseries.show.0perc, "plot.partial.CMAs.as.timeseries.show.100perc"=plot.partial.CMAs.as.timeseries.show.100perc, "plot.partial.CMAs.as.overlapping.alternate"=plot.partial.CMAs.as.overlapping.alternate, "plot.partial.CMAs.as.overlapping.col.interval"=plot.partial.CMAs.as.overlapping.col.interval, "plot.partial.CMAs.as.overlapping.col.text"=plot.partial.CMAs.as.overlapping.col.text, "CMA.plot.ratio"=CMA.plot.ratio, "CMA.plot.col"=CMA.plot.col, "CMA.plot.border"=CMA.plot.border, "CMA.plot.bkg"=CMA.plot.bkg, "CMA.plot.text"=CMA.plot.text, "highlight.followup.window"=highlight.followup.window, "followup.window.col"=followup.window.col, "highlight.observation.window"=highlight.observation.window, "observation.window.col"=observation.window.col, "observation.window.opacity"=observation.window.opacity, "show.real.obs.window.start"=show.real.obs.window.start, "alternating.bands.cols"=alternating.bands.cols, "rotate.text"=rotate.text, "bw.plot"=bw.plot, "min.plot.size.in.characters.horiz"=min.plot.size.in.characters.horiz, "min.plot.size.in.characters.vert"=min.plot.size.in.characters.vert, "export.formats"=export.formats, "export.formats.fileprefix"=export.formats.fileprefix, "export.formats.directory"=export.formats.directory, "generate.R.plot"=generate.R.plot, # Computed things: "x"=0, "y"=0, "width"=dims.total.width, "height"=dims.total.height, "x.min"=0, "x.max"=duration.total, "y.min"=1, "y.max"=vert.space.events+vert.space.cmas, "dims.chr.std"=dims.chr.std, "dims.chr.event"=dims.chr.event, "dims.chr.title"=dims.chr.title, "dims.chr.axis"=dims.chr.axis, "dims.chr.lab"=dims.chr.lab, "dims.chr.cma"=dims.chr.cma, "dims.chr.legend"=dims.chr.legend, "dims.chr.legend.title"=dims.chr.legend.title, "dims.event.x"=dims.event.x, "dims.event.y"=dims.event.y, "dims.day"=dims.day, "dims.axis.x"=dims.axis.x, "dims.axis.y"=dims.axis.y, "dims.plot.x"=dims.plot.x, "dims.plot.y"=dims.plot.y, "dims.plot.width"=dims.plot.width, "dims.plot.height"=dims.plot.height, "dims.legend.width"=dims.legend.width, "dims.legend.height"=dims.legend.height, "dims.total.width"=dims.total.width, "dims.total.height"=dims.total.height, ".scale.width.to.SVG.plot"=.scale.width.to.SVG.plot, ".scale.x.to.SVG.plot"=.scale.x.to.SVG.plot, ".scale.height.to.SVG.plot"=.scale.height.to.SVG.plot, ".scale.y.to.SVG.plot"=.scale.y.to.SVG.plot, "svg.stroke.dasharrays"=svg.stroke.dasharrays, "is.cma.TS.or.SW"=is.cma.TS.or.SW, "has.estimated.CMA"=has.estimated.CMA, "cma"=cma, "cmas"=cmas, "categories"=categories, "cols"=cols, ".map.category.to.color"=.map.category.to.color, "categories.to.classes"=categories.to.classes, ".map.category.to.class"=.map.category.to.class, "earliest.date"=earliest.date, "correct.earliest.followup.window"=correct.earliest.followup.window, "endperiod"=endperiod, "adh.plot.space"=adh.plot.space, "duration.total"=duration.total, "id.labels"=id.labels, "date.labels"=date.labels, "x.label"=x.label, "y.label"=y.label, "vert.space.cmas"=vert.space.cmas ); if(plot.dose || print.dose) { .last.cma.plot.info$SVG$dose.range <- dose.range; if( plot.dose.lwd.across.medication.classes ) .last.cma.plot.info$SVG$dose.range.global <- dose.range.global; .last.cma.plot.info$SVG$adjust.dose.lwd <- adjust.dose.lwd; } } # Functions mapping an event given as (days, row) to the plotting coordinates: .map.event.x <- function(x) { return (adh.plot.space[2] + x); } .map.event.date <- function(d, adjust.for.earliest.date=TRUE) { if( adjust.for.earliest.date ) { return (as.numeric(d - earliest.date + adh.plot.space[2] + correct.earliest.followup.window)); } else { return (as.numeric(d + adh.plot.space[2] + correct.earliest.followup.window)); } } .map.event.y <- function(y) { return (y); } # Save plot info: if( .do.R ) { .last.cma.plot.info$baseR$.map.event.x <- .map.event.x; .last.cma.plot.info$baseR$.map.event.date <- .map.event.date; .last.cma.plot.info$baseR$.map.event.y <- .map.event.y; } if( .do.SVG ) { .last.cma.plot.info$SVG$.map.event.x <- .map.event.x; .last.cma.plot.info$SVG$.map.event.date <- .map.event.date; .last.cma.plot.info$SVG$.map.event.y <- .map.event.y; } # Function mapping the CMA values to the appropriate x-coordinates: if( plot.CMA && has.estimated.CMA ) { adh.max <- ifelse(is.cma.TS.or.SW, 1.0, max(c(getCMA(cma)$CMA, 1.0),na.rm=TRUE)); # maximum achieved CMA (used for plotting, forced to 1.0 for PE and SW) .rescale.xcoord.for.CMA.plot <- function(x, pfree=0.20, plot.space=adh.plot.space, max.x=adh.max) { return (plot.space[1] + (x / max.x) * (plot.space[2] * (1-pfree) - plot.space[1])); } # Save plot info: if( .do.R ) { .last.cma.plot.info$baseR$adh.max <- adh.max; .last.cma.plot.info$baseR$.rescale.xcoord.for.CMA.plot <- .rescale.xcoord.for.CMA.plot; } if( .do.SVG ) { .last.cma.plot.info$SVG$adh.max <- adh.max; .last.cma.plot.info$SVG$.rescale.xcoord.for.CMA.plot <- .rescale.xcoord.for.CMA.plot; } } ## ## Plot most of the plot components #### ## if( !do.not.draw.plot ) { # Only if we actually draw the plot... # Initialisations y.cur <- 1; # the current vertical line at which plotting takes place alternating.band.to.draw <- 1; # for this patient, which alternating band to draw? # For each event in cma$data, as well as for each of the partial CMAs (if the case), record important plotting info if( .do.R ) { .last.cma.plot.info$baseR$cma$data <- cbind(.last.cma.plot.info$baseR$cma$data, ".X.OW.START"=NA, ".X.OW.END"=NA, ".Y.OW.START"=NA, ".Y.OW.END"=NA, # observation window extension on the plot ".X.ROW.START"=NA, ".X.ROW.END"=NA, ".Y.ROW.START"=NA, ".Y.ROW.END"=NA, # "real" observation window extension on the plot ".X.FUW.START"=NA, ".X.FUW.END"=NA, ".Y.FUW.START"=NA, ".Y.FUW.END"=NA, # follow-up window extension on the plot ".X.START"=NA, ".X.END"=NA, ".Y.START"=NA, ".Y.END"=NA, # event extension on the plot ".EV.LWD"=NA, # the event's line width ".X.DOSE"=NA, ".Y.DOSE"=NA, ".FONT.SIZE.DOSE"=NA, # dose text position and size ".X.EVC.START"=NA, ".X.EVC.END"=NA, ".Y.EVC.START"=NA, ".Y.EVC.END"=NA, # event covered extension on the plot ".X.EVNC.START"=NA, ".X.EVNC.END"=NA, ".Y.EVNC.START"=NA, ".Y.EVNC.END"=NA, # event not covered extension on the plot ".X.CNT.START"=NA, ".X.CNT.END"=NA, ".Y.CNT.START"=NA, ".Y.CNT.END"=NA, # continuation lines extension on the plot ".X.SCMA.START"=NA, ".X.SCMA.END"=NA, ".Y.SCMA.START"=NA, ".Y.SCMA.END"=NA # summary CMA extension on the plot ); .last.cma.plot.info$baseR$partialCMAs <- NULL; } if( .do.SVG ) { .last.cma.plot.info$SVG$cma$data <- cbind(.last.cma.plot.info$SVG$cma$data, ".X.OW.START"=NA, ".X.OW.END"=NA, ".Y.OW.START"=NA, ".Y.OW.END"=NA, # observation window extension on the plot ".X.ROW.START"=NA, ".X.ROW.END"=NA, ".Y.ROW.START"=NA, ".Y.ROW.END"=NA, # "real" observation window extension on the plot ".X.FUW.START"=NA, ".X.FUW.END"=NA, ".Y.FUW.START"=NA, ".Y.FUW.END"=NA, # follow-up window extension on the plot ".X.START"=NA, ".X.END"=NA, ".Y.START"=NA, ".Y.END"=NA, # event extension on the plot ".EV.LWD"=NA, # the event's line width ".X.DOSE"=NA, ".Y.DOSE"=NA, ".FONT.SIZE.DOSE"=NA, # dose text position and size ".X.EVC.START"=NA, ".X.EVC.END"=NA, ".Y.EVC.START"=NA, ".Y.EVC.END"=NA, # event covered extension on the plot ".X.EVNC.START"=NA, ".X.EVNC.END"=NA, ".Y.EVNC.START"=NA, ".Y.EVNC.END"=NA, # event not covered extension on the plot ".X.CNT.START"=NA, ".X.CNT.END"=NA, ".Y.CNT.START"=NA, ".Y.CNT.END"=NA, # continuation lines extension on the plot ".X.SCMA.START"=NA, ".X.SCMA.END"=NA, ".Y.SCMA.START"=NA, ".Y.SCMA.END"=NA # summary CMA extension on the plot ); .last.cma.plot.info$SVG$partialCMAs <- NULL; } ## For sliding windows and per episode, prepare the inner.event.info (if it exists) for plotting #### # Prepare the plot title: title.inner.event.info <- ""; # empty in most cases # Check the conditions: if( (inherits(cma, "CMA_per_episode") || inherits(cma, "CMA_sliding_window")) && "inner.event.info" %in% names(cma) && !is.null(cma$inner.event.info) && show.event.intervals ) { if( !(show.overlapping.event.intervals %in% c("first", "last", "min gap", "max gap", "average")) ) { if( !suppress.warnings ) .report.ewms(paste0("Unknown 'show.overlapping.event.intervals' value '",show.overlapping.event.intervals,"': assuming 'first'.\n"), "warning", "plot", "AdhereR"); show.overlapping.event.intervals <- "first"; } # Identify the overlapping events (i.e., those events that belong to the patient but fall in different windows/episodes): proc.inner.event.info <- as.data.table(cma$inner.event.info); .combine.overlapping.events <- function(data4event) { if( nrow(data4event) == 0 ) return (NULL); # The non-missing-data rows: s <- which(!is.na(data4event$event.interval) & !is.na(data4event$gap.days)); if( length(s) == 0 ) { r1 <- r2 <- NA_real_; } else { if( show.overlapping.event.intervals == "first" ) { # Use the values of the first window/episode with non-NA: i <- min(s); r1 <- data4event$event.interval[i]; r2 <- data4event$gap.days[i]; } else if( show.overlapping.event.intervals == "last" ) { # Use the values of the last window/episode with non-NA: i <- max(s); r1 <- data4event$event.interval[i]; r2 <- data4event$gap.days[i]; } else if( show.overlapping.event.intervals == "min gap" ) { # Use the minimum gap: i <- s[which.min(data4event$gap.days[s])]; r1 <- data4event$event.interval[i]; r2 <- data4event$gap.days[i]; } else if( show.overlapping.event.intervals == "max gap" ) { # Use the maximum gap: i <- s[which.max(data4event$gap.days[s])]; r1 <- data4event$event.interval[i]; r2 <- data4event$gap.days[i]; } else if( show.overlapping.event.intervals == "average" ) { # Use the average event interval and gap: r1 <- mean(data4event$event.interval[s]); r2 <- mean(data4event$gap.days[s]); } else { # This should now have happened! Assume "first": i <- min(s); r1 <- data4event$event.interval[i]; r2 <- data4event$gap.days[i]; } } # Return the value: #r1s <- r2s <- rep(NA, nrow(data4event)); r1s[s] <- r1; r2s[s] <- r2; # use the new values only for the originally non-NA ones... #return (data.frame(r1s, r2s)); return (data.frame(r1, r2)); } proc.inner.event.info <- proc.inner.event.info[ , .combine.overlapping.events(.SD), by=c(col.patid, cma$event.date.colname, cma$event.daily.dose.colname, cma$medication.class.colname, cma$event.duration.colname)]; colnames(proc.inner.event.info)[(-1:0)+ncol(proc.inner.event.info)] <- c("event.interval", "gap.days"); proc.inner.event.info2 <- cma$data; proc.inner.event.info2$.ORIG.ROW.ORDER <- 1:nrow(proc.inner.event.info2); proc.inner.event.info2 <- merge(proc.inner.event.info2, proc.inner.event.info, all.x=TRUE, all.y=FALSE); proc.inner.event.info2 <- proc.inner.event.info2[ order(proc.inner.event.info2$.ORIG.ROW.ORDER), ]; # Put back the information needed for plotting: cma$inner.event.info <- as.data.frame(proc.inner.event.info2); # Prepare the plot title: title.inner.event.info <- paste0("; overlapping events: ", show.overlapping.event.intervals); } # For each individual event in turn: alternating.band.mg.to.draw <- FALSE; y.old.mg <- y.cur; for( i in 1:nrow(cma$data) ) { # The current plot ID: cur_plot_id <- cma$data[i,col.plotid]; # For a new patient, draw the alternating bands, show the CMA and print the y-axis label: if( i == 1 || (cur_plot_id != cma$data[i-1,col.plotid]) ) { # Save the current vertical position (for drawing the FUW and OW windows): y.old <- y.cur; # Select the events and partial CMAs belonging to this patient: s.events <- which(cma$data[,col.plotid] == cur_plot_id); s.cmas <- which(cmas[,col.plotid] == cur_plot_id); # Vertical space needed by this patient for the events and overall: vspace.needed.events <- ifelse(plot.events.vertically.displaced, length(s.events), 1); vspace.needed.partial.cmas <- ifelse(has.estimated.CMA, (length(s.cmas)+1) * as.numeric("stacked" %in% plot.partial.CMAs.as) + 3 * as.numeric("overlapping" %in% plot.partial.CMAs.as) + plot.partial.CMAs.as.timeseries.vspace * as.numeric("timeseries" %in% plot.partial.CMAs.as), 0); vspace.needed.total <- vspace.needed.events + vspace.needed.partial.cmas; # Reset the clipping region to the whole plotting area... if( .do.R ) # Rplot: { clip(.last.cma.plot.info$baseR$xlim[1], .last.cma.plot.info$baseR$xlim[2], .last.cma.plot.info$baseR$ylim[1], .last.cma.plot.info$baseR$ylim[2]); } ## ## The alternating bands #### ## # Draw the alternating bands if( !is.null(alternating.bands.cols) && !(length(alternating.bands.cols) == 1 && is.na(alternating.bands.cols)) ) { if( .do.R ) # Rplot: { rect( 0.0 - 1.0, y.cur - 0.5, duration.total + 1.0, y.cur + vspace.needed.total - 0.5, col=alternating.bands.cols[alternating.band.to.draw], border=NA ); } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.rect(x=.scale.x.to.SVG.plot(0), y=.scale.y.to.SVG.plot(y.cur - 0.5 + vspace.needed.total), width=dims.plot.width, height=.scale.height.to.SVG.plot(vspace.needed.total), fill=alternating.bands.cols[alternating.band.to.draw], class=paste0("alternating-bands-",alternating.band.to.draw), comment="The alternating band"); } alternating.band.to.draw <- if(alternating.band.to.draw >= length(alternating.bands.cols)) 1 else (alternating.band.to.draw + 1); # move to the next band } } ## ## Medication groups within patients #### ## # Draw the separators over the alternating bands but bellow all other graphical elements: if( cma.mg && medication.groups.separator.show && (i == 1 || (i > 1 && cma$data[i,col.patid] != cma$data[i-1,col.patid]) || i == nrow(cma$data)) ) { # The y coordinates: y.mg.start <- ifelse(i == nrow(cma$data), y.cur + vspace.needed.partial.cmas + 0.5, y.cur - 0.5); y.mg.end <- (y.old.mg - 0.5); if( .do.R ) # Rplot: { # The separating line: segments(par("usr")[1], y.mg.start, par("usr")[2], y.mg.start, col=medication.groups.separator.color, lty=medication.groups.separator.lty, lwd=medication.groups.separator.lwd); if( i > 1 && alternating.band.mg.to.draw ) { rect( par("usr")[1], y.mg.start, 0.0, y.mg.end, col=medication.groups.separator.color, border=NA ); rect( duration.total + 1.0, y.mg.start, par("usr")[2], y.mg.end, col=medication.groups.separator.color, border=NA ); } } if( .do.SVG ) # SVG: { # Draw: svg.str[[length(svg.str)+1]] <- # The separating line: .SVG.lines(x=c(dims.plot.x, dims.plot.x+dims.plot.width), y=rep(.scale.y.to.SVG.plot(y.mg.start),2), connected=FALSE, stroke=medication.groups.separator.color, lty=medication.groups.separator.lty, stroke_width=medication.groups.separator.lwd, class="medication-groups-separator-hline", comment="Medication groups separator: horizontal line", suppress.warnings=suppress.warnings); if( i > 1 && alternating.band.mg.to.draw ) { svg.str[[length(svg.str)+1]] <- # The left and right lines: .SVG.lines(x=c(dims.plot.x, dims.plot.x), y=c(.scale.y.to.SVG.plot(y.mg.start), .scale.y.to.SVG.plot(y.mg.end)), connected=FALSE, stroke=medication.groups.separator.color, lty=medication.groups.separator.lty, stroke_width=medication.groups.separator.lwd, class="medication-groups-separator-vline", comment="Medication groups separator: vertical lines", suppress.warnings=suppress.warnings); svg.str[[length(svg.str)+1]] <- .SVG.lines(x=c(dims.plot.x, dims.plot.x)+dims.plot.width, y=c(.scale.y.to.SVG.plot(y.mg.start), .scale.y.to.SVG.plot(y.mg.end)), connected=FALSE, stroke=medication.groups.separator.color, lty=medication.groups.separator.lty, stroke_width=medication.groups.separator.lwd, class="medication-groups-separator-vline", comment="Medication groups separator: vertical lines", suppress.warnings=suppress.warnings); } } alternating.band.mg.to.draw <- !alternating.band.mg.to.draw; y.old.mg <- y.cur; } # Continue doing things for a new patient... if( i == 1 || (cur_plot_id != cma$data[i-1,col.plotid]) ) { ## ## FUW and OW #### ## # The follow-up and observation windows (these are drawn only after all the other stuff for this patient has been drawn): if( highlight.followup.window ) { if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".X.FUW.START"] <- (adh.plot.space[2] + as.numeric(cmas$.FU.START.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.FUW.START"] <- (y.cur - 0.5); .last.cma.plot.info$baseR$cma$data[s.events,".X.FUW.END"] <- (adh.plot.space[2] + as.numeric(cmas$.FU.END.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.FUW.END"] <- (y.cur + vspace.needed.events - 0.5); # Draw: rect(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.FUW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.FUW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.FUW.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.FUW.END"], col=NA, border=followup.window.col, lty="dashed", lwd=2); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".X.FUW.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(cmas$.FU.START.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.FUW.START"] <- .scale.y.to.SVG.plot(y.cur + vspace.needed.events - 0.5); .last.cma.plot.info$SVG$cma$data[s.events,".X.FUW.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(cmas$.FU.END.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.FUW.END"] <- .scale.y.to.SVG.plot(y.cur + 0.5); # Draw: svg.str[[length(svg.str)+1]] <- # FUW: .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[s.events[1],".X.FUW.START"], y=.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.FUW.START"], width=.scale.width.to.SVG.plot(as.numeric(cmas$.FU.END.DATE[s.cmas[1]] - cmas$.FU.START.DATE[s.cmas[1]])), height=.scale.height.to.SVG.plot(vspace.needed.events), stroke=followup.window.col, stroke_width=2, lty="dashed", fill="white", fill_opacity=0.0, # fully transparent but tooltips also work class="fuw", comment="The Follow-Up Window (FUW)", tooltip="Follow-Up Window (FUW)"); } } if( highlight.observation.window ) { # The "given" OW: if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".X.OW.START"] <- (adh.plot.space[2] + as.numeric(cmas$.OBS.START.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.OW.START"] <- (y.cur - 0.5); .last.cma.plot.info$baseR$cma$data[s.events,".X.OW.END"] <- (adh.plot.space[2] + as.numeric(cmas$.OBS.END.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.OW.END"] <- (y.cur + vspace.needed.events - 0.5); # Draw: rect(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.OW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.OW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.OW.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.OW.END"], col=adjustcolor(observation.window.col,alpha.f=observation.window.opacity), border=NA); #, density=observation.window.density, angle=observation.window.angle); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".X.OW.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(cmas$.OBS.START.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.OW.START"] <- .scale.y.to.SVG.plot(y.cur + vspace.needed.events - 0.5); .last.cma.plot.info$SVG$cma$data[s.events,".X.OW.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(cmas$.OBS.END.DATE[s.cmas[1]] - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.OW.END"] <- .scale.y.to.SVG.plot(y.cur + 0.5); # Draw: svg.str[[length(svg.str)+1]] <- # OW: .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[s.events[1],".X.OW.START"], y=.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.OW.START"], width=.scale.width.to.SVG.plot(as.numeric(cmas$.OBS.END.DATE[s.cmas[1]] - cmas$.OBS.START.DATE[s.cmas[1]])), height=.scale.height.to.SVG.plot(vspace.needed.events), stroke="none", fill=observation.window.col, fill_opacity=observation.window.opacity, class="ow", comment="The Observation Window (OW)", tooltip="Observation Window (OW)"); } if( !is.null(cma.realOW) ) { # For CMA8, the OW might have been changed, so we also have a "real" OW: s.realOW <- which(cma.realOW[,col.plotid] == cur_plot_id); # Find the beginning of the "real" OW: if( length(s.realOW) == 1) { if( !is.null(cma.realOW$window.start) && !is.na(cma.realOW$window.start[s.realOW]) ) { real.obs.window.start <- cma.realOW$window.start[s.realOW]; } else { real.obs.window.start <- evinfo$.OBS.START.DATE[s.events[1]]; } if( !is.null(cma.realOW$window.end) && !is.na(cma.realOW$window.end[s.realOW]) ) { real.obs.window.end <- cma.realOW$window.end[s.realOW]; } else { real.obs.window.end <- evinfo$.OBS.END.DATE[s.events[1]]; } # Draw the "real" OW: if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".X.ROW.START"] <- (adh.plot.space[2] + as.numeric(real.obs.window.start - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.ROW.START"] <- (y.cur - 0.5); .last.cma.plot.info$baseR$cma$data[s.events,".X.ROW.END"] <- (adh.plot.space[2] + as.numeric(real.obs.window.end - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.ROW.END"] <- (y.cur + vspace.needed.events - 0.5); # Draw: rect(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.ROW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.ROW.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.ROW.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.ROW.END"], col=adjustcolor(observation.window.col,alpha.f=observation.window.opacity), border=NA); #, density=real.obs.window.density, angle=real.obs.window.angle); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".X.ROW.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(real.obs.window.start - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.ROW.START"] <- .scale.y.to.SVG.plot(y.cur + vspace.needed.events - 0.5); .last.cma.plot.info$SVG$cma$data[s.events,".X.ROW.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + as.numeric(real.obs.window.start - earliest.date) + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.ROW.END"] <- .scale.y.to.SVG.plot(y.cur + 0.5); # Draw: svg.str[[length(svg.str)+1]] <- # "real" OW: .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[s.events[1],".X.ROW.START"], y=.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.ROW.START"], width=.scale.width.to.SVG.plot(as.numeric(real.obs.window.end - real.obs.window.start)), height=.scale.height.to.SVG.plot(vspace.needed.events), stroke="none", fill=observation.window.col, fill_opacity=observation.window.opacity, class="ow-real", comment="The 'real' Observation Window", tooltip="'Real' Observation Window"); } } } } ## ## The y-axis labels #### ## # The y-axis label: pid <- cur_plot_id; y.mean <- y.cur + vspace.needed.total/2 - ifelse(plot.events.vertically.displaced, 0.0, 0.5); # vertical position of the label (centered on patient) if( .do.R ) # Rplot: { text(par("usr")[1], y.mean, pid, cex=cex.axis, srt=-rotate.text, pos=2, xpd=TRUE); # Save the info: .last.cma.plot.info$baseR$y.labels <- rbind(.last.cma.plot.info$baseR$y.labels, data.frame("string"=pid, "x"=par("usr")[1], "y"=y.mean, "cex"=cex.axis)); } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.text(x=(dims.plot.x - dims.chr.axis), y=.scale.y.to.SVG.plot(y.cur + vspace.needed.total/2), text=pid, font_size=dims.chr.axis, h.align="right", v.align="center", rotate=-(90+rotate.text), class="axis-labels-y", comment="The y-axis labels", suppress.warnings=suppress.warnings); # Save the info: .last.cma.plot.info$SVG$y.labels <- rbind(.last.cma.plot.info$SVG$y.labels, data.frame("string"=pid, "x"=(dims.plot.x - dims.chr.axis), "y"=.scale.y.to.SVG.plot(y.cur + vspace.needed.total/2), "font.size"=dims.chr.axis)); } ## ## The summary CMA plots #### ## # The patient's CMA plot: if( plot.CMA && has.estimated.CMA && adh.plot.space[2] > 0 ) { if( is.cma.TS.or.SW ) { # For per episode and sliding windows we show the distribution of the "partial" CMAs: if( .do.R ) # Rplot: { # The CMA plot background: # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".X.SCMA.START"] <- .rescale.xcoord.for.CMA.plot(0.0); .last.cma.plot.info$baseR$cma$data[s.events,".Y.SCMA.START"] <- (y.mean - 2); .last.cma.plot.info$baseR$cma$data[s.events,".X.SCMA.END"] <- .rescale.xcoord.for.CMA.plot(1.0); .last.cma.plot.info$baseR$cma$data[s.events,".Y.SCMA.END"] <- (y.mean + 2); # Draw: segments(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.START"], lty="solid", col=CMA.plot.col); segments(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.END"], lty="solid", col=CMA.plot.col); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".X.SCMA.START"] <- .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.SCMA.START"] <- .scale.y.to.SVG.plot(y.mean - 2); .last.cma.plot.info$SVG$cma$data[s.events,".X.SCMA.END"] <- .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.SCMA.END"] <- .scale.y.to.SVG.plot(y.mean + 2); # Draw: svg.str[[length(svg.str)+1]] <- # The CMA plot background: .SVG.lines(x=c(.last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.END"], .last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.END"]), y=c(.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.START"], .last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.START"], .last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.END"], .last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.END"]), connected=FALSE, stroke=CMA.plot.col, stroke_width=1, class="cma-drawing-area-background", comment="The CMA plot background", suppress.warnings=suppress.warnings); } # The non-missing CMA values: adh <- na.omit(cmas[s.cmas,"CMA"]); # Scale the CMA (itself or density) in such a way that if within 0..1 stays within 0..1 but scales if it goes outside this interval to accommodate it if( plot.CMA.as.histogram ) { # Plot CMA as histogram (or nothing, if too little data): if( length(adh) > 0 ) svg.str <- .plot.summary.CMA.as.histogram(adh, svg.str); } else { if( length(adh) > 2 ) { # Plot CMA as density plot: adh.density <- density(adh); ss <- (adh.density$x >= min(adh,na.rm=TRUE) & adh.density$x <= max(adh,na.rm=TRUE)); if( sum(ss) == 0 ) { # Probably constant numbers? Plot the individual lines: svg.str <- .plot.summary.CMA.as.lines(adh, svg.str); } else { # Plot as density: svg.str <- .plot.summary.CMA.as.density(adh.density$x[ss], adh.density$y[ss], svg.str); } } else { if( length(adh) == 0 ) { # No points at all: nothing to plot! } else { # Plot the individual lines: svg.str <- .plot.summary.CMA.as.lines(adh, svg.str); } } } } else if( inherits(cma, "CMA1") ) { # For CMA1+ we show the actual point estimate: # The adherence estimate: adh <- cmas[s.cmas,"CMA"]; if( !is.na(adh) ) { # The vertical position where it will be drawn and its vertical extent: if( plot.events.vertically.displaced ) { # Events are vertically displaced: adh.y <- mean(s.events); adh.h <- ifelse(length(s.events) < 2, 0.5, ifelse(length(s.events) == 2, 0.75, 1.0)); } else { # Events are all on a single line: adh.y <- y.cur; adh.h <- 0.25; } if( .do.R ) # Rplot: { # Draw the background rectangle: # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".X.SCMA.START"] <- .rescale.xcoord.for.CMA.plot(0.0); .last.cma.plot.info$baseR$cma$data[s.events,".Y.SCMA.START"] <- (adh.y - adh.h); .last.cma.plot.info$baseR$cma$data[s.events,".X.SCMA.END"] <- .rescale.xcoord.for.CMA.plot(max(1.0,adh.max)); .last.cma.plot.info$baseR$cma$data[s.events,".Y.SCMA.END"] <- (adh.y + adh.h); # Draw: rect(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.START"], .rescale.xcoord.for.CMA.plot(min(adh,adh.max)), .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.END"], col=CMA.plot.col, border=NA); rect(.last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.START"], .last.cma.plot.info$baseR$cma$data[s.events[1],".X.SCMA.END"], .last.cma.plot.info$baseR$cma$data[s.events[1],".Y.SCMA.END"], col=NA, border=CMA.plot.border); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".X.SCMA.START"] <- .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)); .last.cma.plot.info$SVG$cma$data[s.events,".Y.SCMA.START"] <- .scale.y.to.SVG.plot(adh.y + adh.h); .last.cma.plot.info$SVG$cma$data[s.events,".X.SCMA.END"] <- .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(max(1.0,adh.max))); .last.cma.plot.info$SVG$cma$data[s.events,".Y.SCMA.END"] <- .scale.y.to.SVG.plot(adh.y - adh.h); # Draw: svg.str[[length(svg.str)+1]] <- # Draw the CMA estimate background rectangle: .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.START"], y=.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.START"], width=.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(min(adh,adh.max)) - .rescale.xcoord.for.CMA.plot(0.0)), height=.scale.height.to.SVG.plot(2*adh.h), stroke="none", fill=CMA.plot.col, class="cma-estimate-bkg", comment="The CMA estimate backgound"); svg.str[[length(svg.str)+1]] <- .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[s.events[1],".X.SCMA.START"], y=.last.cma.plot.info$SVG$cma$data[s.events[1],".Y.SCMA.START"], width=.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(max(1.0,adh.max)) - .rescale.xcoord.for.CMA.plot(0.0)), height=.scale.height.to.SVG.plot(2*adh.h), stroke=CMA.plot.border, stroke_width=1, fill="none", class="cma-estimate-bkg"); } cma.string <- sprintf("%.1f%%",adh*100); available.x.space <- abs(.rescale.xcoord.for.CMA.plot(max(1.0,adh.max)) - .rescale.xcoord.for.CMA.plot(0.0)); if( .do.R ) # Rplot: { if( strwidth(cma.string, cex=CMA.cex) <= available.x.space ) { # horizontal writing of the CMA: text(x=(.rescale.xcoord.for.CMA.plot(0.0) + .rescale.xcoord.for.CMA.plot(max(1.0,adh.max)))/2, y=adh.y, labels=cma.string, col=CMA.plot.text, cex=CMA.cex); } else if( strheight(cma.string, cex=CMA.cex) <= available.x.space ) { # vertical writing of the CMA: text(x=(.rescale.xcoord.for.CMA.plot(0.0) + .rescale.xcoord.for.CMA.plot(max(1.0,adh.max)))/2, y=adh.y, labels=cma.string, col=CMA.plot.text, cex=CMA.cex, srt=90); } else if( force.draw.text ) { # force horizontal writing of the CMA: text(x=(.rescale.xcoord.for.CMA.plot(0.0) + .rescale.xcoord.for.CMA.plot(max(1.0,adh.max)))/2, y=adh.y, labels=cma.string, col=CMA.plot.text, cex=CMA.cex); } # otherwise, there's no space for showing the CMA here } if( .do.SVG ) # SVG: { if( available.x.space * dims.event.x >= dims.chr.cma ) { svg.str[[length(svg.str)+1]] <- # Write the CMA estimate (always vertically): .SVG.text(x=.scale.x.to.SVG.plot((.rescale.xcoord.for.CMA.plot(0.0) + .rescale.xcoord.for.CMA.plot(max(1.0,adh.max)))/2), y=.scale.y.to.SVG.plot(adh.y), text=cma.string, col=CMA.plot.text, font_size=dims.chr.cma, h.align="center", v.align="center", rotate=-90, class="cma-estimate-text", comment="The CMA estimate (as text)", suppress.warnings=suppress.warnings); } } } } } # Set the clipping region to make sure no events "overflows" in other bits of the plot... if( .do.R ) # Rplot: { clip(.last.cma.plot.info$baseR$adh.plot.space[2]-1, .last.cma.plot.info$baseR$xlim[2], .last.cma.plot.info$baseR$ylim[1], .last.cma.plot.info$baseR$ylim[2]); } } ## ## The event #### ## # Get the event start and end dates: start <- as.numeric(cma$data$.DATE.as.Date[i] - earliest.date + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); end <- start + cma$data[i,cma$event.duration.colname]; # Map medication classes to colors: if( is.na(cma$medication.class.colname) || !(cma$medication.class.colname %in% names(cma$data)) ) { col <- .map.category.to.color(unspecified.category.label); if( .do.SVG ){ med.class.svg <- NA; med.class.svg.name <- unspecified.category.label; } } else { col <- .map.category.to.color(cma$data[i,cma$medication.class.colname]); if( .do.SVG ) med.class.svg <- .map.category.to.class(med.class.svg.name <- cma$data[i,cma$medication.class.colname]); } if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[i,".X.START"] <- (adh.plot.space[2] + start); .last.cma.plot.info$baseR$cma$data[i,".Y.START"] <- (y.cur); .last.cma.plot.info$baseR$cma$data[i,".X.END"] <- (adh.plot.space[2] + end); .last.cma.plot.info$baseR$cma$data[i,".Y.END"] <- (y.cur); # Plot the beginning and end of the event: points(.last.cma.plot.info$baseR$cma$data[i,".X.START"], .last.cma.plot.info$baseR$cma$data[i,".Y.START"], pch=pch.start.event, col=col, cex=cex); points(.last.cma.plot.info$baseR$cma$data[i,".X.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.END"], pch=pch.end.event, col=col, cex=cex); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[i,".X.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + start); .last.cma.plot.info$SVG$cma$data[i,".Y.START"] <- .scale.y.to.SVG.plot(y.cur); .last.cma.plot.info$SVG$cma$data[i,".X.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + end); .last.cma.plot.info$SVG$cma$data[i,".Y.END"] <- .scale.y.to.SVG.plot(y.cur); # Draw: # svg.str[[length(svg.str)+1]] <- c( # # The beginning of the event: # .SVG.points(x=.last.cma.plot.info$SVG$cma$data[i,".X.START"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.START"], # pch=pch.start.event, col=col, cex=cex, # class=paste0("event-start",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), # tooltip=med.class.svg.name, suppress.warnings=suppress.warnings), # # The end of the event: # .SVG.points(x=.last.cma.plot.info$SVG$cma$data[i,".X.END"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.END"], # pch=pch.end.event, col=col, cex=cex, # class=paste0("event-end",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), # tooltip=med.class.svg.name, suppress.warnings=suppress.warnings) # ); svg.str[[length(svg.str)+1]] <- # The beginning of the event: .SVG.points(x=.last.cma.plot.info$SVG$cma$data[i,".X.START"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.START"], pch=pch.start.event, col=col, cex=cex, class=paste0("event-start",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name, suppress.warnings=suppress.warnings); svg.str[[length(svg.str)+1]] <- # The end of the event: .SVG.points(x=.last.cma.plot.info$SVG$cma$data[i,".X.END"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.END"], pch=pch.end.event, col=col, cex=cex, class=paste0("event-end",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name, suppress.warnings=suppress.warnings); } # Show event intervals as rectangles? # Cache the event info for plotting the events: if( inherits(cma, "CMA0") ) { # For simple CMAs, use the "standard" event info data: plot_evinfo <- evinfo; } else if( inherits(cma, "CMA_per_episode") || inherits(cma, "CMA_sliding_window") ) { # Complex CMAs are a bit more complicated: if the have the "inner" event info, use it (if the user wants to plot the information within): if( "inner.event.info" %in% names(cma) && show.event.intervals ) { plot_evinfo <- cma$inner.event.info; } else { plot_evinfo <- NULL; } } if( show.event.intervals && !is.null(plot_evinfo) && !is.na(plot_evinfo$event.interval[i]) ) { # The end of the prescription: end.pi <- start + plot_evinfo$event.interval[i] - plot_evinfo$gap.days[i]; if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[i,".X.EVC.START"] <- (adh.plot.space[2] + start); .last.cma.plot.info$baseR$cma$data[i,".Y.EVC.START"] <- (y.cur - char.height/2); .last.cma.plot.info$baseR$cma$data[i,".X.EVC.END"] <- (adh.plot.space[2] + end.pi); .last.cma.plot.info$baseR$cma$data[i,".Y.EVC.END"] <- (y.cur + char.height/2); # Draw: rect(.last.cma.plot.info$baseR$cma$data[i,".X.EVC.START"], .last.cma.plot.info$baseR$cma$data[i,".Y.EVC.START"], .last.cma.plot.info$baseR$cma$data[i,".X.EVC.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.EVC.END"], col=adjustcolor(col,alpha.f=0.2), border=col); if( plot_evinfo$gap.days[i] > 0 ) { # Save the info: .last.cma.plot.info$baseR$cma$data[i,".X.EVNC.START"] <- (adh.plot.space[2] + end.pi); .last.cma.plot.info$baseR$cma$data[i,".Y.EVNC.START"] <- (y.cur - char.height/2); .last.cma.plot.info$baseR$cma$data[i,".X.EVNC.END"] <- (adh.plot.space[2] + end.pi + plot_evinfo$gap.days[i]); .last.cma.plot.info$baseR$cma$data[i,".Y.EVNC.END"] <- (y.cur + char.height/2); # Draw: rect(.last.cma.plot.info$baseR$cma$data[i,".X.EVNC.START"], .last.cma.plot.info$baseR$cma$data[i,".Y.EVNC.START"], .last.cma.plot.info$baseR$cma$data[i,".X.EVNC.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.EVNC.END"], #density=25, col=adjustcolor(col,alpha.f=0.5), col=NA, border=col); } } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[i,".X.EVC.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + start); .last.cma.plot.info$SVG$cma$data[i,".Y.EVC.START"] <- .scale.y.to.SVG.plot(y.cur) - dims.event.y/2; .last.cma.plot.info$SVG$cma$data[i,".X.EVC.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + end.pi); .last.cma.plot.info$SVG$cma$data[i,".Y.EVC.END"] <- .last.cma.plot.info$SVG$cma$data[i,".Y.EVC.START"] + dims.event.y; # Draw: svg.str[[length(svg.str)+1]] <- .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[i,".X.EVC.START"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.EVC.START"], xend=.last.cma.plot.info$SVG$cma$data[i,".X.EVC.END"], height=dims.event.y, stroke=col, fill=col, fill_opacity=0.2, class=paste0("event-interval-covered",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name); if( plot_evinfo$gap.days[i] > 0 ) { # Save the info: .last.cma.plot.info$SVG$cma$data[i,".X.EVNC.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + end.pi); .last.cma.plot.info$SVG$cma$data[i,".Y.EVNC.START"] <- .scale.y.to.SVG.plot(y.cur) - dims.event.y/2; .last.cma.plot.info$SVG$cma$data[i,".X.EVNC.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + end.pi + plot_evinfo$gap.days[i]); .last.cma.plot.info$SVG$cma$data[i,".Y.EVNC.END"] <- .last.cma.plot.info$SVG$cma$data[i,".Y.EVNC.START"] + dims.event.y; # Draw: svg.str[[length(svg.str)+1]] <- .SVG.rect(x=.last.cma.plot.info$SVG$cma$data[i,".X.EVNC.START"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.EVNC.START"], xend=.last.cma.plot.info$SVG$cma$data[i,".X.EVNC.END"], height=dims.event.y, stroke=col, fill="none", class=paste0("event-interval-not-covered",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name); } } } # Do we show dose? seg.x1 <- adh.plot.space[2] + start; seg.x2 <- adh.plot.space[2] + end; seg.lwd <- NA; if( plot.dose ) { # Show dose using event line width: if( nrow(dose.range) == 1 ) { # Just one dose: seg.lwd <- adjust.dose.lwd(cma$data[i,cma$event.daily.dose.colname]) } else { # There is a range of doses: if( plot.dose.lwd.across.medication.classes ) { # Line width across all medication classes: seg.lwd <- adjust.dose.lwd(cma$data[i,cma$event.daily.dose.colname], dose.min=dose.range.global$min, dose.max=dose.range.global$max); } else { # Line width per medication class: dose.for.cat <- (dose.range$category == cma$data[i,cma$medication.class.colname]); if( sum(dose.for.cat,na.rm=TRUE) == 1 ) { # Found the corresponding medication class: seg.lwd <- adjust.dose.lwd(cma$data[i,cma$event.daily.dose.colname], dose.min=dose.range$min[dose.for.cat], dose.max=dose.range$max[dose.for.cat]); } else { # Use a fixed width: seg.lwd <- lwd.event; } } } } else { # Use a fixed line width: seg.lwd <- lwd.event; } if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[s.events,".EV.LWD"] <- seg.lwd; # Draw: segments( seg.x1, y.cur, seg.x2, y.cur, col=col, lty=lty.event, lwd=seg.lwd); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[s.events,".EV.LWD"] <- seg.lwd; # Draw: svg.str[[length(svg.str)+1]] <- # The beginning of the event: .SVG.lines(x=c(.scale.x.to.SVG.plot(seg.x1), .scale.x.to.SVG.plot(seg.x2)), y=rep(.scale.y.to.SVG.plot(y.cur),2), connected=FALSE, stroke=col, stroke_width=seg.lwd, class=paste0("event-segment",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name, suppress.warnings=suppress.warnings); } # Prepare the text to print (dose, episode/window...): text.to.print <- ""; if( print.dose || print.episode.or.sliding.window ) { # The position of the text on the plot: if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[i,".X.DOSE"] <- (adh.plot.space[2] + (start + end)/2); .last.cma.plot.info$baseR$cma$data[i,".Y.DOSE"] <- (y.cur - ifelse(print.dose.centered, 0, dose.text.height*2/3)); # print it on or below the dose segment? .last.cma.plot.info$baseR$cma$data[i,".FONT.SIZE.DOSE"] <- cex.dose; } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[i,".X.DOSE"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + (start + end)/2); .last.cma.plot.info$SVG$cma$data[i,".Y.DOSE"] <- .scale.y.to.SVG.plot(y.cur - ifelse(print.dose.centered, 0, 3/4)); .last.cma.plot.info$SVG$cma$data[i,".FONT.SIZE.DOSE"] <- (dims.chr.std * cex.dose); } } if( print.dose ) { text.to.print <- paste0(text.to.print, cma$data[i,cma$event.daily.dose.colname]); # the dose } if( print.episode.or.sliding.window ) { # Show the corresponding episode or sliding window (if any) as actual numbers on the plot: if( inherits(cma, "CMA_per_episode") ) { s.epiwnd <- which(cma$mapping.episodes.to.events$event.index.in.data == i); if( length(s.epiwnd) > 0 ) { if( text.to.print != "" ) text.to.print <- paste0(text.to.print," "); text.to.print <- paste0(text.to.print, "[", paste0(sort(cma$mapping.episodes.to.events$episode.ID[s.epiwnd]), collapse=","), "]"); } } if( inherits(cma, "CMA_sliding_window") ) { s.epiwnd <- which(cma$mapping.windows.to.events$event.index.in.data == i); if( length(s.epiwnd) > 0 ) { if( text.to.print != "" ) text.to.print <- paste0(text.to.print," "); text.to.print <- paste0(text.to.print, "[", paste0(sort(cma$mapping.windows.to.events$window.ID[s.epiwnd]), collapse=","), "]"); } } } if( text.to.print != "" ) { # Do the actual printing: if( .do.R ) # Rplot: { # Draw: text(.last.cma.plot.info$baseR$cma$data[i,".X.DOSE"], .last.cma.plot.info$baseR$cma$data[i,".Y.DOSE"], text.to.print, cex=cex.dose, col=ifelse(is.na(print.dose.col),col,print.dose.col), font=2); } if( .do.SVG ) # SVG: { # Draw: svg.str[[length(svg.str)+1]] <- # The dose text: .SVG.text(x=.last.cma.plot.info$SVG$cma$data[i,".X.DOSE"], y=.last.cma.plot.info$SVG$cma$data[i,".Y.DOSE"], text=text.to.print, font_size=.last.cma.plot.info$SVG$cma$data[i,".FONT.SIZE.DOSE"], h.align="center", v.align="center", col=if(is.na(print.dose.col)) col else print.dose.col, other_params=if(!is.na(print.dose.outline.col)) paste0(' stroke="',.SVG.color(print.dose.outline.col,return_string=TRUE),'" stroke-width="0.5"'), class=paste0("event-dose-text",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg.name, suppress.warnings=suppress.warnings); } } # Advance to the next vertical line: if( plot.events.vertically.displaced ) { y.cur <- y.cur + 1; } # Continuation between successive events: if( i < nrow(cma$data) && (cur_plot_id == cma$data[i+1,col.plotid]) ) { # We're still plotting the same patient: show the continuation line: start.next <- as.numeric(cma$data$.DATE.as.Date[i+1] - earliest.date + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); # How many lines to jump? cont.v.jump <- ifelse(plot.events.vertically.displaced, 1, 0); if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$cma$data[i,".X.CNT.START"] <- (adh.plot.space[2] + end); .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.START"] <- (y.cur - cont.v.jump); .last.cma.plot.info$baseR$cma$data[i,".X.CNT.END"] <- (adh.plot.space[2] + start.next); .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.END"] <- (y.cur); # Draw: segments( .last.cma.plot.info$baseR$cma$data[i,".X.CNT.START"], .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.START"], .last.cma.plot.info$baseR$cma$data[i,".X.CNT.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.START"], col=col.continuation, lty=lty.continuation, lwd=lwd.continuation); segments( .last.cma.plot.info$baseR$cma$data[i,".X.CNT.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.START"], .last.cma.plot.info$baseR$cma$data[i,".X.CNT.END"], .last.cma.plot.info$baseR$cma$data[i,".Y.CNT.END"], col=col.continuation, lty=lty.continuation, lwd=lwd.continuation); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$cma$data[i,".X.CNT.START"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + end); .last.cma.plot.info$SVG$cma$data[i,".Y.CNT.START"] <- .scale.y.to.SVG.plot(y.cur - cont.v.jump); .last.cma.plot.info$SVG$cma$data[i,".X.CNT.END"] <- .scale.x.to.SVG.plot(adh.plot.space[2] + start.next); .last.cma.plot.info$SVG$cma$data[i,".Y.CNT.END"] <- .scale.y.to.SVG.plot(y.cur); # Draw: svg.str[[length(svg.str)+1]] <- # The continuation line: .SVG.lines(x=c(.last.cma.plot.info$SVG$cma$data[i,".X.CNT.START"], rep(.last.cma.plot.info$SVG$cma$data[i,".X.CNT.END"],3)), y=c(rep(.last.cma.plot.info$SVG$cma$data[i,".Y.CNT.START"],3), .last.cma.plot.info$SVG$cma$data[i,".Y.CNT.END"]), connected=TRUE, stroke=col.continuation, stroke_width=lwd.continuation, lty=lty.continuation, class=paste0("continuation-line",if(!is.na(med.class.svg)) paste0("-",med.class.svg)), tooltip=med.class.svg, suppress.warnings=suppress.warnings); } } else { # The patient is changing or is the last one: # Advance to next line of need be: if( !plot.events.vertically.displaced ) { y.cur <- y.cur + 1; } ## ## Partial CMAs #### ## # Draw its sub-periods (if so requested, meaningful and possible): if( is.cma.TS.or.SW && has.estimated.CMA ) { if( length(s.cmas) > 0 ) #&& !all(is.na(cmas$CMA[s.cmas])) ) # also show the partial (empty) frame even when all are NA { # We do have non-missing partial CMAs to plot: # Compute the start, end, location and string to display for these partial estimates: ppts <- data.frame("start"=as.numeric(cmas$start[s.cmas] - earliest.date), "end" =as.numeric(cmas$end[s.cmas] - earliest.date), "x" =NA, "y" =cmas$CMA[s.cmas], "text" =paste0(ifelse(!is.na(cmas$CMA[s.cmas]), sprintf("%.0f%%", 100*cmas$CMA[s.cmas]), "?"), if(print.episode.or.sliding.window){paste0(" [",cmas$WND.ID[s.cmas],"]")}else{""}) ); ppts$x <- (ppts$start + ppts$end)/2; # Cache stuff: corrected.x <- (adh.plot.space[2] + ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0)); corrected.x.start <- (corrected.x+ppts$start); corrected.x.end <- (corrected.x+ppts$end); x.start.min <- min(ppts$start,na.rm=TRUE); x.end.max <- max(ppts$end, na.rm=TRUE); corrected.x.text <- (corrected.x + ppts$x); if(all(is.na(ppts$y))) # guard against warnings when talking the min and max of only NAs { min.y <- NA; max.y <- NA; } else { min.y <- min(ppts$y,na.rm=TRUE); max.y <- max(ppts$y,na.rm=TRUE); } # Plotting type: if( "stacked" %in% plot.partial.CMAs.as ) { # Show subperiods as stacked: ys <- (y.cur + 1:nrow(ppts) - 1); # cache this h <- (ppts$end - ppts$start) * pmax(pmin(ppts$y, 1.0), 0.0); # cache the actual CMA estimates scaled for plotting if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, "type"="stacked", "x.region.start"=min(corrected.x.start, na.rm=TRUE), "y.region.start"=min(ys, na.rm=TRUE), "x.region.end"=max(corrected.x.end, na.rm=TRUE), "y.region.end"=max(ys, na.rm=TRUE)+1, "x.partial.start"=corrected.x.start, "y.partial.start"=ys + 0.10, "x.partial.end"=corrected.x.end, "y.partial.end"=ys + 0.90)); # The intervals as empty rectangles: rect(corrected.x.start, ys + 0.10, corrected.x.end, ys + 0.90, border=gray(0.7), col="white"); # The CMAs as filled rectangles of length proportional to the CMA: rect(corrected.x.start, ys + 0.10, corrected.x.start + h, ys + 0.90, border=plot.partial.CMAs.as.stacked.col.border, col=plot.partial.CMAs.as.stacked.col.bars); if( force.draw.text || print.CMA && char.height.CMA <= 0.80 ) { text(corrected.x.text, ys + 0.5, ppts$text, cex=CMA.cex, col=plot.partial.CMAs.as.stacked.col.text); } } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="stacked", "x.region.start"=.scale.x.to.SVG.plot(min(corrected.x.start, na.rm=TRUE)), "y.region.start"=.scale.y.to.SVG.plot(max(ys, na.rm=TRUE)+1), "x.region.end"=.scale.x.to.SVG.plot(max(corrected.x.end, na.rm=TRUE)), "y.region.end"=.scale.y.to.SVG.plot(min(ys, na.rm=TRUE)), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start), "y.partial.start"=.scale.y.to.SVG.plot(ys + 0.90), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end), "y.partial.end"=.scale.y.to.SVG.plot(ys + 0.10))); svg.str[[length(svg.str)+1]] <- .SVG.comment("Partial CMAs as stacked bars:", newpara=TRUE); for( j in 1:nrow(ppts) ) { svg.str[[length(svg.str)+1]] <- list( # The background rect: .SVG.rect(x=.scale.x.to.SVG.plot(corrected.x.start[j]), y=.scale.y.to.SVG.plot(ys[j] + 0.90), xend=.scale.x.to.SVG.plot(corrected.x.end[j]), yend=.scale.y.to.SVG.plot(ys[j] + 0.10), stroke="gray70", fill="white", class="partial_cma_stacked_rect_bkg"), # The CMA estimate rect: .SVG.rect(x=.scale.x.to.SVG.plot(corrected.x.start[j]), y=.scale.y.to.SVG.plot(ys[j] + 0.90), xend=.scale.x.to.SVG.plot(corrected.x.start[j] + h[j]), yend=.scale.y.to.SVG.plot(ys[j] + 0.10), stroke=plot.partial.CMAs.as.stacked.col.border, fill=plot.partial.CMAs.as.stacked.col.bars, class="partial_cma_stacked_rect_estimate"), # The numeric estimate: if( force.draw.text || print.CMA && dims.chr.cma <= dims.chr.event ) { .SVG.text(.scale.x.to.SVG.plot(corrected.x.text[j]), y=.scale.y.to.SVG.plot(ys[j] + 0.50), text=ppts$text[j], font_size=dims.chr.cma, col=plot.partial.CMAs.as.stacked.col.text, h.align="center", v.align="center", class="partial_cma_stacked_text_estimate", suppress.warnings=suppress.warnings) } ); } } # Advance to next patient: y.cur <- (y.cur + nrow(ppts) + 1); } if( "overlapping" %in% plot.partial.CMAs.as ) { # Show subperiods as overlapping segments: if( is.na(range.y <- (max.y - min.y)) || range.y <= 0 ) range.y <- 1; # avoid division by 0 if there's only one value or if there's none ppts$y.norm <- (ppts$y - min.y)/range.y; if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.comment("Partial CMAs as overlapping segments:", newpara=TRUE); } if( !is.na(plot.partial.CMAs.as.overlapping.col.interval) ) { if( plot.partial.CMAs.as.overlapping.alternate ) { v <- rep(c(0,1), nrow(ppts))[1:nrow(ppts)]; # alternate between low (0) and high (1) -- not the best way but works fine } else { v <- rep(0,nrow(ppts)); # all segments are drawn low (0) } y.norm.v <- (ppts$y.norm * -(v*2-1)); # -(v*2-1) maps 0 to 1 and 1 to -1 if( .do.R ) # Rplot: { # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, "type"="overlapping", "x.region.start"=min(corrected.x.start, na.rm=TRUE), "y.region.start"=min(y.cur + 0.5 + v, na.rm=TRUE), "x.region.end"=max(corrected.x.end, na.rm=TRUE), "y.region.end"=max(y.cur + 0.5 + v + ifelse(!is.na(y.norm.v),y.norm.v,0), na.rm=TRUE), "x.partial.start"=corrected.x.start, "y.partial.start"=y.cur + 0.5 + v, "x.partial.end"=corrected.x.end, "y.partial.end"=y.cur + 0.5 + v + ifelse(!is.na(y.norm.v),y.norm.v,0))); segments(corrected.x.start, y.cur + 0.5 + v, corrected.x.end, y.cur + 0.5 + v, col=plot.partial.CMAs.as.overlapping.col.interval); segments(corrected.x.start, y.cur + 0.5 + v, corrected.x.start, y.cur + 0.5 + v + y.norm.v, col=plot.partial.CMAs.as.overlapping.col.interval); segments(corrected.x.end, y.cur + 0.5 + v, corrected.x.end, y.cur + 0.5 + v + y.norm.v, col=plot.partial.CMAs.as.overlapping.col.interval); } if( .do.SVG ) # SVG: { # Save the info: .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="stacked", "x.region.start"=.scale.x.to.SVG.plot(min(corrected.x.start, na.rm=TRUE)), "y.region.start"=.scale.y.to.SVG.plot(max(y.cur + 0.5 + v + ifelse(!is.na(y.norm.v),y.norm.v,0), na.rm=TRUE)), "x.region.end"=.scale.x.to.SVG.plot(max(corrected.x.end, na.rm=TRUE)), "y.region.end"=.scale.y.to.SVG.plot(min(y.cur + 0.5 + v, na.rm=TRUE)), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start), "y.partial.start"=.scale.y.to.SVG.plot(y.cur + 0.5 + v + ifelse(!is.na(y.norm.v),y.norm.v,0)), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end), "y.partial.end"=.scale.y.to.SVG.plot(y.cur + 0.5 + v))); for( j in 1:nrow(ppts) ) { svg.str[[length(svg.str)+1]] <- # The connected segments one by one: .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x.start[j], corrected.x.end[j])), y=.scale.y.to.SVG.plot(c(y.cur + 0.5 + v[j], y.cur + 0.5 + v[j])), connected=FALSE, stroke=plot.partial.CMAs.as.overlapping.col.interval, class="partial_cma_overlapping_segments", suppress.warnings=suppress.warnings); if(!is.na(y.norm.v[j])) svg.str[[length(svg.str)+1]] <- .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x.start[j], corrected.x.start[j], corrected.x.end[j], corrected.x.end[j])), y=.scale.y.to.SVG.plot(c(y.cur + 0.5 + v[j], y.cur + 0.5 + v[j] + y.norm.v[j], y.cur + 0.5 + v[j], y.cur + 0.5 + v[j] + y.norm.v[j])), connected=FALSE, stroke=plot.partial.CMAs.as.overlapping.col.interval, class="partial_cma_overlapping_segments", suppress.warnings=suppress.warnings); } } } if( .do.R ) # Rplot: { if( print.CMA && (force.draw.text || char.height.CMA <= 0.80) && !is.na(plot.partial.CMAs.as.overlapping.col.text) ) { text(corrected.x.text, y.cur + 1.0, ppts$text, cex=CMA.cex, col=plot.partial.CMAs.as.overlapping.col.text); } } if( .do.SVG ) # SVG: { if( print.CMA && (force.draw.text || dims.chr.cma <= dims.chr.event) && !is.na(plot.partial.CMAs.as.overlapping.col.text) ) { svg.str[[length(svg.str)+1]] <- # The text estimates: .SVG.text(x=.scale.x.to.SVG.plot(corrected.x.text), y=.scale.y.to.SVG.plot(rep(y.cur + 1.0,length(corrected.x.text))), text=ppts$text, col=plot.partial.CMAs.as.overlapping.col.text, font_size=dims.chr.cma, h.align="center", v.align="center", class="partial_cma_overlapping_text", suppress.warnings=suppress.warnings); } } # Advance to next patient: y.cur <- y.cur+3; } if( "timeseries" %in% plot.partial.CMAs.as ) { # Show subperiods as a time series if( plot.partial.CMAs.as.timeseries.start.from.zero ) min.y <- min(min.y,0,na.rm=TRUE); if( is.na(range.y <- (max.y - min.y)) || range.y <= 0 ) range.y <- 1; # avoid division by 0 if there's only one value or if there's none ppts$y.norm <- (y.cur + 1 + (plot.partial.CMAs.as.timeseries.vspace - 3) * (ppts$y - min.y)/range.y); if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- .SVG.comment("Partial CMAs as time series:", newpara=TRUE); } # The axes: if(all(is.na(ppts$y.norm))) # guard against warnings when talking the min and max of only NAs { min.y.norm <- NA; max.y.norm <- NA; } else { min.y.norm <- min(ppts$y.norm,na.rm=TRUE); max.y.norm <- max(ppts$y.norm,na.rm=TRUE); } if( .do.R ) # Rplot: { segments(corrected.x + x.start.min, y.cur + 0.5, corrected.x + x.end.max, y.cur + 0.5, lty="solid", col="black"); # horizontal axis segments(corrected.x + x.start.min, y.cur + 0.5, corrected.x + x.start.min, y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, lty="solid", col="black"); # vertical axis segments(corrected.x + x.start.min, min.y.norm, corrected.x + x.end.max, min.y.norm, lty="dashed", col="black"); # the minimum value segments(corrected.x + x.start.min, max.y.norm, corrected.x + x.end.max, max.y.norm, lty="dashed", col="black"); # the minimum value } if( .do.SVG ) # SVG { svg.str[[length(svg.str)+1]] <- # The axes: .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x + x.start.min, corrected.x + x.end.max, corrected.x + x.start.min, corrected.x + x.start.min, corrected.x + x.start.min, corrected.x + x.end.max, corrected.x + x.start.min, corrected.x + x.end.max)), y=.scale.y.to.SVG.plot(c(y.cur + 0.5, y.cur + 0.5, y.cur + 0.5, y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, min.y.norm, min.y.norm, max.y.norm, max.y.norm)), connected=FALSE, stroke="black", lty=c("solid", "solid", "dashed", "dashed"), class="partial_cma_timeseries_axes", suppress.warnings=suppress.warnings); } # 0% if( plot.partial.CMAs.as.timeseries.show.0perc && (y.for.0perc <- (y.cur + 1 + (plot.partial.CMAs.as.timeseries.vspace-3) * (0 - min.y)/range.y)) >= y.cur + 0.5 ) { if( .do.R ) # Rplot: { segments(corrected.x + x.start.min, y.for.0perc, corrected.x + x.end.max, y.for.0perc, lty="dotted", col="red"); # 0% } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- # 0% line .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x + x.start.min, corrected.x + x.end.max)), y=.scale.y.to.SVG.plot(c(y.for.0perc, y.for.0perc)), connected=FALSE, stroke="red", lty="dotted", class="partial_cma_timeseries_0perc-line", suppress.warnings=suppress.warnings); } } # 100% if( plot.partial.CMAs.as.timeseries.show.100perc && (y.for.100perc <- (y.cur + 1 + (plot.partial.CMAs.as.timeseries.vspace-3) * (1.0 - min.y)/range.y)) <= y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0 ) { if( .do.R ) # Rplot: { segments(corrected.x + x.start.min, y.for.100perc, corrected.x + x.end.max, y.for.100perc, lty="dotted", col="red"); # 100% } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- # 100% line .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x + x.start.min, corrected.x + x.end.max)), y=.scale.y.to.SVG.plot(c(y.for.100perc, y.for.100perc)), connected=FALSE, stroke="red", lty="dotted", class="partial_cma_timeseries_100perc-line", suppress.warnings=suppress.warnings); } } # Numeric values: if( .do.R ) # Rplot: { if( print.CMA && (force.draw.text || char.height.CMA <= 0.80) ) { if( !is.na(min.y.norm) && !is.na(max.y.norm) ) { if(min.y.norm < max.y.norm) text(corrected.x + x.start.min, min.y.norm, sprintf("%.1f%%",100*min.y), pos=2, cex=CMA.cex, col="black"); # avoid collisions text(corrected.x + x.start.min, max.y.norm, sprintf("%.1f%%",100*max.y), pos=2, cex=CMA.cex, col="black"); } if( plot.partial.CMAs.as.timeseries.show.0perc && y.for.0perc >= y.cur + 0.5 ) { text(corrected.x + x.start.min, y.for.0perc, "0%", pos=2, cex=CMA.cex, col="red"); } if( plot.partial.CMAs.as.timeseries.show.100perc && y.for.100perc <= y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0 ) { text(corrected.x + x.start.min, y.for.100perc, "100%", pos=2, cex=CMA.cex, col="red"); } } } if( .do.SVG ) # SVG: { if( print.CMA && (force.draw.text || dims.chr.cma <= dims.chr.event) ) { svg.str[[length(svg.str)+1]] <- # Text .SVG.text(x=.scale.x.to.SVG.plot(c(corrected.x + x.start.min, corrected.x + x.start.min)), y=.scale.y.to.SVG.plot(c(min.y.norm, max.y.norm)), text=c( sprintf("%.1f%%",100*min.y), sprintf("%.1f%%",100*max.y)), col="black", font_size=dims.chr.cma, h.align="right", v.align="center", rotate=rotate.text, class="partial_cma_timeseries_axis_text", suppress.warnings=suppress.warnings); if( plot.partial.CMAs.as.timeseries.show.0perc && y.for.0perc >= y.cur + 0.5 ) { svg.str[[length(svg.str)+1]] <- .SVG.text(x=.scale.x.to.SVG.plot(corrected.x + x.start.min), y=.scale.y.to.SVG.plot(y.for.0perc), text="0%", col="red", font_size=dims.chr.cma, h.align="right", v.align="center", rotate=rotate.text, class="partial_cma_timeseries_axis_text", suppress.warnings=suppress.warnings); } if( plot.partial.CMAs.as.timeseries.show.100perc && y.for.100perc <= y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0 ) { svg.str[[length(svg.str)+1]] <- .SVG.text(x=.scale.x.to.SVG.plot(corrected.x + x.start.min), y=.scale.y.to.SVG.plot(y.for.100perc), text="100%", col="red", font_size=dims.chr.cma, h.align="right", v.align="center", rotate=rotate.text, class="partial_cma_timeseries_axis_text", suppress.warnings=suppress.warnings); } } } # The intervals: if(all(is.na(ppts$y.norm))) ppts_y.norm_notna <- 1 else ppts_y.norm_notna <- !is.na(ppts$y.norm); # cache the non-NA ppts$y.norm and avoid crashing if all are NAs if( !is.na(plot.partial.CMAs.as.timeseries.col.interval) ) { if( plot.partial.CMAs.as.timeseries.interval.type == "none" ) { # Nothing to plot, but save the actual points: if( .do.R ) { .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, type="timeseries", "x.region.start"=corrected.x + x.start.min, "y.region.start"=y.cur + 0.5, "x.region.end"=corrected.x + x.end.max, "y.region.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, "x.partial.start"=corrected.x.text[ppts_y.norm_notna], "y.partial.start"=ppts$y.norm[ppts_y.norm_notna], "x.partial.end"=corrected.x.text[ppts_y.norm_notna], "y.partial.end"=ppts$y.norm[ppts_y.norm_notna])); } if( .do.SVG ) { .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, type="timeseries", "x.region.start"=.scale.x.to.SVG.plot(corrected.x + x.start.min), "y.region.start"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), "x.region.end"=.scale.x.to.SVG.plot(corrected.x + x.end.max), "y.region.start"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.text[ppts_y.norm_notna]), "y.partial.start"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna]), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.text[ppts_y.norm_notna]), "y.partial.end"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna]))); } } else if( plot.partial.CMAs.as.timeseries.interval.type %in% c("segments", "arrows", "lines") ) { if( .do.R ) # Rplot: { # The lines: segments(corrected.x.start, ppts$y.norm, corrected.x.end, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); if( plot.partial.CMAs.as.timeseries.interval.type == "segments" ) { # The segment endings: segments(corrected.x.start, ppts$y.norm - 0.2, corrected.x.start, ppts$y.norm + 0.2, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); segments(corrected.x.end, ppts$y.norm - 0.2, corrected.x.end, ppts$y.norm + 0.2, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, type="timeseries", "x.region.start"=corrected.x + x.start.min, "y.region.start"=y.cur + 0.5, "x.region.end"=corrected.x + x.end.max, "y.region.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, "x.partial.start"=corrected.x.start[ppts_y.norm_notna], "y.partial.start"=ppts$y.norm[ppts_y.norm_notna] - 0.2, "x.partial.end"=corrected.x.end[ppts_y.norm_notna], "y.partial.end"=ppts$y.norm[ppts_y.norm_notna] + 0.2)); } else if( plot.partial.CMAs.as.timeseries.interval.type == "arrows" ) { # The arrow endings: segments(corrected.x.start + char.width/2, ppts$y.norm - char.height/2, corrected.x.start, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); segments(corrected.x.start + char.width/2, ppts$y.norm + char.height/2, corrected.x.start, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); segments(corrected.x.end - char.width/2, ppts$y.norm - char.height/2, corrected.x.end, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); segments(corrected.x.end - char.width/2, ppts$y.norm + char.height/2, corrected.x.end, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.interval, lwd=plot.partial.CMAs.as.timeseries.lwd.interval); # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, type="timeseries", "x.region.start"=corrected.x + x.start.min, "y.region.start"=y.cur + 0.5, "x.region.end"=corrected.x + x.end.max, "y.region.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, "x.partial.start"=corrected.x.start[ppts_y.norm_notna], "y.partial.start"=ppts$y.norm[ppts_y.norm_notna] - char.height/2, "x.partial.end"=corrected.x.end[ppts_y.norm_notna], "y.partial.end"=ppts$y.norm[ppts_y.norm_notna] + char.height/2)); } else { # Just the lines: # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, type="timeseries", "x.region.start"=corrected.x + x.start.min, "y.region.start"=y.cur + 0.5, "x.region.end"=corrected.x + x.end.max, "y.region.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, "x.partial.start"=corrected.x.start[ppts_y.norm_notna], "y.partial.start"=ppts$y.norm[ppts_y.norm_notna], "x.partial.end"=corrected.x.end[ppts_y.norm_notna], "y.partial.end"=ppts$y.norm[ppts_y.norm_notna])); } } if( .do.SVG ) # SVG: { for( j in 1:nrow(ppts) ) { svg.str[[length(svg.str)+1]] <- # The lines: .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x.start[j], corrected.x.end[j])), y=.scale.y.to.SVG.plot(c(ppts$y.norm[j], ppts$y.norm[j])), stroke=plot.partial.CMAs.as.timeseries.col.interval, stroke_width=plot.partial.CMAs.as.timeseries.lwd.interval, class="partial_cma_timeseries_lines", suppress.warnings=suppress.warnings); if( plot.partial.CMAs.as.timeseries.interval.type == "segments" ) { # The segment endings: svg.str[[length(svg.str)+1]] <- .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x.start[j], corrected.x.start[j], corrected.x.end[j], corrected.x.end[j])), y=.scale.y.to.SVG.plot(c(ppts$y.norm[j] - 0.2, ppts$y.norm[j] + 0.2, ppts$y.norm[j] - 0.2, ppts$y.norm[j] + 0.2)), connected=FALSE, stroke=plot.partial.CMAs.as.timeseries.col.interval, stroke_width=plot.partial.CMAs.as.timeseries.lwd.interval, class="partial_cma_timeseries_lines", suppress.warnings=suppress.warnings); } else if( plot.partial.CMAs.as.timeseries.interval.type == "arrows" ) { # The arrow endings: svg.str[[length(svg.str)+1]] <- .SVG.lines(x=.scale.x.to.SVG.plot(c(corrected.x.start[j] + dims.event.x/2, corrected.x.start[j], corrected.x.start[j] + dims.event.x/2, corrected.x.start[j], corrected.x.end[j] - dims.event.x/2, corrected.x.end[j], corrected.x.end[j] - dims.event.x/2, corrected.x.end[j])), y=.scale.y.to.SVG.plot(c(ppts$y.norm[j] - 0.2, ppts$y.norm[j], ppts$y.norm[j] + 0.2, ppts$y.norm[j], ppts$y.norm[j] - 0.2, ppts$y.norm[j], ppts$y.norm[j] + 0.2, ppts$y.norm[j])), connected=FALSE, stroke=plot.partial.CMAs.as.timeseries.col.interval, stroke_width=plot.partial.CMAs.as.timeseries.lwd.interval, class="partial_cma_timeseries_lines", suppress.warnings=suppress.warnings); } } # Save the info: if( plot.partial.CMAs.as.timeseries.interval.type == "segments" ) { .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="timeseries", "x.region.start"=.scale.x.to.SVG.plot(corrected.x + x.start.min), "y.region.start"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), "x.region.end"=.scale.x.to.SVG.plot(corrected.x + x.end.max), "y.region.end"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start[ppts_y.norm_notna]), "y.partial.start"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna] - 0.2), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end[ppts_y.norm_notna]), "y.partial.end"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna] + 0.2))); } else if( plot.partial.CMAs.as.timeseries.interval.type == "arrows" ) { .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="timeseries", "x.region.start"=.scale.x.to.SVG.plot(corrected.x + x.start.min), "y.region.start"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), "x.region.end"=.scale.x.to.SVG.plot(corrected.x + x.end.max), "y.region.end"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start[ppts_y.norm_notna]), "y.partial.start"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna] - 0.2), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end[ppts_y.norm_notna]), "y.partial.end"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna] + 0.2))); } else # just lines { .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="timeseries", "x.region.start"=.scale.x.to.SVG.plot(corrected.x + x.start.min), "y.region.start"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), "x.region.end"=.scale.x.to.SVG.plot(corrected.x + x.end.max), "y.region.end"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start[ppts_y.norm_notna]), "y.partial.start"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna]), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end[ppts_y.norm_notna]), "y.partial.end"=.scale.y.to.SVG.plot(ppts$y.norm[ppts_y.norm_notna]))); } } } else if( plot.partial.CMAs.as.timeseries.interval.type == "rectangles" ) { if( .do.R ) # Rplot: { # As semi-transparent rectangles: rect(corrected.x.start, y.cur + 0.5, corrected.x.end, y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, #col=scales::alpha(plot.partial.CMAs.as.timeseries.col.interval, alpha=plot.partial.CMAs.as.timeseries.alpha.interval), col=adjustcolor(plot.partial.CMAs.as.timeseries.col.interval, alpha.f=plot.partial.CMAs.as.timeseries.alpha.interval), border=plot.partial.CMAs.as.timeseries.col.interval, lty="dotted"); # Save the info: .last.cma.plot.info$baseR$partialCMAs <- rbind(.last.cma.plot.info$baseR$partialCMAs, data.frame("pid"=cur_plot_id, "type"="timeseries", "x.region.start"=corrected.x + x.start.min, "y.region.start"=y.cur + 0.5, "x.region.end"=corrected.x + x.end.max, "y.region.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0, "x.partial.start"=corrected.x.start[ppts_y.norm_notna], "y.partial.start"=y.cur + 0.5, "x.partial.end"=corrected.x.end[ppts_y.norm_notna], "y.partial.end"=y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0)); } if( .do.SVG ) # SVG: { for( j in 1:nrow(ppts) ) { svg.str[[length(svg.str)+1]] <- # As semi-transparent rectangles: .SVG.rect(x=.scale.x.to.SVG.plot(corrected.x.start[j]), y=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), xend=.scale.x.to.SVG.plot(corrected.x.end[j]), yend=.scale.y.to.SVG.plot(y.cur + 0.5), fill=plot.partial.CMAs.as.timeseries.col.interval, fill_opacity=plot.partial.CMAs.as.timeseries.alpha.interval, stroke=plot.partial.CMAs.as.timeseries.col.interval, lty="dotted", class="partial_cma_timeseries_rect"); } # Save the info: .last.cma.plot.info$SVG$partialCMAs <- rbind(.last.cma.plot.info$SVG$partialCMAs, data.frame("pid"=cur_plot_id, "type"="timeseries", "x.region.start"=.scale.x.to.SVG.plot(corrected.x + x.start.min), "y.region.start"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.region.end"=.scale.x.to.SVG.plot(corrected.x + x.end.max), "y.region.end"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0), "x.partial.start"=.scale.x.to.SVG.plot(corrected.x.start[ppts_y.norm_notna]), "y.partial.start"=.scale.y.to.SVG.plot(y.cur + 0.5), "x.partial.end"=.scale.x.to.SVG.plot(corrected.x.end[ppts_y.norm_notna]), "y.partial.end"=.scale.y.to.SVG.plot(y.cur + plot.partial.CMAs.as.timeseries.vspace - 1.0))); } } } # The points and connecting lines: if( !is.na(plot.partial.CMAs.as.timeseries.col.dot) ) { if( .do.R ) # Rplot: { points(corrected.x.text, ppts$y.norm, col=plot.partial.CMAs.as.timeseries.col.dot, cex=CMA.cex, type="o", pch=19, lty="solid"); } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- # The connecting lines: .SVG.lines(x=.scale.x.to.SVG.plot(corrected.x.text), y=.scale.y.to.SVG.plot(ppts$y.norm), connected=TRUE, stroke=plot.partial.CMAs.as.timeseries.col.dot, lty="solid", class="partial_cma_timeseries_connecting_lines", suppress.warnings=(suppress.warnings || length(ppts$y.norm) == 1)); # avoid useless warning when only 1 svg.str[[length(svg.str)+1]] <- # The points: .SVG.points(x=.scale.x.to.SVG.plot(corrected.x.text), y=.scale.y.to.SVG.plot(ppts$y.norm), col=plot.partial.CMAs.as.timeseries.col.dot, cex=CMA.cex, pch=19, class="partial_cma_timeseries_points", suppress.warnings=suppress.warnings); } } # The actual values: if( .do.R ) # Rplot: { if( print.CMA && (force.draw.text || char.height.CMA <= 0.80) && !is.na(plot.partial.CMAs.as.timeseries.col.text) ) { text(corrected.x.text, ppts$y.norm, ppts$text, adj=c(0.5,-0.5), cex=CMA.cex, col=plot.partial.CMAs.as.timeseries.col.text); } } if( .do.SVG ) # SVG: { if( print.CMA && (force.draw.text || dims.chr.cma <= dims.chr.event) && !is.na(plot.partial.CMAs.as.timeseries.col.text) ) { svg.str[[length(svg.str)+1]] <- # The actual values: .SVG.text(x=.scale.x.to.SVG.plot(corrected.x.text), y=.scale.y.to.SVG.plot(ppts$y.norm) + dims.chr.cma, text=ppts$text, col=plot.partial.CMAs.as.timeseries.col.text, font_size=dims.chr.cma, h.align="center", v.align="center", class="partial_cma_timeseries_values", suppress.warnings=suppress.warnings); } } # Advance to next patient: y.cur <- y.cur + plot.partial.CMAs.as.timeseries.vspace; } } } } } # Reset the clipping region to the whole plotting area... if( .do.R ) # Rplot: { clip(.last.cma.plot.info$baseR$xlim[1], .last.cma.plot.info$baseR$xlim[2], .last.cma.plot.info$baseR$ylim[1], .last.cma.plot.info$baseR$ylim[2]); } ## ## Separator between CMA and event plotting areas #### ## # Mark the drawing area for the CMAs: if( has.estimated.CMA && adh.plot.space[2] > 0 ) { if( is.cma.TS.or.SW ) { if( .do.R ) # Rplot: { # Background: rect(.rescale.xcoord.for.CMA.plot(0.0), par("usr")[3], .rescale.xcoord.for.CMA.plot(max(adh.max,1.0)), par("usr")[4], col=adjustcolor(CMA.plot.bkg,alpha.f=0.25), border=NA); # Vertical guides: abline(v=c(.rescale.xcoord.for.CMA.plot(0.0), .rescale.xcoord.for.CMA.plot(1.0)), col=CMA.plot.col, lty=c("solid","dotted"), lwd=1); } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- list( # Background: .SVG.rect(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), y=dims.plot.y + dims.adjust.for.tall.legend, width=.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.max)), height=dims.plot.height, stroke="none", fill=CMA.plot.bkg, fill_opacity=0.25, class="cma-drawing-area-bkg", tooltip="CMA estimate"), # Vertical guides: .SVG.comment("The vertical guides for the CMA drawing area"), .SVG.lines(x=rep(c(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0))), each=2), y=rep(c(dims.plot.y, dims.plot.y + dims.plot.height), times=2) + dims.adjust.for.tall.legend, connected=FALSE, stroke=CMA.plot.border, stroke_width=1, lty=c("solid", "dotted"), class="cma-drawing-area-guides-lines", suppress.warnings=suppress.warnings) ); } } else { if( .do.R ) # Rplot: { if( adh.max > 1.0 ) { rect(.rescale.xcoord.for.CMA.plot(0.0), par("usr")[3], .rescale.xcoord.for.CMA.plot(adh.max), par("usr")[4], col=adjustcolor(CMA.plot.bkg,alpha.f=0.25), border=NA); abline(v=c(.rescale.xcoord.for.CMA.plot(0.0), .rescale.xcoord.for.CMA.plot(1.0), .rescale.xcoord.for.CMA.plot(adh.max)), col=CMA.plot.border, lty=c("solid","dotted","solid"), lwd=1); mtext( c("0%",sprintf("%.1f%%",adh.max*100)), 3, line=0.5, at=c(.rescale.xcoord.for.CMA.plot(0), .rescale.xcoord.for.CMA.plot(adh.max)), las=2, cex=cex.axis, col=CMA.plot.border ); if( (.rescale.xcoord.for.CMA.plot(adh.max) - .rescale.xcoord.for.CMA.plot(1.0)) > 1.5*strwidth("0", cex=cex.axis) ) # Don't overcrowd the 100% and maximum CMA by omitting 100% { mtext( c("100%"), 3, line=0.5, at=c(.rescale.xcoord.for.CMA.plot(1.0)), las=2, cex=cex.axis, col=CMA.plot.border ); } } else { rect(.rescale.xcoord.for.CMA.plot(0.0), par("usr")[3], .rescale.xcoord.for.CMA.plot(1.0), par("usr")[4], col=adjustcolor(CMA.plot.bkg,alpha.f=0.25), border=NA); abline(v=c(.rescale.xcoord.for.CMA.plot(0.0), .rescale.xcoord.for.CMA.plot(1.0)), col=CMA.plot.border, lty="solid", lwd=1); mtext( c("0%","100%"), 3, line=0.5, at=c(.rescale.xcoord.for.CMA.plot(0), .rescale.xcoord.for.CMA.plot(1.0)), las=2, cex=cex.axis, col=CMA.plot.border ); } } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- list( # Background: .SVG.rect(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), y=dims.plot.y + dims.adjust.for.tall.legend, width=.scale.width.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.max)), height=dims.plot.height, stroke="none", fill=CMA.plot.bkg, fill_opacity=0.25, class="cma-drawing-area-bkg", tooltip="CMA estimate"), # Vertical guides: .SVG.lines(x=rep(c(.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0)), if(adh.max > 1.0) .scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.max))), each=2), y=rep(c(dims.plot.y, dims.plot.y + dims.plot.height), times=ifelse(adh.max > 1.0, 3, 2)) + dims.adjust.for.tall.legend, connected=FALSE, stroke=CMA.plot.border, stroke_width=1, lty=if(adh.max > 1.0) c("solid", "dotted", "solid") else "solid", class="cma-drawing-area-guides-lines", suppress.warnings=suppress.warnings), # Text guides: .SVG.text(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(0.0)), y=(dims.plot.y + dims.adjust.for.tall.legend - dims.chr.axis/2), text="0%", col="black", font="Arial", font_size=dims.chr.axis, h.align="left", v.align="center", rotate=-(90+rotate.text), class="cma-drawing-area-guides-text", suppress.warnings=suppress.warnings), if(adh.max > 1.0) { c( .SVG.text(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(adh.max)), y=(dims.plot.y + dims.adjust.for.tall.legend - dims.chr.axis/2), text=sprintf("%.1f%%",adh.max*100), col="black", font="Arial", font_size=dims.chr.axis, h.align="left", v.align="center", rotate=-30, class="cma-drawing-area-guides-text", suppress.warnings=suppress.warnings), if(dims.event.x*(.rescale.xcoord.for.CMA.plot(adh.max) - .rescale.xcoord.for.CMA.plot(1.0))/dims.day > 2.0*dims.chr.axis) { # Don't overcrowd the 100% and maximum CMA .SVG.text(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0)), y=(dims.plot.y + dims.adjust.for.tall.legend - dims.chr.axis/2), text="100%", col="black", font="Arial", font_size=dims.chr.axis, h.align="left", v.align="center", rotate=-(90+rotate.text), class="cma-drawing-area-guides-text", suppress.warnings=suppress.warnings) } ) } else { .SVG.text(x=.scale.x.to.SVG.plot(.rescale.xcoord.for.CMA.plot(1.0)), y=(dims.plot.y + dims.adjust.for.tall.legend - dims.chr.axis/2), text="100%", col="black", font="Arial", font_size=dims.chr.axis, h.align="left", v.align="center", rotate=-(90+rotate.text), class="cma-drawing-area-guides-text", suppress.warnings=suppress.warnings) } ); } } } ## ## Title, box and axes #### ## title.string <- paste0(ifelse(is.null(title),"", # the plot title ifelse(length(title)==1, title, ifelse(align.all.patients, title["aligned"], title["notaligned"]))), ifelse(!is.null(title) && show.cma, paste0(" ", switch(class(cma)[1], "CMA_sliding_window"=paste0("sliding window (",cma$computed.CMA, title.inner.event.info,")"), "CMA_per_episode"= paste0("per episode (",cma$computed.CMA, title.inner.event.info,")"), class(cma)[1]) ), "")); if( .do.R ) # Rplot: { box(); # bounding box xlab.string <- ifelse(is.null(xlab), # x axis label "", ifelse(length(xlab)==1, xlab, xlab[show.period])); title(main=title.string, cex.main=cex.title, # title xlab=xlab.string, cex.lab=cex.lab); # x-axis label mtext(y.label$string, side=2, line=par("mar")[2]-1, at=(par("usr")[4] + par("usr")[3])/2, cex=cex.lab, las=3); # y-axis label # Save the info: .last.cma.plot.info$baseR$title <- data.frame("string"=title.string, "x"=NA, "y"=NA, "cex"=NA); .last.cma.plot.info$baseR$x.label <- data.frame("string"=xlab.string, "x"=NA, "y"=NA, "cex"=cex.lab); .last.cma.plot.info$baseR$y.label <- data.frame("string"=y.label$string, "x"=par("mar")[2]-1, "y"=(par("usr")[4] + par("usr")[3])/2, "cex"=cex.lab); } if( .do.SVG ) # SVG: { svg.str[[length(svg.str)+1]] <- list( # The bounding box: .SVG.rect(x=dims.plot.x, y=dims.plot.y, width=dims.plot.width, height=dims.plot.height + dims.adjust.for.tall.legend, stroke="black", stroke_width=1, fill="none", class="bounding-box", comment="The bounding box"), # The title: .SVG.text(x=(dims.plot.x + dims.total.width)/2, y=dims.chr.title, text=title.string, col="black", font="Arial", font_size=dims.chr.title, h.align="center", v.align="center", class="main-title", comment="The main title", suppress.warnings=suppress.warnings), # The y axis label: .SVG.text(x=dims.chr.axis, y=dims.total.height/2, text=as.character(y.label$string), col="black", font="Arial", font_size=dims.chr.lab, h.align="center", v.align="center", rotate=-90, class="axis-name-y", comment="The y-axis label", tooltip="Y axis: patients, events and (possibly) CMA estimates", suppress.warnings=suppress.warnings), # The x axis label: .SVG.text(x=(dims.plot.x + dims.total.width)/2, y=(dims.total.height - dims.chr.axis), text=as.character(x.label), col="black", font="Arial", font_size=dims.chr.lab, h.align="center", v.align="center", class="axis-name-x", comment="The x-axis label", tooltip="X axis: the events ordered in time (from left to right)", suppress.warnings=suppress.warnings) ); # Save the info: .last.cma.plot.info$SVG$title <- data.frame("string"=title.string, "x"=(dims.plot.x + dims.total.width)/2, "y"=dims.chr.title, "font.size"=dims.chr.title); .last.cma.plot.info$SVG$x.label <- data.frame("string"=as.character(x.label), "x"=(dims.plot.x + dims.total.width)/2, "y"=(dims.total.height - dims.chr.axis), "font.size"=dims.chr.lab); .last.cma.plot.info$SVG$y.label <- data.frame("string"=as.character(y.label$string), "x"=dims.chr.axis, "y"=dims.total.height/2, "font.size"=dims.chr.lab); } # The x-axis and vertical guides: if( period.in.days > 0 ) { #xpos <- seq(0, as.numeric(endperiod), by=period.in.days); # where to put lables and guidelines #if( show.period=="dates" ) #{ # axis.labels <- as.character(earliest.date + round(xpos, 1), format=cma$date.format); #} else #{ # axis.labels <- as.character(round(xpos - ifelse(align.first.event.at.zero, correct.earliest.followup.window, 0), 1)); #} if( .do.R ) # Rplot: { axis( 1, at=adh.plot.space[2] + xpos, labels=FALSE); text(adh.plot.space[2] + xpos, par("usr")[3], labels=axis.labels, cex=cex.axis, srt=30, adj=c(1,3), xpd=TRUE); abline( v=adh.plot.space[2] + xpos, lty="dotted", col=gray(0.5) ); abline( v=adh.plot.space[2] + endperiod, lty="solid", col=gray(0.5) ); # Save the info: .last.cma.plot.info$baseR$x.labels <- data.frame("string"=axis.labels, "x"=adh.plot.space[2] + xpos, "y"=par("usr")[3], "cex"=cex.axis); } } if( .do.SVG ) # SVG: { if( !is.null(date.labels) ) { xs <- (dims.plot.x + dims.event.x * date.labels$position/dims.day); ys <- (dims.plot.y + dims.plot.height + dims.chr.axis + dims.adjust.for.tall.legend); svg.str[[length(svg.str)+1]] <- list( # Axis labels: .SVG.text(x=xs, y=rep(ys, length(xs)), text=as.character(date.labels$string), col="black", font="Arial", font_size=dims.chr.axis, h.align="right", v.align="center", rotate=-(90+rotate.text), class="axis-labels-x", suppress.warnings=suppress.warnings), # Axis ticks: .SVG.lines(x=rep(xs,each=2), y=dims.plot.y + dims.plot.height + dims.adjust.for.tall.legend + rep(c(0, dims.chr.axis/2), times=length(xs)), connected=FALSE, stroke="black", stroke_width=1, class="axis-ticks-x", suppress.warnings=suppress.warnings), # Vertical dotted lines: .SVG.lines(x=rep(xs,each=2), y=dims.plot.y + rep(c(dims.plot.height + dims.adjust.for.tall.legend, 0), times=length(xs)), connected=FALSE, stroke="gray50", stroke_width=1, lty="dotted", class="vertical-date-lines", suppress.warnings=suppress.warnings) ); # Save the info: .last.cma.plot.info$SVG$x.labels <- data.frame("string"=as.character(date.labels$string), "x"=xs, "y"=rep(ys, length(xs)), "font.size"=dims.chr.axis); } } } ## ## The legend #### ## if( show.legend ) { if( do.not.draw.plot ) { # Just draw the legend by itself: do it in (0,0): legend.x <- legend.y <- 0; } if( .do.R ) # Rplot: { # Character size for the legend: legend.char.width <- strwidth("O",cex=legend.cex); legend.char.height <- strheight("O",cex=legend.cex); legend.size <- .legend.R(do.plot=FALSE); x <- legend.x; y <- legend.y; if( is.na(x) || x == "right" ) { x <- par("usr")[2] - legend.size["width"] - legend.char.width; } else if( x == "left" ) { x <- par("usr")[1] + legend.char.width; } else if( !is.numeric(x) && length(x) != 1 ) { x <- par("usr")[2] - legend.size["width"] - legend.char.width; } if( is.na(y) || y == "bottom" ) { y <- par("usr")[3] + legend.char.height; } else if( y == "top" ) { y <- par("usr")[4] - legend.size["height"] - legend.char.height; } else if( !is.numeric(y) && length(y) != 1 ) { y <- par("usr")[3] + legend.char.height; } ret.val <- .legend.R(x, y, as.numeric(legend.size["width"]), as.numeric(legend.size["height"])); # Remove superfluous rownames from the saved info: if( !is.null(.last.cma.plot.info$baseR$legend$box) ) rownames(.last.cma.plot.info$baseR$legend$box) <- NULL; if( !is.null(.last.cma.plot.info$baseR$legend$title) ) rownames(.last.cma.plot.info$baseR$legend$title) <- NULL; if( !is.null(.last.cma.plot.info$baseR$legend$components) ) rownames(.last.cma.plot.info$baseR$legend$components) <- NULL; } if( .do.SVG ) # SVG: { # Compute the bounding box of the legend without showing it yet: .legend.SVG(legend.x, legend.y, do.plot=FALSE); # Display the legend where it should be displayed: svg.str[[length(svg.str)+1]] <- # The legend: .legend.SVG(.last.cma.plot.info$SVG$legend$box$x.start, .last.cma.plot.info$SVG$legend$box$y.start + dims.adjust.for.tall.legend, do.plot=TRUE); # Remove superfluous rownames from the saved info: if( !is.null(.last.cma.plot.info$SVG$legend$box) ) rownames(.last.cma.plot.info$SVG$legend$box) <- NULL; if( !is.null(.last.cma.plot.info$SVG$legend$title) ) rownames(.last.cma.plot.info$SVG$legend$title) <- NULL; if( !is.null(.last.cma.plot.info$SVG$legend$components) ) rownames(.last.cma.plot.info$SVG$legend$components) <- NULL; } } # # Finish and possibly export the file(s) #### # if( .do.R ) # Rplot: { #par(old.par); # restore graphical params } exported.file.names <- NULL; # the list of exported files (if any) if( .do.SVG ) # Close the <svg> tag: { svg.str[[length(svg.str)+1]] <- '</svg>\n'; # Flatten svg.str to a character vector: svg.str <- unlist(svg.str); # Export to various formats (if so requested): if( !is.null(export.formats) ) { file.svg <- NULL; svg.placeholder.filename <- NULL; if( "svg" %in% export.formats ) { ## Export as stand-alone SVG file #### file.svg <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".svg"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".svg")) ); exported.file.names <- c(exported.file.names, file.svg); # Export SVG: writeLines(c(svg.header, svg.str), file.svg, sep=""); } if( "html" %in% export.formats ) { ## Export as self-contained HTML document #### file.html <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".html"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".html")) ); exported.file.names <- c(exported.file.names, file.html); # Load the CSS template: if( !is.null(export.formats.html.css) ) { # Try to load the given template: if( length(export.formats.html.css) != 1 || !file.exists(as.character(export.formats.html.css)) ) { if( !suppress.warnings ) .report.ewms("The given CSS template '",as.character(export.formats.html.css),"' does not seem to exist: falling back to the default one!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.html.css <- NULL; } else { css.template.path <- as.character(export.formats.html.css); } } if( is.null(export.formats.html.css) ) { # Load the default CSS template: css.template.path <- system.file('html-templates/css-template.css', package='AdhereR'); if( is.null(css.template.path) || css.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the CSS template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } } # Load the JavaScript template: if( !is.null(export.formats.html.javascript) ) { # Try to load the given template: if( length(export.formats.html.javascript) != 1 || !file.exists(as.character(export.formats.html.javascript)) ) { if( !suppress.warnings ) .report.ewms("The given JavaScript template '",as.character(export.formats.html.javascript),"' does not seem to exist: falling back to the default one!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.html.javascript <- NULL; } else { js.template.path <- as.character(export.formats.html.javascript); } } if( is.null(export.formats.html.javascript) ) { # Load the default JavaScript template: js.template.path <- system.file('html-templates/javascript-template.js', package='AdhereR'); if( is.null(js.template.path) || js.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the JavaScript template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } } # Read the templates: css.template <- readLines(css.template.path); js.template <- readLines(js.template.path); # Add the medication categories to class names mapping as a dictionary: js.template <- c(js.template, '// Mapping between medication categories and -med-class-X class names', 'adh_svg["medication_classes"] = {\n', paste0(' "',names(categories.to.classes),'" : "',categories.to.classes,'"',collapse=",\n"), '\n};\n'); if( export.formats.save.svg.placeholder ) { # Check that base64 exists: if( !requireNamespace("base64", quietly=TRUE) ) { # Does not seem to: if( !suppress.warnings ) .report.ewms("Package 'base64' required for emedding images in HTML documents does not seem to exist: we'll store the images outside the HTML document!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.svg.placeholder.embed <- FALSE; } if( !export.formats.svg.placeholder.embed ) { # The SVG placeholder is an external file: add its filename: svg.placeholder.filename <- ifelse( is.na(export.formats.directory), tempfile(paste0(export.formats.fileprefix,"-svg-placeholder"), fileext=paste0(".",export.formats.svg.placeholder.type)), file.path(export.formats.directory, paste0(paste0(export.formats.fileprefix,"-svg-placeholder"),paste0(".",export.formats.svg.placeholder.type))) ); js.template <- c(js.template, "// The SVG placeholder's filename:", paste0('adh_svg["svg_placeholder_file_name"] = "',basename(svg.placeholder.filename),'";\n')); } else { # The SVG placeholder must be embedded in base_64 encoded-form into en <img> tag: if( !(export.formats.svg.placeholder.type %in% c("jpg", "png")) ) { if( !suppress.warnings ) .report.ewms("Can only embed a JPEG or PNG image as a placeholder for the SVG image: defaulting to JPEG!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.svg.placeholder.type <- "jpg"; } # Base encode the placeholder: # Need to covert the SVG to one of these, so we need to export it (if not already exported): if( is.null(file.svg) ) { file.svg <- tempfile(export.formats.fileprefix, fileext=".svg"); writeLines(c(svg.header, svg.str), file.svg, sep=""); } # Convert the SVG: svg.placeholder.png.tmpfile <- tempfile(paste0(export.formats.fileprefix,"-svg-placeholder"), fileext=".png"); rsvg::rsvg_png(file.svg, file=svg.placeholder.png.tmpfile, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); if( export.formats.svg.placeholder.type == "jpg" ) { # Covert it to JPEG first: svg.placeholder.tmpfile <- paste0(svg.placeholder.png.tmpfile,".jpg"); jpeg::writeJPEG(png::readPNG(svg.placeholder.png.tmpfile), svg.placeholder.tmpfile, quality=0.90); } else if( export.formats.svg.placeholder.type == "png" ) { # Already exported: svg.placeholder.tmpfile <- svg.placeholder.png.tmpfile; } svg.placeholder.end64.tmpfile <- paste0(svg.placeholder.tmpfile,"-enc64.txt"); # Encode it to base64: base64::encode(svg.placeholder.tmpfile, svg.placeholder.end64.tmpfile, linebreaks=FALSE); # Load it and embed it: svg.placeholder.end64 <- try(readLines(svg.placeholder.end64.tmpfile), silent=TRUE); if( inherits(svg.placeholder.end64, "try-error") ) { if( !suppress.warnings ) .report.ewms("Failed embedding an image in the HTML document: reverting to having it as an external file!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.svg.placeholder.embed <- FALSE; try(unlink(c(svg.placeholder.tmpfile, svg.placeholder.end64.tmpfile)), silent=TRUE); # clean up the temp files # The SVG placeholder is an external file: add its filename: svg.placeholder.filename <- ifelse( is.na(export.formats.directory), tempfile(paste0(export.formats.fileprefix,"-svg-placeholder"), fileext=paste0(".",export.formats.svg.placeholder.type)), file.path(export.formats.directory, paste0(paste0(export.formats.fileprefix,"-svg-placeholder"),paste0(".",export.formats.svg.placeholder.type))) ); js.template <- c(js.template, "// The SVG placeholder's filename:", paste0('adh_svg["svg_placeholder_file_name"] = "',basename(svg.placeholder.filename),'";\n')); } else { js.template <- c(js.template, "// The SVG placeholder's content:", paste0('adh_svg["svg_placeholder_file_name"] = "data:image/', ifelse(export.formats.svg.placeholder.type == "png", "png", "jpeg"), ';base64,',svg.placeholder.end64,'";\n')); # Clean up the temp files try(unlink(c(svg.placeholder.tmpfile, svg.placeholder.end64.tmpfile)), silent=TRUE); } } } # Load the HTML template and replace generics by their actual values before saving it in the desired location: if( !is.null(export.formats.html.template) ) { # Try to load the given template: if( length(export.formats.html.template) != 1 || !file.exists(as.character(export.formats.html.template)) ) { if( !suppress.warnings ) .report.ewms("The given HTML template '",as.character(export.formats.html.template),"' does not seem to exist: falling back to the default one!\n", "warning", ".plot.CMAs", "AdhereR"); export.formats.html.template <- NULL; } else { html.template.path <- as.character(export.formats.html.template); } } if( is.null(export.formats.html.template) ) { # Load the default HTML template: html.template.path <- system.file('html-templates/html-template.html', package='AdhereR'); if( is.null(html.template.path) || html.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the HTML template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } } # Load it: html.template <- readLines(html.template.path); # Check place-holders and replace them with the actual values: if( length(grep('<script type="text/javascript" src="PATH-TO-JS"></script>', html.template, fixed=TRUE)) != 1 ) { if( !suppress.warnings ) .report.ewms("The HTML template seems corrupted: there should 1 and only 1 '<script type=\"text/javascript\" src=\"PATH-TO-JS\"></script>'!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } if( length(grep('<link rel="stylesheet" href="PATH-TO-CSS">', html.template, fixed=TRUE)) != 1 ) { if( !suppress.warnings ) .report.ewms("The HTML template seems corrupted: there should 1 and only 1 '<link rel=\"stylesheet\" href=\"PATH-TO-CSS\">'!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } html.template <- sub('<script type="text/javascript" src="PATH-TO-JS"></script>', paste0('<script type="text/javascript">\n', paste0(js.template, collapse="\n"), '\n</script>'), html.template, fixed=TRUE); # JavaScript html.template <- sub('<link rel="stylesheet" href="PATH-TO-CSS">', paste0('<style>\n', paste0(css.template, collapse="\n"), '\n</style>'), html.template, fixed=TRUE); # CSS # SVG: if( length(grep('<object id="adherence_plot" data="PATH-TO-IMAGE" type="image/svg+xml">Please use a modern browser!</object>', html.template, fixed=TRUE)) != 1 ) { if( !suppress.warnings ) .report.ewms("The HTML template seems corrupted: there should 1 and only 1 '<object id=\"adherence_plot\" data=\"PATH-TO-IMAGE\" type=\"image/svg+xml\">Please use a modern browser!</object>'!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } svg.str.embedded <- c('<svg id="adherence_plot" ', # add id and (possibly) the dimensions to the <svg> tag if( FALSE ) 'height="600" ', # height (if defined) if( TRUE ) paste0('width="',(dims.plot.width / dims.chr.std),'" '), # width in "standard" charters svg.str[-1]); html.template <- sub('<object id="adherence_plot" data="PATH-TO-IMAGE" type="image/svg+xml">Please use a modern browser!</object>', paste0(paste0(svg.str.embedded, collapse=""), "\n"), html.template, fixed=TRUE); # SVG # Export the self-contained HTML document: writeLines(html.template, file.html, sep="\n"); } if( (export.formats.save.svg.placeholder && !is.null(svg.placeholder.filename)) || any(c("jpg", "png", "ps", "pdf", "webp") %in% export.formats) ) { ## Export to flat file formats (PNG, JPG, PS, PDF or WEBP) #### # Need to covert the SVG to one of these, so we need to export it (if not already exported): if( is.null(file.svg) ) { file.svg <- tempfile(export.formats.fileprefix, fileext=".svg"); writeLines(c(svg.header, svg.str), file.svg, sep=""); } if( export.formats.save.svg.placeholder || any(c("jpg", "png","webp") %in% export.formats) ) { # # For the bitmapped formats, render it once: # bitmap <- rsvg::rsvg(file.svg, # height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality # width =if(!is.na(export.formats.width)) export.formats.width else NULL); if( export.formats.save.svg.placeholder && !is.null(svg.placeholder.filename) ) { # The SVG placeholder: exported.file.names <- c(exported.file.names, svg.placeholder.filename); if( export.formats.svg.placeholder.type == "jpg" ) { png2jpg.file <- tempfile(export.formats.fileprefix, fileext="-png.jpg") rsvg::rsvg_png(file.svg, file=png2jpg.file, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); jpeg::writeJPEG(png::readPNG(png2jpg.file), svg.placeholder.filename, quality=0.90); #jpeg::writeJPEG(bitmap, svg.placeholder.filename, quality=0.90); } else if( export.formats.svg.placeholder.type == "png" ) { rsvg::rsvg_png(file.svg, file=svg.placeholder.filename, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); #png::writePNG(bitmap, svg.placeholder.filename, dpi=150); } else if( export.formats.svg.placeholder.type == "webp" ) { rsvg::rsvg_webp(file.svg, file=svg.placeholder.filename, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); #webp::write_webp(bitmap, svg.placeholder.filename, quality=90); } } if( "jpg" %in% export.formats ) { # JPG file: file.jpg <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".jpg"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".jpg")) ); exported.file.names <- c(exported.file.names, file.jpg); png2jpg.file <- tempfile(export.formats.fileprefix, fileext="-png.jpg") rsvg::rsvg_png(file.svg, file=png2jpg.file, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); jpeg::writeJPEG(png::readPNG(png2jpg.file), file.jpg, quality=0.90); #jpeg::writeJPEG(bitmap, file.jpg, quality=0.90); } if( "png" %in% export.formats ) { # PNG file: file.png <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".png"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".png")) ); exported.file.names <- c(exported.file.names, file.png); rsvg::rsvg_png(file.svg, file=file.png, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); #png::writePNG(bitmap, file.png, dpi=150); } if( "webp" %in% export.formats ) { # WEBP file: file.webp <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".webp"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".webp")) ); exported.file.names <- c(exported.file.names, file.webp); rsvg::rsvg_webp(file.svg, file=file.webp, height=if(!is.na(export.formats.height)) export.formats.height else dims.total.height * 2, # prepare for high DPI/quality width =if(!is.na(export.formats.width)) export.formats.width else NULL); #webp::write_webp(bitmap, file.webp, quality=90); } } if( "ps" %in% export.formats ) { # PS file: file.ps <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".ps"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".ps")) ); exported.file.names <- c(exported.file.names, file.ps); rsvg::rsvg_ps(file.svg, file=file.ps); } if( "pdf" %in% export.formats ) { # PDF file: file.pdf <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".pdf"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".pdf")) ); exported.file.names <- c(exported.file.names, file.pdf); rsvg::rsvg_pdf(file.svg, file=file.pdf); } } } } ## Save plot info into the external environment #### assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # Return value: return (invisible(exported.file.names)); } ## The error plotting function #### plot.CMA.error <- function(cma=NA, patients.to.plot=NULL, export.formats=NULL, export.formats.fileprefix="AdhereR-plot", export.formats.directory=NA, generate.R.plot=TRUE ) { # What sorts of plots to generate (use short names for short if statements): .do.R <- generate.R.plot; .do.SVG <- (!is.null(export.formats) && any(c("svg", "html", "jpg", "png", "webp", "ps", "pdf") %in% export.formats)); if( !.do.R && !.do.SVG ) { # Nothing to plot! return (invisible(NULL)); } if( .do.R ) { #dev.new(); # clear any previous plots old.par <- par(no.readonly=TRUE); # save the origial par par(mar=c(0,0,0,0), bg="gray60"); plot.new(); segments(0, 0, 1, 1, col="gray40", lwd=10); segments(0, 1, 1, 0, col="gray40", lwd=10); par(old.par); # restore the original par at the end } exported.file.names <- NULL; # the list of exported files (if any) if( .do.SVG ) { # Build the SVG plot: svg.header <- c('<?xml version="1.0" standalone="no"?>\n', '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'); svg.str <- c( '<svg ', 'viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n', # the plotting surface # Comments, notes and clarifications: .SVG.comment("This is the self-contained SVG error plot.", newpara=TRUE), # Clear the area: .SVG.rect(comment="Clear the whole plotting area", class="plotting-area-background", x=0, y=0, width=100, height=100, fill="gray60", stroke="none"), '\n', # one empty line .SVG.lines(x=c(0,100, 0,100), y=c(0,100, 100,0), stroke="gray40", stroke_width=5), '</svg>\n'); # Export to various formats (if so requested): if( !is.null(export.formats) ) { file.svg <- NULL; if( "svg" %in% export.formats ) { ## Export as stand-alone SVG file #### file.svg <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".svg"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".svg")) ); exported.file.names <- c(exported.file.names, file.svg); # Export SVG: writeLines(c(svg.header, svg.str), file.svg, sep=""); } if( "html" %in% export.formats ) { ## Export as self-contained HTML document #### file.html <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".html"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".html")) ); exported.file.names <- c(exported.file.names, file.html); # Load the CSS and JavaScript templates: css.template.path <- system.file('html-templates/css-template.css', package='AdhereR'); if( is.null(css.template.path) || css.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the CSS template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } js.template.path <- system.file('html-templates/javascript-template.js', package='AdhereR'); if( is.null(js.template.path) || js.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the JavaScript template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } css.template <- readLines(css.template.path); js.template <- readLines(js.template.path); # Load the HTML template and replace generics by their actual values before saving it in the desired location: html.template.path <- system.file('html-templates/html-template.html', package='AdhereR'); if( is.null(html.template.path) || html.template.path=="" ) { if( !suppress.warnings ) .report.ewms("Cannot load the HTML template -- please reinstall the AdhereR package!\n", "error", ".plot.CMAs", "AdhereR"); .last.cma.plot.info$SVG <- NULL; assign(".last.cma.plot.info", .last.cma.plot.info, envir=.adherer.env); # save the plot infor into the environment plot.CMA.error(export.formats=export.formats, export.formats.fileprefix=export.formats.fileprefix, export.formats.directory=export.formats.directory, generate.R.plot=FALSE); return (invisible(NULL)); } html.template <- readLines(html.template.path); html.template <- sub('<script type="text/javascript" src="PATH-TO-JS"></script>', paste0('<script type="text/javascript">\n', paste0(js.template, collapse="\n"), '\n</script>'), html.template, fixed=TRUE); # JavaScript html.template <- sub('<link rel="stylesheet" href="PATH-TO-CSS">', paste0('<style>\n', paste0(css.template, collapse="\n"), '\n</style>'), html.template, fixed=TRUE); # CSS # SVG: svg.str.embedded <- c('<svg id="adherence_plot" ', # add id and (possibly) the dimensions to the <svg> tag if( TRUE ) 'height="600" ', # height (if defined) if( FALSE ) 'width="600" ', # width (if defined) svg.str[-1]); html.template <- sub('<object id="adherence_plot" data="PATH-TO-IMAGE" type="image/svg+xml">Please use a modern browser!</object>', paste0(paste0(svg.str.embedded, collapse=""), "\n"), html.template, fixed=TRUE); # SVG # Explort the self-contained HTML document: writeLines(html.template, file.html, sep="\n"); } if( any(c("jpg", "png", "ps", "pdf", "webp") %in% export.formats) ) { ## Export to flat file formats (PNG, JPG, PS, PDF or WEBP) #### # Need to covert the SVG to one of these, so we need to export it (if not already exported): if( is.null(file.svg) ) { file.svg <- tempfile(export.formats.fileprefix, fileext=".svg"); writeLines(c(svg.header, svg.str), file.svg, sep=""); } if( any(c("jpg", "png","webp") %in% export.formats) ) { # For the bitmapped formats, render it once: bitmap <- rsvg::rsvg(file.svg); # , height = 1440 if( "jpg" %in% export.formats ) { # JPG file: file.jpg <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".jpg"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".jpg")) ); exported.file.names <- c(exported.file.names, file.jpg); jpeg::writeJPEG(bitmap, file.jpg, quality=0.90); } if( "png" %in% export.formats ) { # PNG file: file.png <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".png"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".png")) ); exported.file.names <- c(exported.file.names, file.png); #rsvg::rsvg_png(file.svg, file=file.png); png::writePNG(bitmap, file.png, dpi=150); } if( "webp" %in% export.formats ) { # WEBP file: file.webp <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".webp"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".webp")) ); exported.file.names <- c(exported.file.names, file.webp); #rsvg::rsvg_webp(file.svg, file=file.webp); webp::write_webp(bitmap, file.webp, quality=90); } } if( "ps" %in% export.formats ) { # PS file: file.ps <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".ps"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".ps")) ); exported.file.names <- c(exported.file.names, file.ps); rsvg::rsvg_ps(file.svg, file=file.ps); } if( "pdf" %in% export.formats ) { # PDF file: file.pdf <- ifelse( is.na(export.formats.directory), tempfile(export.formats.fileprefix, fileext=".pdf"), file.path(export.formats.directory, paste0(export.formats.fileprefix,".pdf")) ); exported.file.names <- c(exported.file.names, file.pdf); rsvg::rsvg_pdf(file.svg, file=file.pdf); } } } } # No last plot (really)... assign(".last.cma.plot.info", NULL, envir=.adherer.env); # Return value: return (invisible(exported.file.names)); }
/scratch/gouwar.j/cran-all/cranData/AdhereR/R/plotting.R
############################################################################################### # # This file is part of AdhereR. # Copyright (C) 2018 Samuel Allemann, Dan Dediu & Alexandra Dima # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### # Declare some variables as global to avoid NOTEs during package building: globalVariables(c(".PATIENT.MED.ID", ".new.ID", ".obs.duration", "EVENT.ID", "ID.colname", "PATIENT_ID", "carry.only.for.same.medication", "carryover.from.last", "carryover.into.obs.window", "carryover.total", "carryover.within.obs.window", "consider.dosage.change", "date.format", "event.daily.dose.colname", "event.date.colname", "event.duration.colname", "event.interval.colname", "followup.window.duration", "followup.window.duration.unit", "followup.window.start", "followup.window.start.unit", "gap.days", "gap.days.colname", "intersect.ID", "intersect.duration", "intersect.end", "intersect.start", "medication.class.colname", "medication.group", "observation.window.duration", "observation.window.duration.unit", "observation.window.start", "observation.window.start.unit", "process.seq", "process.seq.num", "prop.trt.groups.available", "suppress.warnings", "group")); ################ function to calculate simple CMA for polypharmacy #' CMA constructor for polypharmacy. #' #' Constructs a CMA (continuous multiple-interval measures of medication #' availability/gaps) object for polypharmacy. #' #' #' @param data A \emph{\code{data.frame}} containing the events (prescribing or #' dispensing) used to compute the CMA. Must contain, at a minimum, the patient #' unique ID, the event date and duration, medication type, and might also contain the daily #' dosage (the actual column names are defined in the #' following four parameters). #' @param medication.groups A \emph{string} with the name of the column containing the medication #' groups. If multiple medication classes should belong to the same treatment group, they can be #' differentiated here (important to investigate treatment switches) #' @param CMA.to.apply A \emph{string} giving the name of the CMA function (1 to #' 9) that will be computed for each treatment group. #' @param aggregate.first \emph{Logical}, if \code{TRUE}, aggregate across treatment groups before #' summarizing over time during OW. #' @param aggregation.method A \emph{string} giving the name of the function to #' aggregate CMA values of medication group, or \code{NA} to return only raw CMA estimates #' per medication group. Accepts summary functions such as "mean", "sd", "var", "min", "max", #' and "median". Custom functions are possible as long as they take a numeric vector as input #' and return a single numeric value. #' @param aggregation.method.arguments optional, A \emph{named list} of additional arguments to the #' function given in \code{aggregation method}, e.g. \code{na.rm = TRUE}. #' @param thresholds optional, a \emph{number} to apply as threshold between aggregation and summarizing. #' @param ID.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type. Defaults to #' \code{medication.class.colname}. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter); must be present. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days); must be present. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the medication type, or \code{NA} if not defined. #' @param carry.only.for.same.medication \emph{Logical}, if \code{TRUE}, the #' carry-over applies only across medication of the same type; valid only for #' CMAs 5 to 9, in which case it is coupled (i.e., the same value is used for #' computing the treatment episodes and the CMA on each treatment episode). #' @param consider.dosage.change \emph{Logical}, if \code{TRUE}, the carry-over #' is adjusted to also reflect changes in dosage; valid only for CMAs 5 to 9, in #' which case it is coupled (i.e., the same value is used for computing the #' treatment episodes and the CMA on each treatment episode). #' @param followup.window.start If a \emph{\code{Date}} object, it represents #' the actual start date of the follow-up window; if a \emph{string} it is the #' name of the column in \code{data} containing the start date of the follow-up #' window either as the numbers of \code{followup.window.start.unit} units after #' the first event (the column must be of type \code{numeric}) or as actual #' dates (in which case the column must be of type \code{Date}); if a #' \emph{number} it is the number of time units defined in the #' \code{followup.window.start.unit} parameter after the begin of the #' participant's first event; or \code{NA} if not defined. #' @param followup.window.start.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.start} refers to (when a number), or #' \code{NA} if not defined. #' @param followup.window.duration either a \emph{number} representing the #' duration of the follow-up window in the time units given in #' \code{followup.window.duration.unit}, or a \emph{string} giving the column #' containing these numbers. Should represent a period for which relevant #' medication events are recorded accurately (e.g. not extend after end of #' relevant treatment, loss-to-follow-up or change to a health care provider #' not covered by the database). #' @param followup.window.duration.unit can be either \emph{"days"}, #' \emph{"weeks"}, \emph{"months"} or \emph{"years"}, and represents the time #' units that \code{followup.window.duration} refers to, or \code{NA} if not #' defined. #' @param observation.window.start,observation.window.start.unit,observation.window.duration,observation.window.duration.unit the definition of the observation window #' (see the follow-up window parameters above for details). Can be defined separately #' for each patient and treatment group. #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param summary Metadata as a \emph{string}, briefly describing this CMA. #' @param force.NA.CMA.for.failed.patients \emph{Logical} describing how the #' patients for which the CMA estimation fails are treated: if \code{TRUE} #' they are returned with an \code{NA} CMA estimate, while for #' \code{FALSE} they are omitted. #' @param parallel.backend Can be "none" (the default) for single-threaded #' execution, "multicore" (using \code{mclapply} in package \code{parallel}) #' for multicore processing (NB. not currently implemented on MS Windows and #' automatically falls back on "snow" on this platform), or "snow", #' "snow(SOCK)" (equivalent to "snow"), "snow(MPI)" or "snow(NWS)" specifying #' various types of SNOW clusters (can be on the local machine or more complex #' setups -- please see the documentation of package \code{snow} for details; #' the last two require packages \code{Rmpi} and \code{nws}, respectively, not #' automatically installed with \code{AdhereR}). #' @param parallel.threads Can be "auto" (for \code{parallel.backend} == #' "multicore", defaults to the number of cores in the system as given by #' \code{options("cores")}, while for \code{parallel.backend} == "snow", #' defaults to 2), a strictly positive integer specifying the number of parallel #' threads, or a more complex specification of the SNOW cluster nodes for #' \code{parallel.backend} == "snow" (see the documentation of package #' \code{snow} for details). #' @param suppress.warnings \emph{Logical}, if \code{TRUE} don't show any #' warnings. #' @param suppress.special.argument.checks \emph{Logical} parameter for internal #' use; if \code{FALSE} (default) check if the important columns in the \code{data} #' have some of the reserved names, if \code{TRUE} this check is not performed. #' @param ... other possible parameters #' @return An \code{S3} object of class \code{CMA_polypharmacy} with the #' following fields: #' \itemize{ #' \item \code{data} The actual event data, as given by the \code{data} #' parameter. #' \item \code{ID.colname} the name of the column in \code{data} containing the #' unique patient ID, as given by the \code{ID.colname} parameter. #' \item \code{event.date.colname} the name of the column in \code{data} #' containing the start date of the event (in the format given in the #' \code{date.format} parameter), as given by the \code{event.date.colname} #' parameter. #' \item \code{event.duration.colname} the name of the column in \code{data} #' containing the event duration (in days), as given by the #' \code{event.duration.colname} parameter. #' \item \code{event.daily.dose.colname} the name of the column in \code{data} #' containing the prescribed daily dose, as given by the #' \code{event.daily.dose.colname} parameter. #' \item \code{medication.class.colname} the name of the column in \code{data} #' containing the classes/types/groups of medication, as given by the #' \code{medication.class.colname} parameter. #' \item \code{carry.only.for.same.medication} whether the carry-over applies #' only across medication of the same type, as given by the #' \code{carry.only.for.same.medication} parameter. #' \item \code{consider.dosage.change} whether the carry-over is adjusted to #' reflect changes in dosage, as given by the \code{consider.dosage.change} #' parameter. #' \item \code{followup.window.start} the beginning of the follow-up window, as #' given by the \code{followup.window.start} parameter. #' \item \code{followup.window.start.unit} the time unit of the #' \code{followup.window.start}, as given by the #' \code{followup.window.start.unit} parameter. #' \item \code{followup.window.duration} the duration of the follow-up window, #' as given by the \code{followup.window.duration} parameter. #' \item \code{followup.window.duration.unit} the time unit of the #' \code{followup.window.duration}, as given by the #' \code{followup.window.duration.unit} parameter. #' \item \code{observation.window.start} the beginning of the observation #' window, as given by the \code{observation.window.start} parameter. #' \item \code{observation.window.start.unit} the time unit of the #' \code{observation.window.start}, as given by the #' \code{observation.window.start.unit} parameter. #' \item \code{observation.window.duration} the duration of the observation #' window, as given by the \code{observation.window.duration} parameter. #' \item \code{observation.window.duration.unit} the time unit of the #' \code{observation.window.duration}, as given by the #' \code{observation.window.duration.unit} parameter. #' \item \code{date.format} the format of the dates, as given by the #' \code{date.format} parameter. #' \item \code{summary} the metadata, as given by the \code{summary} parameter. #' \item \code{event.info} the \code{data.frame} containing the event info #' (irrelevant for most users; see \code{\link{compute.event.int.gaps}} for #' details). #' \item \code{aggregation.method} the aggregation method to combine CMA values #' from different groups. #' \item \code{computed.CMA} the class name of the computed CMA. #' \item \code{medication.groups} a \code{data.frame} with medication groups and #' classes #' \item \code{CMA} the \code{data.frame} containing the actual \code{CMA} #' estimates for each participant (the \code{ID.colname} column) and #' sometimes treatment group, with columns: #' \itemize{ #' \item \code{ID.colname} the patient ID as given by the \code{ID.colname} #' parameter. #' \item \code{medication.groups} only when no aggregation method is used #' (\code{aggregation.method = NA}); the treatment group as given by the #' \code{medication.groups} parameter. #' \item \code{CMA} the treatment episode's estimated CMA. #' } #' } #' @examples #' \dontrun{ #' CMA_PP <- CMA_polypharmacy(data = med.events.pp, #' medication.groups = med.groups, #' CMA.to.apply = "CMA7", #' aggregate.first = TRUE, # aggregate before summarizing #' aggregation.method = "mean", # compute mean of CMAs #' aggregation.method.arguments = list(na.rm = TRUE), # remove NA's during calculation #' thresholds = NA, # don't apply threshold #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY", #' followup.window.start=0, #' observation.window.start=180, #' observation.window.duration=365, #' carry.only.for.same.medication = TRUE);} #' @export CMA_polypharmacy <- function(data = data, medication.groups = medication.class.colname, #if multiple medication classes should belong to the same treatment group, they can be differentiated here (important to investigate treatment switches) CMA.to.apply = NA, aggregate.first = TRUE, #if TRUE, aggregate across treatment groups before summarizing during OW aggregation.method = NA, #custom function possible, NA for raw data only aggregation.method.arguments = NA, #a named list of additional arguments to aggregation function thresholds = NA, #threshold to apply between aggregation and summarizing ID.colname = NA, event.date.colname = NA, event.duration.colname = NA, event.daily.dose.colname = NA, medication.class.colname = NA, carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = use the CMA's values) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = use the CMA's values) # The follow-up window: followup.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.duration=365*2, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=c("days", "weeks", "months", "years")[1],# the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=0, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=365*2, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Comments and metadata: summary="CMA for polypharmacy", # Dealing with failed estimates: force.NA.CMA.for.failed.patients=TRUE, # force the failed patients to have NA CM estimate? # Parallel processing: parallel.backend=c("none","multicore","snow","snow(SOCK)","snow(MPI)","snow(NWS)")[1], # parallel backend to use parallel.threads="auto", # specification (or number) of parallel threads # Misc: suppress.warnings=FALSE, suppress.special.argument.checks=TRUE, # used internally to suppress the check that we don't use special argument names ...){ # Get the CMA function corresponding to the name: if( !(is.character(CMA.to.apply) || is.factor(CMA.to.apply)) ) { if( !suppress.warnings ) warning(paste0("'CMA.to.apply' must be a string contining the name of the simple CMA to apply!\n)")); return (NULL); } CMA.FNC <- switch(as.character(CMA.to.apply), # if factor, force it to string "CMA1" = CMA1, "CMA2" = CMA2, "CMA3" = CMA3, "CMA4" = CMA4, "CMA5" = CMA5, "CMA6" = CMA6, "CMA7" = CMA7, "CMA8" = CMA8, "CMA9" = CMA9, {if( !suppress.warnings ) warning(paste0("Unknown 'CMA.to.apply' '",CMA.to.apply,"': defaulting to CMA0!\n)")); CMA0;}); # by default, fall back to CMA0 # get aggregation function if(exists(aggregation.method, mode='function')) { # check if aggregation method exists as a function POLY.FNC <- get(aggregation.method); } else { POLY.FNC <- mean; # by default, fall back to mean if( !suppress.warnings ) warning(paste0("Unknown 'aggregation.method' '",aggregation.method,"': defaulting to mean!\n)")); } # # Get the CMA class corresponding to the name # if( !(is.character(CMA.class) || is.factor(CMA.class)) ) # { # if( !suppress.warnings ) warning(paste0("'CMA.class' must be a string contining the name of the CMA class to apply!\n)")); # return (NULL); # } # Default argument values and overrides: def.vals <- formals(CMA.FNC); if( CMA.to.apply %in% c("CMA1", "CMA2", "CMA3", "CMA4") ) { carryover.into.obs.window <- carryover.within.obs.window <- FALSE; if( !is.na(carry.only.for.same.medication) && carry.only.for.same.medication && !suppress.warnings ) cat("Warning: 'carry.only.for.same.medication' cannot be defined for CMAs 1-4!\n"); carry.only.for.same.medication <- FALSE; if( !is.na(consider.dosage.change) && consider.dosage.change && !suppress.warnings ) cat("Warning: 'consider.dosage.change' cannot be defined for CMAs 1-4!\n"); consider.dosage.change <- FALSE; } else if( CMA.to.apply %in% c("CMA5", "CMA6") ) { carryover.into.obs.window <- FALSE; carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else if( CMA.to.apply %in% c("CMA7", "CMA8", "CMA9") ) { carryover.into.obs.window <- carryover.within.obs.window <- TRUE; if( is.na(carry.only.for.same.medication) ) carry.only.for.same.medication <- def.vals[["carry.only.for.same.medication"]]; # use the default value from CMA if( is.na(consider.dosage.change) ) consider.dosage.change <- def.vals[["consider.dosage.change"]]; # use the default value from CMA } else { if( !suppress.warnings ) warning("I know how to do CMA for polypharmacy only for CMAs 1 to 9!\n"); return (NULL); } # Create the return value skeleton and check consistency: ret.val <- CMA0(data, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, summary=NA); if( is.null(ret.val) ) return (NULL); # The workhorse auxiliary function: For a given (subset) of data, compute the polypharmacy CMA and event information: .workhorse.function <- function(data=NULL, ID.colname=NULL, event.date.colname=NULL, event.duration.colname=NULL, event.daily.dose.colname=NULL, medication.class.colname=NULL, event.interval.colname=NULL, gap.days.colname=NULL, carryover.within.obs.window=NULL, carryover.into.obs.window=NULL, carry.only.for.same.medication=NULL, consider.dosage.change=NULL, followup.window.start=NULL, followup.window.start.unit=NULL, followup.window.duration=NULL, followup.window.duration.unit=NULL, observation.window.start=NULL, observation.window.start.unit=NULL, observation.window.duration=NULL, observation.window.duration.unit=NULL, date.format=NULL, suppress.warnings=NULL, suppress.special.argument.checks=NULL ) { # auxiliary function to compute intersection of episodes (when aggregate.first = TRUE) episodes.intersections <- function(episode.start, episode.end, #.OBS.START.DATE, .OBS.END.DATE, #not used intersect.name = "intersect"){ episode.dates <- sort(unique(c(episode.start,episode.end #, .OBS.START.DATE, .OBS.END.DATE #not used ))) episodes <- data.table(episode.dates[1:(length(episode.dates)-1)], episode.dates[2:length(episode.dates)]) intersect.start.name <- paste0(intersect.name,".start") intersect.end.name <- paste0(intersect.name, ".end") intersect.duration.name <- paste0(intersect.name, ".duration") setnames(episodes, c(intersect.start.name, intersect.end.name)) episodes[,(intersect.duration.name) := as.numeric(get(intersect.end.name) - get(intersect.start.name))] } # auxiliary function to apply thresholds apply.thresholds <- function(x, thresholds, medication.groups){ if(is.list(thresholds)) { medication.groups <- first(medication.groups) if(medication.groups %in% names(thresholds)) { thresholds <- thresholds[[medication.groups]] } else { if( !suppress.warnings ) warning(paste0("No thresholds specified for treatment group '",medication.groups,"'!\n")); return (x); } } # if thresholds is numeric, cut and scale between 0 and 1 if(is.numeric(thresholds)){ breaks <- sort(unique(c(ifelse(min(x, na.rm = TRUE) >= min(thresholds), min(thresholds)+0.00001, 0), thresholds, ifelse(max(x, na.rm = TRUE) <= max(thresholds), max(thresholds)+1, max(x, na.rm = TRUE)) ) ) ) ret <- cut(x, breaks, include.lowest = TRUE, right = FALSE) ret <- as.vector(scale(as.numeric(ret)-1, center = FALSE, scale = nlevels(ret)-1)) } else { if( !suppress.warnings ) warning("Thresholds must be either numeric or a named list of numeric thresholds per treatment group!\n"); return (x); } return(ret) } # cache data and various parameters data.2 <- copy(data) ID.colname.2 <- ID.colname followup.window.start.2 <- followup.window.start followup.window.duration.2 <- followup.window.duration observation.window.start.2 <- observation.window.start observation.window.duration.2 <- observation.window.duration observation.window.duration.unit.2 <- observation.window.duration.unit setnames(data.2, old = .orig.ID.colname, new = "PATIENT_ID") # # Add back the patient and episode IDs: # tmp <- as.data.table(merge(cma$CMA, treat.epi)[,c(ID.colname, "episode.ID", "episode.start", "end.episode.gap.days", "episode.duration", "episode.end", "CMA")]); # setkeyv(tmp, c(ID.colname,"episode.ID")); # When aggregate.first = FALSE if(aggregate.first == FALSE){ # compute CMAs by medication group # CMA_all_by_group <- by(data.2, data.2[["group"]], CMA.FNC, # CMA.to.apply = CMA.to.apply, # ID.colname = ID.colname.2, # event.date.colname = event.date.colname, # event.duration.colname = event.duration.colname, # medication.class.colname = medication.class.colname, # event.daily.dose.colname = event.daily.dose.colname, # followup.window.start=followup.window.start, # followup.window.start.unit=followup.window.start.unit, # followup.window.duration=followup.window.duration, # followup.window.duration.unit=followup.window.duration.unit, # observation.window.start=observation.window.start.2, # observation.window.start.unit=observation.window.start.unit, # observation.window.duration=observation.window.duration.2, # observation.window.duration.unit=observation.window.duration.unit.2, # date.format=date.format,parallel.backend="none") CMA_all_by_group <- CMA.FNC(data.2, ID.colname = ID.colname.2, event.date.colname = event.date.colname, event.duration.colname = event.duration.colname, medication.class.colname = medication.class.colname, event.daily.dose.colname = event.daily.dose.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start.2, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration.2, observation.window.duration.unit=observation.window.duration.unit.2, carry.only.for.same.medication=carry.only.for.same.medication, date.format=date.format,parallel.backend="none", suppress.special.argument.checks=suppress.special.argument.checks) # get CMA values CMA_per_group <- as.data.table(getCMA(CMA_all_by_group)) # merge back original ID and group and sort by original ID CMA_per_group <- merge(unique(data.2[,c(ID.colname, "PATIENT_ID", "group"), with = FALSE]), CMA_per_group, by = ID.colname) setkeyv(CMA_per_group, "PATIENT_ID") # CMA_per_group <- lapply(CMA_all_by_group, FUN = function(x){ # cbind(group = first(x$data[["group"]]), x$CMA) # }) # CMA_per_group <- rbindlist(CMA_per_group) # # setkeyv(CMA_per_group, ID.colname) # construct intermediate CMA object CMA_intermediate <- CMA_per_group[,c("PATIENT_ID", "group", "CMA"), with = FALSE] setkeyv(CMA_intermediate, "PATIENT_ID") # get event information event_info <- as.data.table(CMA_all_by_group$event.info) # event_info <- lapply(CMA_all_by_group, FUN = function(x){ # x$event.info # }) # event_info <- rbindlist(event_info) # merge back original ID and group and sort by original ID # setkeyv(event_info, "PATIENT_ID") # <- DD: I think this is an error, as there's no PATIENT_ID column in this event_info (as it uses ID.colname.2 as patient ID)... # aggregate CMAs CMA <- copy(CMA_per_group) # if thresholds are provided if(length(thresholds) >= 1 && !is.na(thresholds)){ CMA[,CMA := apply.thresholds(CMA, thresholds, as.character(group)), by = group] } CMA[,CMA := do.call(POLY.FNC, c(list(x=CMA), aggregation.method.arguments)), by = c("PATIENT_ID")] CMA <- CMA[,`:=` (group = NULL, .new.ID = NULL)] # construct return object tmp <- list(CMA = unique(CMA), CMA.intermediate = CMA_intermediate, event.info = event_info[,c(ID.colname) := NULL]) return(tmp) } else { # compute CMA if aggregate.first = TRUE # auxiliary function to summarize over time summarize_longitudinal <- function(data, ID){ # if(anyNA(data$prop.trt.groups.available)){ # # if( !suppress.warnings ) warning(paste0("Aggregation of availability returns NA for patient with ID '",first(ID), "' for some intervals, only considering other intervals for final results!\n")); # } #rep(unique(na.omit(data, cols = "prop.trt.groups.available") data[,sum(intersect.duration*prop.trt.groups.available)/.obs.duration] # ), nrow(data)) } # calculate CMA_per_episode with maximum permissible gap of 0 days CMA_full_per_day <- CMA_per_episode(data.2, treat.epi = NULL, maximum.permissible.gap = 0, maximum.permissible.gap.unit = "days", CMA.to.apply = CMA.to.apply, ID.colname = ID.colname.2, event.date.colname = event.date.colname, event.duration.colname = event.duration.colname, medication.class.colname = medication.class.colname, event.daily.dose.colname = event.daily.dose.colname, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start.2, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration.2, observation.window.duration.unit=observation.window.duration.unit.2, carry.only.for.same.medication = carry.only.for.same.medication, date.format=date.format, force.NA.CMA.for.failed.patients = TRUE, suppress.warnings = TRUE, suppress.special.argument.checks=suppress.special.argument.checks ) # select ID.colnames # ifelse(ID.colname == ID.colname.2, ID.colnames <- ID.colname, ID.colnames <- c(ID.colname, ID.colname.2)) # get CMA values CMA_per_day <- as.data.table(getCMA(CMA_full_per_day)) # merge back original ID and group and sort by original ID CMA_per_day <- merge(unique(data.2[,c(ID.colname, "PATIENT_ID", "group"), with = FALSE]), CMA_per_day, by = ID.colname) setkeyv(CMA_per_day, "PATIENT_ID") if(CMA.to.apply == "CMA9") { CMA_per_day[,`:=` (episode.end = episode.end + end.episode.gap.days, CMA = episode.duration / (episode.duration + end.episode.gap.days), episode.duration = episode.duration + end.episode.gap.days ) ] } # get event information event_info <- as.data.table(CMA_full_per_day$event.info) # merge back original ID and group and sort by original ID event_info <- merge(unique(data.2[,c(ID.colname, "PATIENT_ID", "group"), with = FALSE]), event_info, by = ID.colname) setkeyv(event_info, "PATIENT_ID") # merge event_info to CMA_per_day # CMA_per_day <- merge(CMA_per_day, event_info[,c(ID.colname, ".OBS.START.DATE", ".OBS.END.DATE"), with = FALSE], by = c(ID.colname)) #not used # create intersections of availability episodes episodes <- CMA_per_day[,episodes.intersections(episode.start, episode.end, #.OBS.START.DATE, .OBS.END.DATE, # not used "intersect"), by = "PATIENT_ID"] episodes[,intersect.ID := seq_len(.N), by = "PATIENT_ID"] CMA_per_day_intersect <- merge(CMA_per_day[,c("group", "PATIENT_ID", "episode.start", "end.episode.gap.days", "episode.duration", "episode.end", "CMA"), with = FALSE], episodes, by = "PATIENT_ID", allow.cartesian=TRUE) CMA_per_day_intersect <- merge(CMA_per_day_intersect, event_info, by = c("PATIENT_ID", "group")) # CMA_per_day_intersect[,CMA := 0] # set availability to 0 # if intersection is not covered by an episode, set CMA to 0 CMA_per_day_intersect[intersect.start >= episode.end | intersect.end <= episode.start, CMA := 0] # if the OW starts after the end of the intersection or ends before the start of an intersection, set CMA to NA CMA_per_day_intersect[intersect.end <= .OBS.START.DATE | intersect.start >= .OBS.END.DATE, CMA := NA] # keep only one row per intersection CMA <- CMA_per_day_intersect[, list(CMA = max(CMA)), by = c("PATIENT_ID", "group", "intersect.start", "intersect.end", "intersect.ID", "intersect.duration", ".OBS.START.DATE", ".OBS.END.DATE")] # # add number of medication groups per patient # CMA[!is.na(CMA),med.groups := length(unique(medication.groups)), by = c(ID.colname, "intersect.ID")] # aggregate availability of all medication group per patient and intersection CMA[,prop.trt.groups.available := do.call(POLY.FNC, c(list(x=CMA), aggregation.method.arguments)), by = c("PATIENT_ID", "intersect.ID")] CMA_intermediate <- CMA[,c("PATIENT_ID", "group", "intersect.start", "intersect.end", "intersect.ID", "intersect.duration", "CMA", "prop.trt.groups.available"), with = FALSE] CMA_intermediate <- dcast(CMA, PATIENT_ID + intersect.start + intersect.end + intersect.ID + intersect.duration + prop.trt.groups.available ~ group, value.var = "CMA") # if thresholds are provided if(!is.na(thresholds)){ CMA[,prop.trt.groups.available := apply.thresholds(prop.trt.groups.available, thresholds, as.character(group)), by = group] } # select unique episodes per patient CMA[, `:=` (.OBS.START.DATE = min(.OBS.START.DATE), .OBS.END.DATE = max(.OBS.END.DATE)), by = "PATIENT_ID"] CMA <- unique(na.omit(CMA, cols = "CMA"), by = c("PATIENT_ID", "intersect.ID")) # adjust end of last episode and intersect.duration CMA[intersect.end > .OBS.END.DATE, `:=` (intersect.end = .OBS.END.DATE, intersect.duration = as.numeric(.OBS.END.DATE-intersect.start))] # compute total duration of observation CMA[,.obs.duration := as.numeric(.OBS.END.DATE-.OBS.START.DATE), by = c("PATIENT_ID")] # CMA_ret <- switch(as.character(aggregation.method), # "DPPR" = unique(CMA[,list(CMA = sum(intersect.duration*prop.med.groups.available)/.obs.duration), by = c(ID.colname)]), # "any" = unique(CMA[prop.med.groups.available > 0,list(CMA = sum(intersect.duration)/.obs.duration), by = ID.colname]), # "all" = unique(CMA[round(prop.med.groups.available,0) == 1,list(CMA = sum(intersect.duration)/.obs.duration), by = ID.colname])); CMA_ret <- unique(CMA[,list(CMA = summarize_longitudinal(data = .SD, ID = PATIENT_ID)), by = c("PATIENT_ID")]) setnames(CMA_ret, old = "PATIENT_ID", .orig.ID.colname) setnames(CMA_intermediate, old = "PATIENT_ID", .orig.ID.colname) setnames(event_info, old = "PATIENT_ID", .orig.ID.colname) tmp <- list(CMA = CMA_ret, CMA.intermediate = CMA_intermediate, event.info = event_info) return(tmp) } } # Construct the return object: # Convert to data.table, cache event dat as Date objects, and key by patient ID and event date data.copy <- data.table(data); data.copy[, .DATE.as.Date := as.Date(get(event.date.colname),format=date.format)]; # .DATE.as.Date: convert event.date.colname from formatted string to Date # if medication.groups is a named list, merge medication.groups into data if(is.character(medication.groups)){ if(medication.groups %in% names(data.copy)){ med.groups.dt <- unique(data.copy[,c(medication.groups, medication.class.colname), with = FALSE]) if(medication.groups == medication.class.colname){ setnames(med.groups.dt, c("group", medication.class.colname)) data.copy <- merge(data.copy, med.groups.dt, by = medication.class.colname) } else {setnames(data.copy, old = medication.groups, new = "group")} } else { if( !suppress.warnings ) warning(paste0("Column medication.groups = '",medication.groups,"' must appear in the data!\n)")); return (NULL); } # } else if(.check.medication.groups(medication.groups, # list.of.medication.classes = unique(data[[medication.class.colname]]))) # { # # if(is.null(medication.groups)){ # medication.groups <- unique(data[[medication.class.colname]]) # } # # med.groups.dt <- as.data.table(.fill.medication.groups(medication.groups, # list.of.medication.classes = unique(data[[medication.class.colname]]), # already.checked = TRUE)) # # setnames(med.groups.dt, old = "class", new = medication.class.colname) # # data.copy <- merge(data.copy, med.groups.dt, by = medication.class.colname) } else { return (NULL); } # create new ID from Patient ID and medication group data.copy[,.new.ID := paste(get(ID.colname), group, sep = "_")] .orig.ID.colname = ID.colname # Compute the workhorse function: tmp <- .compute.function(.workhorse.function, fnc.ret.vals=3, parallel.backend=parallel.backend, parallel.threads=parallel.threads, data=data.copy, ID.colname=".new.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname=event.interval.colname, gap.days.colname=gap.days.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, suppress.warnings=suppress.warnings, suppress.special.argument.checks=suppress.special.argument.checks); if( is.null(tmp) || is.null(tmp$CMA) || is.null(tmp$event.info) || is.null(tmp$CMA.intermediate)) return (NULL); # Construct the return object: class(ret.val) <- "CMA_polypharmacy"; ret.val$event.info <- as.data.frame(tmp$event.info); ret.val$aggregation.method = aggregation.method; ret.val$computed.CMA <- CMA.to.apply; ret.val$medication.groups <- as.data.frame(med.groups.dt); ret.val$summary <- summary; ret.val$CMA <- as.data.frame(tmp$CMA); ret.val$CMA.intermediate <- as.data.frame(tmp$CMA.intermediate); return (ret.val); } #' @export getCMA.CMA_polypharmacy <- function(x, flatten.medication.groups=FALSE, medication.groups.colname=".MED_GROUP_ID") { cma <- x; # parameter x is required for S3 consistency, but I like cma more if( is.null(cma) || !inherits(cma, "CMA_polypharmacy") || !("CMA" %in% names(cma)) || is.null(cma$CMA) ) return (NULL); return (cma$CMA); } subsetCMA.CMA_polypharmacy <- function(cma, patients, suppress.warnings=FALSE) { if( inherits(patients, "factor") ) patients <- as.character(patients); all.patients <- unique(cma$data[,cma$ID.colname]); patients.to.keep <- intersect(patients, all.patients); if( length(patients.to.keep) == length(all.patients) ) { # Keep all patients: return (cma); } if( length(patients.to.keep) == 0 ) { if( !suppress.warnings ) warning("No patients to subset on!\n"); return (NULL); } if( length(patients.to.keep) < length(patients) && !suppress.warnings ) warning("Some patients in the subsetting set are not in the CMA itsefl and are ignored!\n"); ret.val <- cma; ret.val$data <- ret.val$data[ ret.val$data[,ret.val$ID.colname] %in% patients.to.keep, ]; if( !is.null(ret.val$event.info) ) ret.val$event.info <- ret.val$event.info[ ret.val$event.info[,ret.val$ID.colname] %in% patients.to.keep, ]; if( ("CMA" %in% names(ret.val)) && !is.null(ret.val$CMA) ) ret.val$CMA <- ret.val$CMA[ ret.val$CMA[,ret.val$ID.colname] %in% patients.to.keep, ]; return (ret.val); } # for CMA_per_episode: { # auxiliary function to handle precomputed treatment episodes compute.treat.epi <- function(treat.epi = treat.epi){ # Convert treat.epi to data.table, cache event dat as Date objects, and key by patient ID and event date treat.epi <- as.data.table(treat.epi); treat.epi[, `:=` (episode.start = as.Date(episode.start,format=date.format), episode.end = as.Date(episode.end,format=date.format) )]; # .DATE.as.Date: convert event.date.colname from formatted string to Date setkeyv(treat.epi, c(ID.colname, group, "episode.ID")); # key (and sorting) by patient and episode ID # Compute the real observation windows (might differ per patient) only once per patient (speed things up & the observation window is the same for all events within a patient): tmp <- data[!duplicated(data[,c(ID.colname,group), with = FALSE]),]; # the reduced dataset for computing the actual OW: tmp[,.PATIENT.MED.ID := paste(get(ID.colname),get(group),sep="*")] event.info2 <- compute.event.int.gaps(data=as.data.frame(tmp), ID.colname=".PATIENT.MED.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, event.interval.colname="event.interval", gap.days.colname="gap.days", carryover.within.obs.window=FALSE, carryover.into.obs.window=FALSE, carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, return.data.table=TRUE); if( is.null(event.info2) ) return (NULL); # Merge the observation window start and end dates back into the treatment episodes: treat.epi <- merge(treat.epi, event.info2[,c(ID.colname, "group", ".OBS.START.DATE", ".OBS.END.DATE"),with=FALSE], all.x=TRUE, by = c(ID.colname, "group")); setnames(treat.epi, ncol(treat.epi)-c(1,0), c(".OBS.START.DATE.PRECOMPUTED", ".OBS.END.DATE.PRECOMPUTED")); # Get the intersection between the episode and the observation window: treat.epi[, c(".INTERSECT.EPISODE.OBS.WIN.START", ".INTERSECT.EPISODE.OBS.WIN.END") := list(max(episode.start, .OBS.START.DATE.PRECOMPUTED), min(episode.end, .OBS.END.DATE.PRECOMPUTED)), by=c(ID.colname,"episode.ID", "group")]; treat.epi <- treat.epi[ .INTERSECT.EPISODE.OBS.WIN.START < .INTERSECT.EPISODE.OBS.WIN.END, ]; # keep only the episodes which fall within the OW treat.epi[, c("episode.duration", ".INTERSECT.EPISODE.OBS.WIN.DURATION", ".PATIENT.MED.EPISODE.ID") := list(as.numeric(episode.end - episode.start), as.numeric(.INTERSECT.EPISODE.OBS.WIN.END - .INTERSECT.EPISODE.OBS.WIN.START), paste(get(ID.colname),group,episode.ID,sep="*"))]; # Merge the data and the treatment episodes info: data.epi <- merge(treat.epi, data, allow.cartesian=TRUE); setkeyv(data.epi, c(".PATIENT.MED.EPISODE.ID", ".DATE.as.Date")); # compute end.episode.gap.days data.epi2 <- compute.event.int.gaps(data=as.data.frame(data.epi), ID.colname=".PATIENT.MED.EPISODE.ID", event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start="episode.start", followup.window.start.unit=followup.window.start.unit, followup.window.duration="episode.duration", followup.window.duration.unit=followup.window.duration.unit, observation.window.start=".INTERSECT.EPISODE.OBS.WIN.START", observation.window.duration=".INTERSECT.EPISODE.OBS.WIN.DURATION", observation.window.duration.unit="days", date.format=date.format, keep.window.start.end.dates=TRUE, remove.events.outside.followup.window=FALSE, parallel.backend="none", # make sure this runs sequentially! parallel.threads=1, suppress.warnings=suppress.warnings, return.data.table=TRUE); episode.gap.days <- data.epi2[which(.EVENT.WITHIN.FU.WINDOW), c(ID.colname, medication.group, "episode.ID", "gap.days"), by = c(ID.colname, "episode.ID", "group"), with = FALSE]; # gap days during the follow-up window end.episode.gap.days <- episode.gap.days[,list(end.episode.gap.days = last(gap.days)), by = c(ID.colname, "episode.ID", "group")]; # gap days during the last event treat.epi <- merge(treat.epi, end.episode.gap.days, all.x = TRUE, by = c(ID.colname, "episode.ID", "group")); # merge end.episode.gap.days back to data.epi treat.epi[, episode.duration := as.numeric(.INTERSECT.EPISODE.OBS.WIN.END-.INTERSECT.EPISODE.OBS.WIN.START)]; data.epi.ret <- data.epi[, c(ID.colname, "groups", event.date.colname, event.duration.colname, event.daily.dose.colname, medication.class.colname, "episode.start", "episode.duration", ".PATIENT.MED.EPISODE.ID", ".INTERSECT.EPISODE.OBS.WIN.START", ".INTERSECT.EPISODE.OBS.WIN.DURATION", ".INTERSECT.EPISODE.OBS.WIN.END"), with = FALSE] setnames(data.epi.ret, old = c("episode.start", "episode.duration", ".INTERSECT.EPISODE.OBS.WIN.START", ".INTERSECT.EPISODE.OBS.WIN.DURATION", ".INTERSECT.EPISODE.OBS.WIN.END"), new = c("med.episode.start", "med.episode.duration", ".MED.INTERSECT.EPISODE.OBS.WIN.START", ".MED.INTERSECT.EPISODE.OBS.WIN.DURATION", ".MED.INTERSECT.EPISODE.OBS.WIN.END")) treat.epi.ret <- treat.epi[,c(ID.colname, ".PATIENT.MED.EPISODE.ID", "group", "episode.ID", "episode.start", "episode.end", "episode.duration", "end.episode.gap.days"), with = FALSE] # construct return object ret <- list(data.epi = data.epi.ret, treat.epi = treat.epi.ret) return(ret) } }
/scratch/gouwar.j/cran-all/cranData/AdhereR/R/polypharmacy.R
## ---- echo=FALSE, message=FALSE, warning=FALSE, results='hide'---------------- # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ## ---- echo=TRUE, results='asis'----------------------------------------------- # Load the AdhereR library: library(AdhereR); # Select the two patients with IDs 37 and 76 from the built-in dataset "med.events": ExamplePats <- med.events[med.events$PATIENT_ID %in% c(37, 76), ]; # Display them as pretty markdown table: knitr::kable(ExamplePats, caption = "<a name=\"Table-1\"></a>**Table 1.** Medication events for two example patients"); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1\"></a>**Figure 1.** Medication histories - two example patients", fig.height=6, fig.width=8, out.width="100%"---- # Create an object "cma0" of the most basic CMA type, "CMA0": cma0 <- CMA0(data=ExamplePats, # use the two selected patients ID.colname="PATIENT_ID", # the name of the column containing the IDs event.date.colname="DATE", # the name of the column containing the event date event.duration.colname="DURATION", # the name of the column containing the duration event.daily.dose.colname="PERDAY", # the name of the column containing the dosage medication.class.colname="CATEGORY", # the name of the column containing the category followup.window.start=0, # FUW start in days since earliest event observation.window.start=182, # OW start in days since earliest event observation.window.duration=365, # OW duration in days date.format="%m/%d/%Y"); # date format (mm/dd/yyyy) # Plot the object (CMA0 shows the actual event data only): plot(cma0, # the object to plot align.all.patients=TRUE); # align all patients for easier comparison ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 1 (a).** Same plot as in **Figure 1**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"---- # Same plot as above but also showing the daily doses: plot(cma0, # the object to plot print.dose=TRUE, plot.dose=TRUE, align.all.patients=TRUE); # align all patients for easier comparison ## ---- echo=TRUE, results='asis'----------------------------------------------- # Compute the treatment episodes for the two patients: TEs3<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, # carry-over into the OW carry.only.for.same.medication = TRUE, # & only for same type consider.dosage.change = TRUE, # dosage change starts new episode... medication.change.means.new.treatment.episode = TRUE, # & type change maximum.permissible.gap = 180, # & a gap longer than 180 days maximum.permissible.gap.unit = "days", # unit for the above (days) followup.window.start = 0, # 2-years FUW starts at earliest event followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); knitr::kable(TEs3, caption = "<a name=\"Table-2\"></a>**Table 2.** Example output `compute.treatment.episodes()` function"); ## ---- echo=TRUE, results='asis'----------------------------------------------- # Compute the treatment episodes for the two patients # but now a change in medication type does not start a new episode: TEs4<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = TRUE, consider.dosage.change = TRUE, medication.change.means.new.treatment.episode = FALSE, # here maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start = 0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); # Pretty print the events: knitr::kable(TEs4, caption = "<a name=\"Table-3\"></a>**Table 3.** Alternative scenario output `compute.treatment.episodes()` function"); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-2\"></a>**Figure 2.** Simple CMA 1", fig.height=5, fig.width=7, out.width="100%"---- # Create the CMA1 object with the given parameters: cma1 <- CMA1(data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); # Display the summary: cma1 # Display the estimated CMA table: cma1$CMA # and equivalently using an accessor function: getCMA(cma1); # Compute the CMA value for patient 76, as percentage rounded at 2 digits: round(cma1$CMA[cma1$CMA$PATIENT_ID== 76, 2]*100, 2) # Plot the CMA: # The legend shows the actual duration, the days covered and gap days, # the drug (medication) type, the FUW and OW, and the estimated CMA. plot(cma1, patients.to.plot=c("76"), # plot only patient 76 legend.x=520); # place the legend in a nice way ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-3\"></a>**Figure 3.** Simple CMA 2", fig.height=5, fig.width=7, out.width="100%"---- cma2 <- CMA2(data=ExamplePats, # we're estimating CMA2 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma2, patients.to.plot=c("76"), show.legend=FALSE); # don't show legend to avoid clutter (see above) ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-4\"></a>**Figure 4.** Simple CMA 3", fig.height=5, fig.width=7, out.width="100%"---- cma3 <- CMA3(data=ExamplePats, # we're estimating CMA3 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma3, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-5\"></a>**Figure 5.** Simple CMA 4", fig.height=5, fig.width=7, out.width="100%"---- cma4 <- CMA4(data=ExamplePats, # we're estimating CMA4 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma4,patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-6\"></a>**Figure 6.** Simple CMA 5", fig.height=5, fig.width=7, out.width="100%"---- cma5 <- CMA5(data=ExamplePats, # we're estimating CMA5 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, # carry-over across medication types consider.dosage.change=FALSE, # don't consider canges in dosage followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma5,patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-7\"></a>**Figure 7.** Simple CMA 6", fig.height=5, fig.width=7, out.width="100%"---- cma6 <- CMA6(data=ExamplePats, # we're estimating CMA6 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma6,patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 7 (a).** Same plot as in **Figure 7**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"---- # Same plot as above but also showing the daily doses: plot(cma6, # the object to plot patients.to.plot=c("76"), # plot only patient 76 print.dose=TRUE, plot.dose=TRUE, legend.x=520); # place the legend in a nice way ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-8\"></a>**Figure 8.** Simple CMA 7", fig.height=5, fig.width=7, out.width="100%"---- cma7 <- CMA7(data=ExamplePats, # we're estimating CMA7 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma7, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-9\"></a>**Figure 9.** Simple CMA 8", fig.height=5, fig.width=7, out.width="100%"---- cma8 <- CMA8(data=ExamplePats, # we're estimating CMA8 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=374, observation.window.duration=294, date.format="%m/%d/%Y"); plot(cma8, patients.to.plot=c("76"), show.legend=FALSE); # The value for patient 76, rounded at 2 digits round(cma8$CMA[cma8$CMA$PATIENT_ID== 76, 2]*100, 2); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-10\"></a>**Figure 10.** Simple CMA 9", fig.height=5, fig.width=7, out.width="100%"---- cma9 <- CMA9(data=ExamplePats, # we're estimating CMA9 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma9, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-11\"></a>**Figure 11.** CMA 9 per episode", fig.height=5, fig.width=7, out.width="100%", warning=FALSE---- cmaE <- CMA_per_episode(CMA="CMA9", # apply the simple CMA9 to each treatment episode data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = FALSE, consider.dosage.change = FALSE, # conditions on treatment episodes medication.change.means.new.treatment.episode = TRUE, maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start=0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", observation.window.start=0, observation.window.start.unit = "days", observation.window.duration=365*2, observation.window.duration.unit = "days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaE; # The CMA estimates table: cmaE$CMA getCMA(cmaE); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits: round(cmaE$CMA[cmaE$CMA$PATIENT_ID== 76, 7]*100, 2); # Plot: plot(cmaE, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-12\"></a>**Figure 12.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"---- cmaW <- CMA_sliding_window(CMA.to.apply="CMA9", # apply the simple CMA9 to each sliding window data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # sliding windows definition sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=120, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaW; # The CMA estimates table: cmaW$CMA getCMA(cmaW); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits round(cmaW$CMA[cmaW$CMA$PATIENT_ID== 76, 5]*100, 2); # Plot: plot(cmaW, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-13\"></a>**Figure 13.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"---- cmaW1 <- CMA_sliding_window(CMA.to.apply="CMA9", data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # different sliding windows sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=30, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Plot: plot(cmaW1, patients.to.plot=c("76"), show.legend=FALSE); ## ---- echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-14\"></a>**Figure 14.** Per episodes with CMA 1, showing which events belong to which episode: for events, the number(s) between '[]' represent the event they belong to, while for an event, the number between '[]' is what the events use as its identifier. (e.g., the 3rd even from the left for patient 1 has a '[2]', meaning that it belongs to event '2', which is identified as such with a '[2]' immediately after is estimated CMA of '136%'). Please note that the same plot for CMA9 would be quite different, as the rules for which events are considered differ (e.g., the last events of the episodes would be included).", fig.height=7, fig.width=7, out.width="100%"---- cmaE <- CMA_per_episode(CMA="CMA1", data=med.events[med.events$PATIENT_ID %in% 1:2,], ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=-90, observation.window.start=0, observation.window.duration=365, maximum.permissible.gap=10, return.mapping.events.episodes=TRUE, # ask for the mapping medication.change.means.new.treatment.episode=TRUE, date.format="%m/%d/%Y"); getEventsToEpisodesMapping(cmaE); # get the mapping (here, print it) plot(cmaE, align.all.patients=TRUE, print.dose.centered=TRUE, print.episode.or.sliding.window=TRUE); # show the mapping visually ## ---- echo=FALSE-------------------------------------------------------------- knitr::kable(head(med.events.ATC, n=5), row.names=FALSE, caption="First 5 lines of the `med.events.ATC` dataset."); ## ---- eval=FALSE-------------------------------------------------------------- # event_durations <- compute_event_durations(disp.data = durcomp.dispensing, # presc.data = durcomp.prescribing, # special.periods.data = durcomp.hospitalisation, # ID.colname = "ID", # presc.date.colname = "DATE.PRESC", # disp.date.colname = "DATE.DISP", # medication.class.colnames = c("ATC.CODE", "UNIT", "FORM"), # total.dose.colname = "TOTAL.DOSE", # presc.daily.dose.colname = "DAILY.DOSE", # presc.duration.colname = "PRESC.DURATION", # visit.colname = "VISIT", # split.on.dosage.change = TRUE, # force.init.presc = TRUE, # force.presc.renew = TRUE, # trt.interruption = "continue", # special.periods.method = "continue", # date.format = "%Y-%m-%d", # suppress.warnings = FALSE, # return.data.table = FALSE); # med.events.ATC <- event_durations$event_durations[ !is.na(event_durations$event_durations$DURATION) & # event_durations$event_durations$DURATION > 0, # c("ID", "DISP.START", "DURATION", "DAILY.DOSE", "ATC.CODE")]; # names(med.events.ATC) <- c("PATIENT_ID", "DATE", "DURATION", "PERDAY", "CATEGORY"); # # Groups from the ATC codes: # sort(unique(med.events.ATC$CATEGORY)); # all the ATC codes in the data # # Level 1: # med.events.ATC$CATEGORY_L1 <- vapply(substr(med.events.ATC$CATEGORY,1,1), switch, character(1), # "A"="ALIMENTARY TRACT AND METABOLISM", # "B"="BLOOD AND BLOOD FORMING ORGANS", # "J"="ANTIINFECTIVES FOR SYSTEMIC USE", # "R"="RESPIRATORY SYSTEM", # "OTHER"); # # Level 2: # med.events.ATC$CATEGORY_L2 <- vapply(substr(med.events.ATC$CATEGORY,1,3), switch, character(1), # "A02"="DRUGS FOR ACID RELATED DISORDERS", # "A05"="BILE AND LIVER THERAPY", # "A09"="DIGESTIVES, INCL. ENZYMES", # "A10"="DRUGS USED IN DIABETES", # "A11"="VITAMINS", # "A12"="MINERAL SUPPLEMENTS", # "B02"="ANTIHEMORRHAGICS", # "J01"="ANTIBACTERIALS FOR SYSTEMIC USE", # "J02"="ANTIMYCOTICS FOR SYSTEMIC USE", # "R03"="DRUGS FOR OBSTRUCTIVE AIRWAY DISEASES", # "R05"="COUGH AND COLD PREPARATIONS", # "OTHER"); ## ----eval=FALSE--------------------------------------------------------------- # med.groups <- c("Vitamins" = "(CATEGORY_L2 == 'VITAMINS')", # "VitaResp" = "({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')", # "VitaShort" = "({Vitamins} & DURATION <= 30)", # "VitELow" = "(CATEGORY == 'A11HA03' & PERDAY <= 500)", # "VitaComb" = "({VitaShort} | {VitELow})", # "NotVita" = "(!{Vitamins})"); ## ---- echo=FALSE-------------------------------------------------------------- knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *Vitamins* medication group."); ## ---- echo=FALSE-------------------------------------------------------------- knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS' | med.events.ATC$CATEGORY_L1 == 'RESPIRATORY SYSTEM',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *VitaResp* medication group."); ## ----------------------------------------------------------------------------- cma1_mg <- CMA1(data=med.events.ATC, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", medication.groups=med.groups, followup.window.start=0, observation.window.start=0, observation.window.duration=365, date.format="%m/%d/%Y"); cma1_mg; # print it ## ----echo=FALSE--------------------------------------------------------------- getMGs(cma1_mg)$def; ## ----echo=FALSE--------------------------------------------------------------- head(getMGs(cma1_mg)$obs, n=10); ## ----------------------------------------------------------------------------- getCMA(cma1_mg); ## ----------------------------------------------------------------------------- getCMA(cma1_mg, flatten.medication.groups=TRUE); ## ----echo=TRUE, message=FALSE, warning=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-15\"></a>**Figure 15.** CMA 1 with medication groups.", fig.height=9, fig.width=9, out.width="100%"---- plot(cma1_mg, #medication.groups.to.plot=c("VitaResp", "VitaShort", "VitaComb"), patients.to.plot=1:3, show.legend=FALSE); ## ----eval=FALSE--------------------------------------------------------------- # cma0_types <- CMA0(data=med.events.ATC, # ID.colname="PATIENT_ID", # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # medication.groups="CATEGORY_L1", # #flatten.medication.groups=TRUE, # #followup.window.start.per.medication.group=TRUE, # followup.window.start=0, # observation.window.start=0, # observation.window.duration=365, # date.format="%m/%d/%Y"); ## ----echo=FALSE--------------------------------------------------------------- tmp <- sort(unique(med.events.ATC$CATEGORY_L1)); cat(paste0("c(", paste0('"',tmp,'"',' = "(CATEGORY_L1 == \'',tmp,'\')"',collapse=",\n "), ");")); ## ----eval=FALSE--------------------------------------------------------------- # library(dplyr); # # # Compute, then get the CMA, change it and print it: # x <- med.events %>% # use med.events # filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients # CMA9(ID.colname="PATIENT_ID", # compute CMA9 # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # followup.window.start=230, # followup.window.duration=705, # observation.window.start=41, # observation.window.duration=100, # date.format="%m/%d/%Y") %>% # getCMA() %>% # get the CMA estimates # mutate(CMA=sprintf("%.1f%%",100*CMA)); # make them percents # print(x); # print it # # # Plot some CMAs: # med.events %>% # use med.events # filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients # CMA_sliding_window(CMA.to.apply="CMA7", # sliding windows CMA7 # ID.colname="PATIENT_ID", # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # followup.window.start=230, # followup.window.duration=705, # observation.window.start=41, # observation.window.duration=100, # date.format="%m/%d/%Y") %>% # plot(align.all.patients=TRUE, show.legend=TRUE); # plot it ## ----echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-16\"></a>**Figure 16.** Modifying an `AdhereR` plot is easy using the `get.plotted.events()` function.", fig.height=8, fig.width=8, out.width="100%"---- # Plot CMA7 for patients 5 and 8: cma7 <- CMA7(data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=30, observation.window.start=30, observation.window.duration=365, date.format="%m/%d/%Y" ); plot(cma7, patients.to.plot=c(5,8), show.legend=TRUE); # good plot after an error plot # Access the plotting info: pevs <- get.plotted.events(); # get the plotted events with their plotting info # Let's add a vertical line for patient 8 between the medication change: # Find the event where the medication changes: i <- which(pevs$PATIENT_ID == "8" & pevs$CATEGORY != c(pevs$CATEGORY[-1], pevs$CATEGORY[nrow(pevs)])); # Half-way between the events where medication changes: x <- (pevs$.X.END[i] + pevs$.X.START[i+1])/2; # Draw the line: segments(x, pevs$.Y.OW.START[i], x, pevs$.Y.OW.END[i], col="blue", lty="solid", lwd=3); # Put a star * next to the 4th event of patient 5: # Find the event: i <- which(pevs$PATIENT_ID == "5")[4]; # Plot the star: text(pevs$.X.START[i]-strwidth("* "), pevs$.Y.START[i], "*", cex=3.0, col="darkgreen"); # Add some random text over the figure: text((pevs$.X.FUW.START[1] + pevs$.X.FUW.END[1])/2, # X center of patient 5's FUW (pevs$.Y.FUW.START[nrow(pevs)] + pevs$.Y.FUW.END[nrow(pevs)])/2, # Y center of 8's FUW "Change with care!!!", srt=45, cex=1.5, col="darkred") ## ----eval=FALSE--------------------------------------------------------------- # cmaW3 <- CMA_sliding_window(CMA="CMA1", # data=med.events, # ID.colname="PATIENT_ID", # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # carry.only.for.same.medication=FALSE, # consider.dosage.change=FALSE, # sliding.window.duration=30, # sliding.window.step.duration=30, # parallel.backend="snow", # make clear we want to use snow # parallel.threads=c(rep( # list(list(host="user@workhorse", # host (and user) # rscript="/usr/local/bin/Rscript", # Rscript location # snowlib="/usr/local/lib64/R/library/") # snow package location # ), # 2))) # two remote threads
/scratch/gouwar.j/cran-all/cranData/AdhereR/inst/doc/AdhereR-overview.R
--- title: "AdhereR: Adherence to Medications" author: "Alexandra L. Dima, Dan Dediu & Samuel Allemann" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: yes toc_depth: 4 fig_caption: yes vignette: > %\VignetteEncoding{UTF-8} %\VignetteIndexEntry{AdhereR: Adherence to Medications} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` Estimating the *adherence to medications* from *electronic healthcare data* (EHD) has been central to research and clinical practice across clinical conditions. For example, large retrospective database studies may estimate the prevalence of non-adherence in specific patient groups and model its potential predictors and impact on health outcomes, while clinicians may have access to individual patient records that flag up possible non-adherence for further clinical investigation and intervention. Yet, adherence measurement is a matter of controversy. Many methodological studies show that the same data can generate different prevalence estimates under different parametrisations ([Greevy *et al.*, 2011](#Ref-Greevy2011); [Gardarsdottir *et al.*, 2010](#Ref-Gardarsdottir2010); [Souverein *et al.*, *in press*](#Ref-SouvereinInPress); [Vollmer *et al.*, 2012](#Ref-Vollmer2012); [Van Wijk *et al.*, 2006](#Ref-VanWijk2006)). These parametrisation choices are usually not transparently reported in published empirical studies, and adherence algorithms are either developed ad-hoc or for proprietary software. This lack of transparency and standardization has been one of the main methodological barriers against the development of a solid evidence base on adherence from EHD, and may lead to misinformed clinical decisions. Here we describe `AdhereR`, an R package that aims to facilitate the computing of adherence from EHD, as well as the transparent reporting of the chosen calculations. It contains a set of `R` `S3` *classes* and *functions* that *compute*, *summarize* and *plot* various estimates of adherence. A hypothetical dataset of medication events is included for demonstration and testing purposes. In this vignette, we start by defining the terms used in `AdhereR`. We then use medication records of two patients in the included dataset to illustrate the various decisions required and their impact on estimates, starting with the visualization of medication events, computation of persistence (treatment episode length), and computation of adherence (9 functions available in 3 versions: simple, per-treatment-episode, and sliding-window). Visualizations for each function are illustrated, and the interactive visualization function is presented. While we tested the package relatively extensively, we cannot guarantee that bugs and errors do not exist, and we encourage the users to contact us with suggestions, bug reports, comments (or even just to share their experiences using the package) either by e-mail (to Dan <[email protected]> or Alexandra <[email protected]>) or using GitHub's reporting mechanism at our repository <https://github.com/ddediu/AdhereR>, which contains the full source code of the package (including this vignette). ## Definitions <a name="Section-definitions"></a> Adherence to medications is described as a process consisting of 3 successive elements/stages: *initiation*, *implementation*, and *discontinuation* [(Vrijens et al., 2012)](#Ref-Vrijens2012). After initiating treatment (first medication intake), a patient would continue with implementing the regimen for a time period, ideally equal to the recommended time necessary for achieving therapeutic benefits; the quality of implementation is commonly labelled *adherence* and broadly operationalized as a *ratio of medication quantity used versus prescribed in a time period*. If patients discontinue medication earlier than the recommended time period, the period before discontinuation is described as *persistence*, in contrast to the following period of *non-persistence*. The ideal measurement of this process would record the prescription moment and every medication intake with an exact time-stamp. This would allow, for example, to describe adherence to a twice-daily medication prescribed for 1 year in maximum detail: how long was the delay between prescription and the moment of the first medication intake, whether each of the two prescribed administrations per day corresponded to an intake event and at what time, how much medication was taken versus prescribed on any time interval while the patient persisted with treatment, any specific implementation patterns (e.g. missing or delaying the first daily dose), and when exactly the last medication intake event took place during that year. While this level of detail can be obtained by careful use of *electronic monitoring devices*, electronic healthcare data usually include much less information. *Administrative claims* or *pharmacy databases* record *medication dispensation events*, including patient identifier, date of event, type of medication, and quantity dispensed, and less frequently daily dosage recommended. The same information may be available for prescription events in *electronic medical records* used in health care organizations (e.g primary care practices, secondary care centers). In between two dispensing or prescribing events, we don't know whether and how medication has been used. What we do know is that, if taken as prescribed, the medication supplied at the first event would have lasted a number of days. If the time interval between the two events is longer than this number it is likely that the patient ran out of medication before re-supplying or used less during that time. If the interval is substantially longer or there is no second event, then the patient has probably finished the supply at some point and then discontinued medication. Thus, EHD-based algorithms estimate medication adherence and persistence based on the availability of current supply, under four main assumptions: - the regimen requires the use of a fixed daily dosage of medication (if medication is to be taken as needed, a ratio cannot be computed) - all medication supplied for that patient in that period of time is recorded and the patient does not use medication from other sources (if the patient uses other medication, adherence and/or persistence will be underestimated) - the medication supplied is used by the patient it has been supplied for (if other persons use the medication, adherence and/or persistence will be overestimated) - medication is supposed to be supplied at least two times during that period (if all medication is supplied once at the beginning of the treatment, there are no differences between patients regarding the supply patterns and all patients would be 100% covered for the whole treatment period) (Several other assumptions apply to individual algorithms, and will be discussed later.) `AdhereR` was developed to compute adherence and persistence estimates from EHD based on the principles described above. The current version is based on a single data source, therefore an algorithm for initiation (time interval between first prescription and first dispensing event) is not implemented (it is a time difference calculation easy to implement in with basic R functions). The following terms and definitions are used: - *Adherence* (*implementation*) = the extent to which a patient's medication use corresponds to prescribed use, - *CMA* = continuous multiple-interval measures of medication availability/gaps, representing various indicators of the quality of implementation, - *Medication event* = prescribing or dispensing record of a given medication for a given patient; usually includes the patient's unique identifier, an event date, and a duration, - *Duration* = number of days the quantity of supplied medication would last if used as recommended, - *Quantity* = number of doses supplied at a medication event, - *Daily dosage* = number of doses recommended to be taken daily, - *Medication type* = classification performed by the researcher depending on study aims, e.g. based on therapeutic use, mechanism of action, chemical molecule or pharmaceutical formulation, - *Follow-up window* (FUW) = the total period for which relevant medication events are recorded for included patients, - *Observation window* (OW) = the period within the FUW for which adherence or persistence is computed, - *Persistence* = the length of time during which the patient continues to use medication, before discontinuing for a time period longer than a pre-specified permissible gap, - *Treatment episode* = a period of active medication use, represented by the number of consecutive days between a first medication supply event and the moment when the supply of the last medication event was finished (in a row of consecutive medication events where the interval between any two consecutive events is lower than the duration of the first plus a researcher-defined permissible gap), - *Permissible gap* = a researcher-defined value representing the maximum number of days between the end of the supply from one medication event and the start of the following one that can be considered as continuous medication use. ## Data preparation and example dataset `AdhereR` requires a dataset of medication events over a FUW of sufficient length in relation to the recommended treatment duration. To our knowledge, no research has been performed to date on the relationship between FUW length and recommended treatment duration. `AdhereR` offers the opportunity for answering such methodological questions, but we would hypothesize that the FUW duration also depends on the duration of medication events (shorter durations would allow shorter FUW windows to be informative). The minimum necessary dataset includes 3 variables for each medication event: *patient unique identifier*, *event date*, and *duration*. *Daily dosage* and *medication type* are optional.`AdhereR` is thus designed to use datasets that have already been extracted from EHD and prepared for calculation. These preliminary steps depend to a large extent on the specific database used and the type of medication and research design. Several general guidelines can be consulted ([Arnet *et al.*, 2016](#Ref-Arnet2016); [Peterson *et al.*, 2007](#Ref-Peterson2007)), as well as database-specific documentation. In essence, these steps should entail: - selecting medication events applicable to the research question based on relevant time intervals and medication codes, - coding medication type depending on clinical considerations, for example coding different therapeutic classes in polypharmacy studies, - checking plausible values and correcting any deviations, - handling missing data. For demonstration purposes, we included in `AdhereR` a hypothetical dataset of 1080 medication events from 100 patients in a 2-year FUW. Five variables are included in this dataset: - patient unique identifier (`PATIENT_ID`), - event date (`DATE`; from 6 July 2030 to 3 September 2044, in the "mm/dd/yyyy" format), - daily dosage (`PERDAY`; median 4, range 2-20 doses per day), - medication type (`CATEGORY`; 50.8% medA and 49.2% medB), and - duration (`DURATION`; median 50, range 20-150 days). [Table 1](#Table-1) shows the medication events of two example patients: 19 medication events related to two medication types (`medA` and `medB`). They were selected to represent two different medication histories. Patient `37` had a stable daily dosage but event duration changes with medication change. Patient `76` had a more variable pattern, including medication, daily dosage and duration changes. ```{r, echo=TRUE, results='asis'} # Load the AdhereR library: library(AdhereR); # Select the two patients with IDs 37 and 76 from the built-in dataset "med.events": ExamplePats <- med.events[med.events$PATIENT_ID %in% c(37, 76), ]; # Display them as pretty markdown table: knitr::kable(ExamplePats, caption = "<a name=\"Table-1\"></a>**Table 1.** Medication events for two example patients"); ``` ## Visualization of patient records A first step towards deciding which algorithm is appropriate for these data is to explore medication histories visually. We do this by creating an object of type `CMA0` for the two example patients, and plotting it. This type of plots can of course be created for a much bigger subsample of patients and saved as as a `JPEG`, `PNG`, `TIFF`, `EPS` or `PDF` file using `R`'s plotting system for data exploration. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1\"></a>**Figure 1.** Medication histories - two example patients", fig.height=6, fig.width=8, out.width="100%"} # Create an object "cma0" of the most basic CMA type, "CMA0": cma0 <- CMA0(data=ExamplePats, # use the two selected patients ID.colname="PATIENT_ID", # the name of the column containing the IDs event.date.colname="DATE", # the name of the column containing the event date event.duration.colname="DURATION", # the name of the column containing the duration event.daily.dose.colname="PERDAY", # the name of the column containing the dosage medication.class.colname="CATEGORY", # the name of the column containing the category followup.window.start=0, # FUW start in days since earliest event observation.window.start=182, # OW start in days since earliest event observation.window.duration=365, # OW duration in days date.format="%m/%d/%Y"); # date format (mm/dd/yyyy) # Plot the object (CMA0 shows the actual event data only): plot(cma0, # the object to plot align.all.patients=TRUE); # align all patients for easier comparison ``` We can see that patient `76` had an interruption of more than 100 days between the second and third `medB` supply and several situations of new supply acquired while the previous supply was not exhausted. Patient `37` had shorter gaps between consecutive events, but very little overlap in supplies. For patient `76`, the switch to `medB` happened while the `medA` supply was still available, then a switch back to `medA` happened later, at the end of the second year. For patient `37`, there was a single medication switch (to `medB`) without an overlap at that point. Sometimes it is useful to also see the daily dose: ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 1 (a).** Same plot as in **Figure 1**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"} # Same plot as above but also showing the daily doses: plot(cma0, # the object to plot print.dose=TRUE, plot.dose=TRUE, align.all.patients=TRUE); # align all patients for easier comparison ``` These observations highlight several decision points in calculating persistence and adherence, which need to be informed by the clinical context of the study: - what OW is relevant for calculating adherence and persistence? Both patients have been on treatment during the 2 years, they had a substantial number of events of relatively short duration, and variable delays between the end of a supply and the next event. Thus, their adherence might have oscillated substantially during this period. We could compute adherence and/or persistence for the full 2-year period, or consider shorter intervals; - is the largest interruption seen in patient `76` an indication of non-persistence, or of lower adherence over that time interval? If the medication is likely to be used rarely despite daily use recommendations, such an interval might indicate a period of low adherence. If usual adherence rates are close to 100% when used, that delay is likely to indicate a treatment gap and needs to be treated as such, and the last 2 events as reinitiation of treatment (new treatment episode); - is the switch from `medA` to `medB` an indicator of a new treatment episode? If `medA` and `medB` are two alternative formulations of the same chemical molecule, there might be clinical arguments for considering them as part of the same treatment episode (e.g. the pharmacist provided an alternative option to a product unavailable at the moment). If they are two distinct drug classes with different mechanisms of action and recommendations of use, it may be more appropriate to consider that patient `76` has had 3 treatment episodes and patient `37` one episode; - is it necessary to consider carry-over of oversupply from previous events? For patient `37` this seems to matter very little, as there is little overlap between event durations, but patient `76` has substantial overlaps. If available medication is not likely to be either overused or discarded at every new medication event, it is important to control for carry-over; - it is necessary to consider carry-over also when medication changes? Patient `76` has changed from `medA` to `medB` while still having a large supply of `medA` available. Was the patient more likely to discard the remaining `medA` the moment of receiving `medB` or finish it before starting the `medB` supply? If they are two alternative formulations and `medB` was (for example) given because `medA` was not in stock at the moment, probably this came with a recommendation to finish the available supply. If they are two distinct drug classes and the switch happens usually after assessment of therapeutic versus side effects, probably this came with a recommendation to stop using `medA`. These decisions therefore need to be taken based on a good understanding of the pharmacological properties of the medication studied, and the most plausible clinical decision-making in routine care. This information can be collected from an advisory committee with relevant expertise (e.g. based on consensus protocols), or (even better) qualitative or survey research on the routine practices in prescribing, dispensing and using that specific medication. Of course, this is not always possible -- a second-best option (or even complementary option, if consensus is not reached) is to compare systematically the effects of different analysis choices on the hypotheses tested (e.g. as sensitivity analyses). ## Persistence -- treatment episodes An essential first decision is to distinguish between persistence with treatment and quality of implementation (once the patient started treatment -- which, as explained above, is assumed in situations when we have only one data source of prescribing or dispensing events). The function `compute.treatment.episodes()` was developed for this purpose. We provide below an example of how this function can be used. Let's imagine that `medA` and `medB` are two different types of medication, and clinicians in our advisory committee agree that whenever a health care professional changes the type of medication supplied this should be considered as a new treatment episode; we will specify this as setting the parameter `medication.change.means.new.treatment.episode` to `TRUE`. They also agree that a minumum of 6 months (180 days) need to pass after the end of a medication supply (taken as prescribed) without receiving a new supply in order to be reasonably confident that the patient has discontinued/interrupted the treatment -- they can conclude this for example based on an approximate calculation considering that specific medication is usually supplied for 1-2 months, daily dosage is usually 2 to 4 pills a day, and patients often use as low as 1/4 of the recommended dose in a given interval. We will specify this as `maximum.permissible.gap = 180`, and `maximum.permissible.gap.unit = "days"`. (If in another scenario the clinical information we obtain suggests that the permissible gap should depend on the duration of the last supply, for example 6 times that interval should go by before a discontinuation becoming likely, we can specify this as `maximum.permissible.gap = 600`, and `maximum.permissible.gap.unit = "percent"`.) We might also have some clinical confirmation that usually people finish existing supply before starting the new one (`carryover.within.obs.window = TRUE`), but of course only for the same medication if `medA` and `medB` are supplied with a recommendation to start a new treatment immediately (`carry.only.for.same.medication = TRUE`), take the existing supply based on the new dosage recommendations if these change (`consider.dosage.change = TRUE`). The rest of the parameters specify the name of the dataset (here `ExamplePats`), names of the variables in the dataset (here based on the demo dataset, described above), and the FUW (here the whole 2-year window). ```{r, echo=TRUE, results='asis'} # Compute the treatment episodes for the two patients: TEs3<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, # carry-over into the OW carry.only.for.same.medication = TRUE, # & only for same type consider.dosage.change = TRUE, # dosage change starts new episode... medication.change.means.new.treatment.episode = TRUE, # & type change maximum.permissible.gap = 180, # & a gap longer than 180 days maximum.permissible.gap.unit = "days", # unit for the above (days) followup.window.start = 0, # 2-years FUW starts at earliest event followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); knitr::kable(TEs3, caption = "<a name=\"Table-2\"></a>**Table 2.** Example output `compute.treatment.episodes()` function"); ``` The function produces a dataset as the one shown in [Table 2](#Table-2). It includes each treatment episode for each patient (here 2 episodes for patient `37` and 3 for patient `76`) and records the patient ID, episode number, date of episode start, gap days at the end of or after the treatment episode, duration of episode, and episode end date: - the date of the episode start is taken as the first medication event for a particular medication, - the end of the episode is taken as the day when the last supply of that medication finished (if a medication change happened, or if a period longer than the permissible gap preceded the next medication event) or the end of the FUW (if no other medication event followed until the end of the FUW), - the number of end episode gap days represents either the number of days **after** the end of the treatment episode (if medication changed, or if a period longer than the permissible gap preceded the next medication event) or **at** the end of (and within) the episode, i.e. the number of days after the last supply finished (if no other medication event followed until the end of the FUW), - the duration of the episode is the interval between the episode start and episode end (and may include the gap days at the end, in the latter condition described above). Notes: 1. just the number of gap days **after** the end of the episode can be computed by keeping all values larger than the permissible gap and by replacing the others by 0, 2. when medication change represents a new treatment episode, the previous episode ends when the last supply is finished (irrespective of the length of gap compared to a maximum permissible gap); any days before the date of the new medication supply are considered a gap. This maintains consistence with the computation of gaps between episodes (whether they are constructed based on the maximum permissible gap rule or the medication change rule). In some scenarios, it is important to imagine that the episodes also **include** the maximum permissible gap when the gap is larger than this maximum (i.e., not when a new episode is due to a change in treatment or dose before this maximum permissible gap was exceeded). To allow such scenarios, `compute.treatment.episodes()` has a logical parameter, `maximum.permissible.gap.append.to.episode`, which, when set to `TRUE` appends the maximum permissible gap at the end of the episodes (its default value `FALSE` means that the episodes end as described above). This output can be used on its own to study causes and consequences of medication persistence (e.g. by using episode duration in time-to-event analyses). This function is also a basis for the `CMA_per_episode` class, which is described later in the vignette. ## Adherence -- continuous multiple interval measures of medication availability/gaps (CMA) Let's consider another scenario: `medA` and `medB` are alternative formulations of the same chemical molecule, and clinicians agree that they can be used by patients within the same treatment episode. In this case, both patients had a single treatment episode for the whole duration of the follow-up ([Table 3](#Table-3)). We can therefore compute adherence for any observation window (OW) within these 2 years without any concern that we might confuse quality of implementation with (non-)persistence. ```{r, echo=TRUE, results='asis'} # Compute the treatment episodes for the two patients # but now a change in medication type does not start a new episode: TEs4<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = TRUE, consider.dosage.change = TRUE, medication.change.means.new.treatment.episode = FALSE, # here maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start = 0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); # Pretty print the events: knitr::kable(TEs4, caption = "<a name=\"Table-3\"></a>**Table 3.** Alternative scenario output `compute.treatment.episodes()` function"); ``` Once we clarified that we indeed measure quality of implementation and not (non)-persistence, several `CMA` classes can be used to compute this specific component of adherence. We will discuss first in turn the *simple* `CMA` classes, then present the more complex (or *iterated*) `CMA_per_episode` and `CMA_sliding_window` ones. ### The simple CMAs A first decision to consider when calculating the quality of implementation is what is the appropriate observation window -- when it should start and how long it should last? We can see for example that patient `76` had some periods of regular (even overlapping) supplies, and periods when there were some large delays between consecutive medication events. Thus, estimating adherence for a whole 2-year period might be too coarse-grained to mean anything for how patients actually managed their treatment at any particular moment. As mentioned earlier in the [Definitions section](#Section-definitions), EHD don't have good granularity to start with, so we need to do the best with what we've got -- and compressing all this information into a single estimate might not be the best solution, at least not the obvious first choice. On the other hand, due to the low granularity, we cannot target very short observation windows either because we simply don't know what happened every day. This decision needs to be informed again by information collected from the advisory committee or qualitative/quantitative studies in the target population. It also needs to take into account the average duration of medication supply from one event, and the average time interval between two events -- which can be examined in exploratory plots ([Figure 1](#Figure-1)) -- and the research question and design of the study. For example, if we expect that the quality of implementation reduces in time from the start of a treatment episode, medication is usually supplied for one month, and patients can take up to 4 times as much to use up their supplies, we might want to consider comparing successive 4-month OWs. If we want to examine quality of implementation 6 months before a clinical event (on the clinical assumption that how a patient takes medication in previous 6 months may impact on the probability of a health event occurring or not), we might want to consider an OW start 6 months before the event, and a 6-month duration. The posibilities here are endless, and research on the impact of different analysis choices on substantive results is still scarce. When the consensus is not reached based on the available information, one or more parametrisations can be compared -- and formulated as research questions. For demonstration purposes, let's imagine a scenario when an adherence intervention takes place 6 months (182 days) after the start of the treatment episode, and we hypothesize that it will improve the quality of implementation in the next year (365 days) in the intervention group compared to the control group. We can specify this as `followup.window.start=0`, `observation.window.start=182`, and `observation.window.duration=365` (we can of course divide this interval into shorter windows and compare the two groups in terms of longitudinal changes in adherence, as we shall see later, but for the moment let's stick to a global 1-year estimate). We have 9 CMA classes that can produce very different estimates of the quality of implementation, the first eight have been described by [Vollmer and colleagues (2012)](#Ref-Vollmer2012) as applied to randomized controlled trials. We implemented them in `AdhereR` based on the authors' description, and in essence are defined by 4 parameters: 1) how is the OW delimited (whether time intervals before the first event and after the last event are considered), 2) whether CMA values are capped at 100%, 3) whether medication oversupply is carried over to the next event interval, and 4) whether medication available before a first event is considered in supply calculations or OW definition. #### CMA1 *CMA1* is the simplest method, often described in the literature as the *medication possession ratio* (MPR). It simply adds up the duration of all medication events within the OW, excluding the last event, and divides this by the number of days between the first and last event (multiplied by 100 to obtain a percentage). Thus, it can be higher than 1 (or 100% adherence) and, if the OW does not start and end with a medication event for all patients, it can actually refer to different lengths of time within the OW for different patients. For example, for patient `76` below CMA1 is computed for the period starting with the first event in the highlighted interval and ending at the date if the last event -- thus, it considers only 4 events with considerable overlaps and results in a CMA1 of 140%, indicating overuse. Creating an object of class `CMA1` with various parameters automatically performs the estimation of CMA1 for all the patients in the dataset; moreover, the object is smart enough to allow the appropriate printing and plotting. The object includes all the parameter values with which it was created, as well as the `CMA` `data.frame`, which is the main result, with two columns: patient ID and the corresponding CMA estimate. The CMA estimates appear as ratios, but can be trivially transformed into percentages and rounded, as we did for patient `76` below (rounded to 2 decimals). The plots show the CMA as percentage rounded to 1 decimal. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-2\"></a>**Figure 2.** Simple CMA 1", fig.height=5, fig.width=7, out.width="100%"} # Create the CMA1 object with the given parameters: cma1 <- CMA1(data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); # Display the summary: cma1 # Display the estimated CMA table: cma1$CMA # and equivalently using an accessor function: getCMA(cma1); # Compute the CMA value for patient 76, as percentage rounded at 2 digits: round(cma1$CMA[cma1$CMA$PATIENT_ID== 76, 2]*100, 2) # Plot the CMA: # The legend shows the actual duration, the days covered and gap days, # the drug (medication) type, the FUW and OW, and the estimated CMA. plot(cma1, patients.to.plot=c("76"), # plot only patient 76 legend.x=520); # place the legend in a nice way ``` #### CMA2 Thus, CMA1 assumes that there is a treatment episode within the OW (shorter or equal to the OW) when the patient used the medication, and every new medication event happened when the previous supply finished (possibly due to overuse). These assumptions rarely fit with real life use patterns. One limitation is not considering the last event -- which represents almost a half of the OW in the case of patient `76`. To address this limitation, *CMA2* includes the duration of the last event in the numerator and the period from the last event to the end of the OW in the denominator. Thus, the estimate [Figure 3](#Figure-3) is 77.9%, more in line with the medication history of this patient in the year after the intervention. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-3\"></a>**Figure 3.** Simple CMA 2", fig.height=5, fig.width=7, out.width="100%"} cma2 <- CMA2(data=ExamplePats, # we're estimating CMA2 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma2, patients.to.plot=c("76"), show.legend=FALSE); # don't show legend to avoid clutter (see above) ``` #### CMA3 and CMA4 Both CMA1 and CMA2 can be higher that 1 (100% adherence) based on the assumption that medication supply is finished until the last event (CMA1) or the end of the OW (CMA2). But sometimes this is not plausible, because patients can refill their supply earlier (for example when going on holidays) and overuse is a less frequent behaviour for some medications (when side effects are considerable for overuse, or medications are expensive). Or it may be that it does not matter whether patients use 100% or more that 100% of their medication, the therapeutic effect is the same with no risks or side effects. Again, this is a matter of inquiry to the advisory committee or investigation in the target population. If it is likely that implementation does not exceed 100% (or does not make a difference if it does), *CMA3* and *CMA4* below adjust for this by capping CMA1 and CMA2 respectively to 100%. As shown in [Figures 4](#Figure-4) and [5](#Figure-5), CMA3 is now capped at 100%, and CMA4 remains the same as CMA2 (because it was already lower than 100%). ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-4\"></a>**Figure 4.** Simple CMA 3", fig.height=5, fig.width=7, out.width="100%"} cma3 <- CMA3(data=ExamplePats, # we're estimating CMA3 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma3, patients.to.plot=c("76"), show.legend=FALSE); ``` ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-5\"></a>**Figure 5.** Simple CMA 4", fig.height=5, fig.width=7, out.width="100%"} cma4 <- CMA4(data=ExamplePats, # we're estimating CMA4 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma4,patients.to.plot=c("76"), show.legend=FALSE); ``` #### CMA5 and CMA6 All CMAs from 1 to 4 have a major limitation: they don't take into account the *timing* of the events. But if there is a large gap between two events it is more likely that the person had used the medication less than prescribed at least in part of that interval. Just capping the values as in CMA3 and CMA4 does not account for that likely reduction in adherence -- two patients with the same quantity of supply will have the same percentage of adherence even if one has had substantial delays in supply at some points and the other supplied in time. To adjust for this, *CMA5* and *CMA6* provide alternative calculations to CMA1 and CMA2 respectively. Thus, we instead calculate the number of gap days, extract it from the total time interval, and divide this value by the total time interval (first to last event in CMA5, and first event to end of OW in CMA6). By considering the gaps, we now need to decide whether to control for how any remaining supply is used when a new supply is obtained. Two additional parameters are included here: `carry.only.for.same.medication` and `consider.dosage.change`. Both are set here as `FALSE`, to specify the fact that carry over should always happen irrespective of what medication is supplied, and that the duration of the remaining supply should be modified if the dosage recommendations are changed with a new medication event. As shown in [Figures 6](#Figure-6) and [7](#Figure-7), these alternative calculations do not make any difference for patient `76`, because there are no gaps between the 5 events in the OW highighted. There could be, however, situations in which large gaps between some events in the OW result in lower CMA estimates when considering timing of events. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-6\"></a>**Figure 6.** Simple CMA 5", fig.height=5, fig.width=7, out.width="100%"} cma5 <- CMA5(data=ExamplePats, # we're estimating CMA5 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, # carry-over across medication types consider.dosage.change=FALSE, # don't consider canges in dosage followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma5,patients.to.plot=c("76"), show.legend=FALSE); ``` ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-7\"></a>**Figure 7.** Simple CMA 6", fig.height=5, fig.width=7, out.width="100%"} cma6 <- CMA6(data=ExamplePats, # we're estimating CMA6 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma6,patients.to.plot=c("76"), show.legend=FALSE); ``` Sometimes it is useful to also see the daily dose: ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 7 (a).** Same plot as in **Figure 7**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"} # Same plot as above but also showing the daily doses: plot(cma6, # the object to plot patients.to.plot=c("76"), # plot only patient 76 print.dose=TRUE, plot.dose=TRUE, legend.x=520); # place the legend in a nice way ``` #### CMA7 All CMAs so far have another limitation: they do not consider the interval between the start of the OW and the first event within the OW. For situations in which the OW start coincides with the treatment episode start, this limitation has no consequences. But in scenarios like ours (OW starts during the episode) this has two major drowbacks. First, the time interval for calculating CMA is not the same for all patients; this can result in biases, for example if the intervention group tends to refill sooner after the intervention moment than the control group, the control group might seem more adherent but it is because CMA is calculated on a shorter time interval within the following year. And second, if there is any medication supply left from before the OW start, this is not considered (so CMA may be underestimated). *CMA7* addresses this limitation by extending the nominator to the whole OW interval, and by considering carry over both from before and within the OW. The same paremeters are available to specify whether this depends on the type of medication and considers dosage changes (applied now to both types of carry over). [Figure 8](#Figure-8) shows how considering the period at the OW start and the prior supply reduces CMA7 to 69%, due to the gap visible in the medication history plot between the event before the OW and the first event within the OW. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-8\"></a>**Figure 8.** Simple CMA 7", fig.height=5, fig.width=7, out.width="100%"} cma7 <- CMA7(data=ExamplePats, # we're estimating CMA7 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma7, patients.to.plot=c("76"), show.legend=FALSE); ``` #### CMA8 When entering a randomized controlled trial involving a new medication, a patient on ongoing treatment may be more likely to finish the current supply before starting the trial medication. In these situations, it may be more appropriate to consider a lagged start of the OW (even if this results in a different denominator for trial participants). Let's consider this different scenario for patient `76`: at day 374, a new treatment (`medB`) starts and we need to estimate CMA for the next 294 days (until the next medication change). But there is still some `medA` left, so it is likely that the patient finished this first. [Figure 9](#Figure-9) shows how the OW is shortened with the number of days it would have taken to finish the remaining `medA` (assuming use as prescribed); *CMA8* is quite low 36.1%, given the long gaps between medB events. In a future version, it might be interesting to implement the possibility to also move the end of OW so that its length is preserved. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-9\"></a>**Figure 9.** Simple CMA 8", fig.height=5, fig.width=7, out.width="100%"} cma8 <- CMA8(data=ExamplePats, # we're estimating CMA8 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=374, observation.window.duration=294, date.format="%m/%d/%Y"); plot(cma8, patients.to.plot=c("76"), show.legend=FALSE); # The value for patient 76, rounded at 2 digits round(cma8$CMA[cma8$CMA$PATIENT_ID== 76, 2]*100, 2); ``` #### CMA9 The previous 8 CMAs were described by [Vollmer and colleagues (2012)](#Ref-Vollmer2012) in relation to randomized controlled trials, and may apply to many observational designs as well. However, they all rely on an assumption that might not hold for longitudinal cohort studies with multiple repeated measures: the medication is used as prescribed until current supply ends. In CMA7, this may introduce additional variation in adherence estimates depending on where the start of the OW is located relative to the last event before the OW and the first event within the OW: an OW start closer to the first event in the OW generates lower estimates for the same number of gap days between the two events. To address this, *CMA9* first computes a ratio of days’ supply for each event in the FUW (until the next event or FUW end), then weighs all days in the OW by their corresponding ratio to generate an average CMA value for the OW. For the same scenario as in CMA1 to CMA7, [Figure 10](#Figure-10) shows the estimate for CMA9, which is higher than for CMA7 (70.6% versus 69%). This value would be the same no matter if the OW starts slightly earlier or later, because CMA9 considers the same intervals between events (the one starting before and the one ending after the OW). Thus, it depends less on the actual date when the OW starts. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-10\"></a>**Figure 10.** Simple CMA 9", fig.height=5, fig.width=7, out.width="100%"} cma9 <- CMA9(data=ExamplePats, # we're estimating CMA9 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma9, patients.to.plot=c("76"), show.legend=FALSE); ``` ### The iterated CMAs We introduce here two complex (or iterated) CMAs that share the property that they apply a given single CMA iteratively to a set of sub-periods (or windows), defined in various ways. #### CMA per episode When we calculated the persistence and implementation above, we first defined the *treatment episodes*, and then computed the CMAs within the episode. The `CMA_per_episode` class allows us to do this in one single step. In our intervention scenario, both example patients had a 2-year treatment episode and we computed the various simple CMAs for a 1-year period within this longer episode. But if we consider that medication change triggers a new treatment episode, patient `76` would have 3 episodes. `CMA_per_episode` can compute any of the 9 simple CMAs for all treatment episodes for all patients. As with the simple CMAs, the `CMA_per_episode` class contains a list that includes all the parameter values, as well as a `CMA` `data.frame` (with all columns of the `compute.treatment.episodes()` output table, plus a new column with the CMA values). The `CMA_per_episode` values can also be transformed into percentages and rounded, as we did for patient `76` below (rounded to 2 decimals). Plots now include an extra section at the top, where each episode is shown as a horizontal bar of length equal to the episode duration, and the corresponding CMA estimates are given both as percentage (rounded to 1 decimal) and as a grey area. An extra area on the right of the plot displays the distribution of all CMA values for the whole FUW as a histogram or as smoothed kernel density (see [Figure 11](#Figure-11)). ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-11\"></a>**Figure 11.** CMA 9 per episode", fig.height=5, fig.width=7, out.width="100%", warning=FALSE} cmaE <- CMA_per_episode(CMA="CMA9", # apply the simple CMA9 to each treatment episode data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = FALSE, consider.dosage.change = FALSE, # conditions on treatment episodes medication.change.means.new.treatment.episode = TRUE, maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start=0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", observation.window.start=0, observation.window.start.unit = "days", observation.window.duration=365*2, observation.window.duration.unit = "days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaE; # The CMA estimates table: cmaE$CMA getCMA(cmaE); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits: round(cmaE$CMA[cmaE$CMA$PATIENT_ID== 76, 7]*100, 2); # Plot: plot(cmaE, patients.to.plot=c("76"), show.legend=FALSE); ``` #### Sliding-window CMA When discussing the issue of granularity earlier, we mentioned that estimating adherence for a whole 2-year period might be too coarse-grained to be clinically relevant, and that shorter intervals may be more appropriate, for example in studies that aim to investigate how the quality of implementation varies in time during a long-term treatment episode. In such cases, we might want to compare successive intervals, for example 4-month intervals. `CMA_sliding_window` allows us to compute any of the 9 simple CMAs for repeated time intervals (*sliding windows*) within an OW. A similar output is produced as for `CMA_per_episode`, including a CMA table (with patient ID, window ID, window start and end dates, and the CMA estimate). [Figure 12](#Figure-12) shows the results of CMA9 for patient `76`: 6 sliding windows of 4 months, among which 2 have a CMA higher than 80%, two have values around 60% and two around 40%, suggesting a variable quality of implementation. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-12\"></a>**Figure 12.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"} cmaW <- CMA_sliding_window(CMA.to.apply="CMA9", # apply the simple CMA9 to each sliding window data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # sliding windows definition sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=120, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaW; # The CMA estimates table: cmaW$CMA getCMA(cmaW); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits round(cmaW$CMA[cmaW$CMA$PATIENT_ID== 76, 5]*100, 2); # Plot: plot(cmaW, patients.to.plot=c("76"), show.legend=FALSE); ``` The sliding windows can also overlap, as illustrated below. This can for example be used to estimate the variation of adherence (implementation) during an episode. [Figure 13](#Figure-13) shows 21 sliding windows of 4 month for patient `76`, in steps of 1 month. The patient's quality of implementation oscillated between 37% and 100% during the 2 years of follow-up. This output can be further analyzed in relation to patterns of health status if such data are available for the same time period. ```{r, echo=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-13\"></a>**Figure 13.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"} cmaW1 <- CMA_sliding_window(CMA.to.apply="CMA9", data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # different sliding windows sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=30, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Plot: plot(cmaW1, patients.to.plot=c("76"), show.legend=FALSE); ``` #### Mapping events to episodes and sliding windows The functions `compute.treatment.episodes`, `CMA_per_episode` and `CMA_sliding_window` can return the mapping between events and episodes or sliding windows, respectively, in the sense that they can specify, for each episode or sliding which, which events participate in it. For the latter two, this correspondence can also be shown visually in plots (see [Figure 14](#Figure-14)). Please note that, as the details of which events belong to which episode may depend on the particular simple CMA used, it is recommended to take the mapping produced by `compute.treatment.episodes` as orientative, and use instead the mapping produced by `CMA_per_episode` for a particular simple CMA. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-14\"></a>**Figure 14.** Per episodes with CMA 1, showing which events belong to which episode: for events, the number(s) between '[]' represent the event they belong to, while for an event, the number between '[]' is what the events use as its identifier. (e.g., the 3rd even from the left for patient 1 has a '[2]', meaning that it belongs to event '2', which is identified as such with a '[2]' immediately after is estimated CMA of '136%'). Please note that the same plot for CMA9 would be quite different, as the rules for which events are considered differ (e.g., the last events of the episodes would be included).", fig.height=7, fig.width=7, out.width="100%"} cmaE <- CMA_per_episode(CMA="CMA1", data=med.events[med.events$PATIENT_ID %in% 1:2,], ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=-90, observation.window.start=0, observation.window.duration=365, maximum.permissible.gap=10, return.mapping.events.episodes=TRUE, # ask for the mapping medication.change.means.new.treatment.episode=TRUE, date.format="%m/%d/%Y"); getEventsToEpisodesMapping(cmaE); # get the mapping (here, print it) plot(cmaE, align.all.patients=TRUE, print.dose.centered=TRUE, print.episode.or.sliding.window=TRUE); # show the mapping visually ``` ## Interactive plotting <a name="Section-interactive-plotting"></a> During the exploratory phases of data analysis, it is sometimes extremely useful to be able to plot interactively various views of the data using different parameter settings. We have implemented such interactive plotting of medication histories and (simple and iterative) CMA estimates within [`RStudio`](https://www.rstudio.com) and outside it (using [`Shiny`](https://shiny.rstudio.com/); this is the default as it very flexible and independent of running `AdhereR` within `RStudio`) through the `plot_interactive_cma()` function. This function is generic and interactive, and can be given a large set of parameters (including the dataset on which to work) or it can interactively acquire these parameters directly from the user. Please note that this interactive plotting is actually implemented in a different package, `AdhereRViz` (which extends `AdhereR`); for more info, please see the vignette [AdhereR: Interactive plotting (and more) with Shiny](https://cran.r-project.org/package=AdhereRViz/vignettes/adherer_interctive_plots.html) from package `AdhereRViz`. ## Computing event duration from prescription, dispensing, and hospitalization data <a name="Section-compute-event-duration"></a> Computation of CMAs requires a supply duration for medications dispensed to patients. If medications are not supplied for fixed durations but as a quantity that may last for various durations based on the prescribed dose, the supply duration has to be calculated based on dispensed and prescribed doses. Treatments may be interrupted and resumed at later times, for which existing supplies may or may not be taken into account. Patients may be hospitalized or incarcerated, and may not use their own supplies during these periods. The function `compute_event_durations` calculates the supply durations, taking into account the aforementioned situations and offering parameters for flexible adjustments. ## Computing time to initiation <a name="Section-compute-time-to-initiation"></a> The period between the first prescription event and the first dose administration may impact health outcomes differently than omitting doses once on treatment or interrupting medication for longer periods of time. Primary non-adherence (not acquiring the first prescription) or delayed initiation may have a negative impact on health outcomes. The function `time_to_initiation` calculates the time between the first prescription and the first dispensing event, taking into account multiple variables to differentiate between treatments. ## Defining medication groups <a name="Section-defining-medication-groups"></a> The main idea behind *medication groups* is that there might be meaningful ways of grouping medications both for the computation of CMAs and their plotting. For example, a patient might receive medication for treating a hart conditions and medication for a dermatological condition, and we might want to investigate the patient's patterns of adherence to each of these two broad types (or groups) of medication separately. However, the mechanism for defining such groups much be flexible enough to allow, for example, the same medication to belong to two groups based on dose, duration or other characteristics. Therefore, we implemented this using a very flexible yet powerful and intuitive mechanism that can use any type of information associated to the actual events. To illustrate, we will use the data that comes with the package: `med.events.ATC` and `med.groups`. `med.events.ATC` is a `data.frame` with `r nrow(med.events.ATC)` events (one per row) for `r length(unique(med.events.ATC$PATIENT_ID))` patients, containing the patient's unique identifier (column `PATIENT_ID`), the event date (`DATE`) and duration (`DURATION`), and the medication's [ATC code](https://www.whocc.no/atc/structure_and_principles/) (column `CATEGORY`), further detailing its first two levels: level 1 (one letter giving the anatomical main group, e.g., "A" for "Alimentary tract and metabolism"; column `CATEGORY_L1`) and level 2 (the therapeutic subgroup, e.g., "A02" for "Drugs for acid related disorders"): ```{r, echo=FALSE} knitr::kable(head(med.events.ATC, n=5), row.names=FALSE, caption="First 5 lines of the `med.events.ATC` dataset."); ``` In fact, `med.events.ATC` is derived from the `durcomp` data as follows: ```{r, eval=FALSE} event_durations <- compute_event_durations(disp.data = durcomp.dispensing, presc.data = durcomp.prescribing, special.periods.data = durcomp.hospitalisation, ID.colname = "ID", presc.date.colname = "DATE.PRESC", disp.date.colname = "DATE.DISP", medication.class.colnames = c("ATC.CODE", "UNIT", "FORM"), total.dose.colname = "TOTAL.DOSE", presc.daily.dose.colname = "DAILY.DOSE", presc.duration.colname = "PRESC.DURATION", visit.colname = "VISIT", split.on.dosage.change = TRUE, force.init.presc = TRUE, force.presc.renew = TRUE, trt.interruption = "continue", special.periods.method = "continue", date.format = "%Y-%m-%d", suppress.warnings = FALSE, return.data.table = FALSE); med.events.ATC <- event_durations$event_durations[ !is.na(event_durations$event_durations$DURATION) & event_durations$event_durations$DURATION > 0, c("ID", "DISP.START", "DURATION", "DAILY.DOSE", "ATC.CODE")]; names(med.events.ATC) <- c("PATIENT_ID", "DATE", "DURATION", "PERDAY", "CATEGORY"); # Groups from the ATC codes: sort(unique(med.events.ATC$CATEGORY)); # all the ATC codes in the data # Level 1: med.events.ATC$CATEGORY_L1 <- vapply(substr(med.events.ATC$CATEGORY,1,1), switch, character(1), "A"="ALIMENTARY TRACT AND METABOLISM", "B"="BLOOD AND BLOOD FORMING ORGANS", "J"="ANTIINFECTIVES FOR SYSTEMIC USE", "R"="RESPIRATORY SYSTEM", "OTHER"); # Level 2: med.events.ATC$CATEGORY_L2 <- vapply(substr(med.events.ATC$CATEGORY,1,3), switch, character(1), "A02"="DRUGS FOR ACID RELATED DISORDERS", "A05"="BILE AND LIVER THERAPY", "A09"="DIGESTIVES, INCL. ENZYMES", "A10"="DRUGS USED IN DIABETES", "A11"="VITAMINS", "A12"="MINERAL SUPPLEMENTS", "B02"="ANTIHEMORRHAGICS", "J01"="ANTIBACTERIALS FOR SYSTEMIC USE", "J02"="ANTIMYCOTICS FOR SYSTEMIC USE", "R03"="DRUGS FOR OBSTRUCTIVE AIRWAY DISEASES", "R05"="COUGH AND COLD PREPARATIONS", "OTHER"); ``` For this dataset, we could define the following medication groups: - *Vitamins*: all 'VITAMINS' (i.e., all medications of ATC subgroup "A11"), - *VitaResp*: groups all *Vitamins* and medications referring to the 'RESPIRATORY SYSTEM' (ATC group "R"), - *VitaShort*: all *Vitamins* administered for less than 31 days, - *VitELow*: tocopherol (vit E) (ATC code "A11HA03") at doses lower or equal to 500mg, - *VitaComb*: groups *VitaShort* and *VitELow* (i.e., vitamines for less than 31 days and tocopherol at at most 500mg), - *NotVita*: all non-*Vitamins*. These are defined in `med.groups`, which is a named vector of characters: ```{r eval=FALSE} med.groups <- c("Vitamins" = "(CATEGORY_L2 == 'VITAMINS')", "VitaResp" = "({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')", "VitaShort" = "({Vitamins} & DURATION <= 30)", "VitELow" = "(CATEGORY == 'A11HA03' & PERDAY <= 500)", "VitaComb" = "({VitaShort} | {VitELow})", "NotVita" = "(!{Vitamins})"); ``` The `names` in the vector are the names of the various medication groups (e.g., "Vitamins" is the name of the first group, corresponding to all the vitamins), while the values of the vector are the actual definitions and use the same syntax, operators and conventions as any `R` *expression*. The name of a medication group can be pretty much any string of characters not containing "}", but it is recommended to keep them short, expressive and (as much as possible) free of non-alphanumeric symbols (in fact, the best recommendation is to stick to the rules for defining legal `R` variable and function names). Focussing on the first one, `(CATEGORY_L2 == 'VITAMINS')`, `CATEGORY_L2` refers to the `CATEGORY_L2` column in the `med.events.ATC` dataset, `'VITAMINS'` is a possible value that may appear in that column, and `(`, `)` and `==` have the usual interpretation in `R` (grouping and test of equality, respectively). In fact, this *is* translated internally into an expression that is evaluated on the `med.events.ATC` dataset, resulting in a vector of logical values, one per row, saying which events in `med.events.ATC` correspond to this medication group (`TRUE`, there are `r sum(med.events.ATC$CATEGORY_L2 == 'VITAMINS',na.rm=TRUE)` such events) and which not (`FALSE`, the remaining `r sum(!(med.events.ATC$CATEGORY_L2 == 'VITAMINS'),na.rm=TRUE)` events): ```{r, echo=FALSE} knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *Vitamins* medication group."); ``` A special notation is used to "make reference" to another named medication group, by surrounding the medication group's name by `{` and `}`: the second medication group "VitaResp" si defined as `({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')`, where `{Vitamins}` simply refers to the events corresponding to the "Vitamins" group discussed above; internally, the "Vitamins" group is evaluated and its vector of logicals is combined using `|` (OR) with the vector of logicals corresponding to `CATEGORY_L1 == 'RESPIRATORY SYSTEM'`: ```{r, echo=FALSE} knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS' | med.events.ATC$CATEGORY_L1 == 'RESPIRATORY SYSTEM',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *VitaResp* medication group."); ``` This mechanism is very flexible and extensible, allowing, for example, tests involving the duration ("VitaShort") and the dosage ("VitELow"), and the combination of several defined groups ("VitaComb"). However, it is important to remember that: a) these must be well-formed and meaningful expressions, b) using column names and values in the dataset containing the events, c) and/or other groups between `{` and `}`, d) and must evaluate to valid logical vectors of the same length as the number of events (rows) in the dataset. By default, an extra special medication group `__ALL_OTHERS__` is automatically computed, including all events that are not covered by any of the explicitly defined medication groups (if any). Please note that, for security reasons, this evaluation is performed in a separate environment where only certain functions and operators are allowed (the functions in the `Math`, `Arith`, `Logic` and `Compare` groups, and the operators `(`, `[` and `!`). With these, definitions of medication groups can be passed to all CMA functions using the `medication.groups` parameter: ```{r} cma1_mg <- CMA1(data=med.events.ATC, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", medication.groups=med.groups, followup.window.start=0, observation.window.start=0, observation.window.duration=365, date.format="%m/%d/%Y"); cma1_mg; # print it ``` There is a new function, `getMGs()`, which returns the medication groups for a CMA object (if none, `NULL`); this is a list with two members (here, for `getMGs(cma1_mg)`): - `def`, which contains the definitions of the medication groups (+ `__ALL_OTHERS__`) as a `data.frame` with columns `name` and `def`: ```{r echo=FALSE} getMGs(cma1_mg)$def; ``` - `obs`, which is logical `matrix` with as many rows as the dataset on which the CMA was estimated (here, `med.events.ATC`) and as many columns as medication groups (including `__ALL_OTHERS__`); a value of `TRUE` means that the corresponding event in the dataset is selected by the corresponding medication group (here, its first 10 rows): ```{r echo=FALSE} head(getMGs(cma1_mg)$obs, n=10); ``` The `getCMA()` function works as before, except that now, by default, it returns a list with as many entries as there are medication groups (+ `__ALL_OTHERS__`), each containing its own CMA estimates: ```{r} getCMA(cma1_mg); ``` Thus, patient `2` has a `CMA1` of ~1.77 for "Vitamins", of ~1.76 for "VitaResp", none (`NA`) for "VitaShort", "VitELow" and "VitaComb", of ~2.76 for "NotVita". Here, as can also be seen in the `obs` component of `getMGs(cma1_mg)`, the default `__ALL_OTHERS__` did not select any events, results in an empty CMA estimate for it. Sometimes, however, this structuring of the CMAs as a list may not be desirable, in which case the parameter `flatten.medication.groups = TRUE` comes in handy: ```{r} getCMA(cma1_mg, flatten.medication.groups=TRUE); ``` (It can also be directly passed to the CMA function.) Please note that, by default, all medication groups belonging to one patient share the same follow-up and observation windows, but this can be changed by setting the parameter `followup.window.start.per.medication.group = TRUE` so that each medication group has its own follow-up and observation windows. The medication groups also affect the plotting: ```{r echo=TRUE, message=FALSE, warning=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-15\"></a>**Figure 15.** CMA 1 with medication groups.", fig.height=9, fig.width=9, out.width="100%"} plot(cma1_mg, #medication.groups.to.plot=c("VitaResp", "VitaShort", "VitaComb"), patients.to.plot=1:3, show.legend=FALSE); ``` The medication groups are ordered within patients, and visually grouped using alternating thick blue lines (which can be controlled through the parameters `medication.groups.separator.show`, `medication.groups.separator.lty`, `medication.groups.separator.lwd` and `medication.groups.separator.color`); likewise, the name of the special `__ALL_OTHERS__` groups can be controlled with the `medication.groups.allother.label` parameter (defaults to "*"). Only the medication groups that contain at least one event are shown for each patient. If desired, the parameter `medication.groups.to.plot` can be used to explicitly list the names of the medication groups to include in the plot (by default, all). Medication groups work in the same way across all simple and complex CMAs, an are included in the interactive `Shiny` interface as well. As a special case, the `medication.groups` parameter can simply be the name of a column in the `data` that define the medication groups through its values. For example, ```{r eval=FALSE} cma0_types <- CMA0(data=med.events.ATC, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", medication.groups="CATEGORY_L1", #flatten.medication.groups=TRUE, #followup.window.start.per.medication.group=TRUE, followup.window.start=0, observation.window.start=0, observation.window.duration=365, date.format="%m/%d/%Y"); ``` defines `r length(unique(med.events.ATC$CATEGORY_L1))` medication groups `r paste0('"',sort(unique(med.events.ATC$CATEGORY_L1)),'"',collapse=", ")` using the `CATEGORY_L1` column in the example `med.events.ATC` dataset. Behind the scenes, this is simply expanded into the medication group definitions: ```{r echo=FALSE} tmp <- sort(unique(med.events.ATC$CATEGORY_L1)); cat(paste0("c(", paste0('"',tmp,'"',' = "(CATEGORY_L1 == \'',tmp,'\')"',collapse=",\n "), ");")); ``` Please note that if no medication groups are defined (the default), then *nothing* changes in the behaviour of the package (so it is fully backwards compatible). ## Working with very large databases <a name="Section-working-with-databases"></a> `AdhereR` can use data stored in a variety of "classical" `RDBMS`'s (Relational Database Management Systems), such as [`MySQL`](https://www.mysql.com/) or [`SQLite`](https://www.sqlite.org/index.html), either through explicit [`SQL`](https://en.wikipedia.org/wiki/SQL) queries or transparently through [`dbplyr`](https://db.rstudio.com/dplyr/), or in other systems, such as the [`Apache Hadoop`](https://hadoop.apache.org/). Thus, `AdhereR` can access (very) large quantities of data stored in various formats and using different backends, and can process it ranging from single-threaded set-ups on a client machine to large heterogeneous distributed clusters (using, for example, various explicit parallel processing frameworks or `Hadoop`'s `MapReduce` framework). All these are detailed in a dedicated vignette *"Using `AdhereR` with various database technologies for processing very large datasets"*. ## Using `AdhereR` from other programming languages and platforms <a name="Section-calling-adherer-from-other"></a> `AdhereR` can be transparently used from other programming languages than `R` (such as `Python`) or platforms (such as `Stata`) by implementing a startdized interface defined for these purposes. A working implementation for `Python 3` is included in the package (and inteded also as a hands-on guide to further implementations) and is described in detailed in a dedicated vignette *"Calling AdhereR from Python3"*. ## AdhereR is pipe (`%>%` or `|>`)-friendly <a name="pipe-friendly"></a> The [pipe operator (`%>%`)](https://r4ds.had.co.nz/pipes.html) has been originally introduced in `R` by the [`magrittr` package](https://cran.r-project.org/package=magrittr/vignettes/magrittr.html) and is a central feature of the [Tidyverse](https://www.tidyverse.org/), and is since `R` 4.1 also available natively as `|>` [(but there are some subtle differences from `%>%`)](https://www.infoworld.com/article/3621369/use-the-new-r-pipe-built-into-r-41.html). `AdhereR` is compatible with pipe (because for all functions the first parameter encapsulates the "important" data, with the others providing various "tweaks"), so, code such as the following is fully functional: ```{r eval=FALSE} library(dplyr); # Compute, then get the CMA, change it and print it: x <- med.events %>% # use med.events filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients CMA9(ID.colname="PATIENT_ID", # compute CMA9 event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=230, followup.window.duration=705, observation.window.start=41, observation.window.duration=100, date.format="%m/%d/%Y") %>% getCMA() %>% # get the CMA estimates mutate(CMA=sprintf("%.1f%%",100*CMA)); # make them percents print(x); # print it # Plot some CMAs: med.events %>% # use med.events filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients CMA_sliding_window(CMA.to.apply="CMA7", # sliding windows CMA7 ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=230, followup.window.duration=705, observation.window.start=41, observation.window.duration=100, date.format="%m/%d/%Y") %>% plot(align.all.patients=TRUE, show.legend=TRUE); # plot it ``` ## Modifying `AdhereR` plots *a posteriori* <a name="modify-plots"></a> ```{r echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-16\"></a>**Figure 16.** Modifying an `AdhereR` plot is easy using the `get.plotted.events()` function.", fig.height=8, fig.width=8, out.width="100%"} # Plot CMA7 for patients 5 and 8: cma7 <- CMA7(data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=30, observation.window.start=30, observation.window.duration=365, date.format="%m/%d/%Y" ); plot(cma7, patients.to.plot=c(5,8), show.legend=TRUE); # good plot after an error plot # Access the plotting info: pevs <- get.plotted.events(); # get the plotted events with their plotting info # Let's add a vertical line for patient 8 between the medication change: # Find the event where the medication changes: i <- which(pevs$PATIENT_ID == "8" & pevs$CATEGORY != c(pevs$CATEGORY[-1], pevs$CATEGORY[nrow(pevs)])); # Half-way between the events where medication changes: x <- (pevs$.X.END[i] + pevs$.X.START[i+1])/2; # Draw the line: segments(x, pevs$.Y.OW.START[i], x, pevs$.Y.OW.END[i], col="blue", lty="solid", lwd=3); # Put a star * next to the 4th event of patient 5: # Find the event: i <- which(pevs$PATIENT_ID == "5")[4]; # Plot the star: text(pevs$.X.START[i]-strwidth("* "), pevs$.Y.START[i], "*", cex=3.0, col="darkgreen"); # Add some random text over the figure: text((pevs$.X.FUW.START[1] + pevs$.X.FUW.END[1])/2, # X center of patient 5's FUW (pevs$.Y.FUW.START[nrow(pevs)] + pevs$.Y.FUW.END[nrow(pevs)])/2, # Y center of 8's FUW "Change with care!!!", srt=45, cex=1.5, col="darkred") ``` ## Technical details Here we overview some technical details, including the main `S3` classes and functions (probably useful for scripting and extension), our treatment of dates and durations, and the issue of performance and parallelism (useful for large datasets). ### Main `S3` classes and functions The `S3` class `CMA0` is the most basic object, basically encapsulating the dataset and desired parameter values; it should not be normally used directly (except for plotting the event data as such), but it is the foundation for the other classes. A `CMA0` (and derived) object can print itself (the output is optimized either for text, LaTeX or Markdown), can plot itself (with various parameters controlling exactly how), and offers the accessor function `getCMA()` for easy access to the CMA estimate. Please note that these CMAs all work for datasets that contain more than one patient, and the estimates are computed for each patient independently, and the plotting can display more than one patient (in this case the patients are plotted on top of each other vertically), as shown in [Figure 1](#Figure-1). The simple CMAs are implemented by the `S3` classes `CMA1` -- `CMA9`, that are derived from `CMA0` and reload its methods. Thus, one can easily implement a new simple CMA by extending the base `CMA0` class. The iterative CMAs, in contrast, are not derived from `CMA0` but use internally such a simple CMA to perform their computations. For the moment, they can *not* be extended to new simple CMAs derived from `CMA0`, but, if needed, such a mechanism could be implemented. The most important functions are: - `compute.event.int.gaps()`: for a given event database, this computes the gap days and event intervals in various scenarious, and while it should not in general be directly used, it is exported in case a use scenario requires this explicit computation; - `compute.treatment.episodes()`: this computes the treatment episodes for each patient in various scenarios; - `getCMA()`: getter functions, giving access to the estimated CMAs; - `plot_interactive_cma()`: plots interactively within RStudio (see the [Interactive plotting section](#Section-interactive-plotting)). ### Calendar dates and durations A potentially confusing (but very powerful and flexible) aspect of our implementation concerns our treatment of dates and durations. First, the *duration of an event* is given in a *column* in the dataset containing, for each event, its duration (as a positive integer) in *days*. However, *other durations* (such as for FUW or the sliding windows) are given as positive integers representing the number of *units*; these units can be "days" (the default), "weeks", "months", or "years". The *date of an event* is given in a *column* in the dataset containing, for each event, its start date as a string (`character`) in the format given by the `date.format` parameter (by default, mm/dd/yyyy). The *start* of the FUW, OW and sliding windows can be given either as the number (integer) of *units* ("days", "weeks", "months", or "years") since the first recorded event for the patient, or as an object of *class `Date`* representing the actual calendar start date, or a string (`character`) giving a *column name* in the dataset containing, per patient, either the calendar start date as `Date` object (i.e., this column must be of type `Date`) or as the number of units if the column has type `numeric`. While this might be confusing, it allows greater flexibility in specifying the start dates; the most important pitfall is in passing a date as a string (type `character`) which will result in an error as there is no such column in the dataset -- make sure it is converted to a `Date` object by using, for example, `as.Date()`! However, for most scenarios, the default of giving the number of units since the earliest event is more than enough and is the recommended (and most carefully tested) way. ### Performance, parallelism and implementation While currently implemented in pure `R`, we have extensively profiled and optimized our code to allow the processing of large databases even on consumer-grade hardware. For example, [Table 4](#Table-4) below gives the running times (single-threaded and two parallel multicore threads -- see below for details) for a database of 13,922 unique patients and 112,984 prescriptions of all CMAs described here, on an Apple MacBook Air 11" (7,1; early 2015) with 8Go RAM (DDR3 @ 1600MHz) and a Core i7-5650U CPU (2 cores, 4 threads with hyperthreading @ 2.20GHz, Turbo Boost to 3.10GHz), using MacOS X "El Capitan" (10.11.6), `R` 3.3.1 (64 bits) and `RStudio` 1.0.44. [Table 5](#Table-5) below shows the running times (single-threaded and four parallel multicore threads) for a very large database of 500,000 unique patients and 4,058,110 prescriptions (generated by repeatedly concatenating the database described above and uniquely renaming the participants) of all CMAs described here, on a desktop computer with 16Go RAM and a Core i7-3770 CPU (4 cores, 8 threads with hyperthreading @ 3.40GHz, Turbo Boost to 3.90GHz), using OpenSuse 13.2 (Linux kernel 3.16.7) and `R` 3.3.2 (64 bits). [Table 6](#Table-6) shows the same information as [Table 5](#Table-5), but on a high-end desktop computer with 32Go RAM and a Core i7-4790K CPU (4 cores, 8 threads with hyperthreading @ 4.00GHz, Turbo Boost to 4.40GHz), running Windows 10 Professional 64 bits (version 1607) and `R` 3.2.4 (64 bits); as dicusssed below, the "multicore" backend is currently not available on Windows. As these benchmarking results show, a database close to the median sample sizes in the literature (median 10,265 patients versus our 13,922 patients; [Sattler *et al.*, 2011](#Ref-Sattler2011)) can be processed almost in real-time on a consumer laptop, while very large databases (half a million patients) require tens of minutes to a few hours on a mid-to-high end desktop computers, especially when making use of parallel processing. Interestingly, Linux seems to have a small but measurable performance advantage over Windows (despite the slightly lower-end hardware) and the "multicore" backend becomes preferable to the "snow" backend for very large databases (probably due to the data transmission and collection overheads), but not by a very large margin. Therefore, for very large databases, we recommend Linux on a multi-core/multi-CPU mechine with enough RAM and the "multicore" backend. | CMA | Single-threaded | Two threads (multicore) | Two threads (snow) | |-----------------|----------------:|------------------------:|-------------------:| | CMA 1 | 40.8 (0.7) | 20.8 (0.4) | 22.0 (0.4) | | CMA 2 | 41.2 (0.7) | 21.7 (0.4) | 24.4 (0.4) | | CMA 3 | 39.3 (0.7) | 20.4 (0.3) | 22.9 (0.4) | | CMA 4 | 40.2 (0.7) | 21.3 (0.4) | 23.0 (0.4) | | CMA 5 | 56.6 (0.9) | 29.7 (0.5) | 31.5 (0.5) | | CMA 6 | 58.0 (1.0) | 30.9 (0.5) | 32.5 (0.5) | | CMA 7 | 55.5 (0.9) | 28.9 (0.5) | 30.6 (0.5) | | CMA 8 | 131.8 (2.2) | 72.5 (1.2) | 71.6 (1.2) | | CMA 9 | 159.4 (2.7) | 85.2 (1.4) | 86.5 (1.4) | | per episode | 263.9 (4.4) | 139.0 (2.3) | 139.7 (2.3) | | sliding window | 643.6 (10.7) | 347.9 (5.8) | 339.5 (5.7) | Table: <a name="Table-4"></a>**Table 4.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a large database with 13,922 patients with 112,983 events on a consumer-grade MacBook Air laptop running MacOSX El Capitan. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function) and minutes. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the multicore and snow times are slightly longer than half the single-core times due to various data transmission and collection overheads. | CMA | Single-threaded | Four threads (multicore) | Four threads (snow) | |-----------------|-------------------------------:|------------------------------:|------------------------------:| | CMA 1 | 1839.7 (30.6) | 577.0 (9.6) | 755.5 (12.6) | | CMA 2 | 1779.0 (29.7) | 490.1 (8.2) | 915.7 (15.3) | | CMA 3 | 1680.6 (28.0) | 458.5 (7.6) | 608.3 (10.1) | | CMA 4 | 1778.9 (30.0) | 489.0 (8.2) | 644.5 (10.7) | | CMA 5 | 2500.7 (41.7) | 683.3 (11.4) | 866.2 (14.4) | | CMA 6 | 2599.8 (43.3) | 714.5 (11.9) | 1123.8 (18.7) | | CMA 7 | 2481.2 (41.4) | 679.4 (11.3) | 988.1 (16.5) | | CMA 8 | 5998.0 (100.0 = 1.7 hours) | 1558.1 (26.0) | 2019.6 (33.7) | | CMA 9 | 7039.7 (117.3 = 1.9 hours) | 1894.7 (31.6) | 3002.7 (50.0) | | per episode | 11548.5 (192.5 = 3.2 hours) | 3030.5 (50.5) | 3994.2 (66.6) | | sliding window | 27651.3 (460.8 = 7.7 hours) | 7198.3 (120.0 = 2.0 hours) | 12288.8 (204.8 = 3.4 hours) | Table: <a name="Table-5"></a>**Table 5.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a very large large database with 500,000 patients with 4,058,110 events on a mid/high-range consumer desktop running OpenSuse 13.2 Linux. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function), minutes and, if large enough, hours. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the multicore and especially the snow times are slightly longer than a quarter the single-core times due to various data transmission and collection overheads. | CMA | Single-threaded | Four threads (snow) | |-----------------|-------------------------------:|------------------------------:| | CMA 1 | 2070.9 (34.5) | 653.1 (10.9) | | CMA 2 | 2098.9 (35.0) | 667.5 (13.4) | | CMA 3 | 2013.8 (33.6) | 661.5 (22.0) | | CMA 4 | 2094.4 (34.9) | 685.2 (11.4) | | CMA 5 | 2823.4 (47.1) | 881.0 (14.7) | | CMA 6 | 2909.0 (48.5) | 910.3 (15.2) | | CMA 7 | 2489.1 (41.5) | 772.6 (12.9) | | CMA 8 | 5982.5 (99.7 = 1.7 hours) | 1810.1 (30.2) | | CMA 9 | 6030.2 (100.5 = 1.7 hours) | 2142.1 (35.7) | | per episode | 10717.1 (178.6 = 3.0 hours) | 3877.2 (64.6) | | sliding window | 25769.5 (429.5 = 7.2 hours) | 9353.6 (155.9 = 2.6 hours) | Table: <a name="Table-6"></a>**Table 6.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a very large large database with 500,000 patients with 4,058,110 events on a high-end desktop computer running Windows 10. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function), minutes and, if large enough, hours. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the snow times are longer than a quarter the single-core times due to various data transmission and collection overheads. Concerning *parallelism*, if run on a multi-core/multi-processor machine or cluster, `AdhereR` gives the user the possibility to use (completely transparently) two parallel backends: *multicore* (available on Linux, \*BSD and MacOS, but currently not on Microsoft Windows) and *snow* (Simple Network of Workstations, available on all platforms; in fact, this can use various types of backends, see the documentation in package `snow` for details). Parallelism is available through the `parallel.backend` and `parallel.threads` parameters, where the first controlls the actual backend to use ("none" -- the default, uses a single thread --, "multicore", and several versions of snow: "snow", "snow(SOCK)", "snow(MPI)", "snow(NWS)") and the second the number of desired parallel threads ("auto" defaults to the reported number of cores for "multicore" or 2 otherwise, and to 2 for "snow") or a more complex specification of the nodes for "snow" (see the `snow` package documentation for details and [Appendix I: Distributing computations on remote Linux hosts]). The implementation uses `mclapply` (in package `parallel`) and `parLapply` (package `snow`), is completely hidden from the user, and tries to pre-allocate whole chunks of patients to the CPUs/cores in order to reduce the various overheads (such as data transfer). In general, for "multicore" and "snow" with nodes on the local machine, do not use more than the number of physical cores in the system, and be mindful of the various overheads involved, meaning that the gains, while substantial especially for large databases, will be very slightly lower than the expected 1/#threads (as a corrolary, it might not be a good idea to paralellize very small datasets). Also, memory might be of concern when parallelizing, as at least parts of `R`'s environment will be replicated across threads/processes; this, in turn, for large environments and systems low on RAM, might result in massive performance loss due to swapping (or even result in crashes). For more information on parallelism in `R` please see, for example, [CRAN Task View: High-Performance and Parallel Computing with R](https://CRAN.R-project.org/view=HighPerformanceComputing) and the various blogposts and books on the matter. Conceptually, we exploited various optimization techniques (see, for example, Hadley Wickham's [Advanced R](http://adv-r.had.co.nz/) and other blogposts on profiling and optimizing `R` code), but the two most important architectural decisions are to (a) extensively use [`data.table`](http://r-datatable.com/) and (b) to pre-allocate chunks of participants for parallel processing. The general framework is to define a "workhorse" function that can process a set of participants and returns one `data.frame` or `data.table` (or several, in which case they must be encapsulated in a `list()`), workhorse function that is transparently called for the whole dataset (if `parallel.backend` is "none"), or in parallel for subsets of the whole dataset of roughly 1/`parallel.threads` size (for "multicore" and "snow"), in the latter case the results being transparently recombined (even if multiple results are returned in a `list()`). Internally, the workhorse functions tend to make extensive use of the `data.table` "reference semantics" (the `:=` operator) to perform in-place changes and avoid unnecessary copying of objects, `key`s for fast indexing, search and selection, and the `by` grouping mechanism, allowing the application of a specialized function to each individual patient (or episode or sliding window, as needed). We decided to keep everything "pure `R`" (so there is so far no `C++` code) and the code is extensively commented and hopefully clear to understand, change and extend. ## Conclusions 'AdhereR' was developed to facilitate flexible and comprehensive analyses of adherence to medication from electronic healthcare data. All objects included in this package ('compute.treatment.episodes', 'CMA1' to 'CMA9', and their 'CMA_per_episode' and CMA_sliding_window versions) can be adapted to various research questions and designs, and we provided here only a few examples of the vast range of possibilities for use. Depending on the type of medication, study population, length of follow-up, etc., the various alternative parametrizations may lead to substantial differences or negligible variation. Very little evidence is available on the impact of these choices in specific scenarios. This package makes it easy to integrate such methodological investigations into data analysis plans, and to communicate these to the scientific community. We have also aimed to facilitate replicability. Thus, summaries of functions include all parameter values and are easily printed for transparent reporting (for example in an appendix or a supplementary online material). The calculation of adherence values via 'AdhereR' can also be integrated in larger data analysis scripts and made available in a data repository for future use in similar studies, freely-available or with specific access rights. This allows other research teams to use the same parametrizations (for example if studying the same type of medication in different populations), and thus increase homogeneity of studies for the benefit of later meta-analytic efforts. If these parametrizations are complemented by justifications of each decision based on clinical and/or research evidence in specific clinical areas, they can be subject to discussion and clinical consensus building and thus represent transparent and easily-implementable guidelines for EHD-based adherence research in those areas. In this situation, comparisons across medications can also take into account any differences in analysis choices, and general rules derived for adherence calculation across domains. ## References <a name="Ref-Arnet2016"></a>Arnet I., Kooij M.J., Messerli M., Hersberger K.E., Heerdink E.R., Bouvy M. (2016) [Proposal of Standardization to Assess Adherence With Medication Records Methodology Matters](https://pubmed.ncbi.nlm.nih.gov/26917817/). *The Annals of Pharmacotherapy* **50**(5):360–8. [doi:10.1177/1060028016634106](https://pubmed.ncbi.nlm.nih.gov/26917817/). <a name="Ref-Gardarsdottir2010"></a>Gardarsdottir H., Souverein P.C., Egberts T.C.G., Heerdink E.R. (2010) [Construction of drug treatment episodes from drug-dispensing histories is influenced by the gap length](https://pubmed.ncbi.nlm.nih.gov/19880282/). *J Clin Epidemiol.* **63**(4):422–7. [doi:10.1016/j.jclinepi.2009.07.001](http://dx.doi.org/10.1016/j.jclinepi.2009.07.001). <a name="Ref-Greevy2011"></a>Greevy R.A., Huizinga M.M., Roumie C.L., Grijalva C.G., Murff H., Liu X., Griffin, M.R. (2011). [Comparisons of Persistence and Durability Among Three Oral Antidiabetic Therapies Using Electronic Prescription-Fill Data: The Impact of Adherence Requirements and Stockpiling](https://pubmed.ncbi.nlm.nih.gov/22048232/). *Clinical Pharmacology & Therapeutics* **90**(6):813–819. [10.1038/clpt.2011.228](https://pubmed.ncbi.nlm.nih.gov/22048232/). <a name="Ref-Peterson2007"></a>Peterson A.M., Nau D.P., Cramer J.A., Benner J., Gwadry-Sridhar F., Nichol M. (2007) [A checklist for medication compliance and persistence studies using retrospective databases](https://pubmed.ncbi.nlm.nih.gov/17261111/). *Value in Health: Journal of the International Society for Pharmacoeconomics and Outcomes Research* **10**(1):3–12. [doi:10.1111/j.1524-4733.2006.00139.x](http://dx.doi.org/10.1111/j.1524-4733.2006.00139.x). <a name="Ref-SouvereinInPress"></a>Souverein PC, Koster ES, Colice G, van Ganse E, Chisholm A, Price D, et al. (*in press*) [Inhaled Corticosteroid Adherence Patterns in a Longitudinal Asthma Cohort.](https://www.sciencedirect.com/science/article/abs/pii/S2213219816304238) *J Allergy Clin Immunol Pract*. [doi:10.1016/j.jaip.2016.09.022](http://dx.doi.org/10.1016/j.jaip.2016.09.022). <a name="Ref-Vollmer2012"></a>Vollmer W.M., Xu M., Feldstein A., Smith D., Waterbury A., Rand C. (2012) [Comparison of pharmacy-based measures of medication adherence](https://pubmed.ncbi.nlm.nih.gov/22691240/). *BMC Health Services Research* **12**(1):155. [doi:10.1186/1472-6963-12-155](http://dx.doi.org/10.1186/1472-6963-12-155). <a name="Ref-Vrijens2012"></a>Vrijens B., De Geest S., Hughes D.A., Przemyslaw K., Demonceau J., Ruppar T., Dobbels F., Fargher E., Morrison V., Lewek P., Matyjaszczyk M., Mshelia C., Clyne W., Aronson J.K., Urquhart J.; ABC Project Team (2012) [A new taxonomy for describing and defining adherence to medications](https://pubmed.ncbi.nlm.nih.gov/22486599/). *British Journal of Clinical Pharmacology* **73**(5):691–705. [doi:10.1111/j.1365-2125.2012.04167.x](https://pubmed.ncbi.nlm.nih.gov/22486599/). <a name="Ref-VanWijk2006"></a>Van Wijk B.L.G., Klungel O.H., Heerdink E.R., de Boer A. (2006). [Refill persistence with chronic medication assessed from a pharmacy database was influenced by method of calculation](https://pubmed.ncbi.nlm.nih.gov/16360556/). *Journal of Clinical Epidemiology* **59**(1), 11–17. [doi:10.1016/j.jclinepi.2005.05.005](http://dx.doi.org/10.1016/j.jclinepi.2005.05.005). <a name="Ref-Sattler2013"></a>Sattler E., Lee J., Perri M. (2011). [Medication (Re)fill Adherence Measures Derived from Pharmacy Claims Data in Older Americans: A Review of the Literature](https://pubmed.ncbi.nlm.nih.gov/23553512/). *Drugs & Aging* **30**(6), 383–99. [doi:10.1007/s40266-013-0074-z](http://dx.doi.org/10.1007/s40266-013-0074-z). ## Appendix I: Distributing computations on remote Linux hosts For example, we show here how to compute CMA1 on a remote `Linux` machine from `macOS` and `Windows 10` hosts. The Linux machine (hostname `workhorse`) runs `Ubuntu 16.04` (64 bits) with `R 3.4.1` manually compiled and installed in `/usr/local/lib64/R`, and an `OpenSSH` server allowing access to the user `user`. The `macOS` laptop is running `macOS High Sierra 10.13.4`, `R 3.4.3`, `openssh` (installed through [homebrew](https://brew.sh/)) and we set up passwordless ssh access to `workhorse` (see, for example, the tutorial [here](http://www.linuxproblem.org/art_9.html)). The `Windows 10` desktop is running `Microsoft Windows 10 Pro 1709 64 bits` with `openssh` installed vias [Cygwin](http://www.cygwin.com/) (also with passwordless ssh access to `workhorse`) and `Microsoft R Open 3.4.3`. All machines have the latest version of `AdhereR` and `snow` installed. With these, we can, for example do: ```{r eval=FALSE} cmaW3 <- CMA_sliding_window(CMA="CMA1", data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, sliding.window.duration=30, sliding.window.step.duration=30, parallel.backend="snow", # make clear we want to use snow parallel.threads=c(rep( list(list(host="user@workhorse", # host (and user) rscript="/usr/local/bin/Rscript", # Rscript location snowlib="/usr/local/lib64/R/library/") # snow package location ), 2))) # two remote threads ``` where we use `parallel.backend="snow"` and we specify the `workhorse` node(s) we want to use. Here, `parallel.threads` is a list of host specifications (one per thread), each a list contaning the `host` (possibly with the username for ssh access), `rscript` (the location on the remote host of `Rscript`) and `snowlib` (the location on the remote host of the `snow` package, usually the location where the `R` packages are installed). In this exmple, we create 2 such identical hosts (using `rep(..., 2)`) which measn that we will have two parallel threads running on `workhorse`. If everything is fine, the results should be returned to the user as usual. *NB1.* This procedure was tested only on `Linux` hosts, but it should *in principle* also work with `Windows` hosts as well (but the setup is currently much more complex and apparently less reliable; moreover, in most high-performance production environments we expect `Linux` rather that `Windows` compute nodes). <!-- Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format: --> <!-- - Never uses retina figures --> <!-- - Has a smaller default figure size --> <!-- - Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style --> <!-- ## Vignette Info --> <!-- Note the various macros within the `vignette` section of the metadata block above. These are required in order to instruct R how to build the vignette. Note that you should change the `title` field and the `\VignetteIndexEntry` to match the title of your vignette. --> <!-- ## Styles --> <!-- The `html_vignette` template includes a basic CSS theme. To override this theme you can specify your own CSS in the document metadata as follows: --> <!-- output: --> <!-- rmarkdown::html_vignette: --> <!-- css: mystyles.css --> <!-- ## More Examples --> <!-- You can write math expressions, e.g. $Y = X\beta + \epsilon$, footnotes^[A footnote here.] --> <!-- Also a quote using `>`: --> <!-- > "He who gives up [code] safety for [code] speed deserves neither." --> <!-- ([via](https://twitter.com/hadleywickham/status/504368538874703872)) -->
/scratch/gouwar.j/cran-all/cranData/AdhereR/inst/doc/AdhereR-overview.Rmd
## ---- echo=FALSE, message=FALSE, warning=FALSE, results='hide'---------------- # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg");
/scratch/gouwar.j/cran-all/cranData/AdhereR/inst/doc/calling-AdhereR-from-python3.R
--- title: "Calling `AdhereR` from `Python 3`" author: "Dan Dediu" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Calling AdhereR from Python3} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` ## Overview While `AdhereR` is written in `R` and makes extensive use of various `R` packages and techniques (such as `data.table` and parallel processing), it is possible to use it from other programming languages and applications. This is accomplished through a very generic mecahnism that only requires the caller to be able to *read and write files* in a location of its choice and to *invoke an external command* with a set of arguments. These requirements are widely available in programming languages (such as `C`/`C++`, `Java`, `Python 2` and `3`, and `R` itself), can be accomplished from the scripting available in several applications (e.g., `VBA` in Microsoft Excel, `STATA` scripting or `SAS` programs), and works in similar ways across the major Operating Systems (`Linux` flavors, `macOS` and `Microsoft Windows`). We present here this generic mechanism using its *reference implementation* for `Python 3`. While this reference implementation is definitely usable in production environments (including from [Jupyter Notebooks](#from-a-jupyter-notebook)) and comes with the `R` `AdhereR` package (see [here](#making-the-adherer-module-visible-to-python-aka-installation) on how to "install" it in `Python 3`), this can probably be improved both in terms of calling and passing data between `Python` and `R`, as well as in terms of the "pythonicity" of the `Python` side of the implementation. Nevertheless, we hope this implementation will be useful to users of `Python` that would like to access `AdhereR` without switching to `R`, and will provide a template and working example for further implementations that aim to make `AdhereR` available to other programming languages and platforms. ## Table of Contents - [Introduction](#introduction) - [General ideas](#general-ideas) - [Fundamentals of calling `AdhereR` from `Python 3`](#fundamentals-of-calling-adherer-from-python-3) - [The `Python 3` wrapper: the `adherer` module](#the-python-3-wrapper-the-adherer-module) - [Making the `adherer` module visible to Python (aka installation)](#making-the-adherer-module-visible-to-python-aka-installation) - [Importing the `adherer` module and initializations](#importing-the-adherer-module-and-initializations) - [The class hierarchy](#the-class-hierarchy) - [The `CallAdhereRError` exception class](#the-calladherererror-exception-class) - [The base class `CMA0`](#the-base-class-cma0) - [Class `CMA1` and its daughter classes `CMA2`, `CMA3` and `CMA4`](#class-cma1-and-its-daughter-classes-cma2-cma3-and-cma4) - [Class `CMA5` and its daughter classes `CMA6`, `CMA7`, `CMA8` and `CMA9`](#class-cma5-and-its-daughter-classes-cma6-cma7-cma8-and-cma9) - [Classes `CMAPerEpisode` and `CMASlidingWindow`](#classes-cmaperepisode-and-cmaslidingwindow) - [Examples of use](#examples-of-use) - [Basic usage](#basic-usage) - [Importing `adherer` and checking autodetection](#importing-adherer-and-checking-autodetection) - [Export the test dataset from `R` and import it in `Python`](#export-the-test-dataset-from-r-and-import-it-in-python) - [Compute and plot test CMA](#compute-and-plot-test-cma) - [Interactive plotting](#interactive-plotting) - [From a Jupyter Notebook](#from-a-jupyter-notebook) - [Parallel processing (locally and on different machines)](#parallel-processing-locally-and-on-different-machines) - [Single thread on the local machine](#single-thread-on-the-local-machine) - [Multi-threaded on the local machine](#multi-threaded-on-the-local-machine) - [Parallel on remote machines over a network](#parallel-on-remote-machines-over-a-network) - [Appendix I: the communication protocol](#appendix-i-the-communication-protocol) - [Context](#context) - [Protocol](#protocol) - [PARAMETERS](#parameters1) - [COMMENTS](#comments) - [SPECIAL PARAMETERS](#special-parameters2) - [FUNCTIONS](#functions) - [PLOTTING](#plotting) - [`CMA1`, `CMA2`, `CMA3`, `CMA4`](#cma1-cma2-cma3-cma4) - [`CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9`](#cma5-cma6-cma7-cma8-cma9) - [`CMA_per_episode`](#cma_per_episode) - [`CMA_sliding_window`](#cma_sliding_window) - [`compute_event_int_gaps`](#compute_event_int_gaps) - [`compute_treatment_episodes`](#compute_treatment_episodes) - [`plot_interactive_cma`](#plot_interactive_cma) - [Appendix II: the `Python 3` code](#appendix-ii-the-python-3-code) - [Notes](#notes) ## General ideas The mechanism is very general, and is based on a *wrapper* being available on the *caller platform* (here, `Python 3`) that performs the following general tasks: - *exposes* to the users on the caller platform a *set of functions/methods/objects* (or other mechanisms specific to that platform) that encapsulate, in a platform-specific way, the main functionalities from `AdhereR` that are of interest to the platform's users; - when the user *calls* such an exposed function with a given set of argument values, the wrapper *transparently translates* these argument values in a format understandable by `AdhereR`; in particular, it saves any datasets to be processed (as TAB-separated `CSV files`) and writes the argument values to `text file` (in a standardised format), all in a directory of its choice (henceforth, the *data sharing directory*); - the wrapper uses the *`shell` mechanism* to call `R` (as it is installed on the caller system) and instructs it to execute a simple sequence of `R` commands; - these `R` commands load the `AdhereR` package and execute the `callAdhereR()` function from the package, passing it the path to the data sharing directory as its only argument; - internally, `callAdhereR()`: - parses and loads the data and arguments, - performs basic consistency checks, - calls the appropriate `AdhereR` method(s) with the appropriate arguments, - checks the results and, as appropriate, - writes back to a predefined file any error messages, warnings or any other messages generated, and, if the case, - saves the results to TAB-separated `CSV` files or image files; - the wrapper is notified when the `R` has finished executing, and: - loads the file containing the errors, warnings and messages, and possibly the results, - packs them into objects appropriate to the caller platform, and - returns them to the user. The full protocol is detailed in [**Appendix I**](#appendix-1). ## Fundamentals of calling `AdhereR` from `Python 3` We will use here a `macOS` setup for illustration purposes, but this is very similar on the other supported `OS`s. Essentially, the `Python 3` wrapper creates the *input files* `parameters.log` and `dataset.csv` in the data sharing directory (let us denote it as `DATA_SHARING_DIRECTORY`, by default, a unique temorary directory). Let's assume that `DATA_SHARING_DIRECTORY` is set to `/var/folders/kx/bphryt7j5tz1n_fcjk5809940000gn/T/adherer-qmx4pw7t`; then, before calling `AdhereR`, this directory should contain the files: . |-parameters.log \-dataset.csv Please note that `R` must be *properly installed* on the system such that `Rscript` (or `Rscript.exe` on Windows) does exist and works; the `Python 3` wrapper tries to locate it using a variety of strategies (in order, `which`, followed by a set of standard locations on `macOS` and `Linux` or a set of standard Windows Registry Keys on `MS Windows`) but if this fails or if the user wants to use a non-standard `R` installation, the wrapper allows this through the exported function `set_rscript_path()`. Let's assume for now that `Rscript` is located in `/usr/local/bin/Rscript` and its automatic detection was successful (let us denote this path as `RSCRIPT_PATH`). With these path variables automatically or manually set, the `Python 3` wrapper is ready to call `AdhereR`: ``` python import subprocess # allow shell calls [...] # Call adhereR: rscript_cmd = '"' + RSCRIPT_PATH + '"' + ' --vanilla -e ' + \ '"library(AdhereR); ' + \ `callAdhereR(` + DATA_SHARING_DIRECTORY + '\')"' return_code = subprocess.call(rscript_cmd, shell=True) ``` When the `Rscript` process returns, `return_code` should be `0` for success (in the sense of calling `AdhereR`, not in the sense that `AdhereR` also succeeded in the task it was assigned to do) or something else for errors. If `return_code != 0`, the process returns with a warning. Otherwise, an attempt is made to read the messages produced by `AdhereR` (available in the `Adherer-results.txt` file in the `DATA_SHARING_DIRECTORY` directory) and checking if the last line begins with `OK:`. If it does not, a warning contaning the messages is thrown and the process returns. If it does, the appropriate output files are read, parsed and loaded (depending on the invoked function, these files might differ). For example, after successfully invoking `CMA1`, the `DATA_SHARING_DIRECTORY` might look like: . |-parameters.log |-dataset.csv |-Adherer-results.txt \-CMA.csv In this example, the wrapper would parse and load `CMA.csv` as a `pandas` table: ``` python import pandas # load pandas [...] # Expecting CMA.csv ret_val['CMA'] = pandas.read_csv(os.path.join(path_to_data_directory, 'CMA.csv'), sep='\t', header=0) ``` If plotting was requested, the resulting plot is also loaded using the `PIL`/`Pillow` library: ``` python from PIL import Image # load images [...] # Load the produced image (if any): ret_val['plot'] = Image.open(os.path.join((plot_save_to if not (plot_save_to is None) else DATA_SHARING_DIRECTORY), 'adherer-plot' + '.' + plot_save_as)) ``` where `plot_save_to` and `plot_save_as` may specify where the plots are to be saved and in which format. ## The `Python 3` wrapper: the `adherer` module ### Making the `adherer` module visible to Python (aka installation) The reference implementation is contained in single file (`adherer.py`) included with the `R` `AdhereR` package and whose location can be obtained using the function `getCallerWrapperLocation(full.path=TRUE)` from `AdhereR` (*N.B.* it is located in the directory where the `AdhereR` package is installed on the system, subdirectory `wrappers/python3/adherer.py`; for example, on the example `macos` machine this is `/Library/Frameworks/R.framework/Versions/3.4/Resources/library/AdhereR/wrappers/python3/adherer.py`). In the future, as more wrappers are added, the argument `callig.platform` will allow the selection of the desired wrapper (now it is implicitely set to `python3`). This file can be either: - *copied and placed* in `Python`'s "module search paths" (a list of directories comprising, in order, the directory contining the input script, the environment variable `PYTHONPATH`, and a default location; see [here](https://docs.python.org/3/tutorial/modules.html#the-module-search-path) for details), in which cae it can be simply imported using the standard `Python` syntax (e.g. `import adherer` or `import adherer as ad`), or - *imported from its location* by either: - adding its directory to the `PYTHONPATH` environment variable [the recommended solution], or - using various tricks described, for example, [here](https://stackoverflow.com/a/67692). On the example `macos` machine, this can be achieved by adding: ``` bash # Add AdhereR to PYTHONPATH export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/[...]/AdhereR/wrappers/python3 ``` to the `.bash_profile` file in the user's home folder (if this file does not exist, then it can be created using a text editor such as `nano`; please note that the `[...]` are for shortening the path and should be replaced by the actual path given in full above). The process should be very similar on `Linux`, while on `MS Windows` one should use the system's "Environment Variables" settings (for example, see [here](https://stackoverflow.com/a/4855685) for details). Please note that `adherer` needs `pandas` and `PIL`, which can be installed, for example, using: ``` bash pip3 install pandas pip3 install Pillow ``` *NOTE:* we will consistently use `AdhereR` to refer to the `R` package, and `adherer` to refer to the `Python 3` module. ### Importing the `adherer` module and initializations Thus, the reference implementation is technically a `module` called `adherer` that can be imported in your code (we assume here the recommended solution, but see above for other ways of doing it): ``` python # Import adherer as ad: import adherer as ad ``` When the `adherer` module is imported for the first time, it runs the following *initialization code*: 1. it tries to **autodetect the location where `R` is installed on the system**. More precisely, it looks for `Rscript` (or `Rscript.exe` on Windows) using several strategies, in order: `which`, followed by a set of standard locations on `macOS` (`/usr/bin/Rscript`, `/usr/local/bin/Rscript`, `/opt/local/bin/Rscript` and `/Library/Frameworks/R.framework/Versions/Current/Resources/bin/Rscript`) and `Linux` (`/usr/bin/Rscript`, `/usr/local/bin/Rscript`, `/opt/local/bin/Rscript` and `~/bin/Rscript`) or a set of standard Windows Registry Keys on `MS Windows` (`HKEY_CURRENT_USER\SOFTWARE\R-core\R`, `HKEY_CURRENT_USER\SOFTWARE\R-core\R32`, `HKEY_CURRENT_USER\SOFTWARE\R-core\R64`, `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R`, `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R32` and `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R64`) which should contain `Current Version` and `InstallPath` (with the added complexity that 64 bits Windows hists both 32 and 64 bits regsistries). This procedure is inspired by the way [`RStudio` checks for `R`](https://support.rstudio.com/hc/en-us/articles/200486138-Using-Different-Versions-of-R): - if this process **fails**, a warning is thrown instructing the user to manually set the path using the `set_rscript_path()` function exposed by the `adherer` module, and sets the internal variable `_RSCRIPT_PATH` to `None` (which insures that all future calls to `AdhereR` will fail; - if the process **succeeds**, it checks if the `AdhereR` package is installed for the detected `R` and has a correct version: + if this check **fails**, an appropriate warning is thrown and `_RSCRIPT_PATH` is set to `None`; + if it **succeeds**, continue to step (2) below. 2. it tries to **create a temporary directory** (with prefix `adherer-`) with read and write access for the current user: - if this **fails**, it throws a warning instructing the user to manually set this to a directory with read & write access using the `set_data_sharing_directory()` function, and sets the internal variable `_DATA_SHARING_DIRECTORY` to `None` (ensuring that calls to `AdhereR` will fail); - if it **succeeds**, the initialization code is considered to have finished successfully; also, on exit this temporary `_DATA_SHARING_DIRECTORY` is automatically deleted. ### The class hierarchy The `adherer` module tries to emulate the same philosophy as the `AhereR` package, where various *types* of *CMAs* ("continuous multiple-interval measures of medication availability/gaps") that implement different ways of computing adherence encapsulate the data on which they were computed, the various relevant parameter values used, as well as the results of the computation. Here, we implemented this through the following class hierarchy (image generated with [pyreverse](https://pypi.org/project/pyreverse/), not showing the private attributes): <img src="classes_adherer.png" alt="class hierarchy" style="width: 100%;"/> We will discuss now the main classes in turn. #### The `CallAdhereRError` exception class Errors in the `adherer` code are signalled by throwing `CallAdhereRError` exceptions (the red class shown in the bottom right corner). #### The base class `CMA0` All classes that implement ways to compute adherence (`CMA`s) are derived from `CMA0`. `CMA0` does not in itself compute any sort of adherence, but instead provides the *infrastructure* for *storing* the data, parameter values and results (including errors), and for *interacting* with `AdhereR`. Please note that in the "higher" `CMA`s, the class constructor `__init()__` implicitely performs the actual computation of the `CMA` and saves the results (for `CMA0` there are no such computations and `__init()__` only saves the parameters internally)! 1. **storage of data and parameter values**: `CMA0` allows the user to set various parameters through the constructor `__init()__`, parameters that are stored for later use, printing, saving, and for facilitating easy reconstruction of all types of computations. By main groups, these are (please, see the manual entry for `?CMA0` in the `AdhereR` package and the full protocol in [**Appendix I**](#appendix-1) as well): - `dataset` stores the primary data (as a `Pandas` table with various columns) containing the actual events; must be given; - `id_colname`, `event_date_colname`, `event_duration_colname`, `event_daily_dose_colname` and `medication_class_colname`: these give the *names* of the columns in the `dataset` table containing important information about the events (the first three are required, the last two are optional); - `carryover_within_obs_window`, `carryover_into_obs_window`, `carry_only_for_same_medication`, `consider_dosage_change`, `medication_change_means_new_treatment_episode`, `maximum_permissible_gap`, `maximum_permissible_gap_unit`: optional parameters defining the types of carry-over, changes and treatment episode triggers; - `followup_window_start_type`, `followup_window_start `followup_window_start_unit`, `followup_window_duration_type `followup_window_duration`, `followup_window_duration_unit`, `observation_window_start_type`, `observation_window_start`, `observation_window_start_unit `observation_window_duration_type`, `observation_window_duration`, `observation_window_duration_unit`: optional parameters defining the follow-up and observation windows; - `sliding_window_start_type`, `sliding_window_start`, `sliding_window_start_unit`, `sliding_window_duration_type`, `sliding_window_duration`, `sliding_window_duration_unit`, `sliding_window_step_duration_type`, `sliding_window_step_duration`, `sliding_window_step_unit`, `sliding_window_no_steps`: optional parameters defining the sliding windows; - `cma_to_apply`: optional parameter specifying which "simple" `CMA` is to be used when computing sliding windos and treatment episodes; - `date_format`: optional parameter describing the format of column dates in `dataset` (defaults to month/day/year); - `event_interval_colname`, `gap_days_colname`: optional parameters allowing the user to change the names of the columns where these computed data are stored in the resuling table; - `force_na_cma_for_failed_patients`, `keep_window_start_end_dates`, `remove_events_outside_followup_window`, `keep_event_interval_for_all_events`: optional parameters governing the content of the resuling table; - `parallel_backend`, `parallel_threads`: these optional parameters control the parallelism of the computations (if any); see **PARALLEL PROCESSING** for details; - `suppress_warnings`: should all the internal warning be shown? - `save_event_info`: should this "advanced" info be also made available? - `na_symbol_numeric`, `na_symbol_string`, `logical_symbol_true`, `logical_symbol_false`, `colnames_dot_symbol`, `colnames_start_dot`: these optional parameters allow `AdhereR` to adapt to "non-`R`" conventions concerning the data format for missing values, logicals and column names; - `path_to_rscript`, `path_to_data_directory`: these parameters allow the user to override the `_RSCRIPT_PATH` and `_DATA_SHARING_DIRECTORY` variables; - `print_adherer_messages`: should the important messages be printed to the user as well? 2. **storage of, and access to, the results**: - `get_dataset()`: returns the internally saved `Pandas` table `dataset`; - `get_cma()`: returns the computed `CMA` (if any); - `get_event_info()`: returns the computed event information (if any); - `get_treatment_episodes()`: returns the computed treatment episodes information (if any); - `get_computation_results()`: return the results of the last computation (if any); more precisely, a `dictionary` containing the numeric `code` returned by `AdhereR` and the string `messages` written by `AdhereR` during the computation; 3. **computing event interval and treatment episode info**: this can be done by explicitelly calling the `compute_event_int_gaps()` and `compute_treatment_episodes()` functions; 4. **plotting**: - *static plotting*: this is realized by the `plot()` function that takes several plotting-specific parameters: + `patients_to_plot`: should a subset of the patients present in the `dataset` be plotted (by default, all will be)? + `save_to`, `save_as`, `width`, `height`, `quality`, `dpi`: where should the plot be saved, in what format, dimentions and quality? + `duration`, `align_all_patients`, `align_first_event_at_zero`, `show_period`, `period_in_days`: duration to plots and alignment of patients; + `show_legend`, `legend_x`, `legend_y`, `legend_bkg_opacity`: legend parameters; + `cex`, `cex_axis`, `cex_lab`: the relative size of various text elements; + `show_cma`, `print_cma`, `plot_cma`, `plot_cma_as_histogram`, `cma_plot_ratio`, `cma_plot_col`, `cma_plot_border`, `cma_plot_bkg`, `cma_plot_text`: should the cma be shown and how? + `unspecified_category_label`: implicit label of unlabelled categories? + `lty_event`, `lwd_event`, `pch_start_event`, `pch_end_event`, `show_event_intervals`, `col_na`, `col_continuation`, `lty_continuation`, `lwd_continuation`: visual aspects of events and continuations; + `highlight_followup_window`, `followup_window_col`, `highlight_observation_window`, `observation_window_col`, `observation_window_density`, `observation_window_angle`, `show_real_obs_window_start`, `real_obs_window_density`, `real_obs_window_angle`: visual appearance of the follow-up, obervation and "real observation" windows (the latter for `CMA`s that djust it); + `bw_plot`: produce a grayscel plot? - *interactive plotting*: the `plot_interactive()` function launches a [Shiny](https://shiny.rstudio.com/)-powered interactive plot using the system's WEB browser; the only parameter `patient_to_plot` may specify which patient to show initially, as all the relevant parameters can be interactively altered ar run-time; 5. **printing**: the `__repr__()` function implements a very simple printing mechanism showing the `CMA` type and a summary of the `dataset`; 6. **calling `AdhereR`**: the private function `_call_adherer()` is the real workhorse that manages all the interaction with the `R` `AdhereR` package as described above. This function can take many parameters covering *all* that `AdhereR` can do, but it is not intended to be directly called by the end-user but instead to be internally called by various exposed functions such as `plot()`, `compute_event_int_gaps()` and `__init()__`. Roughly, after some checks, it creates the files needed for communication, calls `AdhereR`, analyses any errors, warnings and messages that it might have generated, and packs the results in a manageable format. To preserve the generality of the interaction with `AdhereR`, all the `CMA` classes define a private static member `_adherer_function` which is the name of the corresponding `S3` class as implemented in `AdhereR`. #### Class `CMA1` and its daughter classes `CMA2`, `CMA3` and `CMA4` `CMA1` is derived from `CMA0` by redefining the `__init__()` constructor to (a) take only a subset of arguments relevant for the `CMA`s 1--4 (see the `AdhereR` help for them), and (b) to internally call `_call_adherer()` with these parameters. It checks if the result of `_call_adherer()` signals an error, in which case ir throws a `CallAdhereRError` exception, otherwise packing the code, messages, cma and (possibly) event information in the corresponding member variables for later access. Due to the generic mechanism implemented by `_adherer_function`, `CMA2`, `CMA3` and `CMA4` are derived directly from `CMA1` but only redefine `_adherer_function` appropriately. #### Class `CMA5` and its daughter classes `CMA6`, `CMA7`, `CMA8` and `CMA9` The same story applies here, with `CMA5` being derived from `CMA0` and redefining `__init__()`, with `CMA6`--`CMA9` only using the `_adherer_function` mechanism. Compared with `CMA1`, `CMA5` defines new required arguments related to medication type and dosage. #### Classes `CMAPerEpisode` and `CMASlidingWindow` Just like `CMA1` and `CMA5`, these two require specific parameters and are thus derived directly from `CMA0` (but, in contrast, they don't have their own derived classes). ### Examples of use Below we show some examples of using the `Python 3` reference wrapper. We are using [`IPython`](https://ipython.org/) from the [`Spyder 3`](https://github.com/spyder-ide/spyder) environment; the `In [n]: ` represents the *input* prompt, the ` ...: ` the *continuation* of the input on the following line(s), and `Out[n]: ` the produced output. #### Basic usage ##### Importing `adherer` and checking autodetection ``` python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) Type "copyright", "credits" or "license" for more information. IPython 6.3.0 -- An enhanced Interactive Python. In [1]: # Import adherer as ad: ...: import adherer as ad In [2]: # Show the _DATA_SHARING_DIRECTORY (should be set automatically to a temporary location): ...: ad._DATA_SHARING_DIRECTORY.name Out[2]: '/var/folders/kx/bphryt7j5tz1n_fcjk5809940000gn/T/adherer-05hdq6el' In [3]: # Show the _RSCRIPT_PATH (should be dectedt automatically): ...: ad._RSCRIPT_PATH Out[3]: '/usr/local/bin/Rscript' ``` Everything seems fine! ##### Export the test dataset from `R` and import it in `Python` Let's export the sample dataset `med.events` included in `AdhereR` as a TAB-separated CSV file in a location for use here (please note that this must be done from an `R` console, such as from `RStudio`, and not from `Python`!): ``` R R version 3.4.3 (2017-11-30) -- "Kite-Eating Tree" Copyright (C) 2017 The R Foundation for Statistical Computing Platform: x86_64-apple-darwin15.6.0 (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > library(AdhereR) # load the AdhereR package > head(med.events) # see how the included med.events dataset looks like PATIENT_ID DATE PERDAY CATEGORY DURATION 286 1 04/26/2033 4 medA 50 287 1 07/04/2033 4 medB 30 288 1 08/03/2033 4 medB 30 289 1 08/17/2033 4 medB 30 291 1 10/13/2033 4 medB 30 290 1 10/16/2033 4 medB 30 > write.table(med.events, file="~/Temp/med-events.csv", quote=FALSE, sep="\t", row.names=FALSE, col.names=TRUE) # save med.events as TAB-separated CSV file in a location (here, in the Temp folder) > ``` Now, back to `Python`: ``` python In [4]: # Import Pandas as pd: ...: import pandas as pd In [5]: # Load the test dataset ...: df = pd.read_csv('~/Temp/med-events.csv', sep='\t', header=0) In [6]: # Let's look at first 6 rows (it should match the R output above except for the row names): ...: df.head(6) Out[6]: PATIENT_ID DATE PERDAY CATEGORY DURATION 0 1 04/26/2033 4 medA 50 1 1 07/04/2033 4 medB 30 2 1 08/03/2033 4 medB 30 3 1 08/17/2033 4 medB 30 4 1 10/13/2033 4 medB 30 5 1 10/16/2033 4 medB 30 ``` All good so far, the data was imported successfully as a `Pandas` table. ##### Compute and plot test CMA Now let's compute `CMA8` on these data in `Python`: ``` python In [7]: # Compute CMA8 as a test: ...: cma8 = ad.CMA8(df, ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY') ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! ``` We can see that things went pretty well, as no exceptions were being thrown and the message starts with a reassuring `Adherer returned code 0`, followed by precisely what `AdhereR` said: - `AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10:`: first, self-identification (its own version and `R`'s version), followed by the date and time the processing was initated; - `OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!`, which means that basically all seems allright but that there might still be some messages or warning displayed above that could be informative or point to subtler issues. Let's see how these results look like: ``` python In [8]: # Summary of cma8: ...: cma8 Out[8]: CMA object of type CMA8 (on 1080 rows). In [9]: # The return value and messages: ...: cma8.get_computation_results() Out[9]: {'code': 0, 'messages': ['AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10:\n', 'OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n']} In [10]: # The CMA (the first 6 rows out of all 100): ...: cma8.get_cma().head(6) Out[10]: PATIENT_ID CMA 0 1 0.947945 1 2 0.616438 2 3 0.994521 3 4 0.379452 4 5 0.369863 5 6 0.406849 In [11]: # Plot it (statically): ...: cma8.plot(patients_to_plot=['1', '2', '3'], ...: align_all_patients=True, ...: period_in_days=30, ...: cex=0.5) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-05 13:22:36: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! Out[11]: ``` The output produced in this case (`Out[11]`) consists of the actual image plotted in the `IPython` console (thanks to the `PIL`/`Pillow` package) and reproduced below: <img src="plotting-python.jpg" alt="static plotting in Python" style="width: 100%;"/> Now, we turn again to `R`: ``` R > # Compute the same CMA8 in R: > cma8 <- CMA8(data=med.events, + ID.colname="PATIENT_ID", + event.date.colname="DATE", + event.duration.colname="DURATION", + medication.class.colname="CATEGORY", + event.daily.dose.colname="PERDAY" + ) > > # The computed CMA: > head(getCMA(cma8)) PATIENT_ID CMA 1 1 0.9479452 2 2 0.6164384 3 3 0.9945205 4 4 0.3794521 5 5 0.3698630 6 6 0.4068493 > > # Plot the cma: > plot(cma8, + patients.to.plot=c("1", "2", "3"), + align.all.patients=TRUE, + period.in.days=30, + cex=0.5) > ``` Again, the output is an image (here, shown in the "Plots" panel in `RStudio`): <img src="plotting-r.jpg" alt="static plotting in R" style="width: 100%;"/> It can be seen that, except for the slightly different dimensions (and x/y ratio and quality) due to the actual plotting and exporting, the images show identical patterns. ##### Interactive plotting We will initate now an interactive plotting session from `Python`: ``` python In [12]: cma8.plot_interactive() ``` The output is represented by an interactive session in the default browser; below is a screenshot of this session in `Firefox`: <img src="plotting-interactive.jpg" alt="interactive plotting screenshot" style="width: 100%;"/> The interactive session ends by pressing the "Exit" button in the browser (and optinally also closing the browser tab/window), at which point the usual text output is provided to `Python` and a `True` value signalling success is returned: ``` python Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-05 18:01:28: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! Out[12]: True ``` Please note that it does not matter how the interactive session is started, as it only needs access to the base `CMA0` object and, more precisely, the raw dataset; all relevant parameters, including the CMA type can be changed interactively (this is why the CMA shown in the screenshot is `CMA1` even if the function `cma8.plot_interactive()` was initiated from a `CMA8` object). #### From a Jupyter Notebook `AdhereR` is very easy to use from within a [Jupyter Notebook](https://jupyter.org/) (the only tricky bit being making sure that `adherer` module is visible to the `Python` kernel, but this is explained in detail in section [Making the `adherer` module visible to Python (aka installation)](#making-the-adherer-module-visible-to-python-aka-installation)). A full example is provided in the `jupyter_notebook_python3_wrapper.ipynb` file accompanying the package in the same directory as the `adherer` module, but the code is reproduced below for convenience: ``` python # import the adherer python module (see above about how to make it findable) import adherer # load the test dataset: import pandas df = pandas.read_csv('./test-dataset.csv', sep='\t', header=0) # Change the column names: df.rename(columns={'ID': 'patientID', 'DATE': 'prescriptionDate', 'PERDAY': 'quantityPerDay', 'CLASS': 'medicationType', 'DURATION': 'prescriptionDuration'}, inplace=True) # check the file was read correctly type(df) # HTML printing of data frames import rpy2.ipython.html rpy2.ipython.html.init_printing() # print it df # create a CMA7 object cma7 = adherer.CMA7(df, id_colname='patientID', event_date_colname='prescriptionDate', event_duration_colname='prescriptionDuration', event_daily_dose_colname='quantityPerDay', medication_class_colname='medicationType', followup_window_start=230, followup_window_duration=705, observation_window_start=41, observation_window_duration=100, date_format="%m/%d/%Y", suppress_warnings=True) # print it for checking cma7 # show the plot directly in the notebook x ``` While this is very easy and transparent, some people might prefer to use the more generic mechanism provided by [`rpy2`](https://rpy2.github.io/index.html), which, in principle, allows the transparent call of `R` code from `Python`. In fact, `AdhereR` seems to play very nicely with `rpy2`, even within a [Jupyter Notebook](https://jupyter.org/), as shown by the code below (the full notebook is available in the `jupyter_notebook_python3_py2.ipynb` file accompanying the package in the same directory as the `adherer` module): ``` python # import ryp2 (please note that you might need to install it as per https://rpy2.github.io/doc.html) import rpy2 # check that all is ok rpy2.__path__ # import R's "AdhereR" package from rpy2.robjects.packages import importr adherer = importr('AdhereR') # access the internal R session import rpy2.robjects as robjects # access the med.events dataset med_events = robjects.r['med.events'] # check its type type(med_events) # HTML printing of data frames import rpy2.ipython.html rpy2.ipython.html.init_printing() # print it med_events # make some AdhereR functions available to Python CMA7 = robjects.r['CMA7'] getCMA = robjects.r['getCMA'] # create a CMA7 object cma7 = CMA7(med_events, ID_colname="PATIENT_ID", event_date_colname="DATE", event_duration_colname="DURATION", event_daily_dose_colname="PERDAY", medication_class_colname="CATEGORY", followup_window_start=230, followup_window_duration=705, observation_window_start=41, observation_window_duration=100, date_format="%m/%d/%Y") # print it for checking cma7 # print the estimated CMAs getCMA(cma7) # plot it # this is some clunky code involving do.call and named lists because # plot has lots of arguments with . that cannot be autmatically handeled by rpy2 # the idea is to use a TaggedList that associated values and argument names import rpy2.rlike.container as rlc # for TaggedList rcall = robjects.r['do.call'] # do.call() grdevices = importr('grDevices') # R graphics device # the actual plotting grdevices.jpeg(file="./cma7plot.jpg", width=512, height=512) rcall("plot", rlc.TaggedList([cma7, robjects.IntVector([1,2,3]), False, True], tags=('cma', 'patients.to.plot', 'show.legend', 'align.all.patients'))) grdevices.dev_off() ``` Arguably, the code is clunkier and, at least in this approach, needs an extra step for showing the plot: ``` Include the CMA7 plot using the Markdown syntax (there are several alternatives: https://stackoverflow.com/questions/32370281/how-to-embed-image-or-picture-in-jupyter-notebook-either-from-a-local-machine-o): ![The plot](./cma7plot.jpg) ``` #### Parallel processing (locally and on different machines) `AdhereR` uses `R`'s parallel processing capacities to split expensive computations and distribute them across multiple CPUs/cores in a single computer or even across a network of computers. As an example, we will compute here `CMA1` across sliding windows on the whole dataset, first in `R` and then in `Python 3`. ##### Single thread on the local machine The default mode of computation uses just a single CPU/core on the local machine. ###### `R` ``` R > # Sliding windows with CMA1 (single thread, locally): > cma1w.1l <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="none", + parallel.threads=1) > head(getCMA(cma1w.1l)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` ``` python In [13]: # Sliding windows with CMA1 (single thread, locally): ...: cma1w_1l = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="none", ...: parallel_threads=1) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-06 15:19:07: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [14]: cma1w_1l.get_cma().head(6) Out[14]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ##### Multi-threaded on the local machine If the local machine has multiple CPUs/cores (even with hyperthreading), it might make sense to use them for lengthy computations. `AdhereR` can use several backends (as provided by the `parallel` package in `R`), of which the most used are "multicore" (preffered on `Linux` and `macOS` but currently not available on `Windows`) and "SNOW" (on all three OS's). `AdhereR` is smart enough to use "SNOW" on `Windows` even if "multicore" was requested. ###### `R` ``` R > # Sliding windows with CMA1 (two threads, multicore, locally): > cma1w.2ml <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="multicore", # <--- multicore + parallel.threads=2) > head(getCMA(cma1w.2ml)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > > cma1w.2sl <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="snow", # <--- SNOW + parallel.threads=2) > head(getCMA(cma1w.2sl)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` ``` python In [15]: # Sliding windows with CMA1 (two threads, multicore, locally): ...: cma1w_2ml = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="multicore", # <--- multicore ...: parallel_threads=2) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 11:44:49: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [16]: cma1w_2ml.get_cma().head(6) Out[16]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 In [17]: # Sliding windows with CMA1 (two threads, snow, locally): ...: cma1w_2sl = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="snow", # <--- SNOW ...: parallel_threads=2) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 11:44:49: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [18]: cma1w_2sl.get_cma().head(6) Out[18]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ##### Parallel on remote machines over a network Sometimes it is better to use one or more powerful machines over a network to do very expensive computations, usually, a `Linux` cluster from a `Windows`/`macos` laptop. `AdhereR` leverages the power of `R`'s [`snow`](https://CRAN.R-project.org/package=snow) package (as exposed through the `parallel` package) to distribute workloads across a network of computing nodes. There are several types of "Simple Network of Workstations" (`snow`), described in the package's manual. For example, one may use an already existing `MPI` ([Message Passing Interface](https://en.wikipedia.org/wiki/Message_Passing_Interface)) cluster, but an even simpler setup (and the one that we will illustrate here) involves a *collection of machines* running `Linux` and connected to a network (local or even over the Internet). The machines are called `workhorse1` and `workhorse2`, have differen hardware configurations (both sport quad-core i7 CPUs of different generations with 16Gb RAM) but run the same version of `Ubuntu 16.04` and `R 3.4.2` (not a requirement, as the architecture can be seriously heterogeneous, combining different OS's and versions of `R`). These two machines are connected to the same WiFi router (but they could be on different networks or even across the Internet). The "master" is the same `macOS` laptop used before, connected to the same WiFi router (not a requirement). As pre-requisites, the worker machines should allow [`SSH`](https://ubuntu.com/server/docs/service-openssh) access (for easiness, we use here *passwordless SSH access* from the "master"; see for example [here](http://www.linuxproblem.org/art_9.html) for this setup) and should have the `snow` package installed in `R`. Let's assume that the username allowing `ssh` into the workers is `user`, so that ``` bash laptop:~> ssh user@workhorse1 ``` works with no password needed. With these, we can distribute our processing to the two "workers" (two parallel threads for each, totalling 4 parallel threads): ###### `R` ``` R > # Sliding windows with CMA1 (two remote machines with two threads each): > # First, we need to specify the workers > # This is a list of lists! > # rep(,2) means that we generate two threads on each worker > workers <- c(rep(list(list(host="workhorse1", # hostname (make sure this works from the "master", otherwise use the IP-address) + user="user", # the username that can ssh into the worker (passwordless highly recommended) + rscript="/usr/local/bin/Rscript", # the location of Rscript on the worker + snowlib="/usr/local/lib64/R/library/")), # the location of the snow package on the worker + 2), + rep(list(list(host="workhorse2", + user="user", + rscript="/usr/local/bin/Rscript", + snowlib="/usr/local/lib64/R/library/")), + 2)); > > cma1w.2sw <- CMA_sliding_window(CMA="CMA1", + data=med.events, + ID.colname="PATIENT_ID", + event.date.colname="DATE", + event.duration.colname="DURATION", + event.daily.dose.colname="PERDAY", + medication.class.colname="CATEGORY", + carry.only.for.same.medication=FALSE, + consider.dosage.change=FALSE, + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="snow", + parallel.threads=workers) > head(getCMA(cma1w.2sw)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` A quick for `Python` is that due to the communication protocol between the wrapper and `AdhereR`, the specification of the computer cluster must be a one-line string literally contaning the `R` code defining it, string that will be verbatim parsed and interpreted by `AdhereR`: ``` python In [19]: # Sliding windows with CMA1 (two remote machines with two threads each): ...: # The workers are defined as *literal R code* this is verbatim sent to AdhereR for parsing and interpretation ...: # Please note, however, that this string should not contain line breaks (i.e., it should be a one-liner): ...: workers = 'c(rep(list(list(host="workhorse1", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2), rep(list(list(host="workhorse2", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2))' In [20]: cma1w_2sw = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="snow", ...: parallel_threads=workers) Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 13:22:21: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [21]: cma1w_2sw.get_cma().head(6) Out[21]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ###### Some caveats for over-the-network distributed computation While this is a very good way to transparently distribute processing to more powerful nodes over a network, there are several (potential) issues one must be aware of: - *it may be very hard to debug failures*: failures of this might result from network issues, firewals blocking connections, incorrect `SSH` setup on the "workers" or errors in accesing the "workers" with the given user accounts; see, for examples, discussion [here](https://stackoverflow.com/q/17966055) and [here](https://stackoverflow.com/questions/17923256/r-making-cluster-in-doparallel-snowfall-hangs/17925618#17925618) in case you need to solve such problems; - *latency over the network*: starting the "workers" and especially transmitting the data to the "workers" and the results back to the "master" may take a non-negligible time, especially on slow networks (such as the Internet) and for large datasets; therefore, the best scenarios would involve relatively large computations (but not too large; see below) distributed to several nodes over a fast network; - *you need to wait for the results*: this process assumes that the "master" will wait for the "workers" to finish and return their results; thus, putting the "master" to sleep, shutting it down or disconnecting it from the network will probably result in not being able to collect the resuls back. If one needs very long computations (say 3+ hours), offline mobility or the network is unreliable, we would suggest setting up a separate compute process (that may itself parallelise computations) on the remote machines using, for example, [`screen`](https://www.howtoforge.com/linux_screen), [`nohup`](https://en.wikipedia.org/wiki/Nohup) or a more specialised cluster management platform such as [Son of a Grid Engine (SGE)](https://github.com/daimh/sge). ## Appendix I: the communication protocol ### Context All arguments are written to the text file `parameters.log`; the input data are in the TAB-separated no quotes file `dataset.csv`. The call returns any errors, warning and messages in the text file `Adherer-results.txt` file, and the actual results as TAB-separated no quotes files (not all necessarily produced, depending on the specific methods called) `CMA.csv`, `EVENTINFO.csv` and `TREATMENTEPISODES.csv`, and various image file(s). The argument values in the `parameters.log` are contained between single (`' '`) or double (`" "`) quotes. ### Protocol #### PARAMETERS[^1] Some are *required* and must be explicitly defined, but for most we can use implicit values (i.e., if the user doesn't set them explicitly, we may simply not specify them to the `parameters.log` file and the default values in `AdhereR` will be used). #### COMMENTS Everything on a line following `///` or `#` is considered a comment and ignored (except when included within quotes `" "` or `' '`). #### SPECIAL PARAMETERS[^2] | PARAMETER | MEANING | DEFAULT VALUE IF MISSING | PYHTON 3 | STATA | |------------|----------|--------------------------|----------|-------| | `NA.SYMBOL.NUMERIC` | the numeric missing data symbol | `NA` | `NA` | `.` | | `NA.SYMBOL.STRING` | the string missing data symbol | `NA` | `NA` | `""` | | `LOGICAL.SYMBOL.TRUE` | the logical `TRUE` symbol | `TRUE` | `TRUE` | `1` | | `LOGICAL.SYMBOL.FALSE` | the logical `FALSE` symbol | `FALSE` | `FALSE` | `0` | | `COLNAMES.DOT.SYMBOL` | can we use `.` in column names, and if not, what to replace it with? | `.` | `.` | `_` | | `COLNAMES.START.DOT` | can begin column names with `.` (or equivalent symbol), and if not, what to replace it with? | `.` | `.` | `internal_` | #### FUNCTIONS Possible values are: - `CMA0`, - `CMA1` ...`CMA9`, - `CMA_per_episode`, - `CMA_sliding_window`, - `compute.event.int.gaps`, - `compute.treatment.episodes` and - `plot_interactive_cma`. #### PLOTTING For all the `CMA` functions (i.e., `CMA0`, `CMA1` ...`CMA9`, `CMA_per_episode`, `CMA_sliding_window`) one can ask for a plot of (a subset) of the patients, in which case the parameter `plot.show` must be `TRUE`, and there are several plotting-specific parameters that can be set: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `function` | YES | `"CMA0"` | can also be `"CMA0"` for plotting! | | `plot.show` | NO | `"FALSE"` | [do the plotting? If `TRUE`, save the resulting dataset with a `"-plotted"` suffix to avoid overwriting previous results] | | `plot.save.to` | NO | `""` | [the folder where to save the plots (by default, same folder as the results)] | | `plot.save.as` | NO | `"jpg"` | `"jpg"`, `"png"`, `"tiff"`, `"eps"`, `"pdf"` [the type of image to save] | | `plot.width` | NO | `"7"` | [plot width in inches] | | `plot.height` | NO | `"7"` | [plot height in inches] | | `plot.quality` | NO | `"90"` | [plot quality (applies only to some types of plots] | | `plot.dpi` | NO | `"150"` | [plot DPI (applies only to some types of plots] | | `plot.patients.to.plot` | NO | `""` | [the patient IDs to plot (if missing, all patients) given as `"id1;id2; .. ;idn"`] | | `plot.duration` | NO | `""` | [duration to plot in days (if missing, determined from the data)] | | `plot.align.all.patients` | NO | `"FALSE"` | [should all patients be aligned? and, if so, place the first event as the horizontal 0?] | | `plot.align.first.event.at.zero` | NO | `"TRUE"` | | | `plot.show.period` | NO | `"days"` | `"dates"`, `"days"` [draw vertical bars at regular interval as dates or days?] | | `plot.period.in.days` | NO | `"90"` | [the interval (in days) at which to draw vertical lines] | | `plot.show.legend` | NO | `"TRUE"` | [legend params and position] | | `plot.legend.x` | NO | `"bottom right"` | | | `plot.legend.y` | NO | `""` | | | `plot.legend.bkg.opacity` | NO | `"0.5"` | [background opacity] | | `plot.legend.cex` | NO | `"0.75"` | | | `plot.legend.cex.title` | NO | `"1.0"` | | | `plot.cex` | NO | `"1.0"` | [various plotting font sizes] | | `plot.cex.axis` | NO | `"0.75"` | | | `plot.cex.lab` | NO | `"1.0"` | | | `plot.cex.title` | NO | `"1.5"` | | | `plot.show.cma` | NO | `"TRUE"` | [show the CMA type] | | `plot.xlab.dates` | NO | `"Date"` | [the x-label when showing the dates] | | `plot.xlab.days` | NO | `"Days"` | [the x-label when showing the number of days] | | `plot.ylab.withoutcma` | NO | `"patient"` | [the y-label when there's no CMA] | | `plot.ylab.withcma` | NO | `"patient (& CMA)"` | [the y-label when there's a CMA] | | `plot.title.aligned` | NO | `"Event patterns (all patients aligned)"` | [the title when patients are aligned] | | `plot.title.notaligned` | NO | `"Event patterns"` | [the title when patients are not aligned] | | `plot.col.cats` | NO | `"rainbow()"` | [single color or a function name (followed by "()", e.g., "rainbow()") mapping the categories to colors; for security reasons, the list of functions currently supported is: `rainbow`, `heat.colors`, `terrain.colors`, `topo.colors` and `cm.colors` from base `R`, and `viridis`, `magma`, `inferno`, `plasma`, `cividis`, `rocket`, `mako` and `turbo` from `viridisLite` (if installed)] | | `plot.unspecified.category.label` | NO | `"drug"` | [the label of the unspecified category of medication] | | `plot.medication.groups.to.plot` | NO | `""` | [the names of the medication groups to plot (by default, all)] | | `plot.medication.groups.separator.show` | NO | `"TRUE"` | [group medication events by patient?] | | `plot.medication.groups.separator.lty` | NO | `"solid"` | | | `plot.medication.groups.separator.lwd` | NO | `"2"` | | | `plot.medication.groups.separator.color` | NO | `"blue"` | | | `plot.medication.groups.allother.label` | NO | `"*"` | [the label to use for the \_\_ALL\_OTHERS\_\_ medication class (defaults to *)] | | `plot.lty.event` | NO | `"solid"` | [style parameters controlling the plotting of events] | | `plot.lwd.event` | NO | `"2"` | | | `plot.pch.start.event` | NO | `"15"` | | | `plot.pch.end.event` | NO | `"16"` | | | `plot.show.event.intervals` | NO | `"TRUE"` | [show the actual prescription intervals] | | `plot.show.overlapping.event.intervals` | NO | `"first"` | [how to plot overlapping event intervals (relevant for sliding windows and per episode); can be: "first", "last", "min gap", "max gap", "average"] | | `plot.plot.events.vertically.displaced` | NO | `"TRUE"` | [display the events on different lines (vertical displacement) or not (defaults to TRUE)?] | | `plot.print.dose` | NO | `"FALSE"` | [print daily dose] | | `plot.cex.dose` | NO | `"0.75"` | | | `plot.print.dose.col` | NO | `"black"` | | | `plot.print.dose.outline.col` | NO | `"white"` | | | `plot.print.dose.centered` | NO | `"FALSE"` | | | `plot.plot.dose` | NO | `"FALSE"` | [draw daily dose as line width] | | `plot.lwd.event.max.dose` | NO | `"8"` | | | `plot.plot.dose.lwd.across.medication.classes` | NO | `"FALSE"` | | | `plot.col.na` | NO | `"lightgray"` | [colour for missing data] | | `plot.col.continuation` | NO | `"black"` | [colour, style and width of the continuation lines connecting consecutive events] | | `plot.lty.continuation` | NO | `"dotted"` | | | `plot.lwd.continuation` | NO | `"1"` | | | `plot.print.CMA` | NO | `"TRUE"` | [print CMA next to the participant's ID?] | | `plot.CMA.cex` | NO | `"0.50"` | | | `plot.plot.CMA` | NO | `"TRUE"` | [plot the CMA next to the participant ID?] | | `plot.plot.CMA.as.histogram` | NO | `"TRUE"` | [plot CMA as a histogram or as a density plot?] | | `plot.plot.partial.CMAs.as` | NO | `"stacked"` | [can be "stacked", "overlapping" or "timeseries"] | | `plot.plot.partial.CMAs.as.stacked.col.bars` | NO | `"gray90"` | | | `plot.plot.partial.CMAs.as.stacked.col.border` | NO | `"gray30"` | | | `plot.plot.partial.CMAs.as.stacked.col.text` | NO | `"black"` | | | `plot.plot.partial.CMAs.as.timeseries.vspace` | NO | `"7"` | | | `plot.plot.partial.CMAs.as.timeseries.start.from.zero` | NO | `"TRUE"` | | | `plot.plot.partial.CMAs.as.timeseries.col.dot` | NO | `"darkblue"` | | | `plot.plot.partial.CMAs.as.timeseries.col.interval` | NO | `"gray70"` | | | `plot.plot.partial.CMAs.as.timeseries.col.text` | NO | `"firebrick"` | | | `plot.plot.partial.CMAs.as.timeseries.interval.type` | NO | `"segments"` | [can be "none", "segments", "arrows", "lines" or "rectangles"] | | `plot.plot.partial.CMAs.as.timeseries.lwd.interval` | NO | `"1"` | | | `plot.plot.partial.CMAs.as.timeseries.alpha.interval` | NO | `"0.25"` | | | `plot.plot.partial.CMAs.as.timeseries.show.0perc` | NO | `"TRUE"` | TRUE | | `plot.plot.partial.CMAs.as.timeseries.show.100perc` | NO | `"FALSE"` | | | `plot.plot.partial.CMAs.as.overlapping.alternate` | NO | `"TRUE"` | | | `plot.plot.partial.CMAs.as.overlapping.col.interval` | NO | `"gray70"` | | | `plot.plot.partial.CMAs.as.overlapping.col.text` | NO | `"firebrick"` | | | `plot.CMA.plot.ratio` | NO | `"0.10"` | [the proportion of the total horizontal plot to be taken by the CMA plot] | | `plot.CMA.plot.col` | NO | `"lightgreen"` | [attributes of the CMA plot] | | `plot.CMA.plot.border` | NO | `"darkgreen"` | | | `plot.CMA.plot.bkg` | NO | `"aquamarine"` | | | `plot.CMA.plot.text` | NO | `""` | [by default, the same as `plot.CMA.plot.border`] | | `plot.highlight.followup.window` | NO | `"TRUE"` | | | `plot.followup.window.col` | NO | `"green"` | | | `plot.highlight.observation.window` | NO | `"TRUE"` | | | `plot.observation.window.col` | NO | `"yellow"` | | | `plot.observation.window.density` | NO | `"35"` | | | `plot.observation.window.angle` | NO | `"-30"` | | | `plot.observation.window.opacity` | NO | `"0.3"` | | | `plot.show.real.obs.window.start` | NO | `"TRUE"` | [for some CMAs, the real observation window starts at a different date] | | `plot.real.obs.window.density` | NO | `"35"` | | | `plot.real.obs.window.angle` | NO | `"30"` | | | `plot.alternating.bands.cols` | NO | `["white", "gray95"]` | [the colors of the alternating vertical bands across patients; ''=don't draw any; if >= 1 color then a list of comma-separated strings] | | `plot.rotate.text` | NO | `"-60"` | [some text (e.g., axis labels) may be rotated by this much degrees] | | `plot.force.draw.text` | NO | `"FALSE"` | [if true, always draw text even if too big or too small] | | `plot.bw.plot` | NO | `"FALSE"` | [if `TRUE`, override all user-given colours and replace them with a scheme suitable for grayscale plotting] | | `plot.min.plot.size.in.characters.horiz` | NO | `"0"` | | | `plot.min.plot.size.in.characters.vert` | NO | `"0"` | | | `plot.max.patients.to.plot` | NO | `"100"` | | | `plot.suppress.warnings` | NO | `"FALSE"` | [suppress warnings?] | | `plot.do.not.draw.plot` | NO | `"FALSE"` | [if TRUE, don't draw the actual plot, but only the legend (if required)] | #### `CMA1`, `CMA2`, `CMA3`, `CMA4` The parameters for these functions are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `medication.groups` | NO | `""` | [a named vector of medication group definitions, the name of a column in the data that defines the groups, or ''; the medication groups are flattened into column __MED_GROUP_ID] | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` The parameters for these functions are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA_per_episode` The parameters for this function are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `CMA.to.apply ` | YES | | `CMA1`, `CMA2`, `CMA3`, `CMA4`, `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `medication.change.means.new.treatment.episode` | NO | `"TRUE"` | | | `maximum.permissible.gap` | NO | `"90"` | | | `maximum.permissible.gap.unit ` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"`, `"percent"` | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA_sliding_window` The parameters for this function are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `CMA.to.apply ` | YES | | `CMA1`, `CMA2`, `CMA3`, `CMA4`, `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character'`, `"date'` | | `sliding.window.start` | NO | `0` | | | `sliding.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.duration.type ` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `sliding.window.duration` | NO | `"90"` | | | `sliding.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.step.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"` | | `sliding.window.step.duration ` | NO | `"30"` | | | `sliding.window.step.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.no.steps` | NO | `"-1"` | | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `compute_event_int_gaps` This function is intended for advanced users only; the parameters for this function are: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | | `event.date.colname` | YES | | | | `event.duration.colname` | YES | | | | `event.daily.dose.colname ` | NO | | | | `medication.class.colname` | NO | | | | `carryover.within.obs.window` | NO | `"FALSE"` | | | `carryover.into.obs.window` | NO | `"FALSE"` | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `"0"` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2`" | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `"0"` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `keep.window.start.end.dates` | NO | `"FALSE"` | | | `remove.events.outside.followup.window` | NO | `"TRUE"` | | | `keep.event.interval.for.all.events` | NO | `"FALSE"` | | | `event.interval.colname` | NO | `"event.interval`" | | | `gap.days.colname ` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none "` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | In this case, always returned is successful | #### `compute_treatment_episodes` This function is intended for advanced users only; the parameters for this function are: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | NO | | | `medication.class.colname ` | NO | | | `carryover.within.obs.window` | NO | `"FALSE"` | | | `carryover.into.obs.window` | NO | `"FALSE"` | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `medication.change.means.new.treatment.episode` | NO | `"TRUE"` | | | `maximum.permissible.gap` | NO | `"90"` | | | `maximum.permissible.gap.unit ` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"`, `"percent"` | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `keep.window.start.end.dates` | NO | `"FALSE"` | | | `remove.events.outside.followup.window` | NO | `"TRUE"` | | | `keep.event.interval.for.all.events` | NO | `"FALSE"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The treatment episodes data, as a TAB-separated no quotes CSV file | `TREATMENTEPISODES.csv ` | Always if successful | #### `plot_interactive_cma` This function initiates the interactive plotting in `AdhereR` using `Shiny`: all the plotting will be done in the current internet browser and there are no results expected (except for errors, warnings and other messages). This function ignores the argument `plot.show = "TRUE"` and takes very few arguments of its own, as most of the relevant parameters can be set interactively through the `Shiny` interface. | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `patient_to_plot` | NO | | defaults to the first patient in the dataset | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | NO | | | `medication.class.colname ` | NO | | | `date.format` | NO | `"%m/%d/%Y"` | | | `followup.window.start.max` | NO | | integer >0 | `followup.window.duration.max` | NO | | integer >0 | `observation.window.start.max` | NO | | integer >0 | `observation.window.duration.max ` | NO | | integer >0 | `maximum.permissible.gap.max ` | NO | | integer >0 | `sliding.window.start.max` | NO | | integer >0 | `sliding.window.duration.max ` | NO | | integer >0 | `sliding.window.step.duration.max` | NO | | integer >0 ## Appendix II: the `Python 3` code This annex lists the `Python 3` code included in this vignette in an easy-to-run form (i.e., no `In []`, `Out []` and prompts): ``` python # Import adherer as ad: import adherer as ad # Show the _DATA_SHARING_DIRECTORY (should be set automatically to a temporary location): ad._DATA_SHARING_DIRECTORY.name # Show the _RSCRIPT_PATH (should be dectedt automatically): ad._RSCRIPT_PATH # Import Pandas as pd: import pandas as pd # Load the test dataset df = pd.read_csv('~/Temp/med-events.csv', sep='\t', header=0) # Let's look at first 6 rows (it should match the R output above except for the row names): df.head(6) # Compute CMA8 as a test: cma8 = ad.CMA8(df, id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY') # Summary of cma8: cma8 # The return value and messages: cma8.get_computation_results() # The CMA (the first 6 rows out of all 100): cma8.get_cma().head(6) # Plot it (statically): cma8.plot(patients_to_plot=['1', '2', '3'], align_all_patients=True, period_in_days=30, cex=0.5) # Interactive plotting: cma8.plot_interactive() # Sliding windows with CMA1 (single thread, locally): cma1w_1l = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="none", parallel_threads=1) cma1w_1l.get_cma().head(6) # Sliding windows with CMA1 (two threads, multicore, locally): cma1w_2ml = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="multicore", # <--- multicore parallel_threads=2) cma1w_2ml.get_cma().head(6) # Sliding windows with CMA1 (two threads, snow, locally): cma1w_2sl = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="snow", # <--- SNOW parallel_threads=2) cma1w_2sl.get_cma().head(6) # Sliding windows with CMA1 (two remote machines with two threads each): # The workers are defined as *literal R code* this is verbatim sent to AdhereR for parsing and interpretation # Please note, however, that this string should not contain line breaks (i.e., it should be a one-liner): workers = 'c(rep(list(list(host="workhorse1", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2), rep(list(list(host="workhorse2", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2))' cma1w_2sw = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="snow", parallel_threads=workers) cma1w_2sw.get_cma().head(6) ``` ## Notes [^1]: For more info on the parameters and their values for all these functions please see the `AdhereR` documentation and vignette. [^2]: While this document concerns mainly `Python 3`, we also give the default values for other platforms, in particular `STATA`.
/scratch/gouwar.j/cran-all/cranData/AdhereR/inst/doc/calling-AdhereR-from-python3.Rmd
--- title: "Using `AdhereR` with various database technologies for processing very large datasets" author: "Dan Dediu" date: "`r format(Sys.time(), '%d %B, %Y')`" output: pdf_document: fig_caption: yes highlight: tango toc: yes toc_depth: 6 html_document: df_print: kable highlight: tango theme: readable toc: yes toc_depth: 6 urlcolor: blue editor_options: chunk_output_type: console csl: apa.csl bibliography: bibliography.bibtex --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Introduction It is sometimes stated that `R` *cannot* be used with very large database as they don't fit in memory. Unfortunately, this has also been used as an argument against giving `AhereR` a try, especially in contexts where it would be most useful, namely for processing (very) large datasets. Here we try to dispel this worry by presenting various methods for dealing with such cases, focusing on data stored in "classic" *relational dabases* (such as [`MySQL`](https://www.mysql.com/), [`MariaDB`](https://mariadb.org/), [`SQLite`](https://www.sqlite.org/index.html), [`PostgreSQL`](https://www.postgresql.org/), [`Microsoft SQL Server`](https://www.microsoft.com/en-us/sql-server) or [`Oracle Database`](https://www.oracle.com/database/index.html)) as well as on a widely-used paradigm for processing large datasets in a distributed manner, namely [`Hadoop`'s `MapReduce`](https://hadoop.apache.org/) paradigm. We will present several techniques that can be used to access such data from `AdhereR` (without attempting to load the whole of it in memory!), to compute the adherence to medication and/or generate plots, and to optionally store the results back into the database. Please note that while the code here was tested on an `Ubuntu 18.04` "server" (an AMD Ryzen 7 2700X CPU with 8 physical cores and 16 logical ones, and 32 GB RAM) and a `macOS High Sierra` "client" (an early 2015 Macbook Air 11" 7,1 with an Intel Core i7-5650U CPU with 2 physical cores and 4 logical ones, and 8 GB RAM), actually running it (and, thus, compiling this very `Rmarkdown` script) requires a complex setup (detailed below). Therefore, we provide this vignette in compiled form as a `PDF` document[^1] together with detailed instructions on how to install the required components for those users that want to reproduce or extend it. ### Prerequisites: load `AdhereR` and `Rmarkdown` setup bits Before we start, load `AdhereR` and various options concerning the figures: ```{r load AdhereR and do various setup things, echo=TRUE, message=TRUE, results='hide'} library(AdhereR); # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=150, dev="jpeg"); ``` ## Relational databases *Relational databases* have a venerable history and are very popular[^2] in a multitude of settings, including those of potential interest for the computation and visualization of patterns of adherence to treatment. In such databases, data is organized in one or more *tables*, each table comprising several *columns* (or *variables*) and *rows* (or *entries*) -- a representation familiar to most users of statistical software such as `SPSS`, `SAS`, `Stata` and `R` (in the latter, this is implemented by `data.frame` and friends). The querying of such databases is usually done through [`SQL`](https://en.wikipedia.org/wiki/SQL) (or *Structured Query Language*), which allows, among others, the selection of entries from such tables that meet certain requirements (for an introduction see, for example, @viescas_sql_2008 among many others). Usually, in practice, there *already* exists such a relational database that contains the relevant patient info organized in one or more tables, hosted by one of the many commercial or free/open source solutions (or *Relational Database Management Systems*, RDBMS) available, and which we can access using `SQL`. For exemplification and reproductibility purposes, here we will also *create* these databases from the `med.events` dataset included in the `AdhereR` package (but these steps are obviously not part of the actual exploitation of the database). We will focus here on [`MySQL`](https://www.mysql.com/), but these can be applied to other RDBMS with minimal changes. `MySQL` is free and widely used, being a good example from the wider class of such systems. `MySQL` (and its close relative, [`MariaDB`](https://mariadb.org/)) is a stand-alone *server* that can be accessed (locally or remotely) by various *clients* who use `SQL` to manipulate the stored data. Thus, `MySQL` stands for the usual scenario where the patient, prescription and event data are stored in a centralized RDBMS (possibly hosted on a dedicated hardware and software infrastructure) which can be queried (possibly over a network or even the Internet) by different specialized clients who perform particular tasks with (parts of) the data. Currently, there are several ways of accessing a RDBMS from `R`, and we will focus here on two: a) using `SQL` directly, and b) transparently generating `SQL` queries through the `dplyr` front-end. At the time of this writing (November 2018), the [*MySQL Community Server*](https://dev.mysql.com/downloads/mysql/) is a free version of the `MySQL` RDBMS which can be installed on several Operating Systems including Microsoft `Windows`, Apple's `macOS` and various flavors of `Linux` and `BSD` (for details, please see https://dev.mysql.com/downloads/mysql/). [`MariaDB`](https://mariadb.org/) is an open source RDBMS that started as a fork of `MySQL` (and is still very similar to it) and can as well be installed on a multitude of Operating Systems (for details, please see https://mariadb.org/download/). ### Installing `MySQL` Generic installation instructions can be found on the MySQL Community Server's [website](https://dev.mysql.com/downloads/mysql/), while step-by-step instructions geared towards `R` can be found, for example, in the [Introduction to MySQL with R](https://programminghistorian.org/en/lessons/getting-started-with-mysql-using-r) and [Connecting R to MySQL/MariaDB](https://moderndata.plot.ly/connecting-r-to-mysql-mariadb/), among others. [How To Install MySQL on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04) is oriented specifically for `Ubuntu 18.04 LTS` (which we use on our test machine). In the following, we will assume that `MySQL` (Community Server) was successfully installed on the local machine. In our case, we are on a machine running `Ubuntu 18.04 LTS` and we follow the procedure described in [How To Install MySQL on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04), with the difference that we create a user named `adherentuser` with password `AdhereR123!` using the command ```sql CREATE USER 'adherentuser'@'localhost' IDENTIFIED BY 'AdhereR123!'; ``` instead of the generic ```sql CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password'; ``` (and please make sure you do not forget to grant the new user the needed privileges:) ```sql GRANT ALL PRIVILEGES ON *.* TO 'adherentuser'@'localhost' WITH GRANT OPTION; ``` #### Creating a sample database Normally, this step is superfluous as the data should already be present in the RDBMS. Nevertheless, for illustration purposes, we transfer here the `med.events` example dataset that comes included with `AdhereR` into several tables in a `MySQL` database. Use `MySQL Workbench` to connect to the database as user `adherentuser` using the password `AdhereR123!`. On our system, this means starting it either from the Desktop Environment's start menu or from the command prompt by typing: ```shell mysql-workbench ``` after which, using the menu `Database` -> `Connect to Database...` we made a local connection using the desired user and credentials. Further, as described in [Introduction to MySQL with R](https://programminghistorian.org/en/lessons/getting-started-with-mysql-using-r#create-database), create a database: ```sql CREATE DATABASE med_events; ``` which should become visible in the left-hand panel under "schemas" (see Figure). ![Creating a database using `MySQL Workbench` on `Ubuntu 18.04` (screenshot taken on the `macOS` "client" using `XQuartz` for display).](./MySQLWorkbench_CREATE_DATABASE.jpg) Then, either using `MySQL Workbench` or `SQL` commands, create *four* tables within the `med_events` database: - `event_patients` with two columns: - `id` of type `INT(11)`, primary key and non-null, and - `patient_id` of type `INT(11)` and non-null, - `event_date` with two columns: - `id` of type `INT(11)`, primary key and non-null, and - `date` of type `DATE` and non-null, - `event_info` with four columns: - `id` of type `INT(11)`, primary key and non-null, - `perday` of type `INT(11)` and non-null, - `category` of type `VARCHAR(45)` and non-null, and - `duration` of type `INT(11)` and non-null. - `patients` with two columns: - `id` of type `INT(11)`, primary key and non-null, and - `sex` of type `CHAR(1)` and non-null, The `SQL` commands for these could be: ```sql CREATE TABLE `med_events`.`event_patients` ( `id` INT NOT NULL, `patient_id` INT NOT NULL, PRIMARY KEY (`id`)); CREATE TABLE `med_events`.`event_date` ( `id` INT NOT NULL, `date` DATE NOT NULL, PRIMARY KEY (`id`)); CREATE TABLE `med_events`.`event_info` ( `id` INT NOT NULL, `perday` INT NOT NULL, `category` VARCHAR(45) NOT NULL, `duration` INT NOT NULL, PRIMARY KEY (`id`)); CREATE TABLE `med_events`.`patients` ( `id` INT NOT NULL, `sex` CHAR(1) NOT NULL, PRIMARY KEY (`id`)); ``` Now, we will fill these tables using the data from `AdhereR`'s `med.events` dataset from `R` itself. First, make sure the the package `RMariaDB` is installed on your system (otherwise simply install it as usual, whether from `RStudio` or with `install.packages("RMariaDB")`) and load the library: ```{r echo=TRUE, message=TRUE, warning=TRUE} library(RMariaDB); ``` Then, connect to the database: ```{r echo=TRUE, message=TRUE, warning=TRUE} med_events_db <- dbConnect(RMariaDB::MariaDB(), # works also for MySQL user="adherentuser", # the username password="AdhereR123!", # and password (insecure but ok here) dbname='med_events', # which database host='localhost' # on which host (here, local machine) ); ``` and, just to check that things are OK, list the tables: ```{r echo=TRUE, message=TRUE, warning=TRUE} db_res_tables <- dbListTables(med_events_db); db_res_tables; ``` Clear the tables (in case there's some junk info in there): ```{r echo=TRUE, message=TRUE, warning=TRUE} # Truncate all the tables: for( i in db_res_tables ) dbExecute(med_events_db, paste0("TRUNCATE ",i,";")); ``` Now, generate an extra column containing the `event_id` unique event id (really, just the row number) and make sure the format of the dates fits `SQL`'s `DATE` type: ```{r echo=TRUE, message=TRUE, warning=TRUE} d <- med.events; # make working a copy d$event_id <- 1:nrow(d); # simply the index of the event in med.events d$DATE <- as.character(as.Date(d$DATE, format="%m/%d/%Y"), format="%Y-%m-%d"); # use the expected format for SQL's DATE ``` Fill in the `patients` table (and allocate some random sexes which we won't really use at all): ```{r echo=TRUE, message=TRUE, warning=TRUE} tmp <- unique(d[,c("PATIENT_ID"),drop=FALSE]); # select the relevant info tmp$sex <- sample(c("F","M"), size=nrow(tmp), replace=TRUE); names(tmp) <- c("id", "sex"); # match the column names # For convenience, write the whole data.frame in one go: dbWriteTable(med_events_db, name="patients", value=tmp, row.names=FALSE, append=TRUE); ``` then spread the event info across the remaining tables: ```{r echo=TRUE, message=TRUE, warning=TRUE} # event_date: tmp <- d[,c("event_id", "DATE")]; # select the relevant info names(tmp) <- c("id", "date"); # match the column names # For convenience, write the whole data.frame in one go: dbWriteTable(med_events_db, name="event_date", value=tmp, row.names=FALSE, append=TRUE); # event_info: tmp <- d[,c("event_id", "PERDAY", "CATEGORY", "DURATION")]; # select the relevant info names(tmp) <- c("id", "perday", "category", "duration"); # match the column names # For convenience, write the whole data.frame in one go: dbWriteTable(med_events_db, name="event_info", value=tmp, row.names=FALSE, append=TRUE); # event_patients: tmp <- d[,c("event_id", "PATIENT_ID")]; # select the relevant info names(tmp) <- c("id", "patient_id"); # match the column names # For convenience, write the whole data.frame in one go: dbWriteTable(med_events_db, name="event_patients", value=tmp, row.names=FALSE, append=TRUE); ``` Check that the data was correctly written either using `MySQL Workbench` or from `R`: ```{r echo=TRUE, message=TRUE, warning=TRUE} # Fetch the whole results as they are small enough for display: knitr::kable(dbGetQuery(med_events_db, "SELECT * FROM patients LIMIT 5;"), align=c("l","l"), caption="First 5 rows of the `patients` table (please note that the `sex` may differ from your results and between runs)."); knitr::kable(dbGetQuery(med_events_db, "SELECT * FROM event_date LIMIT 5;"), align=c("l","l"), caption="First 5 rows of the `event_date` table."); knitr::kable(dbGetQuery(med_events_db, "SELECT * FROM event_info LIMIT 5;"), align=c("l","l"), caption="First 5 rows of the `event_info` table."); knitr::kable(dbGetQuery(med_events_db, "SELECT * FROM event_patients LIMIT 5;"), align=c("l","l"), caption="First 5 rows of the `event_patients` table."); ``` Finally, don't forget to close the connection to the database: ```{r echo=TRUE, message=TRUE, warning=TRUE} dbDisconnect(med_events_db); ``` ### Access the database and estimate adherence using explicit `SQL` The first method uses explicit `SQL` statements directed at the `MySQL` server through the `R` library `RMariaDB` (despite its name, it also works for `MySQL`). First, make sure it is installed on your system (for example by running the following or, if you're using `RStudio`, by checking the `Packages` panel): ```{r echo=TRUE, message=TRUE, warning=TRUE} require(RMariaDB); # there should be no warnings ``` If not, install it either using `RStudio`'s *Tools* -> *Install packages* menu, or by running: ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} install.packages("RMariaDB", dep=TRUE); # also install the dependencies ``` (please make sure you check for any errors and follow any indication; for example, on `Ubuntu 18.04` it is necessary to install prior to this the `libmysqlclient-dev` package using, for example, `apt install libmysqlclient-dev`). Now, load it: ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} library(RMariaDB); ``` We will next illustrate a few scenarios concerning the computation and plotting of patterns of adherence accessing data from the database. #### Connect to the database ```{r echo=TRUE, message=TRUE, warning=TRUE} med_events_db <- dbConnect(RMariaDB::MariaDB(), # works also for MySQL user="adherentuser", # the username password="AdhereR123!", # and password (insecure but ok here) dbname='med_events', # which database host='localhost' # on which host (here, local machine) ); db_res_tables <- dbListTables(med_events_db); db_res_tables; # check things are ok ``` #### How many patients are there? ```{r echo=TRUE, message=TRUE, warning=TRUE} no_patients <- dbGetQuery(med_events_db, # overkill, as `id` is the primary key: "SELECT COUNT(DISTINCT id) FROM patients;"); no_patients <- as.numeric(no_patients[1,1]); # single value: convert it to numeric no_patients; ``` #### How many events? ```{r echo=TRUE, message=TRUE, warning=TRUE} no_events <- dbGetQuery(med_events_db, "SELECT COUNT(DISTINCT id) FROM event_info;"); no_events <- as.numeric(no_events[1,1]); # single value: convert it to numeric no_events; ``` #### And how many events per patient? ```{r echo=TRUE, message=TRUE, warning=TRUE} dbGetQuery(med_events_db, "SELECT patient_id, COUNT(*) FROM event_patients GROUP BY patient_id;"); ``` #### Get the list of `patient_id`'s ```{r echo=TRUE, message=TRUE, warning=TRUE} patient_ids <- dbGetQuery(med_events_db, "SELECT id FROM patients;"); # a data.frame patient_ids <- patient_ids$id; # convert it to a vector patient_ids; ``` #### Retreive the data for a given (set of) patient(s) We don't assume here that we can load a lot of patients in memory at a time (after all, the whole point of this exercise is to keep the data in the database as much as possible), so we wrote a simple (but clearly not the most efficient!) function that retrieves the info for a given (set of) patient(s): ```{r echo=TRUE, message=TRUE, warning=TRUE} # Given a (set of) patient(s) ID(s) and a database connection, # retreive his/her/their info and # return it as a data.frame (or NULL) retreive_patients_info <- function(patient_ids, # a single value or a vector db_connection) # the database connection { s <- dbGetQuery(db_connection, paste0(" SELECT event_date.id, event_date.date, event_info.category, event_info.duration, event_info.perday, event_patients.patient_id, patients.sex FROM event_date JOIN event_info ON event_info.id = event_date.id JOIN event_patients ON event_patients.id = event_info.id JOIN patients ON patients.id = event_patients.patient_id WHERE patients.id IN (", paste0(patient_ids,collapse=","), ");")); if( nrow(s) < 1 ) { return (NULL); } else { return (s); } } ``` #### Compute `CMA9` for all the patients and store it in the database Also, for the sake of the exercise, we cannot assume that we can store the computed CMA values for all the patients in a vector in `R`, so, as soon as we estimate it for a single patient, we write it back to the database. For this, we will create a new table named `cma9_estimates` (with two columns: `patient_id` and `cma`) and we make sure it's empty: ```{r echo=TRUE, message=TRUE, warning=TRUE} dbExecute(med_events_db, "CREATE TABLE IF NOT EXISTS med_events.cma9_estimates ( patient_id INT NOT NULL, cma REAL NULL, PRIMARY KEY (patient_id));"); # create it if not already there dbExecute(med_events_db, "TRUNCATE cma9_estimates;"); # make sure it's emty ``` For each patient in turn, extract his/her data from the database, estimate `CMA9` and write back this estimate to the database (also, for the sake of illustration, we will assume that we can't even store the whole list of patient ID's, so we ask for each individual patient by selecting individual rows in the `patients` table): ```{r echo=TRUE, message=TRUE, warning=TRUE} # Time the whole thing: start.time <- Sys.time(); # First (re)get the number of patients in the whole database: no_patients <- dbGetQuery(med_events_db, "SELECT COUNT(DISTINCT id) FROM patients;"); no_patients <- as.numeric(no_patients[1,1]); # single value: convert it to numeric no_patients; # Select each patient in turn by its row number (remeber: rows count starts at 0 in SQL!): for( i in 0:(no_patients-1) ) { # Get the patient ID in row i: patient_id <- dbGetQuery(med_events_db, paste0("SELECT id FROM patients LIMIT ",i,",1;")); if( is.null(patient_id) || nrow(patient_id) < 1 ) { warning(paste0("Cannot find patient number ",i+1,"!\n")); next; } patient_id <- as.numeric(patient_id[1,1]); # single value: convert it to numeric # Extract the patient's data: s <- retreive_patients_info(patient_id, med_events_db); # retreive all the data if( is.null(s) ) { warning(paste0("Cannot retrieve data for patient '",patient_id,"'!\n")); cma <- NA; } else { # Estimate the CMA: cma <- CMA9(data=s, # compute the CMA ID.colname="patient_id", event.date.colname="date", event.duration.colname="duration", event.daily.dose.colname="perday", medication.class.colname="category", followup.window.start=0, followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%Y-%m-%d", parallel.backend="none"); if( is.null(cma) ) { warning(paste0("Cannot estimate CMA for patient '",patient_id,"'!\n")); cma <- NA; } else { cma <- getCMA(cma)$CMA[1]; # retrieve the estimate } } # Write back this estimate (with replacement, # if there's an already existing estimate for this patient): result <- dbExecute(med_events_db, paste0("REPLACE INTO cma9_estimates (patient_id, cma) VALUES (", patient_id, ", ", ifelse(is.na(cma),"NULL",cma),");")); } end.time <- Sys.time(); cat(paste0("The SQL-mediated computation of CMA9 on the whole database took: ", round(difftime(end.time, start.time, units="secs"),2), " seconds\n")); ``` Also, do it within `R` so we can compare the results of the two procedures: ```{r echo=TRUE, message=TRUE, warning=TRUE} # Also, time it using the same procedure: start.time <- Sys.time(); cma9r <- CMA9(data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=0, followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%m/%d/%Y", parallel.backend="none"); end.time <- Sys.time(); cat(paste0("The computation of CMA9 in R on the whole database took: ", round(difftime(end.time, start.time, units="secs"),2), " seconds\n")); # Retreive the results from the database: cma9sql <- dbGetQuery(med_events_db, "SELECT * FROM cma9_estimates;"); knitr::kable(merge(getCMA(cma9r), cma9sql, by.x="PATIENT_ID", by.y="patient_id", all=TRUE), align=c("c","c","c"), col.names=c("Patient ID", "CMA9 (R)", "CMA9 (MySQL)"), caption="The estimation of CMA9 on all the patients comparing the `MySQL` and `R` estimates (they are, as expected, **identical**!)."); ``` #### Plot a set of patients Here we generate some plots of patients from the database. ```{r echo=TRUE, message=TRUE, warning=TRUE, fig.width=12, fig.height=12, fig.cap="Plot of `CMA0` for the first 5 patients in the `MySQL` database using `SQL`."} # Extract the data of the patient(s) to plot: # (we relax the stringency and assume we can hold a the patient IDs in memory :)): s <- retreive_patients_info(patient_ids[1:5], med_events_db); cma0 <- CMA0(data=s, ID.colname="patient_id", event.date.colname="date", event.duration.colname="duration", event.daily.dose.colname="perday", medication.class.colname="category", followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%Y-%m-%d", parallel.backend="none"); plot(cma0); ``` ```{r echo=TRUE, message=TRUE, warning=TRUE, fig.width=12, fig.height=12, fig.cap="Plot of `CMA9` for the first 5 patients in `MySQL` database using `SQL`."} # Extract the data of the patient(s) to plot: # (we relax the stringency and assume we can hold a the patient IDs in memory :)): s <- retreive_patients_info(patient_ids[1:5], med_events_db); cma9 <- CMA9(data=s, ID.colname="patient_id", event.date.colname="date", event.duration.colname="duration", event.daily.dose.colname="perday", medication.class.colname="category", followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%Y-%m-%d", parallel.backend="none"); plot(cma9); ``` #### Interactive plotting For the interactive plotting of patients directly from the database (i.e., without local caching of data in `R`), we make use of the getter functions allowed by `plot_interactive_cma` through its function arguments `get.colnames.fnc`, `get.patients.fnc` and `get.data.for.patients.fnc`. As detailed in the help page for `plot_interactive_cma`, these arguments allow a user to use other types of data storage than the default `data.frame` by overriding the default behaviors for listing the data column names, listing all the patient IDs and getting the actual data for a (set of) patient ID(s), respectively. Here, we redefined these functions as follows: ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} # Retreive the column names of the data for the first patient: get.colnames.fnc.MySQL <- function(d) { return(names(retreive_patients_info( as.numeric(dbGetQuery(med_events_db, "SELECT id FROM patients LIMIT 0,1;")[1,1]), d) )); } # List all the patient IDs: get.patients.fnc.MySQL <- function(d, idcol) { s <- dbGetQuery(d, "SELECT id FROM patients;"); return(s$id); } # Retreive the data for given (set of) patient ID(s): get.data.for.patients.fnc.MySQL <- function(patientid, d, idcol) { retreive_patients_info(patientid, d); } ``` resulting in the code (not run here as it needs an interactive `R` session with `AdhereR` and `Shiny`): ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} plot_interactive_cma(data=med_events_db, # use the MySQL connection as the data provider ID.colname="patient_id", event.date.colname="date", event.duration.colname="duration", event.daily.dose.colname="perday", medication.class.colname="category", date.format="%Y-%m-%d", # SQL's DATE specification backend=c("shiny","rstudio")[1], # use Shiny use.system.browser=TRUE, # use the system web browser # Override the getter functions to use the MySQL database # (please note that, for consistency, we must keep the # function argments evens if we don't use all of them): get.colnames.fnc=get.colnames.fnc.MySQL, get.patients.fnc=get.patients.fnc.MySQL, get.data.for.patients.fnc=get.data.for.patients.fnc.MySQL ); ``` ![Screenshot of interactive plotting directly from a `MySQL` database using `Shiny` and the system browser (here, `Safari` on a `macOS High Sierra`).](./MySQL_interactive_plotting.jpg) #### Disconnect from the database Finally, we need to disconnect from the database: ```{r echo=TRUE, message=TRUE, warning=TRUE} dbDisconnect(med_events_db); ``` #### Using a non-local `MySQL` database Usually, the `MySQL` database is located on a *different* machine on a network (possibly even somewhere else on the Internet). We will show here how to access the same `MySQL` database we used so far (let's called it here the "*server*") from a different machine (a Macbook Air 11" running `macOS High Sierra` with `R` 3.4.4; called the "*client*"). First, make sure that the `RMariaDB` package is installed on the "*client*". Second, make sure that the user `adherentuser` is allowed to remotely access the `MySQL` database; for our setup, we did the following on the "*server*" (as suggested in https://stackoverflow.com/questions/8380797/enable-remote-mysql-connection-error-1045-28000-access-denied-for-user and https://stackoverflow.com/questions/8380797/enable-remote-mysql-connection-error-1045-28000-access-denied-for-user/21151255#21151255): - as `root` in `MySQL` (obtained by running, for example, `mysql -u root -p` in a terminal), execute: ```sql GRANT ALL PRIVILEGES ON *.* TO 'adherentuser'@'%' IDENTIFIED BY 'AdhereR123!' WITH GRANT OPTION; FLUSH PRIVILEGES; ``` - also as `root`, edit the `/etc/mysql/my.cnf` (or the `/etc/mysql/mysql.conf.d/mysqld.cnf` on newer versions of `MySQL`) and replace the line `bind-address = 127.0.0.1` by `bind-address = 0.0.0.0` - restart `MySQL` (for example, by `sudo service mysql restart`. Now, on the "*client*" we should be able to connect to the remote "*server*": ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} med_events_db <- dbConnect(RMariaDB::MariaDB(), # works also for MySQL user="adherentuser", # the username password="AdhereR123!", # and password (insecure but ok here) dbname='med_events', # which database host='remote.server.sql' # the host's name or IP address ); ``` and check that everything is OK: ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} db_res_tables <- dbListTables(med_events_db); db_res_tables; ``` followed by all the other things you would do with a local database, including closing it at the end (as shown above). Of course, the access and data transfer times will be worse than for a local database, but this can be addressed by judiciously selecting the patients one needs to process and by processing them in chunks of more than one patient. #### Optimisations and security Especially for remote databases (but also for local ones), the access and data transfer are potentially very slow; moreover, `AdhereR` is heavily optimized for processing (possibly in parallel) multiple patients (using `data.table` and other techniques). Therefore, probably the following ideas may help speed up the processing: - as far as possible, information extraction and preparation should be done server-side (i.e., using `SQL`) instead of client-side (i.e., transferring raw data and processing it in `R`); - transfer locally only the data that is strictly needed for computing the adherence and/or plotting (e.g., if computing `CMA1`, it doesn't make any sense to also transfer the column containing the daily dose) and only for the patients for which this needs to be done (i.e., perform an `SQL` pre-selection of the patients and events); - to minimize server querying and transfer, and to maximally use the optimization built in `AdhereR`, split the whole set of patients to process into chunks that are relatively large (but not too large so as not to fit comfortably in the client's RAM even when processed in parallel); - collect the computation results in `R` as much as possible and only write them back to the database in large chunks. In these examples we stored the server name, username and password in clear in the `R` code: while this OK for this demo, it is a ***very bad idea*** in a production environment! There are various techniques for mitigating this, ranging from storing these info in a separate file that is read at run-time, to asking the user to interactively give the username and password, to using the `keyring` package (https://github.com/r-lib/keyring) -- see also https://db.rstudio.com/best-practices/managing-credentials/ for a discussion. Please chose the most appropriate one for your use-case, but whatever you do, ***don't store your credentials in the `R` script***!!! ### Use `dplyr` and `DBI` to transparently access the database This is based on the more extended discussion in https://db.rstudio.com/dplyr/ . While using `SQL` for interacting with the database is very flexible and allows for fine-grained optimization, it requires a certain level of expertise and can be argued to create "chimeras" of `R` and `SQL` that might be more difficult to understand, debug and maintain. The `R` packages `dbplyr` and `DBI` offer an alternative way, where the `SQL` is mostly "hidden" behind a familiar `R` code. Moreover, this allows to use the same code to access a variety of databases, such as `MySQL`, `PostgreSQL` and even Google’s `BigQuery`. For example, we can connect and list the patients with (of course, you need to install first the needed packages, such as `dbplyr`, `dplyr` and `RMySQL`): ```{r echo=TRUE, message=TRUE, warning=TRUE} library(dplyr); db_dplyer <- DBI::dbConnect(RMySQL::MySQL(), user="adherentuser", # the username password="AdhereR123!", # and password (insecure but ok here) dbname='med_events' # which database ); DBI::dbListTables(db_dplyer); # list the tables in the database db_dplyer_patients <- tbl(db_dplyer, "patients"); # connect to the "patients" table # db_dplyer_patients; # print it if you want to ``` Let's get the data from patient with id `1`, compute `CMA9` and plot it: ```{r echo=TRUE, message=TRUE, warning=TRUE, fig.width=10, fig.height=6, fig.cap="Plotting `CMA1` for patient with id `1` directly from a `MySQL` database using `dbplyr` and `DBI`."} # connect to the various event info tables as well: db_dplyer_event_date <- tbl(db_dplyer, "event_date"); db_dplyer_event_info <- tbl(db_dplyer, "event_info"); db_dplyer_event_patients <- tbl(db_dplyer, "event_patients"); # Select and join the various pieces of info for patient with patient_id == 1 # (Please note that the data data is actually transfered from MySQL to R only # at the end, when invoking collect()!!!) s <- inner_join(inner_join(db_dplyer_event_info, # filter the events for patient 1: db_dplyer_event_patients %>% filter(patient_id == 1), by="id"), # join with event_info db_dplyer_event_date, by="id") %>% collect(); cma9 <- CMA9(data=s, # compute CMA9 as usual ID.colname="patient_id", event.date.colname="date", event.duration.colname="duration", event.daily.dose.colname="perday", medication.class.colname="category", followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%Y-%m-%d", parallel.backend="none"); plot(cma9); # plot it ``` Finally, close the connection to the database: ```{r echo=TRUE, message=TRUE, warning=TRUE} DBI::dbDisconnect(db_dplyer); ``` ## How about `SAS` and `Stata` If the dataset is relatively small, probably the easiest is to export it into a format that `R` can read (such as `CSV`); if this is not possible, then maybe one of the methods for importing their native formats in `R` may work (see, for example, https://www.statmethods.net/input/importingdata.html or https://cran.r-project.org/doc/manuals/r-devel/R-data.html#EpiInfo-Minitab-SAS-S_002dPLUS-SPSS-Stata-Systat ). However, if the dataset is (very) large, then probably one should either: - export it into a RDBMS such as `MySQL` where `R` can access it (as described above), or - experimentally, use `ODBC` to access it directly from `SAS` (which might or might not work). ## Finally, let's look at `Hadoop` and `MapReduce`! [Apache `Hadoop`](https://hadoop.apache.org/) is a general framework for the distributed processing of large datasets using a simple programming paradigm (`MapReduce`; see, for example, https://wiki.apache.org/hadoop/ProjectDescription ). Given that `AdhereR` can compute adherence estimates for sets of at least one patient at a time, it is very easy to embed within the `MapReduce` framework using a variety of approaches (see, among others, the outlines [here](https://blog.revolutionanalytics.com/2015/06/using-hadoop-with-r-it-depends.html) or [here]( https://www.dezyre.com/article/r-hadoop-a-perfect-match-for-big-data/292)). Just as an example, we will install here `Hadoop 3.0.3` on the `Ubuntu 18.04` machine and use it to compute `CMA9` on all the patients. ### Installing `Hadoop 3.0.3` on `Ubuntu 18.04` We are following the tutorial [here](https://www.digitalocean.com/community/tutorials/how-to-install-hadoop-in-stand-alone-mode-on-ubuntu-18-04). All of these happen in a `shell` terminal. #### Install `Java` ```shell sudo apt update sudo apt install default-jdk java -version ``` #### Install `Hadoop 3.0.3` Download the 3.0.3 *binary* version: ```shell cd ~/Downloads wget http://mirrors.ircam.fr/pub/apache/hadoop/common/hadoop-3.0.3/hadoop-3.0.3.tar.gz ``` then unpack and move it to `/usr/local/`: ```shell tar -xzvf hadoop-3.0.3.tar.gz sudo mv hadoop-3.0.3 /usr/local/hadoop ``` #### Configure `Hadoop` Add to `/usr/local/hadoop/etc/hadoop/hadoop-env.sh` the line `export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")`. #### Test `Hadoop` Start it first: ```shell /usr/local/hadoop/bin/hadoop ``` and test it: ```shell /usr/local/hadoop/bin/hadoop jar /usr/local/hadoop/share/hadoop/mapreduce/hadoop- mapreduce-examples-3.0.3.jar grep ~/input ~/grep_example 'allowed[.]*' cat ~/grep_example/* ``` which should produce: ``` Output 19 allowed. 1 allowed ``` ### Installing `RHadoop` on `Ubuntu 18.04` We are adapting here various guidelines for [`RedHat`](https://github.com/RevolutionAnalytics/RHadoop/wiki/Installing-RHadoop-on-RHEL) and [`macOS`](http://www.rdatamining.com/big-data/rhadoop). All these happen in `R` (unless specified). #### Set the needed environment variables ```{r echo=TRUE, message=TRUE, warning=TRUE} Sys.setenv("HADOOP_HOME"="/usr/local/hadoop"); # Hadoop HOME Sys.setenv("HADOOP_CMD"="/usr/local/hadoop/bin/hadoop"); # Hadoop binary Sys.setenv("HADOOP_STREAMING"= # Streaming "/usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-3.0.3.jar"); ``` #### Install the needed `R` packages (You probably already have some installed). ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} install.packages(c("rJava", "Rcpp", "RJSONIO", "bitops", "digest", "functional", "stringr", "plyr", "reshape2"), dep=TRUE); ``` Now, manually download the `rhdfs`, `rhbase` and `rmr2` packages from [Revolution Analytics' GitHub repository](https://github.com/RevolutionAnalytics/RHadoop/wiki). In a `shell` terminal: ```shell cd ~/Downloads wget https://github.com/RevolutionAnalytics/rmr2/releases/download/3.3.1/rmr2_3.3.1.tar.gz wget https://github.com/RevolutionAnalytics/rhdfs/blob/master/build/rhdfs_1.0.8.tar.gz?raw=true wget https://github.com/RevolutionAnalytics/rhbase/blob/master/build/rhbase_1.2.1.tar.gz?raw=true ``` and then, in `R`: ```{r echo=TRUE, message=TRUE, warning=TRUE, eval=FALSE} install.packages(c("~/Downloads/HADOOP/rhdfs_1.0.8.tar.gz?raw=true", "~/Downloads/HADOOP/rmr2_3.3.1.tar.gz", "~/Downloads/HADOOP/rhbase_1.2.1.tar.gz"), repos=NULL, dep=TRUE); ``` ### Using `Hadoop` through `RHadoop` to compute `CMA9` With all these in place, we can compute `CMA9` for each participant, as follows (of course, this is not optimized in any sense). Everything here takes place in `R`. #### Load the libraries and initialize things ```{r echo=TRUE, message=TRUE, warning=TRUE} library(rhdfs); # access to HDFS hdfs.init(); # initialize HDFS library(rmr2); # MapReduce in R ``` #### Store the `med.events` data in `HDFS` First, we will store the `med.events` example `AdhereR` dataset in `HDFS` (the [Hadoop Distributed File System](https://hadoop.apache.org/docs/r3.0.3/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html)) as a set of *key-value* pairs: ```{r echo=TRUE, message=TRUE, warning=TRUE} # Transfer med.events to HDFS as a set of key-value pairs: med_events_hdfs <- to.dfs(keyval(med.events$PATIENT_ID, med.events)); ``` This is *not* a very efficient and scalable way of doing it, but it works for this example (normally, the data would be transferred to `HDFS` using specialized tools such as [Sqoop](https://sqoop.apache.org/)). What this does is create a handler (`med_events_hdfs`) to a temporary `HDFS` storage where the rows of the `med.events` `data.frame` (the *values*) are stored paired with the corresponding `PATIENT_ID`s (the *keys*). Importantly the `med_events_hdfs` handler ensures that the actual data is never fully loaded in memory, which is very important for large databases. #### Use `MapReduce` to compute `CMA9` ```{r echo=TRUE, message=TRUE, warning=TRUE} s <- mapreduce(input=med_events_hdfs, # read the data from med_events_hdfs # the mapping function here doesn't do much; # k (= the key) = PATIENT_ID; v (= value) = med.events rows: map=function(k,v) keyval(k,v), # the reduce function computes CMA9 on the data (the values v) # associated with a given PATIENT_ID (the key k): reduce=function(k,v) { cma <- CMA9(v, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=0, followup.window.start.unit="days", followup.window.duration=2*365, followup.window.duration.unit="days", observation.window.start=30, observation.window.start.unit="days", observation.window.duration=1*365, observation.window.duration.unit="days", date.format="%m/%d/%Y", parallel.backend="none"); # Return the computed CMA as the value paired with the PATIENT_ID key: keyval(k, getCMA(cma)[1,"CMA"]); }); ``` The basic idea is to first *map* the (key, value) pairs in the input (here, the `PATEINT_ID`s with their associated event info) to (potentially) different (key, value) pairs (here, we don't do basically anything at this stage), followed by *reducing* all the data associated with a key to a summary value (here, `CMA9`), returning a new summary (key, value) pair. The result `s` is also a pointer to the actual results stored in `HDFS` (temporarily), so that again we don't load anything large in memory. #### Load and use the results Just for the sake of illustration, only now do we load the full results in memory for display as a `data.frame` (to be compared with the other ways of computing `CMA9`): ```{r echo=TRUE, message=TRUE, warning=TRUE} # Only *now* force the loaing of the full results in memory! s <- from.dfs(s); # Convert the (key, value) pairs to a nice data.frame format: cma9hadoop <- data.frame("PATIENT_ID"=s$key, "CMA9"=s$val); # And plot them for comparison with the other methods discussed here: knitr::kable(merge(merge(getCMA(cma9r), cma9sql, by.x="PATIENT_ID", by.y="patient_id", all=TRUE), cma9hadoop, by="PATIENT_ID", all=TRUE), align=c("c","c","c","c"), col.names=c("Patient ID", "CMA9 (R)", "CMA9 (MySQL)", "CMA9 (Haddop)"), caption="The estimation of CMA9 on all the patients comparing the `R`, `MySQL` and `Hadoop` estimates (they are, as expected, **identical**!)."); ``` ## Conclusions We hope to have shown here that, far from being constrained by the "'R' can't process large datasets that don't fit in memory" myth, `AdhereR` can, in fact, nicely and easily interface with both "classical" relational databases (such as `MySQL`)) and with newer technologies (such as Apache `Hadoop`), allowing it to access potentially huge databases (even across the Internet) and process them efficiently (even across massively parallel heterogeneous computational infrastructures). Thus, `AdhereR` can seamlessly scale up from being used for the real-time visualization and computation of adherence of a small-to-medium local database (stored either in a "flat" CSV file or in an [`SQLite`](https://www.sqlite.org/index.html) database) on a *consumer-grade laptop*, up to running on *large heterogenenous computer clusters* where it can process huge amounts of data stored across several RDBMS tables (managed by, for example, [`MySQL`](https://www.mysql.com/)) or as (key, value) pairs in a [`Hadoop`](https://hadoop.apache.org/) `HDFS` file system. The examples (with actual code and step-by-step instructions) presented here should provide a starting point for real-world implementations optimized for the problems at hand. There is a vast literature concerning both "classic" `SQL` and newer `NoSQL` databases, and there is an already mature ecosystem for accessing them from `R`. However, even for very specific cases where this is not feasible, we have provided a flexible framework for seamlessly using `AdhereR` from other programming languages (such as `Python`) for the computation and plotting of adherence. [^1]: We provide only the `PDF` within the package itself as the `HTML` form is rather big due to the embedded images and generates a NOTE when building the package. Moreover, to void an unsuccessful attempt at compiling the vignette during the package build, the actual `.Rmd` source and related images are in the `specialVignettes` subfolder of the package. [^2]: Despite the development of alternative architectures (generically known as ["NoSQL"](https://en.wikipedia.org/wiki/NoSQL); see @harrison_next_2015), `RDBMS`s are still extremely popular and will very probably continue to be so for the foreseeable future. ## References
/scratch/gouwar.j/cran-all/cranData/AdhereR/inst/specialVignettes/adherer_with_databases.Rmd
--- title: "AdhereR: Adherence to Medications" author: "Alexandra L. Dima, Dan Dediu & Samuel Allemann" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: yes toc_depth: 4 fig_caption: yes vignette: > %\VignetteEncoding{UTF-8} %\VignetteIndexEntry{AdhereR: Adherence to Medications} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` Estimating the *adherence to medications* from *electronic healthcare data* (EHD) has been central to research and clinical practice across clinical conditions. For example, large retrospective database studies may estimate the prevalence of non-adherence in specific patient groups and model its potential predictors and impact on health outcomes, while clinicians may have access to individual patient records that flag up possible non-adherence for further clinical investigation and intervention. Yet, adherence measurement is a matter of controversy. Many methodological studies show that the same data can generate different prevalence estimates under different parametrisations ([Greevy *et al.*, 2011](#Ref-Greevy2011); [Gardarsdottir *et al.*, 2010](#Ref-Gardarsdottir2010); [Souverein *et al.*, *in press*](#Ref-SouvereinInPress); [Vollmer *et al.*, 2012](#Ref-Vollmer2012); [Van Wijk *et al.*, 2006](#Ref-VanWijk2006)). These parametrisation choices are usually not transparently reported in published empirical studies, and adherence algorithms are either developed ad-hoc or for proprietary software. This lack of transparency and standardization has been one of the main methodological barriers against the development of a solid evidence base on adherence from EHD, and may lead to misinformed clinical decisions. Here we describe `AdhereR`, an R package that aims to facilitate the computing of adherence from EHD, as well as the transparent reporting of the chosen calculations. It contains a set of `R` `S3` *classes* and *functions* that *compute*, *summarize* and *plot* various estimates of adherence. A hypothetical dataset of medication events is included for demonstration and testing purposes. In this vignette, we start by defining the terms used in `AdhereR`. We then use medication records of two patients in the included dataset to illustrate the various decisions required and their impact on estimates, starting with the visualization of medication events, computation of persistence (treatment episode length), and computation of adherence (9 functions available in 3 versions: simple, per-treatment-episode, and sliding-window). Visualizations for each function are illustrated, and the interactive visualization function is presented. While we tested the package relatively extensively, we cannot guarantee that bugs and errors do not exist, and we encourage the users to contact us with suggestions, bug reports, comments (or even just to share their experiences using the package) either by e-mail (to Dan <[email protected]> or Alexandra <[email protected]>) or using GitHub's reporting mechanism at our repository <https://github.com/ddediu/AdhereR>, which contains the full source code of the package (including this vignette). ## Definitions <a name="Section-definitions"></a> Adherence to medications is described as a process consisting of 3 successive elements/stages: *initiation*, *implementation*, and *discontinuation* [(Vrijens et al., 2012)](#Ref-Vrijens2012). After initiating treatment (first medication intake), a patient would continue with implementing the regimen for a time period, ideally equal to the recommended time necessary for achieving therapeutic benefits; the quality of implementation is commonly labelled *adherence* and broadly operationalized as a *ratio of medication quantity used versus prescribed in a time period*. If patients discontinue medication earlier than the recommended time period, the period before discontinuation is described as *persistence*, in contrast to the following period of *non-persistence*. The ideal measurement of this process would record the prescription moment and every medication intake with an exact time-stamp. This would allow, for example, to describe adherence to a twice-daily medication prescribed for 1 year in maximum detail: how long was the delay between prescription and the moment of the first medication intake, whether each of the two prescribed administrations per day corresponded to an intake event and at what time, how much medication was taken versus prescribed on any time interval while the patient persisted with treatment, any specific implementation patterns (e.g. missing or delaying the first daily dose), and when exactly the last medication intake event took place during that year. While this level of detail can be obtained by careful use of *electronic monitoring devices*, electronic healthcare data usually include much less information. *Administrative claims* or *pharmacy databases* record *medication dispensation events*, including patient identifier, date of event, type of medication, and quantity dispensed, and less frequently daily dosage recommended. The same information may be available for prescription events in *electronic medical records* used in health care organizations (e.g primary care practices, secondary care centers). In between two dispensing or prescribing events, we don't know whether and how medication has been used. What we do know is that, if taken as prescribed, the medication supplied at the first event would have lasted a number of days. If the time interval between the two events is longer than this number it is likely that the patient ran out of medication before re-supplying or used less during that time. If the interval is substantially longer or there is no second event, then the patient has probably finished the supply at some point and then discontinued medication. Thus, EHD-based algorithms estimate medication adherence and persistence based on the availability of current supply, under four main assumptions: - the regimen requires the use of a fixed daily dosage of medication (if medication is to be taken as needed, a ratio cannot be computed) - all medication supplied for that patient in that period of time is recorded and the patient does not use medication from other sources (if the patient uses other medication, adherence and/or persistence will be underestimated) - the medication supplied is used by the patient it has been supplied for (if other persons use the medication, adherence and/or persistence will be overestimated) - medication is supposed to be supplied at least two times during that period (if all medication is supplied once at the beginning of the treatment, there are no differences between patients regarding the supply patterns and all patients would be 100% covered for the whole treatment period) (Several other assumptions apply to individual algorithms, and will be discussed later.) `AdhereR` was developed to compute adherence and persistence estimates from EHD based on the principles described above. The current version is based on a single data source, therefore an algorithm for initiation (time interval between first prescription and first dispensing event) is not implemented (it is a time difference calculation easy to implement in with basic R functions). The following terms and definitions are used: - *Adherence* (*implementation*) = the extent to which a patient's medication use corresponds to prescribed use, - *CMA* = continuous multiple-interval measures of medication availability/gaps, representing various indicators of the quality of implementation, - *Medication event* = prescribing or dispensing record of a given medication for a given patient; usually includes the patient's unique identifier, an event date, and a duration, - *Duration* = number of days the quantity of supplied medication would last if used as recommended, - *Quantity* = number of doses supplied at a medication event, - *Daily dosage* = number of doses recommended to be taken daily, - *Medication type* = classification performed by the researcher depending on study aims, e.g. based on therapeutic use, mechanism of action, chemical molecule or pharmaceutical formulation, - *Follow-up window* (FUW) = the total period for which relevant medication events are recorded for included patients, - *Observation window* (OW) = the period within the FUW for which adherence or persistence is computed, - *Persistence* = the length of time during which the patient continues to use medication, before discontinuing for a time period longer than a pre-specified permissible gap, - *Treatment episode* = a period of active medication use, represented by the number of consecutive days between a first medication supply event and the moment when the supply of the last medication event was finished (in a row of consecutive medication events where the interval between any two consecutive events is lower than the duration of the first plus a researcher-defined permissible gap), - *Permissible gap* = a researcher-defined value representing the maximum number of days between the end of the supply from one medication event and the start of the following one that can be considered as continuous medication use. ## Data preparation and example dataset `AdhereR` requires a dataset of medication events over a FUW of sufficient length in relation to the recommended treatment duration. To our knowledge, no research has been performed to date on the relationship between FUW length and recommended treatment duration. `AdhereR` offers the opportunity for answering such methodological questions, but we would hypothesize that the FUW duration also depends on the duration of medication events (shorter durations would allow shorter FUW windows to be informative). The minimum necessary dataset includes 3 variables for each medication event: *patient unique identifier*, *event date*, and *duration*. *Daily dosage* and *medication type* are optional.`AdhereR` is thus designed to use datasets that have already been extracted from EHD and prepared for calculation. These preliminary steps depend to a large extent on the specific database used and the type of medication and research design. Several general guidelines can be consulted ([Arnet *et al.*, 2016](#Ref-Arnet2016); [Peterson *et al.*, 2007](#Ref-Peterson2007)), as well as database-specific documentation. In essence, these steps should entail: - selecting medication events applicable to the research question based on relevant time intervals and medication codes, - coding medication type depending on clinical considerations, for example coding different therapeutic classes in polypharmacy studies, - checking plausible values and correcting any deviations, - handling missing data. For demonstration purposes, we included in `AdhereR` a hypothetical dataset of 1080 medication events from 100 patients in a 2-year FUW. Five variables are included in this dataset: - patient unique identifier (`PATIENT_ID`), - event date (`DATE`; from 6 July 2030 to 3 September 2044, in the "mm/dd/yyyy" format), - daily dosage (`PERDAY`; median 4, range 2-20 doses per day), - medication type (`CATEGORY`; 50.8% medA and 49.2% medB), and - duration (`DURATION`; median 50, range 20-150 days). [Table 1](#Table-1) shows the medication events of two example patients: 19 medication events related to two medication types (`medA` and `medB`). They were selected to represent two different medication histories. Patient `37` had a stable daily dosage but event duration changes with medication change. Patient `76` had a more variable pattern, including medication, daily dosage and duration changes. ```{r, echo=TRUE, results='asis'} # Load the AdhereR library: library(AdhereR); # Select the two patients with IDs 37 and 76 from the built-in dataset "med.events": ExamplePats <- med.events[med.events$PATIENT_ID %in% c(37, 76), ]; # Display them as pretty markdown table: knitr::kable(ExamplePats, caption = "<a name=\"Table-1\"></a>**Table 1.** Medication events for two example patients"); ``` ## Visualization of patient records A first step towards deciding which algorithm is appropriate for these data is to explore medication histories visually. We do this by creating an object of type `CMA0` for the two example patients, and plotting it. This type of plots can of course be created for a much bigger subsample of patients and saved as as a `JPEG`, `PNG`, `TIFF`, `EPS` or `PDF` file using `R`'s plotting system for data exploration. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1\"></a>**Figure 1.** Medication histories - two example patients", fig.height=6, fig.width=8, out.width="100%"} # Create an object "cma0" of the most basic CMA type, "CMA0": cma0 <- CMA0(data=ExamplePats, # use the two selected patients ID.colname="PATIENT_ID", # the name of the column containing the IDs event.date.colname="DATE", # the name of the column containing the event date event.duration.colname="DURATION", # the name of the column containing the duration event.daily.dose.colname="PERDAY", # the name of the column containing the dosage medication.class.colname="CATEGORY", # the name of the column containing the category followup.window.start=0, # FUW start in days since earliest event observation.window.start=182, # OW start in days since earliest event observation.window.duration=365, # OW duration in days date.format="%m/%d/%Y"); # date format (mm/dd/yyyy) # Plot the object (CMA0 shows the actual event data only): plot(cma0, # the object to plot align.all.patients=TRUE); # align all patients for easier comparison ``` We can see that patient `76` had an interruption of more than 100 days between the second and third `medB` supply and several situations of new supply acquired while the previous supply was not exhausted. Patient `37` had shorter gaps between consecutive events, but very little overlap in supplies. For patient `76`, the switch to `medB` happened while the `medA` supply was still available, then a switch back to `medA` happened later, at the end of the second year. For patient `37`, there was a single medication switch (to `medB`) without an overlap at that point. Sometimes it is useful to also see the daily dose: ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 1 (a).** Same plot as in **Figure 1**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"} # Same plot as above but also showing the daily doses: plot(cma0, # the object to plot print.dose=TRUE, plot.dose=TRUE, align.all.patients=TRUE); # align all patients for easier comparison ``` These observations highlight several decision points in calculating persistence and adherence, which need to be informed by the clinical context of the study: - what OW is relevant for calculating adherence and persistence? Both patients have been on treatment during the 2 years, they had a substantial number of events of relatively short duration, and variable delays between the end of a supply and the next event. Thus, their adherence might have oscillated substantially during this period. We could compute adherence and/or persistence for the full 2-year period, or consider shorter intervals; - is the largest interruption seen in patient `76` an indication of non-persistence, or of lower adherence over that time interval? If the medication is likely to be used rarely despite daily use recommendations, such an interval might indicate a period of low adherence. If usual adherence rates are close to 100% when used, that delay is likely to indicate a treatment gap and needs to be treated as such, and the last 2 events as reinitiation of treatment (new treatment episode); - is the switch from `medA` to `medB` an indicator of a new treatment episode? If `medA` and `medB` are two alternative formulations of the same chemical molecule, there might be clinical arguments for considering them as part of the same treatment episode (e.g. the pharmacist provided an alternative option to a product unavailable at the moment). If they are two distinct drug classes with different mechanisms of action and recommendations of use, it may be more appropriate to consider that patient `76` has had 3 treatment episodes and patient `37` one episode; - is it necessary to consider carry-over of oversupply from previous events? For patient `37` this seems to matter very little, as there is little overlap between event durations, but patient `76` has substantial overlaps. If available medication is not likely to be either overused or discarded at every new medication event, it is important to control for carry-over; - it is necessary to consider carry-over also when medication changes? Patient `76` has changed from `medA` to `medB` while still having a large supply of `medA` available. Was the patient more likely to discard the remaining `medA` the moment of receiving `medB` or finish it before starting the `medB` supply? If they are two alternative formulations and `medB` was (for example) given because `medA` was not in stock at the moment, probably this came with a recommendation to finish the available supply. If they are two distinct drug classes and the switch happens usually after assessment of therapeutic versus side effects, probably this came with a recommendation to stop using `medA`. These decisions therefore need to be taken based on a good understanding of the pharmacological properties of the medication studied, and the most plausible clinical decision-making in routine care. This information can be collected from an advisory committee with relevant expertise (e.g. based on consensus protocols), or (even better) qualitative or survey research on the routine practices in prescribing, dispensing and using that specific medication. Of course, this is not always possible -- a second-best option (or even complementary option, if consensus is not reached) is to compare systematically the effects of different analysis choices on the hypotheses tested (e.g. as sensitivity analyses). ## Persistence -- treatment episodes An essential first decision is to distinguish between persistence with treatment and quality of implementation (once the patient started treatment -- which, as explained above, is assumed in situations when we have only one data source of prescribing or dispensing events). The function `compute.treatment.episodes()` was developed for this purpose. We provide below an example of how this function can be used. Let's imagine that `medA` and `medB` are two different types of medication, and clinicians in our advisory committee agree that whenever a health care professional changes the type of medication supplied this should be considered as a new treatment episode; we will specify this as setting the parameter `medication.change.means.new.treatment.episode` to `TRUE`. They also agree that a minumum of 6 months (180 days) need to pass after the end of a medication supply (taken as prescribed) without receiving a new supply in order to be reasonably confident that the patient has discontinued/interrupted the treatment -- they can conclude this for example based on an approximate calculation considering that specific medication is usually supplied for 1-2 months, daily dosage is usually 2 to 4 pills a day, and patients often use as low as 1/4 of the recommended dose in a given interval. We will specify this as `maximum.permissible.gap = 180`, and `maximum.permissible.gap.unit = "days"`. (If in another scenario the clinical information we obtain suggests that the permissible gap should depend on the duration of the last supply, for example 6 times that interval should go by before a discontinuation becoming likely, we can specify this as `maximum.permissible.gap = 600`, and `maximum.permissible.gap.unit = "percent"`.) We might also have some clinical confirmation that usually people finish existing supply before starting the new one (`carryover.within.obs.window = TRUE`), but of course only for the same medication if `medA` and `medB` are supplied with a recommendation to start a new treatment immediately (`carry.only.for.same.medication = TRUE`), take the existing supply based on the new dosage recommendations if these change (`consider.dosage.change = TRUE`). The rest of the parameters specify the name of the dataset (here `ExamplePats`), names of the variables in the dataset (here based on the demo dataset, described above), and the FUW (here the whole 2-year window). ```{r, echo=TRUE, results='asis'} # Compute the treatment episodes for the two patients: TEs3<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, # carry-over into the OW carry.only.for.same.medication = TRUE, # & only for same type consider.dosage.change = TRUE, # dosage change starts new episode... medication.change.means.new.treatment.episode = TRUE, # & type change maximum.permissible.gap = 180, # & a gap longer than 180 days maximum.permissible.gap.unit = "days", # unit for the above (days) followup.window.start = 0, # 2-years FUW starts at earliest event followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); knitr::kable(TEs3, caption = "<a name=\"Table-2\"></a>**Table 2.** Example output `compute.treatment.episodes()` function"); ``` The function produces a dataset as the one shown in [Table 2](#Table-2). It includes each treatment episode for each patient (here 2 episodes for patient `37` and 3 for patient `76`) and records the patient ID, episode number, date of episode start, gap days at the end of or after the treatment episode, duration of episode, and episode end date: - the date of the episode start is taken as the first medication event for a particular medication, - the end of the episode is taken as the day when the last supply of that medication finished (if a medication change happened, or if a period longer than the permissible gap preceded the next medication event) or the end of the FUW (if no other medication event followed until the end of the FUW), - the number of end episode gap days represents either the number of days **after** the end of the treatment episode (if medication changed, or if a period longer than the permissible gap preceded the next medication event) or **at** the end of (and within) the episode, i.e. the number of days after the last supply finished (if no other medication event followed until the end of the FUW), - the duration of the episode is the interval between the episode start and episode end (and may include the gap days at the end, in the latter condition described above). Notes: 1. just the number of gap days **after** the end of the episode can be computed by keeping all values larger than the permissible gap and by replacing the others by 0, 2. when medication change represents a new treatment episode, the previous episode ends when the last supply is finished (irrespective of the length of gap compared to a maximum permissible gap); any days before the date of the new medication supply are considered a gap. This maintains consistence with the computation of gaps between episodes (whether they are constructed based on the maximum permissible gap rule or the medication change rule). In some scenarios, it is important to imagine that the episodes also **include** the maximum permissible gap when the gap is larger than this maximum (i.e., not when a new episode is due to a change in treatment or dose before this maximum permissible gap was exceeded). To allow such scenarios, `compute.treatment.episodes()` has a logical parameter, `maximum.permissible.gap.append.to.episode`, which, when set to `TRUE` appends the maximum permissible gap at the end of the episodes (its default value `FALSE` means that the episodes end as described above). This output can be used on its own to study causes and consequences of medication persistence (e.g. by using episode duration in time-to-event analyses). This function is also a basis for the `CMA_per_episode` class, which is described later in the vignette. ## Adherence -- continuous multiple interval measures of medication availability/gaps (CMA) Let's consider another scenario: `medA` and `medB` are alternative formulations of the same chemical molecule, and clinicians agree that they can be used by patients within the same treatment episode. In this case, both patients had a single treatment episode for the whole duration of the follow-up ([Table 3](#Table-3)). We can therefore compute adherence for any observation window (OW) within these 2 years without any concern that we might confuse quality of implementation with (non-)persistence. ```{r, echo=TRUE, results='asis'} # Compute the treatment episodes for the two patients # but now a change in medication type does not start a new episode: TEs4<- compute.treatment.episodes(ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = TRUE, consider.dosage.change = TRUE, medication.change.means.new.treatment.episode = FALSE, # here maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start = 0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", date.format = "%m/%d/%Y"); # Pretty print the events: knitr::kable(TEs4, caption = "<a name=\"Table-3\"></a>**Table 3.** Alternative scenario output `compute.treatment.episodes()` function"); ``` Once we clarified that we indeed measure quality of implementation and not (non)-persistence, several `CMA` classes can be used to compute this specific component of adherence. We will discuss first in turn the *simple* `CMA` classes, then present the more complex (or *iterated*) `CMA_per_episode` and `CMA_sliding_window` ones. ### The simple CMAs A first decision to consider when calculating the quality of implementation is what is the appropriate observation window -- when it should start and how long it should last? We can see for example that patient `76` had some periods of regular (even overlapping) supplies, and periods when there were some large delays between consecutive medication events. Thus, estimating adherence for a whole 2-year period might be too coarse-grained to mean anything for how patients actually managed their treatment at any particular moment. As mentioned earlier in the [Definitions section](#Section-definitions), EHD don't have good granularity to start with, so we need to do the best with what we've got -- and compressing all this information into a single estimate might not be the best solution, at least not the obvious first choice. On the other hand, due to the low granularity, we cannot target very short observation windows either because we simply don't know what happened every day. This decision needs to be informed again by information collected from the advisory committee or qualitative/quantitative studies in the target population. It also needs to take into account the average duration of medication supply from one event, and the average time interval between two events -- which can be examined in exploratory plots ([Figure 1](#Figure-1)) -- and the research question and design of the study. For example, if we expect that the quality of implementation reduces in time from the start of a treatment episode, medication is usually supplied for one month, and patients can take up to 4 times as much to use up their supplies, we might want to consider comparing successive 4-month OWs. If we want to examine quality of implementation 6 months before a clinical event (on the clinical assumption that how a patient takes medication in previous 6 months may impact on the probability of a health event occurring or not), we might want to consider an OW start 6 months before the event, and a 6-month duration. The posibilities here are endless, and research on the impact of different analysis choices on substantive results is still scarce. When the consensus is not reached based on the available information, one or more parametrisations can be compared -- and formulated as research questions. For demonstration purposes, let's imagine a scenario when an adherence intervention takes place 6 months (182 days) after the start of the treatment episode, and we hypothesize that it will improve the quality of implementation in the next year (365 days) in the intervention group compared to the control group. We can specify this as `followup.window.start=0`, `observation.window.start=182`, and `observation.window.duration=365` (we can of course divide this interval into shorter windows and compare the two groups in terms of longitudinal changes in adherence, as we shall see later, but for the moment let's stick to a global 1-year estimate). We have 9 CMA classes that can produce very different estimates of the quality of implementation, the first eight have been described by [Vollmer and colleagues (2012)](#Ref-Vollmer2012) as applied to randomized controlled trials. We implemented them in `AdhereR` based on the authors' description, and in essence are defined by 4 parameters: 1) how is the OW delimited (whether time intervals before the first event and after the last event are considered), 2) whether CMA values are capped at 100%, 3) whether medication oversupply is carried over to the next event interval, and 4) whether medication available before a first event is considered in supply calculations or OW definition. #### CMA1 *CMA1* is the simplest method, often described in the literature as the *medication possession ratio* (MPR). It simply adds up the duration of all medication events within the OW, excluding the last event, and divides this by the number of days between the first and last event (multiplied by 100 to obtain a percentage). Thus, it can be higher than 1 (or 100% adherence) and, if the OW does not start and end with a medication event for all patients, it can actually refer to different lengths of time within the OW for different patients. For example, for patient `76` below CMA1 is computed for the period starting with the first event in the highlighted interval and ending at the date if the last event -- thus, it considers only 4 events with considerable overlaps and results in a CMA1 of 140%, indicating overuse. Creating an object of class `CMA1` with various parameters automatically performs the estimation of CMA1 for all the patients in the dataset; moreover, the object is smart enough to allow the appropriate printing and plotting. The object includes all the parameter values with which it was created, as well as the `CMA` `data.frame`, which is the main result, with two columns: patient ID and the corresponding CMA estimate. The CMA estimates appear as ratios, but can be trivially transformed into percentages and rounded, as we did for patient `76` below (rounded to 2 decimals). The plots show the CMA as percentage rounded to 1 decimal. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-2\"></a>**Figure 2.** Simple CMA 1", fig.height=5, fig.width=7, out.width="100%"} # Create the CMA1 object with the given parameters: cma1 <- CMA1(data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); # Display the summary: cma1 # Display the estimated CMA table: cma1$CMA # and equivalently using an accessor function: getCMA(cma1); # Compute the CMA value for patient 76, as percentage rounded at 2 digits: round(cma1$CMA[cma1$CMA$PATIENT_ID== 76, 2]*100, 2) # Plot the CMA: # The legend shows the actual duration, the days covered and gap days, # the drug (medication) type, the FUW and OW, and the estimated CMA. plot(cma1, patients.to.plot=c("76"), # plot only patient 76 legend.x=520); # place the legend in a nice way ``` #### CMA2 Thus, CMA1 assumes that there is a treatment episode within the OW (shorter or equal to the OW) when the patient used the medication, and every new medication event happened when the previous supply finished (possibly due to overuse). These assumptions rarely fit with real life use patterns. One limitation is not considering the last event -- which represents almost a half of the OW in the case of patient `76`. To address this limitation, *CMA2* includes the duration of the last event in the numerator and the period from the last event to the end of the OW in the denominator. Thus, the estimate [Figure 3](#Figure-3) is 77.9%, more in line with the medication history of this patient in the year after the intervention. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-3\"></a>**Figure 3.** Simple CMA 2", fig.height=5, fig.width=7, out.width="100%"} cma2 <- CMA2(data=ExamplePats, # we're estimating CMA2 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma2, patients.to.plot=c("76"), show.legend=FALSE); # don't show legend to avoid clutter (see above) ``` #### CMA3 and CMA4 Both CMA1 and CMA2 can be higher that 1 (100% adherence) based on the assumption that medication supply is finished until the last event (CMA1) or the end of the OW (CMA2). But sometimes this is not plausible, because patients can refill their supply earlier (for example when going on holidays) and overuse is a less frequent behaviour for some medications (when side effects are considerable for overuse, or medications are expensive). Or it may be that it does not matter whether patients use 100% or more that 100% of their medication, the therapeutic effect is the same with no risks or side effects. Again, this is a matter of inquiry to the advisory committee or investigation in the target population. If it is likely that implementation does not exceed 100% (or does not make a difference if it does), *CMA3* and *CMA4* below adjust for this by capping CMA1 and CMA2 respectively to 100%. As shown in [Figures 4](#Figure-4) and [5](#Figure-5), CMA3 is now capped at 100%, and CMA4 remains the same as CMA2 (because it was already lower than 100%). ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-4\"></a>**Figure 4.** Simple CMA 3", fig.height=5, fig.width=7, out.width="100%"} cma3 <- CMA3(data=ExamplePats, # we're estimating CMA3 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma3, patients.to.plot=c("76"), show.legend=FALSE); ``` ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-5\"></a>**Figure 5.** Simple CMA 4", fig.height=5, fig.width=7, out.width="100%"} cma4 <- CMA4(data=ExamplePats, # we're estimating CMA4 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma4,patients.to.plot=c("76"), show.legend=FALSE); ``` #### CMA5 and CMA6 All CMAs from 1 to 4 have a major limitation: they don't take into account the *timing* of the events. But if there is a large gap between two events it is more likely that the person had used the medication less than prescribed at least in part of that interval. Just capping the values as in CMA3 and CMA4 does not account for that likely reduction in adherence -- two patients with the same quantity of supply will have the same percentage of adherence even if one has had substantial delays in supply at some points and the other supplied in time. To adjust for this, *CMA5* and *CMA6* provide alternative calculations to CMA1 and CMA2 respectively. Thus, we instead calculate the number of gap days, extract it from the total time interval, and divide this value by the total time interval (first to last event in CMA5, and first event to end of OW in CMA6). By considering the gaps, we now need to decide whether to control for how any remaining supply is used when a new supply is obtained. Two additional parameters are included here: `carry.only.for.same.medication` and `consider.dosage.change`. Both are set here as `FALSE`, to specify the fact that carry over should always happen irrespective of what medication is supplied, and that the duration of the remaining supply should be modified if the dosage recommendations are changed with a new medication event. As shown in [Figures 6](#Figure-6) and [7](#Figure-7), these alternative calculations do not make any difference for patient `76`, because there are no gaps between the 5 events in the OW highighted. There could be, however, situations in which large gaps between some events in the OW result in lower CMA estimates when considering timing of events. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-6\"></a>**Figure 6.** Simple CMA 5", fig.height=5, fig.width=7, out.width="100%"} cma5 <- CMA5(data=ExamplePats, # we're estimating CMA5 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, # carry-over across medication types consider.dosage.change=FALSE, # don't consider canges in dosage followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma5,patients.to.plot=c("76"), show.legend=FALSE); ``` ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-7\"></a>**Figure 7.** Simple CMA 6", fig.height=5, fig.width=7, out.width="100%"} cma6 <- CMA6(data=ExamplePats, # we're estimating CMA6 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma6,patients.to.plot=c("76"), show.legend=FALSE); ``` Sometimes it is useful to also see the daily dose: ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-1a\"></a>**Figure 7 (a).** Same plot as in **Figure 7**, but also showing the daily doses as numbers and as line thickness", fig.height=6, fig.width=8, out.width="100%"} # Same plot as above but also showing the daily doses: plot(cma6, # the object to plot patients.to.plot=c("76"), # plot only patient 76 print.dose=TRUE, plot.dose=TRUE, legend.x=520); # place the legend in a nice way ``` #### CMA7 All CMAs so far have another limitation: they do not consider the interval between the start of the OW and the first event within the OW. For situations in which the OW start coincides with the treatment episode start, this limitation has no consequences. But in scenarios like ours (OW starts during the episode) this has two major drowbacks. First, the time interval for calculating CMA is not the same for all patients; this can result in biases, for example if the intervention group tends to refill sooner after the intervention moment than the control group, the control group might seem more adherent but it is because CMA is calculated on a shorter time interval within the following year. And second, if there is any medication supply left from before the OW start, this is not considered (so CMA may be underestimated). *CMA7* addresses this limitation by extending the nominator to the whole OW interval, and by considering carry over both from before and within the OW. The same paremeters are available to specify whether this depends on the type of medication and considers dosage changes (applied now to both types of carry over). [Figure 8](#Figure-8) shows how considering the period at the OW start and the prior supply reduces CMA7 to 69%, due to the gap visible in the medication history plot between the event before the OW and the first event within the OW. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-8\"></a>**Figure 8.** Simple CMA 7", fig.height=5, fig.width=7, out.width="100%"} cma7 <- CMA7(data=ExamplePats, # we're estimating CMA7 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma7, patients.to.plot=c("76"), show.legend=FALSE); ``` #### CMA8 When entering a randomized controlled trial involving a new medication, a patient on ongoing treatment may be more likely to finish the current supply before starting the trial medication. In these situations, it may be more appropriate to consider a lagged start of the OW (even if this results in a different denominator for trial participants). Let's consider this different scenario for patient `76`: at day 374, a new treatment (`medB`) starts and we need to estimate CMA for the next 294 days (until the next medication change). But there is still some `medA` left, so it is likely that the patient finished this first. [Figure 9](#Figure-9) shows how the OW is shortened with the number of days it would have taken to finish the remaining `medA` (assuming use as prescribed); *CMA8* is quite low 36.1%, given the long gaps between medB events. In a future version, it might be interesting to implement the possibility to also move the end of OW so that its length is preserved. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-9\"></a>**Figure 9.** Simple CMA 8", fig.height=5, fig.width=7, out.width="100%"} cma8 <- CMA8(data=ExamplePats, # we're estimating CMA8 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=374, observation.window.duration=294, date.format="%m/%d/%Y"); plot(cma8, patients.to.plot=c("76"), show.legend=FALSE); # The value for patient 76, rounded at 2 digits round(cma8$CMA[cma8$CMA$PATIENT_ID== 76, 2]*100, 2); ``` #### CMA9 The previous 8 CMAs were described by [Vollmer and colleagues (2012)](#Ref-Vollmer2012) in relation to randomized controlled trials, and may apply to many observational designs as well. However, they all rely on an assumption that might not hold for longitudinal cohort studies with multiple repeated measures: the medication is used as prescribed until current supply ends. In CMA7, this may introduce additional variation in adherence estimates depending on where the start of the OW is located relative to the last event before the OW and the first event within the OW: an OW start closer to the first event in the OW generates lower estimates for the same number of gap days between the two events. To address this, *CMA9* first computes a ratio of days’ supply for each event in the FUW (until the next event or FUW end), then weighs all days in the OW by their corresponding ratio to generate an average CMA value for the OW. For the same scenario as in CMA1 to CMA7, [Figure 10](#Figure-10) shows the estimate for CMA9, which is higher than for CMA7 (70.6% versus 69%). This value would be the same no matter if the OW starts slightly earlier or later, because CMA9 considers the same intervals between events (the one starting before and the one ending after the OW). Thus, it depends less on the actual date when the OW starts. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-10\"></a>**Figure 10.** Simple CMA 9", fig.height=5, fig.width=7, out.width="100%"} cma9 <- CMA9(data=ExamplePats, # we're estimating CMA9 now! ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=182, observation.window.duration=365, date.format="%m/%d/%Y"); plot(cma9, patients.to.plot=c("76"), show.legend=FALSE); ``` ### The iterated CMAs We introduce here two complex (or iterated) CMAs that share the property that they apply a given single CMA iteratively to a set of sub-periods (or windows), defined in various ways. #### CMA per episode When we calculated the persistence and implementation above, we first defined the *treatment episodes*, and then computed the CMAs within the episode. The `CMA_per_episode` class allows us to do this in one single step. In our intervention scenario, both example patients had a 2-year treatment episode and we computed the various simple CMAs for a 1-year period within this longer episode. But if we consider that medication change triggers a new treatment episode, patient `76` would have 3 episodes. `CMA_per_episode` can compute any of the 9 simple CMAs for all treatment episodes for all patients. As with the simple CMAs, the `CMA_per_episode` class contains a list that includes all the parameter values, as well as a `CMA` `data.frame` (with all columns of the `compute.treatment.episodes()` output table, plus a new column with the CMA values). The `CMA_per_episode` values can also be transformed into percentages and rounded, as we did for patient `76` below (rounded to 2 decimals). Plots now include an extra section at the top, where each episode is shown as a horizontal bar of length equal to the episode duration, and the corresponding CMA estimates are given both as percentage (rounded to 1 decimal) and as a grey area. An extra area on the right of the plot displays the distribution of all CMA values for the whole FUW as a histogram or as smoothed kernel density (see [Figure 11](#Figure-11)). ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-11\"></a>**Figure 11.** CMA 9 per episode", fig.height=5, fig.width=7, out.width="100%", warning=FALSE} cmaE <- CMA_per_episode(CMA="CMA9", # apply the simple CMA9 to each treatment episode data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carryover.within.obs.window = TRUE, carry.only.for.same.medication = FALSE, consider.dosage.change = FALSE, # conditions on treatment episodes medication.change.means.new.treatment.episode = TRUE, maximum.permissible.gap = 180, maximum.permissible.gap.unit = "days", followup.window.start=0, followup.window.start.unit = "days", followup.window.duration = 365 * 2, followup.window.duration.unit = "days", observation.window.start=0, observation.window.start.unit = "days", observation.window.duration=365*2, observation.window.duration.unit = "days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaE; # The CMA estimates table: cmaE$CMA getCMA(cmaE); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits: round(cmaE$CMA[cmaE$CMA$PATIENT_ID== 76, 7]*100, 2); # Plot: plot(cmaE, patients.to.plot=c("76"), show.legend=FALSE); ``` #### Sliding-window CMA When discussing the issue of granularity earlier, we mentioned that estimating adherence for a whole 2-year period might be too coarse-grained to be clinically relevant, and that shorter intervals may be more appropriate, for example in studies that aim to investigate how the quality of implementation varies in time during a long-term treatment episode. In such cases, we might want to compare successive intervals, for example 4-month intervals. `CMA_sliding_window` allows us to compute any of the 9 simple CMAs for repeated time intervals (*sliding windows*) within an OW. A similar output is produced as for `CMA_per_episode`, including a CMA table (with patient ID, window ID, window start and end dates, and the CMA estimate). [Figure 12](#Figure-12) shows the results of CMA9 for patient `76`: 6 sliding windows of 4 months, among which 2 have a CMA higher than 80%, two have values around 60% and two around 40%, suggesting a variable quality of implementation. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-12\"></a>**Figure 12.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"} cmaW <- CMA_sliding_window(CMA.to.apply="CMA9", # apply the simple CMA9 to each sliding window data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # sliding windows definition sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=120, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Summary: cmaW; # The CMA estimates table: cmaW$CMA getCMA(cmaW); # as above but using accessor function # The values for patient 76 only, rounded at 2 digits round(cmaW$CMA[cmaW$CMA$PATIENT_ID== 76, 5]*100, 2); # Plot: plot(cmaW, patients.to.plot=c("76"), show.legend=FALSE); ``` The sliding windows can also overlap, as illustrated below. This can for example be used to estimate the variation of adherence (implementation) during an episode. [Figure 13](#Figure-13) shows 21 sliding windows of 4 month for patient `76`, in steps of 1 month. The patient's quality of implementation oscillated between 37% and 100% during the 2 years of follow-up. This output can be further analyzed in relation to patterns of health status if such data are available for the same time period. ```{r, echo=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-13\"></a>**Figure 13.** Sliding window CMA 9", fig.height=5, fig.width=7, out.width="100%"} cmaW1 <- CMA_sliding_window(CMA.to.apply="CMA9", data=ExamplePats, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, observation.window.start=0, observation.window.duration=365*2, sliding.window.start=0, # different sliding windows sliding.window.start.unit="days", sliding.window.duration=120, sliding.window.duration.unit="days", sliding.window.step.duration=30, sliding.window.step.unit="days", date.format="%m/%d/%Y", parallel.backend="none", parallel.threads=1); # Plot: plot(cmaW1, patients.to.plot=c("76"), show.legend=FALSE); ``` #### Mapping events to episodes and sliding windows The functions `compute.treatment.episodes`, `CMA_per_episode` and `CMA_sliding_window` can return the mapping between events and episodes or sliding windows, respectively, in the sense that they can specify, for each episode or sliding which, which events participate in it. For the latter two, this correspondence can also be shown visually in plots (see [Figure 14](#Figure-14)). Please note that, as the details of which events belong to which episode may depend on the particular simple CMA used, it is recommended to take the mapping produced by `compute.treatment.episodes` as orientative, and use instead the mapping produced by `CMA_per_episode` for a particular simple CMA. ```{r, echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-14\"></a>**Figure 14.** Per episodes with CMA 1, showing which events belong to which episode: for events, the number(s) between '[]' represent the event they belong to, while for an event, the number between '[]' is what the events use as its identifier. (e.g., the 3rd even from the left for patient 1 has a '[2]', meaning that it belongs to event '2', which is identified as such with a '[2]' immediately after is estimated CMA of '136%'). Please note that the same plot for CMA9 would be quite different, as the rules for which events are considered differ (e.g., the last events of the episodes would be included).", fig.height=7, fig.width=7, out.width="100%"} cmaE <- CMA_per_episode(CMA="CMA1", data=med.events[med.events$PATIENT_ID %in% 1:2,], ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=-90, observation.window.start=0, observation.window.duration=365, maximum.permissible.gap=10, return.mapping.events.episodes=TRUE, # ask for the mapping medication.change.means.new.treatment.episode=TRUE, date.format="%m/%d/%Y"); getEventsToEpisodesMapping(cmaE); # get the mapping (here, print it) plot(cmaE, align.all.patients=TRUE, print.dose.centered=TRUE, print.episode.or.sliding.window=TRUE); # show the mapping visually ``` ## Interactive plotting <a name="Section-interactive-plotting"></a> During the exploratory phases of data analysis, it is sometimes extremely useful to be able to plot interactively various views of the data using different parameter settings. We have implemented such interactive plotting of medication histories and (simple and iterative) CMA estimates within [`RStudio`](https://www.rstudio.com) and outside it (using [`Shiny`](https://shiny.rstudio.com/); this is the default as it very flexible and independent of running `AdhereR` within `RStudio`) through the `plot_interactive_cma()` function. This function is generic and interactive, and can be given a large set of parameters (including the dataset on which to work) or it can interactively acquire these parameters directly from the user. Please note that this interactive plotting is actually implemented in a different package, `AdhereRViz` (which extends `AdhereR`); for more info, please see the vignette [AdhereR: Interactive plotting (and more) with Shiny](https://cran.r-project.org/package=AdhereRViz/vignettes/adherer_interctive_plots.html) from package `AdhereRViz`. ## Computing event duration from prescription, dispensing, and hospitalization data <a name="Section-compute-event-duration"></a> Computation of CMAs requires a supply duration for medications dispensed to patients. If medications are not supplied for fixed durations but as a quantity that may last for various durations based on the prescribed dose, the supply duration has to be calculated based on dispensed and prescribed doses. Treatments may be interrupted and resumed at later times, for which existing supplies may or may not be taken into account. Patients may be hospitalized or incarcerated, and may not use their own supplies during these periods. The function `compute_event_durations` calculates the supply durations, taking into account the aforementioned situations and offering parameters for flexible adjustments. ## Computing time to initiation <a name="Section-compute-time-to-initiation"></a> The period between the first prescription event and the first dose administration may impact health outcomes differently than omitting doses once on treatment or interrupting medication for longer periods of time. Primary non-adherence (not acquiring the first prescription) or delayed initiation may have a negative impact on health outcomes. The function `time_to_initiation` calculates the time between the first prescription and the first dispensing event, taking into account multiple variables to differentiate between treatments. ## Defining medication groups <a name="Section-defining-medication-groups"></a> The main idea behind *medication groups* is that there might be meaningful ways of grouping medications both for the computation of CMAs and their plotting. For example, a patient might receive medication for treating a hart conditions and medication for a dermatological condition, and we might want to investigate the patient's patterns of adherence to each of these two broad types (or groups) of medication separately. However, the mechanism for defining such groups much be flexible enough to allow, for example, the same medication to belong to two groups based on dose, duration or other characteristics. Therefore, we implemented this using a very flexible yet powerful and intuitive mechanism that can use any type of information associated to the actual events. To illustrate, we will use the data that comes with the package: `med.events.ATC` and `med.groups`. `med.events.ATC` is a `data.frame` with `r nrow(med.events.ATC)` events (one per row) for `r length(unique(med.events.ATC$PATIENT_ID))` patients, containing the patient's unique identifier (column `PATIENT_ID`), the event date (`DATE`) and duration (`DURATION`), and the medication's [ATC code](https://www.whocc.no/atc/structure_and_principles/) (column `CATEGORY`), further detailing its first two levels: level 1 (one letter giving the anatomical main group, e.g., "A" for "Alimentary tract and metabolism"; column `CATEGORY_L1`) and level 2 (the therapeutic subgroup, e.g., "A02" for "Drugs for acid related disorders"): ```{r, echo=FALSE} knitr::kable(head(med.events.ATC, n=5), row.names=FALSE, caption="First 5 lines of the `med.events.ATC` dataset."); ``` In fact, `med.events.ATC` is derived from the `durcomp` data as follows: ```{r, eval=FALSE} event_durations <- compute_event_durations(disp.data = durcomp.dispensing, presc.data = durcomp.prescribing, special.periods.data = durcomp.hospitalisation, ID.colname = "ID", presc.date.colname = "DATE.PRESC", disp.date.colname = "DATE.DISP", medication.class.colnames = c("ATC.CODE", "UNIT", "FORM"), total.dose.colname = "TOTAL.DOSE", presc.daily.dose.colname = "DAILY.DOSE", presc.duration.colname = "PRESC.DURATION", visit.colname = "VISIT", split.on.dosage.change = TRUE, force.init.presc = TRUE, force.presc.renew = TRUE, trt.interruption = "continue", special.periods.method = "continue", date.format = "%Y-%m-%d", suppress.warnings = FALSE, return.data.table = FALSE); med.events.ATC <- event_durations$event_durations[ !is.na(event_durations$event_durations$DURATION) & event_durations$event_durations$DURATION > 0, c("ID", "DISP.START", "DURATION", "DAILY.DOSE", "ATC.CODE")]; names(med.events.ATC) <- c("PATIENT_ID", "DATE", "DURATION", "PERDAY", "CATEGORY"); # Groups from the ATC codes: sort(unique(med.events.ATC$CATEGORY)); # all the ATC codes in the data # Level 1: med.events.ATC$CATEGORY_L1 <- vapply(substr(med.events.ATC$CATEGORY,1,1), switch, character(1), "A"="ALIMENTARY TRACT AND METABOLISM", "B"="BLOOD AND BLOOD FORMING ORGANS", "J"="ANTIINFECTIVES FOR SYSTEMIC USE", "R"="RESPIRATORY SYSTEM", "OTHER"); # Level 2: med.events.ATC$CATEGORY_L2 <- vapply(substr(med.events.ATC$CATEGORY,1,3), switch, character(1), "A02"="DRUGS FOR ACID RELATED DISORDERS", "A05"="BILE AND LIVER THERAPY", "A09"="DIGESTIVES, INCL. ENZYMES", "A10"="DRUGS USED IN DIABETES", "A11"="VITAMINS", "A12"="MINERAL SUPPLEMENTS", "B02"="ANTIHEMORRHAGICS", "J01"="ANTIBACTERIALS FOR SYSTEMIC USE", "J02"="ANTIMYCOTICS FOR SYSTEMIC USE", "R03"="DRUGS FOR OBSTRUCTIVE AIRWAY DISEASES", "R05"="COUGH AND COLD PREPARATIONS", "OTHER"); ``` For this dataset, we could define the following medication groups: - *Vitamins*: all 'VITAMINS' (i.e., all medications of ATC subgroup "A11"), - *VitaResp*: groups all *Vitamins* and medications referring to the 'RESPIRATORY SYSTEM' (ATC group "R"), - *VitaShort*: all *Vitamins* administered for less than 31 days, - *VitELow*: tocopherol (vit E) (ATC code "A11HA03") at doses lower or equal to 500mg, - *VitaComb*: groups *VitaShort* and *VitELow* (i.e., vitamines for less than 31 days and tocopherol at at most 500mg), - *NotVita*: all non-*Vitamins*. These are defined in `med.groups`, which is a named vector of characters: ```{r eval=FALSE} med.groups <- c("Vitamins" = "(CATEGORY_L2 == 'VITAMINS')", "VitaResp" = "({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')", "VitaShort" = "({Vitamins} & DURATION <= 30)", "VitELow" = "(CATEGORY == 'A11HA03' & PERDAY <= 500)", "VitaComb" = "({VitaShort} | {VitELow})", "NotVita" = "(!{Vitamins})"); ``` The `names` in the vector are the names of the various medication groups (e.g., "Vitamins" is the name of the first group, corresponding to all the vitamins), while the values of the vector are the actual definitions and use the same syntax, operators and conventions as any `R` *expression*. The name of a medication group can be pretty much any string of characters not containing "}", but it is recommended to keep them short, expressive and (as much as possible) free of non-alphanumeric symbols (in fact, the best recommendation is to stick to the rules for defining legal `R` variable and function names). Focussing on the first one, `(CATEGORY_L2 == 'VITAMINS')`, `CATEGORY_L2` refers to the `CATEGORY_L2` column in the `med.events.ATC` dataset, `'VITAMINS'` is a possible value that may appear in that column, and `(`, `)` and `==` have the usual interpretation in `R` (grouping and test of equality, respectively). In fact, this *is* translated internally into an expression that is evaluated on the `med.events.ATC` dataset, resulting in a vector of logical values, one per row, saying which events in `med.events.ATC` correspond to this medication group (`TRUE`, there are `r sum(med.events.ATC$CATEGORY_L2 == 'VITAMINS',na.rm=TRUE)` such events) and which not (`FALSE`, the remaining `r sum(!(med.events.ATC$CATEGORY_L2 == 'VITAMINS'),na.rm=TRUE)` events): ```{r, echo=FALSE} knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *Vitamins* medication group."); ``` A special notation is used to "make reference" to another named medication group, by surrounding the medication group's name by `{` and `}`: the second medication group "VitaResp" si defined as `({Vitamins} | CATEGORY_L1 == 'RESPIRATORY SYSTEM')`, where `{Vitamins}` simply refers to the events corresponding to the "Vitamins" group discussed above; internally, the "Vitamins" group is evaluated and its vector of logicals is combined using `|` (OR) with the vector of logicals corresponding to `CATEGORY_L1 == 'RESPIRATORY SYSTEM'`: ```{r, echo=FALSE} knitr::kable(head(med.events.ATC[med.events.ATC$CATEGORY_L2 == 'VITAMINS' | med.events.ATC$CATEGORY_L1 == 'RESPIRATORY SYSTEM',], n=5), row.names=FALSE, caption="First 5 events in `med.events.ATC` corresponding to the *VitaResp* medication group."); ``` This mechanism is very flexible and extensible, allowing, for example, tests involving the duration ("VitaShort") and the dosage ("VitELow"), and the combination of several defined groups ("VitaComb"). However, it is important to remember that: a) these must be well-formed and meaningful expressions, b) using column names and values in the dataset containing the events, c) and/or other groups between `{` and `}`, d) and must evaluate to valid logical vectors of the same length as the number of events (rows) in the dataset. By default, an extra special medication group `__ALL_OTHERS__` is automatically computed, including all events that are not covered by any of the explicitly defined medication groups (if any). Please note that, for security reasons, this evaluation is performed in a separate environment where only certain functions and operators are allowed (the functions in the `Math`, `Arith`, `Logic` and `Compare` groups, and the operators `(`, `[` and `!`). With these, definitions of medication groups can be passed to all CMA functions using the `medication.groups` parameter: ```{r} cma1_mg <- CMA1(data=med.events.ATC, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", medication.groups=med.groups, followup.window.start=0, observation.window.start=0, observation.window.duration=365, date.format="%m/%d/%Y"); cma1_mg; # print it ``` There is a new function, `getMGs()`, which returns the medication groups for a CMA object (if none, `NULL`); this is a list with two members (here, for `getMGs(cma1_mg)`): - `def`, which contains the definitions of the medication groups (+ `__ALL_OTHERS__`) as a `data.frame` with columns `name` and `def`: ```{r echo=FALSE} getMGs(cma1_mg)$def; ``` - `obs`, which is logical `matrix` with as many rows as the dataset on which the CMA was estimated (here, `med.events.ATC`) and as many columns as medication groups (including `__ALL_OTHERS__`); a value of `TRUE` means that the corresponding event in the dataset is selected by the corresponding medication group (here, its first 10 rows): ```{r echo=FALSE} head(getMGs(cma1_mg)$obs, n=10); ``` The `getCMA()` function works as before, except that now, by default, it returns a list with as many entries as there are medication groups (+ `__ALL_OTHERS__`), each containing its own CMA estimates: ```{r} getCMA(cma1_mg); ``` Thus, patient `2` has a `CMA1` of ~1.77 for "Vitamins", of ~1.76 for "VitaResp", none (`NA`) for "VitaShort", "VitELow" and "VitaComb", of ~2.76 for "NotVita". Here, as can also be seen in the `obs` component of `getMGs(cma1_mg)`, the default `__ALL_OTHERS__` did not select any events, results in an empty CMA estimate for it. Sometimes, however, this structuring of the CMAs as a list may not be desirable, in which case the parameter `flatten.medication.groups = TRUE` comes in handy: ```{r} getCMA(cma1_mg, flatten.medication.groups=TRUE); ``` (It can also be directly passed to the CMA function.) Please note that, by default, all medication groups belonging to one patient share the same follow-up and observation windows, but this can be changed by setting the parameter `followup.window.start.per.medication.group = TRUE` so that each medication group has its own follow-up and observation windows. The medication groups also affect the plotting: ```{r echo=TRUE, message=FALSE, warning=FALSE, fig.show='hold', fig.cap = "<a name=\"Figure-15\"></a>**Figure 15.** CMA 1 with medication groups.", fig.height=9, fig.width=9, out.width="100%"} plot(cma1_mg, #medication.groups.to.plot=c("VitaResp", "VitaShort", "VitaComb"), patients.to.plot=1:3, show.legend=FALSE); ``` The medication groups are ordered within patients, and visually grouped using alternating thick blue lines (which can be controlled through the parameters `medication.groups.separator.show`, `medication.groups.separator.lty`, `medication.groups.separator.lwd` and `medication.groups.separator.color`); likewise, the name of the special `__ALL_OTHERS__` groups can be controlled with the `medication.groups.allother.label` parameter (defaults to "*"). Only the medication groups that contain at least one event are shown for each patient. If desired, the parameter `medication.groups.to.plot` can be used to explicitly list the names of the medication groups to include in the plot (by default, all). Medication groups work in the same way across all simple and complex CMAs, an are included in the interactive `Shiny` interface as well. As a special case, the `medication.groups` parameter can simply be the name of a column in the `data` that define the medication groups through its values. For example, ```{r eval=FALSE} cma0_types <- CMA0(data=med.events.ATC, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", medication.groups="CATEGORY_L1", #flatten.medication.groups=TRUE, #followup.window.start.per.medication.group=TRUE, followup.window.start=0, observation.window.start=0, observation.window.duration=365, date.format="%m/%d/%Y"); ``` defines `r length(unique(med.events.ATC$CATEGORY_L1))` medication groups `r paste0('"',sort(unique(med.events.ATC$CATEGORY_L1)),'"',collapse=", ")` using the `CATEGORY_L1` column in the example `med.events.ATC` dataset. Behind the scenes, this is simply expanded into the medication group definitions: ```{r echo=FALSE} tmp <- sort(unique(med.events.ATC$CATEGORY_L1)); cat(paste0("c(", paste0('"',tmp,'"',' = "(CATEGORY_L1 == \'',tmp,'\')"',collapse=",\n "), ");")); ``` Please note that if no medication groups are defined (the default), then *nothing* changes in the behaviour of the package (so it is fully backwards compatible). ## Working with very large databases <a name="Section-working-with-databases"></a> `AdhereR` can use data stored in a variety of "classical" `RDBMS`'s (Relational Database Management Systems), such as [`MySQL`](https://www.mysql.com/) or [`SQLite`](https://www.sqlite.org/index.html), either through explicit [`SQL`](https://en.wikipedia.org/wiki/SQL) queries or transparently through [`dbplyr`](https://db.rstudio.com/dplyr/), or in other systems, such as the [`Apache Hadoop`](https://hadoop.apache.org/). Thus, `AdhereR` can access (very) large quantities of data stored in various formats and using different backends, and can process it ranging from single-threaded set-ups on a client machine to large heterogeneous distributed clusters (using, for example, various explicit parallel processing frameworks or `Hadoop`'s `MapReduce` framework). All these are detailed in a dedicated vignette *"Using `AdhereR` with various database technologies for processing very large datasets"*. ## Using `AdhereR` from other programming languages and platforms <a name="Section-calling-adherer-from-other"></a> `AdhereR` can be transparently used from other programming languages than `R` (such as `Python`) or platforms (such as `Stata`) by implementing a startdized interface defined for these purposes. A working implementation for `Python 3` is included in the package (and inteded also as a hands-on guide to further implementations) and is described in detailed in a dedicated vignette *"Calling AdhereR from Python3"*. ## AdhereR is pipe (`%>%` or `|>`)-friendly <a name="pipe-friendly"></a> The [pipe operator (`%>%`)](https://r4ds.had.co.nz/pipes.html) has been originally introduced in `R` by the [`magrittr` package](https://cran.r-project.org/package=magrittr/vignettes/magrittr.html) and is a central feature of the [Tidyverse](https://www.tidyverse.org/), and is since `R` 4.1 also available natively as `|>` [(but there are some subtle differences from `%>%`)](https://www.infoworld.com/article/3621369/use-the-new-r-pipe-built-into-r-41.html). `AdhereR` is compatible with pipe (because for all functions the first parameter encapsulates the "important" data, with the others providing various "tweaks"), so, code such as the following is fully functional: ```{r eval=FALSE} library(dplyr); # Compute, then get the CMA, change it and print it: x <- med.events %>% # use med.events filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients CMA9(ID.colname="PATIENT_ID", # compute CMA9 event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=230, followup.window.duration=705, observation.window.start=41, observation.window.duration=100, date.format="%m/%d/%Y") %>% getCMA() %>% # get the CMA estimates mutate(CMA=sprintf("%.1f%%",100*CMA)); # make them percents print(x); # print it # Plot some CMAs: med.events %>% # use med.events filter(PATIENT_ID %in% c(1,2,3)) %>% # first 3 patients CMA_sliding_window(CMA.to.apply="CMA7", # sliding windows CMA7 ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=230, followup.window.duration=705, observation.window.start=41, observation.window.duration=100, date.format="%m/%d/%Y") %>% plot(align.all.patients=TRUE, show.legend=TRUE); # plot it ``` ## Modifying `AdhereR` plots *a posteriori* <a name="modify-plots"></a> ```{r echo=TRUE, fig.show='hold', fig.cap = "<a name=\"Figure-16\"></a>**Figure 16.** Modifying an `AdhereR` plot is easy using the `get.plotted.events()` function.", fig.height=8, fig.width=8, out.width="100%"} # Plot CMA7 for patients 5 and 8: cma7 <- CMA7(data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", followup.window.start=30, observation.window.start=30, observation.window.duration=365, date.format="%m/%d/%Y" ); plot(cma7, patients.to.plot=c(5,8), show.legend=TRUE); # good plot after an error plot # Access the plotting info: pevs <- get.plotted.events(); # get the plotted events with their plotting info # Let's add a vertical line for patient 8 between the medication change: # Find the event where the medication changes: i <- which(pevs$PATIENT_ID == "8" & pevs$CATEGORY != c(pevs$CATEGORY[-1], pevs$CATEGORY[nrow(pevs)])); # Half-way between the events where medication changes: x <- (pevs$.X.END[i] + pevs$.X.START[i+1])/2; # Draw the line: segments(x, pevs$.Y.OW.START[i], x, pevs$.Y.OW.END[i], col="blue", lty="solid", lwd=3); # Put a star * next to the 4th event of patient 5: # Find the event: i <- which(pevs$PATIENT_ID == "5")[4]; # Plot the star: text(pevs$.X.START[i]-strwidth("* "), pevs$.Y.START[i], "*", cex=3.0, col="darkgreen"); # Add some random text over the figure: text((pevs$.X.FUW.START[1] + pevs$.X.FUW.END[1])/2, # X center of patient 5's FUW (pevs$.Y.FUW.START[nrow(pevs)] + pevs$.Y.FUW.END[nrow(pevs)])/2, # Y center of 8's FUW "Change with care!!!", srt=45, cex=1.5, col="darkred") ``` ## Technical details Here we overview some technical details, including the main `S3` classes and functions (probably useful for scripting and extension), our treatment of dates and durations, and the issue of performance and parallelism (useful for large datasets). ### Main `S3` classes and functions The `S3` class `CMA0` is the most basic object, basically encapsulating the dataset and desired parameter values; it should not be normally used directly (except for plotting the event data as such), but it is the foundation for the other classes. A `CMA0` (and derived) object can print itself (the output is optimized either for text, LaTeX or Markdown), can plot itself (with various parameters controlling exactly how), and offers the accessor function `getCMA()` for easy access to the CMA estimate. Please note that these CMAs all work for datasets that contain more than one patient, and the estimates are computed for each patient independently, and the plotting can display more than one patient (in this case the patients are plotted on top of each other vertically), as shown in [Figure 1](#Figure-1). The simple CMAs are implemented by the `S3` classes `CMA1` -- `CMA9`, that are derived from `CMA0` and reload its methods. Thus, one can easily implement a new simple CMA by extending the base `CMA0` class. The iterative CMAs, in contrast, are not derived from `CMA0` but use internally such a simple CMA to perform their computations. For the moment, they can *not* be extended to new simple CMAs derived from `CMA0`, but, if needed, such a mechanism could be implemented. The most important functions are: - `compute.event.int.gaps()`: for a given event database, this computes the gap days and event intervals in various scenarious, and while it should not in general be directly used, it is exported in case a use scenario requires this explicit computation; - `compute.treatment.episodes()`: this computes the treatment episodes for each patient in various scenarios; - `getCMA()`: getter functions, giving access to the estimated CMAs; - `plot_interactive_cma()`: plots interactively within RStudio (see the [Interactive plotting section](#Section-interactive-plotting)). ### Calendar dates and durations A potentially confusing (but very powerful and flexible) aspect of our implementation concerns our treatment of dates and durations. First, the *duration of an event* is given in a *column* in the dataset containing, for each event, its duration (as a positive integer) in *days*. However, *other durations* (such as for FUW or the sliding windows) are given as positive integers representing the number of *units*; these units can be "days" (the default), "weeks", "months", or "years". The *date of an event* is given in a *column* in the dataset containing, for each event, its start date as a string (`character`) in the format given by the `date.format` parameter (by default, mm/dd/yyyy). The *start* of the FUW, OW and sliding windows can be given either as the number (integer) of *units* ("days", "weeks", "months", or "years") since the first recorded event for the patient, or as an object of *class `Date`* representing the actual calendar start date, or a string (`character`) giving a *column name* in the dataset containing, per patient, either the calendar start date as `Date` object (i.e., this column must be of type `Date`) or as the number of units if the column has type `numeric`. While this might be confusing, it allows greater flexibility in specifying the start dates; the most important pitfall is in passing a date as a string (type `character`) which will result in an error as there is no such column in the dataset -- make sure it is converted to a `Date` object by using, for example, `as.Date()`! However, for most scenarios, the default of giving the number of units since the earliest event is more than enough and is the recommended (and most carefully tested) way. ### Performance, parallelism and implementation While currently implemented in pure `R`, we have extensively profiled and optimized our code to allow the processing of large databases even on consumer-grade hardware. For example, [Table 4](#Table-4) below gives the running times (single-threaded and two parallel multicore threads -- see below for details) for a database of 13,922 unique patients and 112,984 prescriptions of all CMAs described here, on an Apple MacBook Air 11" (7,1; early 2015) with 8Go RAM (DDR3 @ 1600MHz) and a Core i7-5650U CPU (2 cores, 4 threads with hyperthreading @ 2.20GHz, Turbo Boost to 3.10GHz), using MacOS X "El Capitan" (10.11.6), `R` 3.3.1 (64 bits) and `RStudio` 1.0.44. [Table 5](#Table-5) below shows the running times (single-threaded and four parallel multicore threads) for a very large database of 500,000 unique patients and 4,058,110 prescriptions (generated by repeatedly concatenating the database described above and uniquely renaming the participants) of all CMAs described here, on a desktop computer with 16Go RAM and a Core i7-3770 CPU (4 cores, 8 threads with hyperthreading @ 3.40GHz, Turbo Boost to 3.90GHz), using OpenSuse 13.2 (Linux kernel 3.16.7) and `R` 3.3.2 (64 bits). [Table 6](#Table-6) shows the same information as [Table 5](#Table-5), but on a high-end desktop computer with 32Go RAM and a Core i7-4790K CPU (4 cores, 8 threads with hyperthreading @ 4.00GHz, Turbo Boost to 4.40GHz), running Windows 10 Professional 64 bits (version 1607) and `R` 3.2.4 (64 bits); as dicusssed below, the "multicore" backend is currently not available on Windows. As these benchmarking results show, a database close to the median sample sizes in the literature (median 10,265 patients versus our 13,922 patients; [Sattler *et al.*, 2011](#Ref-Sattler2011)) can be processed almost in real-time on a consumer laptop, while very large databases (half a million patients) require tens of minutes to a few hours on a mid-to-high end desktop computers, especially when making use of parallel processing. Interestingly, Linux seems to have a small but measurable performance advantage over Windows (despite the slightly lower-end hardware) and the "multicore" backend becomes preferable to the "snow" backend for very large databases (probably due to the data transmission and collection overheads), but not by a very large margin. Therefore, for very large databases, we recommend Linux on a multi-core/multi-CPU mechine with enough RAM and the "multicore" backend. | CMA | Single-threaded | Two threads (multicore) | Two threads (snow) | |-----------------|----------------:|------------------------:|-------------------:| | CMA 1 | 40.8 (0.7) | 20.8 (0.4) | 22.0 (0.4) | | CMA 2 | 41.2 (0.7) | 21.7 (0.4) | 24.4 (0.4) | | CMA 3 | 39.3 (0.7) | 20.4 (0.3) | 22.9 (0.4) | | CMA 4 | 40.2 (0.7) | 21.3 (0.4) | 23.0 (0.4) | | CMA 5 | 56.6 (0.9) | 29.7 (0.5) | 31.5 (0.5) | | CMA 6 | 58.0 (1.0) | 30.9 (0.5) | 32.5 (0.5) | | CMA 7 | 55.5 (0.9) | 28.9 (0.5) | 30.6 (0.5) | | CMA 8 | 131.8 (2.2) | 72.5 (1.2) | 71.6 (1.2) | | CMA 9 | 159.4 (2.7) | 85.2 (1.4) | 86.5 (1.4) | | per episode | 263.9 (4.4) | 139.0 (2.3) | 139.7 (2.3) | | sliding window | 643.6 (10.7) | 347.9 (5.8) | 339.5 (5.7) | Table: <a name="Table-4"></a>**Table 4.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a large database with 13,922 patients with 112,983 events on a consumer-grade MacBook Air laptop running MacOSX El Capitan. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function) and minutes. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the multicore and snow times are slightly longer than half the single-core times due to various data transmission and collection overheads. | CMA | Single-threaded | Four threads (multicore) | Four threads (snow) | |-----------------|-------------------------------:|------------------------------:|------------------------------:| | CMA 1 | 1839.7 (30.6) | 577.0 (9.6) | 755.5 (12.6) | | CMA 2 | 1779.0 (29.7) | 490.1 (8.2) | 915.7 (15.3) | | CMA 3 | 1680.6 (28.0) | 458.5 (7.6) | 608.3 (10.1) | | CMA 4 | 1778.9 (30.0) | 489.0 (8.2) | 644.5 (10.7) | | CMA 5 | 2500.7 (41.7) | 683.3 (11.4) | 866.2 (14.4) | | CMA 6 | 2599.8 (43.3) | 714.5 (11.9) | 1123.8 (18.7) | | CMA 7 | 2481.2 (41.4) | 679.4 (11.3) | 988.1 (16.5) | | CMA 8 | 5998.0 (100.0 = 1.7 hours) | 1558.1 (26.0) | 2019.6 (33.7) | | CMA 9 | 7039.7 (117.3 = 1.9 hours) | 1894.7 (31.6) | 3002.7 (50.0) | | per episode | 11548.5 (192.5 = 3.2 hours) | 3030.5 (50.5) | 3994.2 (66.6) | | sliding window | 27651.3 (460.8 = 7.7 hours) | 7198.3 (120.0 = 2.0 hours) | 12288.8 (204.8 = 3.4 hours) | Table: <a name="Table-5"></a>**Table 5.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a very large large database with 500,000 patients with 4,058,110 events on a mid/high-range consumer desktop running OpenSuse 13.2 Linux. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function), minutes and, if large enough, hours. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the multicore and especially the snow times are slightly longer than a quarter the single-core times due to various data transmission and collection overheads. | CMA | Single-threaded | Four threads (snow) | |-----------------|-------------------------------:|------------------------------:| | CMA 1 | 2070.9 (34.5) | 653.1 (10.9) | | CMA 2 | 2098.9 (35.0) | 667.5 (13.4) | | CMA 3 | 2013.8 (33.6) | 661.5 (22.0) | | CMA 4 | 2094.4 (34.9) | 685.2 (11.4) | | CMA 5 | 2823.4 (47.1) | 881.0 (14.7) | | CMA 6 | 2909.0 (48.5) | 910.3 (15.2) | | CMA 7 | 2489.1 (41.5) | 772.6 (12.9) | | CMA 8 | 5982.5 (99.7 = 1.7 hours) | 1810.1 (30.2) | | CMA 9 | 6030.2 (100.5 = 1.7 hours) | 2142.1 (35.7) | | per episode | 10717.1 (178.6 = 3.0 hours) | 3877.2 (64.6) | | sliding window | 25769.5 (429.5 = 7.2 hours) | 9353.6 (155.9 = 2.6 hours) | Table: <a name="Table-6"></a>**Table 6.** Performance as running times (single- and two-threaded, multicore and snow respectively) when computing CMAs for a very large large database with 500,000 patients with 4,058,110 events on a high-end desktop computer running Windows 10. The times shown are "real" (i.e., clock) running times in seconds (as reported by `R`’s `system.time()` function), minutes and, if large enough, hours. In all cases, the FUW and OW are identical at 2 years long. CMAs per episode (with gap=180 days) and sliding window (length=180 days, step=90 days) used CMA1 for each episode/window. Please note that the snow times are longer than a quarter the single-core times due to various data transmission and collection overheads. Concerning *parallelism*, if run on a multi-core/multi-processor machine or cluster, `AdhereR` gives the user the possibility to use (completely transparently) two parallel backends: *multicore* (available on Linux, \*BSD and MacOS, but currently not on Microsoft Windows) and *snow* (Simple Network of Workstations, available on all platforms; in fact, this can use various types of backends, see the documentation in package `snow` for details). Parallelism is available through the `parallel.backend` and `parallel.threads` parameters, where the first controlls the actual backend to use ("none" -- the default, uses a single thread --, "multicore", and several versions of snow: "snow", "snow(SOCK)", "snow(MPI)", "snow(NWS)") and the second the number of desired parallel threads ("auto" defaults to the reported number of cores for "multicore" or 2 otherwise, and to 2 for "snow") or a more complex specification of the nodes for "snow" (see the `snow` package documentation for details and [Appendix I: Distributing computations on remote Linux hosts]). The implementation uses `mclapply` (in package `parallel`) and `parLapply` (package `snow`), is completely hidden from the user, and tries to pre-allocate whole chunks of patients to the CPUs/cores in order to reduce the various overheads (such as data transfer). In general, for "multicore" and "snow" with nodes on the local machine, do not use more than the number of physical cores in the system, and be mindful of the various overheads involved, meaning that the gains, while substantial especially for large databases, will be very slightly lower than the expected 1/#threads (as a corrolary, it might not be a good idea to paralellize very small datasets). Also, memory might be of concern when parallelizing, as at least parts of `R`'s environment will be replicated across threads/processes; this, in turn, for large environments and systems low on RAM, might result in massive performance loss due to swapping (or even result in crashes). For more information on parallelism in `R` please see, for example, [CRAN Task View: High-Performance and Parallel Computing with R](https://CRAN.R-project.org/view=HighPerformanceComputing) and the various blogposts and books on the matter. Conceptually, we exploited various optimization techniques (see, for example, Hadley Wickham's [Advanced R](http://adv-r.had.co.nz/) and other blogposts on profiling and optimizing `R` code), but the two most important architectural decisions are to (a) extensively use [`data.table`](http://r-datatable.com/) and (b) to pre-allocate chunks of participants for parallel processing. The general framework is to define a "workhorse" function that can process a set of participants and returns one `data.frame` or `data.table` (or several, in which case they must be encapsulated in a `list()`), workhorse function that is transparently called for the whole dataset (if `parallel.backend` is "none"), or in parallel for subsets of the whole dataset of roughly 1/`parallel.threads` size (for "multicore" and "snow"), in the latter case the results being transparently recombined (even if multiple results are returned in a `list()`). Internally, the workhorse functions tend to make extensive use of the `data.table` "reference semantics" (the `:=` operator) to perform in-place changes and avoid unnecessary copying of objects, `key`s for fast indexing, search and selection, and the `by` grouping mechanism, allowing the application of a specialized function to each individual patient (or episode or sliding window, as needed). We decided to keep everything "pure `R`" (so there is so far no `C++` code) and the code is extensively commented and hopefully clear to understand, change and extend. ## Conclusions 'AdhereR' was developed to facilitate flexible and comprehensive analyses of adherence to medication from electronic healthcare data. All objects included in this package ('compute.treatment.episodes', 'CMA1' to 'CMA9', and their 'CMA_per_episode' and CMA_sliding_window versions) can be adapted to various research questions and designs, and we provided here only a few examples of the vast range of possibilities for use. Depending on the type of medication, study population, length of follow-up, etc., the various alternative parametrizations may lead to substantial differences or negligible variation. Very little evidence is available on the impact of these choices in specific scenarios. This package makes it easy to integrate such methodological investigations into data analysis plans, and to communicate these to the scientific community. We have also aimed to facilitate replicability. Thus, summaries of functions include all parameter values and are easily printed for transparent reporting (for example in an appendix or a supplementary online material). The calculation of adherence values via 'AdhereR' can also be integrated in larger data analysis scripts and made available in a data repository for future use in similar studies, freely-available or with specific access rights. This allows other research teams to use the same parametrizations (for example if studying the same type of medication in different populations), and thus increase homogeneity of studies for the benefit of later meta-analytic efforts. If these parametrizations are complemented by justifications of each decision based on clinical and/or research evidence in specific clinical areas, they can be subject to discussion and clinical consensus building and thus represent transparent and easily-implementable guidelines for EHD-based adherence research in those areas. In this situation, comparisons across medications can also take into account any differences in analysis choices, and general rules derived for adherence calculation across domains. ## References <a name="Ref-Arnet2016"></a>Arnet I., Kooij M.J., Messerli M., Hersberger K.E., Heerdink E.R., Bouvy M. (2016) [Proposal of Standardization to Assess Adherence With Medication Records Methodology Matters](https://pubmed.ncbi.nlm.nih.gov/26917817/). *The Annals of Pharmacotherapy* **50**(5):360–8. [doi:10.1177/1060028016634106](https://pubmed.ncbi.nlm.nih.gov/26917817/). <a name="Ref-Gardarsdottir2010"></a>Gardarsdottir H., Souverein P.C., Egberts T.C.G., Heerdink E.R. (2010) [Construction of drug treatment episodes from drug-dispensing histories is influenced by the gap length](https://pubmed.ncbi.nlm.nih.gov/19880282/). *J Clin Epidemiol.* **63**(4):422–7. [doi:10.1016/j.jclinepi.2009.07.001](http://dx.doi.org/10.1016/j.jclinepi.2009.07.001). <a name="Ref-Greevy2011"></a>Greevy R.A., Huizinga M.M., Roumie C.L., Grijalva C.G., Murff H., Liu X., Griffin, M.R. (2011). [Comparisons of Persistence and Durability Among Three Oral Antidiabetic Therapies Using Electronic Prescription-Fill Data: The Impact of Adherence Requirements and Stockpiling](https://pubmed.ncbi.nlm.nih.gov/22048232/). *Clinical Pharmacology & Therapeutics* **90**(6):813–819. [10.1038/clpt.2011.228](https://pubmed.ncbi.nlm.nih.gov/22048232/). <a name="Ref-Peterson2007"></a>Peterson A.M., Nau D.P., Cramer J.A., Benner J., Gwadry-Sridhar F., Nichol M. (2007) [A checklist for medication compliance and persistence studies using retrospective databases](https://pubmed.ncbi.nlm.nih.gov/17261111/). *Value in Health: Journal of the International Society for Pharmacoeconomics and Outcomes Research* **10**(1):3–12. [doi:10.1111/j.1524-4733.2006.00139.x](http://dx.doi.org/10.1111/j.1524-4733.2006.00139.x). <a name="Ref-SouvereinInPress"></a>Souverein PC, Koster ES, Colice G, van Ganse E, Chisholm A, Price D, et al. (*in press*) [Inhaled Corticosteroid Adherence Patterns in a Longitudinal Asthma Cohort.](https://www.sciencedirect.com/science/article/abs/pii/S2213219816304238) *J Allergy Clin Immunol Pract*. [doi:10.1016/j.jaip.2016.09.022](http://dx.doi.org/10.1016/j.jaip.2016.09.022). <a name="Ref-Vollmer2012"></a>Vollmer W.M., Xu M., Feldstein A., Smith D., Waterbury A., Rand C. (2012) [Comparison of pharmacy-based measures of medication adherence](https://pubmed.ncbi.nlm.nih.gov/22691240/). *BMC Health Services Research* **12**(1):155. [doi:10.1186/1472-6963-12-155](http://dx.doi.org/10.1186/1472-6963-12-155). <a name="Ref-Vrijens2012"></a>Vrijens B., De Geest S., Hughes D.A., Przemyslaw K., Demonceau J., Ruppar T., Dobbels F., Fargher E., Morrison V., Lewek P., Matyjaszczyk M., Mshelia C., Clyne W., Aronson J.K., Urquhart J.; ABC Project Team (2012) [A new taxonomy for describing and defining adherence to medications](https://pubmed.ncbi.nlm.nih.gov/22486599/). *British Journal of Clinical Pharmacology* **73**(5):691–705. [doi:10.1111/j.1365-2125.2012.04167.x](https://pubmed.ncbi.nlm.nih.gov/22486599/). <a name="Ref-VanWijk2006"></a>Van Wijk B.L.G., Klungel O.H., Heerdink E.R., de Boer A. (2006). [Refill persistence with chronic medication assessed from a pharmacy database was influenced by method of calculation](https://pubmed.ncbi.nlm.nih.gov/16360556/). *Journal of Clinical Epidemiology* **59**(1), 11–17. [doi:10.1016/j.jclinepi.2005.05.005](http://dx.doi.org/10.1016/j.jclinepi.2005.05.005). <a name="Ref-Sattler2013"></a>Sattler E., Lee J., Perri M. (2011). [Medication (Re)fill Adherence Measures Derived from Pharmacy Claims Data in Older Americans: A Review of the Literature](https://pubmed.ncbi.nlm.nih.gov/23553512/). *Drugs & Aging* **30**(6), 383–99. [doi:10.1007/s40266-013-0074-z](http://dx.doi.org/10.1007/s40266-013-0074-z). ## Appendix I: Distributing computations on remote Linux hosts For example, we show here how to compute CMA1 on a remote `Linux` machine from `macOS` and `Windows 10` hosts. The Linux machine (hostname `workhorse`) runs `Ubuntu 16.04` (64 bits) with `R 3.4.1` manually compiled and installed in `/usr/local/lib64/R`, and an `OpenSSH` server allowing access to the user `user`. The `macOS` laptop is running `macOS High Sierra 10.13.4`, `R 3.4.3`, `openssh` (installed through [homebrew](https://brew.sh/)) and we set up passwordless ssh access to `workhorse` (see, for example, the tutorial [here](http://www.linuxproblem.org/art_9.html)). The `Windows 10` desktop is running `Microsoft Windows 10 Pro 1709 64 bits` with `openssh` installed vias [Cygwin](http://www.cygwin.com/) (also with passwordless ssh access to `workhorse`) and `Microsoft R Open 3.4.3`. All machines have the latest version of `AdhereR` and `snow` installed. With these, we can, for example do: ```{r eval=FALSE} cmaW3 <- CMA_sliding_window(CMA="CMA1", data=med.events, ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, sliding.window.duration=30, sliding.window.step.duration=30, parallel.backend="snow", # make clear we want to use snow parallel.threads=c(rep( list(list(host="user@workhorse", # host (and user) rscript="/usr/local/bin/Rscript", # Rscript location snowlib="/usr/local/lib64/R/library/") # snow package location ), 2))) # two remote threads ``` where we use `parallel.backend="snow"` and we specify the `workhorse` node(s) we want to use. Here, `parallel.threads` is a list of host specifications (one per thread), each a list contaning the `host` (possibly with the username for ssh access), `rscript` (the location on the remote host of `Rscript`) and `snowlib` (the location on the remote host of the `snow` package, usually the location where the `R` packages are installed). In this exmple, we create 2 such identical hosts (using `rep(..., 2)`) which measn that we will have two parallel threads running on `workhorse`. If everything is fine, the results should be returned to the user as usual. *NB1.* This procedure was tested only on `Linux` hosts, but it should *in principle* also work with `Windows` hosts as well (but the setup is currently much more complex and apparently less reliable; moreover, in most high-performance production environments we expect `Linux` rather that `Windows` compute nodes). <!-- Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format: --> <!-- - Never uses retina figures --> <!-- - Has a smaller default figure size --> <!-- - Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style --> <!-- ## Vignette Info --> <!-- Note the various macros within the `vignette` section of the metadata block above. These are required in order to instruct R how to build the vignette. Note that you should change the `title` field and the `\VignetteIndexEntry` to match the title of your vignette. --> <!-- ## Styles --> <!-- The `html_vignette` template includes a basic CSS theme. To override this theme you can specify your own CSS in the document metadata as follows: --> <!-- output: --> <!-- rmarkdown::html_vignette: --> <!-- css: mystyles.css --> <!-- ## More Examples --> <!-- You can write math expressions, e.g. $Y = X\beta + \epsilon$, footnotes^[A footnote here.] --> <!-- Also a quote using `>`: --> <!-- > "He who gives up [code] safety for [code] speed deserves neither." --> <!-- ([via](https://twitter.com/hadleywickham/status/504368538874703872)) -->
/scratch/gouwar.j/cran-all/cranData/AdhereR/vignettes/AdhereR-overview.Rmd
--- title: "Calling `AdhereR` from `Python 3`" author: "Dan Dediu" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Calling AdhereR from Python3} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` ## Overview While `AdhereR` is written in `R` and makes extensive use of various `R` packages and techniques (such as `data.table` and parallel processing), it is possible to use it from other programming languages and applications. This is accomplished through a very generic mecahnism that only requires the caller to be able to *read and write files* in a location of its choice and to *invoke an external command* with a set of arguments. These requirements are widely available in programming languages (such as `C`/`C++`, `Java`, `Python 2` and `3`, and `R` itself), can be accomplished from the scripting available in several applications (e.g., `VBA` in Microsoft Excel, `STATA` scripting or `SAS` programs), and works in similar ways across the major Operating Systems (`Linux` flavors, `macOS` and `Microsoft Windows`). We present here this generic mechanism using its *reference implementation* for `Python 3`. While this reference implementation is definitely usable in production environments (including from [Jupyter Notebooks](#from-a-jupyter-notebook)) and comes with the `R` `AdhereR` package (see [here](#making-the-adherer-module-visible-to-python-aka-installation) on how to "install" it in `Python 3`), this can probably be improved both in terms of calling and passing data between `Python` and `R`, as well as in terms of the "pythonicity" of the `Python` side of the implementation. Nevertheless, we hope this implementation will be useful to users of `Python` that would like to access `AdhereR` without switching to `R`, and will provide a template and working example for further implementations that aim to make `AdhereR` available to other programming languages and platforms. ## Table of Contents - [Introduction](#introduction) - [General ideas](#general-ideas) - [Fundamentals of calling `AdhereR` from `Python 3`](#fundamentals-of-calling-adherer-from-python-3) - [The `Python 3` wrapper: the `adherer` module](#the-python-3-wrapper-the-adherer-module) - [Making the `adherer` module visible to Python (aka installation)](#making-the-adherer-module-visible-to-python-aka-installation) - [Importing the `adherer` module and initializations](#importing-the-adherer-module-and-initializations) - [The class hierarchy](#the-class-hierarchy) - [The `CallAdhereRError` exception class](#the-calladherererror-exception-class) - [The base class `CMA0`](#the-base-class-cma0) - [Class `CMA1` and its daughter classes `CMA2`, `CMA3` and `CMA4`](#class-cma1-and-its-daughter-classes-cma2-cma3-and-cma4) - [Class `CMA5` and its daughter classes `CMA6`, `CMA7`, `CMA8` and `CMA9`](#class-cma5-and-its-daughter-classes-cma6-cma7-cma8-and-cma9) - [Classes `CMAPerEpisode` and `CMASlidingWindow`](#classes-cmaperepisode-and-cmaslidingwindow) - [Examples of use](#examples-of-use) - [Basic usage](#basic-usage) - [Importing `adherer` and checking autodetection](#importing-adherer-and-checking-autodetection) - [Export the test dataset from `R` and import it in `Python`](#export-the-test-dataset-from-r-and-import-it-in-python) - [Compute and plot test CMA](#compute-and-plot-test-cma) - [Interactive plotting](#interactive-plotting) - [From a Jupyter Notebook](#from-a-jupyter-notebook) - [Parallel processing (locally and on different machines)](#parallel-processing-locally-and-on-different-machines) - [Single thread on the local machine](#single-thread-on-the-local-machine) - [Multi-threaded on the local machine](#multi-threaded-on-the-local-machine) - [Parallel on remote machines over a network](#parallel-on-remote-machines-over-a-network) - [Appendix I: the communication protocol](#appendix-i-the-communication-protocol) - [Context](#context) - [Protocol](#protocol) - [PARAMETERS](#parameters1) - [COMMENTS](#comments) - [SPECIAL PARAMETERS](#special-parameters2) - [FUNCTIONS](#functions) - [PLOTTING](#plotting) - [`CMA1`, `CMA2`, `CMA3`, `CMA4`](#cma1-cma2-cma3-cma4) - [`CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9`](#cma5-cma6-cma7-cma8-cma9) - [`CMA_per_episode`](#cma_per_episode) - [`CMA_sliding_window`](#cma_sliding_window) - [`compute_event_int_gaps`](#compute_event_int_gaps) - [`compute_treatment_episodes`](#compute_treatment_episodes) - [`plot_interactive_cma`](#plot_interactive_cma) - [Appendix II: the `Python 3` code](#appendix-ii-the-python-3-code) - [Notes](#notes) ## General ideas The mechanism is very general, and is based on a *wrapper* being available on the *caller platform* (here, `Python 3`) that performs the following general tasks: - *exposes* to the users on the caller platform a *set of functions/methods/objects* (or other mechanisms specific to that platform) that encapsulate, in a platform-specific way, the main functionalities from `AdhereR` that are of interest to the platform's users; - when the user *calls* such an exposed function with a given set of argument values, the wrapper *transparently translates* these argument values in a format understandable by `AdhereR`; in particular, it saves any datasets to be processed (as TAB-separated `CSV files`) and writes the argument values to `text file` (in a standardised format), all in a directory of its choice (henceforth, the *data sharing directory*); - the wrapper uses the *`shell` mechanism* to call `R` (as it is installed on the caller system) and instructs it to execute a simple sequence of `R` commands; - these `R` commands load the `AdhereR` package and execute the `callAdhereR()` function from the package, passing it the path to the data sharing directory as its only argument; - internally, `callAdhereR()`: - parses and loads the data and arguments, - performs basic consistency checks, - calls the appropriate `AdhereR` method(s) with the appropriate arguments, - checks the results and, as appropriate, - writes back to a predefined file any error messages, warnings or any other messages generated, and, if the case, - saves the results to TAB-separated `CSV` files or image files; - the wrapper is notified when the `R` has finished executing, and: - loads the file containing the errors, warnings and messages, and possibly the results, - packs them into objects appropriate to the caller platform, and - returns them to the user. The full protocol is detailed in [**Appendix I**](#appendix-1). ## Fundamentals of calling `AdhereR` from `Python 3` We will use here a `macOS` setup for illustration purposes, but this is very similar on the other supported `OS`s. Essentially, the `Python 3` wrapper creates the *input files* `parameters.log` and `dataset.csv` in the data sharing directory (let us denote it as `DATA_SHARING_DIRECTORY`, by default, a unique temorary directory). Let's assume that `DATA_SHARING_DIRECTORY` is set to `/var/folders/kx/bphryt7j5tz1n_fcjk5809940000gn/T/adherer-qmx4pw7t`; then, before calling `AdhereR`, this directory should contain the files: . |-parameters.log \-dataset.csv Please note that `R` must be *properly installed* on the system such that `Rscript` (or `Rscript.exe` on Windows) does exist and works; the `Python 3` wrapper tries to locate it using a variety of strategies (in order, `which`, followed by a set of standard locations on `macOS` and `Linux` or a set of standard Windows Registry Keys on `MS Windows`) but if this fails or if the user wants to use a non-standard `R` installation, the wrapper allows this through the exported function `set_rscript_path()`. Let's assume for now that `Rscript` is located in `/usr/local/bin/Rscript` and its automatic detection was successful (let us denote this path as `RSCRIPT_PATH`). With these path variables automatically or manually set, the `Python 3` wrapper is ready to call `AdhereR`: ``` python import subprocess # allow shell calls [...] # Call adhereR: rscript_cmd = '"' + RSCRIPT_PATH + '"' + ' --vanilla -e ' + \ '"library(AdhereR); ' + \ `callAdhereR(` + DATA_SHARING_DIRECTORY + '\')"' return_code = subprocess.call(rscript_cmd, shell=True) ``` When the `Rscript` process returns, `return_code` should be `0` for success (in the sense of calling `AdhereR`, not in the sense that `AdhereR` also succeeded in the task it was assigned to do) or something else for errors. If `return_code != 0`, the process returns with a warning. Otherwise, an attempt is made to read the messages produced by `AdhereR` (available in the `Adherer-results.txt` file in the `DATA_SHARING_DIRECTORY` directory) and checking if the last line begins with `OK:`. If it does not, a warning contaning the messages is thrown and the process returns. If it does, the appropriate output files are read, parsed and loaded (depending on the invoked function, these files might differ). For example, after successfully invoking `CMA1`, the `DATA_SHARING_DIRECTORY` might look like: . |-parameters.log |-dataset.csv |-Adherer-results.txt \-CMA.csv In this example, the wrapper would parse and load `CMA.csv` as a `pandas` table: ``` python import pandas # load pandas [...] # Expecting CMA.csv ret_val['CMA'] = pandas.read_csv(os.path.join(path_to_data_directory, 'CMA.csv'), sep='\t', header=0) ``` If plotting was requested, the resulting plot is also loaded using the `PIL`/`Pillow` library: ``` python from PIL import Image # load images [...] # Load the produced image (if any): ret_val['plot'] = Image.open(os.path.join((plot_save_to if not (plot_save_to is None) else DATA_SHARING_DIRECTORY), 'adherer-plot' + '.' + plot_save_as)) ``` where `plot_save_to` and `plot_save_as` may specify where the plots are to be saved and in which format. ## The `Python 3` wrapper: the `adherer` module ### Making the `adherer` module visible to Python (aka installation) The reference implementation is contained in single file (`adherer.py`) included with the `R` `AdhereR` package and whose location can be obtained using the function `getCallerWrapperLocation(full.path=TRUE)` from `AdhereR` (*N.B.* it is located in the directory where the `AdhereR` package is installed on the system, subdirectory `wrappers/python3/adherer.py`; for example, on the example `macos` machine this is `/Library/Frameworks/R.framework/Versions/3.4/Resources/library/AdhereR/wrappers/python3/adherer.py`). In the future, as more wrappers are added, the argument `callig.platform` will allow the selection of the desired wrapper (now it is implicitely set to `python3`). This file can be either: - *copied and placed* in `Python`'s "module search paths" (a list of directories comprising, in order, the directory contining the input script, the environment variable `PYTHONPATH`, and a default location; see [here](https://docs.python.org/3/tutorial/modules.html#the-module-search-path) for details), in which cae it can be simply imported using the standard `Python` syntax (e.g. `import adherer` or `import adherer as ad`), or - *imported from its location* by either: - adding its directory to the `PYTHONPATH` environment variable [the recommended solution], or - using various tricks described, for example, [here](https://stackoverflow.com/a/67692). On the example `macos` machine, this can be achieved by adding: ``` bash # Add AdhereR to PYTHONPATH export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/[...]/AdhereR/wrappers/python3 ``` to the `.bash_profile` file in the user's home folder (if this file does not exist, then it can be created using a text editor such as `nano`; please note that the `[...]` are for shortening the path and should be replaced by the actual path given in full above). The process should be very similar on `Linux`, while on `MS Windows` one should use the system's "Environment Variables" settings (for example, see [here](https://stackoverflow.com/a/4855685) for details). Please note that `adherer` needs `pandas` and `PIL`, which can be installed, for example, using: ``` bash pip3 install pandas pip3 install Pillow ``` *NOTE:* we will consistently use `AdhereR` to refer to the `R` package, and `adherer` to refer to the `Python 3` module. ### Importing the `adherer` module and initializations Thus, the reference implementation is technically a `module` called `adherer` that can be imported in your code (we assume here the recommended solution, but see above for other ways of doing it): ``` python # Import adherer as ad: import adherer as ad ``` When the `adherer` module is imported for the first time, it runs the following *initialization code*: 1. it tries to **autodetect the location where `R` is installed on the system**. More precisely, it looks for `Rscript` (or `Rscript.exe` on Windows) using several strategies, in order: `which`, followed by a set of standard locations on `macOS` (`/usr/bin/Rscript`, `/usr/local/bin/Rscript`, `/opt/local/bin/Rscript` and `/Library/Frameworks/R.framework/Versions/Current/Resources/bin/Rscript`) and `Linux` (`/usr/bin/Rscript`, `/usr/local/bin/Rscript`, `/opt/local/bin/Rscript` and `~/bin/Rscript`) or a set of standard Windows Registry Keys on `MS Windows` (`HKEY_CURRENT_USER\SOFTWARE\R-core\R`, `HKEY_CURRENT_USER\SOFTWARE\R-core\R32`, `HKEY_CURRENT_USER\SOFTWARE\R-core\R64`, `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R`, `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R32` and `HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R64`) which should contain `Current Version` and `InstallPath` (with the added complexity that 64 bits Windows hists both 32 and 64 bits regsistries). This procedure is inspired by the way [`RStudio` checks for `R`](https://support.rstudio.com/hc/en-us/articles/200486138-Using-Different-Versions-of-R): - if this process **fails**, a warning is thrown instructing the user to manually set the path using the `set_rscript_path()` function exposed by the `adherer` module, and sets the internal variable `_RSCRIPT_PATH` to `None` (which insures that all future calls to `AdhereR` will fail; - if the process **succeeds**, it checks if the `AdhereR` package is installed for the detected `R` and has a correct version: + if this check **fails**, an appropriate warning is thrown and `_RSCRIPT_PATH` is set to `None`; + if it **succeeds**, continue to step (2) below. 2. it tries to **create a temporary directory** (with prefix `adherer-`) with read and write access for the current user: - if this **fails**, it throws a warning instructing the user to manually set this to a directory with read & write access using the `set_data_sharing_directory()` function, and sets the internal variable `_DATA_SHARING_DIRECTORY` to `None` (ensuring that calls to `AdhereR` will fail); - if it **succeeds**, the initialization code is considered to have finished successfully; also, on exit this temporary `_DATA_SHARING_DIRECTORY` is automatically deleted. ### The class hierarchy The `adherer` module tries to emulate the same philosophy as the `AhereR` package, where various *types* of *CMAs* ("continuous multiple-interval measures of medication availability/gaps") that implement different ways of computing adherence encapsulate the data on which they were computed, the various relevant parameter values used, as well as the results of the computation. Here, we implemented this through the following class hierarchy (image generated with [pyreverse](https://pypi.org/project/pyreverse/), not showing the private attributes): <img src="classes_adherer.png" alt="class hierarchy" style="width: 100%;"/> We will discuss now the main classes in turn. #### The `CallAdhereRError` exception class Errors in the `adherer` code are signalled by throwing `CallAdhereRError` exceptions (the red class shown in the bottom right corner). #### The base class `CMA0` All classes that implement ways to compute adherence (`CMA`s) are derived from `CMA0`. `CMA0` does not in itself compute any sort of adherence, but instead provides the *infrastructure* for *storing* the data, parameter values and results (including errors), and for *interacting* with `AdhereR`. Please note that in the "higher" `CMA`s, the class constructor `__init()__` implicitely performs the actual computation of the `CMA` and saves the results (for `CMA0` there are no such computations and `__init()__` only saves the parameters internally)! 1. **storage of data and parameter values**: `CMA0` allows the user to set various parameters through the constructor `__init()__`, parameters that are stored for later use, printing, saving, and for facilitating easy reconstruction of all types of computations. By main groups, these are (please, see the manual entry for `?CMA0` in the `AdhereR` package and the full protocol in [**Appendix I**](#appendix-1) as well): - `dataset` stores the primary data (as a `Pandas` table with various columns) containing the actual events; must be given; - `id_colname`, `event_date_colname`, `event_duration_colname`, `event_daily_dose_colname` and `medication_class_colname`: these give the *names* of the columns in the `dataset` table containing important information about the events (the first three are required, the last two are optional); - `carryover_within_obs_window`, `carryover_into_obs_window`, `carry_only_for_same_medication`, `consider_dosage_change`, `medication_change_means_new_treatment_episode`, `maximum_permissible_gap`, `maximum_permissible_gap_unit`: optional parameters defining the types of carry-over, changes and treatment episode triggers; - `followup_window_start_type`, `followup_window_start `followup_window_start_unit`, `followup_window_duration_type `followup_window_duration`, `followup_window_duration_unit`, `observation_window_start_type`, `observation_window_start`, `observation_window_start_unit `observation_window_duration_type`, `observation_window_duration`, `observation_window_duration_unit`: optional parameters defining the follow-up and observation windows; - `sliding_window_start_type`, `sliding_window_start`, `sliding_window_start_unit`, `sliding_window_duration_type`, `sliding_window_duration`, `sliding_window_duration_unit`, `sliding_window_step_duration_type`, `sliding_window_step_duration`, `sliding_window_step_unit`, `sliding_window_no_steps`: optional parameters defining the sliding windows; - `cma_to_apply`: optional parameter specifying which "simple" `CMA` is to be used when computing sliding windos and treatment episodes; - `date_format`: optional parameter describing the format of column dates in `dataset` (defaults to month/day/year); - `event_interval_colname`, `gap_days_colname`: optional parameters allowing the user to change the names of the columns where these computed data are stored in the resuling table; - `force_na_cma_for_failed_patients`, `keep_window_start_end_dates`, `remove_events_outside_followup_window`, `keep_event_interval_for_all_events`: optional parameters governing the content of the resuling table; - `parallel_backend`, `parallel_threads`: these optional parameters control the parallelism of the computations (if any); see **PARALLEL PROCESSING** for details; - `suppress_warnings`: should all the internal warning be shown? - `save_event_info`: should this "advanced" info be also made available? - `na_symbol_numeric`, `na_symbol_string`, `logical_symbol_true`, `logical_symbol_false`, `colnames_dot_symbol`, `colnames_start_dot`: these optional parameters allow `AdhereR` to adapt to "non-`R`" conventions concerning the data format for missing values, logicals and column names; - `path_to_rscript`, `path_to_data_directory`: these parameters allow the user to override the `_RSCRIPT_PATH` and `_DATA_SHARING_DIRECTORY` variables; - `print_adherer_messages`: should the important messages be printed to the user as well? 2. **storage of, and access to, the results**: - `get_dataset()`: returns the internally saved `Pandas` table `dataset`; - `get_cma()`: returns the computed `CMA` (if any); - `get_event_info()`: returns the computed event information (if any); - `get_treatment_episodes()`: returns the computed treatment episodes information (if any); - `get_computation_results()`: return the results of the last computation (if any); more precisely, a `dictionary` containing the numeric `code` returned by `AdhereR` and the string `messages` written by `AdhereR` during the computation; 3. **computing event interval and treatment episode info**: this can be done by explicitelly calling the `compute_event_int_gaps()` and `compute_treatment_episodes()` functions; 4. **plotting**: - *static plotting*: this is realized by the `plot()` function that takes several plotting-specific parameters: + `patients_to_plot`: should a subset of the patients present in the `dataset` be plotted (by default, all will be)? + `save_to`, `save_as`, `width`, `height`, `quality`, `dpi`: where should the plot be saved, in what format, dimentions and quality? + `duration`, `align_all_patients`, `align_first_event_at_zero`, `show_period`, `period_in_days`: duration to plots and alignment of patients; + `show_legend`, `legend_x`, `legend_y`, `legend_bkg_opacity`: legend parameters; + `cex`, `cex_axis`, `cex_lab`: the relative size of various text elements; + `show_cma`, `print_cma`, `plot_cma`, `plot_cma_as_histogram`, `cma_plot_ratio`, `cma_plot_col`, `cma_plot_border`, `cma_plot_bkg`, `cma_plot_text`: should the cma be shown and how? + `unspecified_category_label`: implicit label of unlabelled categories? + `lty_event`, `lwd_event`, `pch_start_event`, `pch_end_event`, `show_event_intervals`, `col_na`, `col_continuation`, `lty_continuation`, `lwd_continuation`: visual aspects of events and continuations; + `highlight_followup_window`, `followup_window_col`, `highlight_observation_window`, `observation_window_col`, `observation_window_density`, `observation_window_angle`, `show_real_obs_window_start`, `real_obs_window_density`, `real_obs_window_angle`: visual appearance of the follow-up, obervation and "real observation" windows (the latter for `CMA`s that djust it); + `bw_plot`: produce a grayscel plot? - *interactive plotting*: the `plot_interactive()` function launches a [Shiny](https://shiny.rstudio.com/)-powered interactive plot using the system's WEB browser; the only parameter `patient_to_plot` may specify which patient to show initially, as all the relevant parameters can be interactively altered ar run-time; 5. **printing**: the `__repr__()` function implements a very simple printing mechanism showing the `CMA` type and a summary of the `dataset`; 6. **calling `AdhereR`**: the private function `_call_adherer()` is the real workhorse that manages all the interaction with the `R` `AdhereR` package as described above. This function can take many parameters covering *all* that `AdhereR` can do, but it is not intended to be directly called by the end-user but instead to be internally called by various exposed functions such as `plot()`, `compute_event_int_gaps()` and `__init()__`. Roughly, after some checks, it creates the files needed for communication, calls `AdhereR`, analyses any errors, warnings and messages that it might have generated, and packs the results in a manageable format. To preserve the generality of the interaction with `AdhereR`, all the `CMA` classes define a private static member `_adherer_function` which is the name of the corresponding `S3` class as implemented in `AdhereR`. #### Class `CMA1` and its daughter classes `CMA2`, `CMA3` and `CMA4` `CMA1` is derived from `CMA0` by redefining the `__init__()` constructor to (a) take only a subset of arguments relevant for the `CMA`s 1--4 (see the `AdhereR` help for them), and (b) to internally call `_call_adherer()` with these parameters. It checks if the result of `_call_adherer()` signals an error, in which case ir throws a `CallAdhereRError` exception, otherwise packing the code, messages, cma and (possibly) event information in the corresponding member variables for later access. Due to the generic mechanism implemented by `_adherer_function`, `CMA2`, `CMA3` and `CMA4` are derived directly from `CMA1` but only redefine `_adherer_function` appropriately. #### Class `CMA5` and its daughter classes `CMA6`, `CMA7`, `CMA8` and `CMA9` The same story applies here, with `CMA5` being derived from `CMA0` and redefining `__init__()`, with `CMA6`--`CMA9` only using the `_adherer_function` mechanism. Compared with `CMA1`, `CMA5` defines new required arguments related to medication type and dosage. #### Classes `CMAPerEpisode` and `CMASlidingWindow` Just like `CMA1` and `CMA5`, these two require specific parameters and are thus derived directly from `CMA0` (but, in contrast, they don't have their own derived classes). ### Examples of use Below we show some examples of using the `Python 3` reference wrapper. We are using [`IPython`](https://ipython.org/) from the [`Spyder 3`](https://github.com/spyder-ide/spyder) environment; the `In [n]: ` represents the *input* prompt, the ` ...: ` the *continuation* of the input on the following line(s), and `Out[n]: ` the produced output. #### Basic usage ##### Importing `adherer` and checking autodetection ``` python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) Type "copyright", "credits" or "license" for more information. IPython 6.3.0 -- An enhanced Interactive Python. In [1]: # Import adherer as ad: ...: import adherer as ad In [2]: # Show the _DATA_SHARING_DIRECTORY (should be set automatically to a temporary location): ...: ad._DATA_SHARING_DIRECTORY.name Out[2]: '/var/folders/kx/bphryt7j5tz1n_fcjk5809940000gn/T/adherer-05hdq6el' In [3]: # Show the _RSCRIPT_PATH (should be dectedt automatically): ...: ad._RSCRIPT_PATH Out[3]: '/usr/local/bin/Rscript' ``` Everything seems fine! ##### Export the test dataset from `R` and import it in `Python` Let's export the sample dataset `med.events` included in `AdhereR` as a TAB-separated CSV file in a location for use here (please note that this must be done from an `R` console, such as from `RStudio`, and not from `Python`!): ``` R R version 3.4.3 (2017-11-30) -- "Kite-Eating Tree" Copyright (C) 2017 The R Foundation for Statistical Computing Platform: x86_64-apple-darwin15.6.0 (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > library(AdhereR) # load the AdhereR package > head(med.events) # see how the included med.events dataset looks like PATIENT_ID DATE PERDAY CATEGORY DURATION 286 1 04/26/2033 4 medA 50 287 1 07/04/2033 4 medB 30 288 1 08/03/2033 4 medB 30 289 1 08/17/2033 4 medB 30 291 1 10/13/2033 4 medB 30 290 1 10/16/2033 4 medB 30 > write.table(med.events, file="~/Temp/med-events.csv", quote=FALSE, sep="\t", row.names=FALSE, col.names=TRUE) # save med.events as TAB-separated CSV file in a location (here, in the Temp folder) > ``` Now, back to `Python`: ``` python In [4]: # Import Pandas as pd: ...: import pandas as pd In [5]: # Load the test dataset ...: df = pd.read_csv('~/Temp/med-events.csv', sep='\t', header=0) In [6]: # Let's look at first 6 rows (it should match the R output above except for the row names): ...: df.head(6) Out[6]: PATIENT_ID DATE PERDAY CATEGORY DURATION 0 1 04/26/2033 4 medA 50 1 1 07/04/2033 4 medB 30 2 1 08/03/2033 4 medB 30 3 1 08/17/2033 4 medB 30 4 1 10/13/2033 4 medB 30 5 1 10/16/2033 4 medB 30 ``` All good so far, the data was imported successfully as a `Pandas` table. ##### Compute and plot test CMA Now let's compute `CMA8` on these data in `Python`: ``` python In [7]: # Compute CMA8 as a test: ...: cma8 = ad.CMA8(df, ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY') ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! ``` We can see that things went pretty well, as no exceptions were being thrown and the message starts with a reassuring `Adherer returned code 0`, followed by precisely what `AdhereR` said: - `AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10:`: first, self-identification (its own version and `R`'s version), followed by the date and time the processing was initated; - `OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!`, which means that basically all seems allright but that there might still be some messages or warning displayed above that could be informative or point to subtler issues. Let's see how these results look like: ``` python In [8]: # Summary of cma8: ...: cma8 Out[8]: CMA object of type CMA8 (on 1080 rows). In [9]: # The return value and messages: ...: cma8.get_computation_results() Out[9]: {'code': 0, 'messages': ['AdhereR 0.2.0 on R 3.4.3 started at 2018-06-04 22:27:10:\n', 'OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)!\n']} In [10]: # The CMA (the first 6 rows out of all 100): ...: cma8.get_cma().head(6) Out[10]: PATIENT_ID CMA 0 1 0.947945 1 2 0.616438 2 3 0.994521 3 4 0.379452 4 5 0.369863 5 6 0.406849 In [11]: # Plot it (statically): ...: cma8.plot(patients_to_plot=['1', '2', '3'], ...: align_all_patients=True, ...: period_in_days=30, ...: cex=0.5) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-05 13:22:36: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! Out[11]: ``` The output produced in this case (`Out[11]`) consists of the actual image plotted in the `IPython` console (thanks to the `PIL`/`Pillow` package) and reproduced below: <img src="plotting-python.jpg" alt="static plotting in Python" style="width: 100%;"/> Now, we turn again to `R`: ``` R > # Compute the same CMA8 in R: > cma8 <- CMA8(data=med.events, + ID.colname="PATIENT_ID", + event.date.colname="DATE", + event.duration.colname="DURATION", + medication.class.colname="CATEGORY", + event.daily.dose.colname="PERDAY" + ) > > # The computed CMA: > head(getCMA(cma8)) PATIENT_ID CMA 1 1 0.9479452 2 2 0.6164384 3 3 0.9945205 4 4 0.3794521 5 5 0.3698630 6 6 0.4068493 > > # Plot the cma: > plot(cma8, + patients.to.plot=c("1", "2", "3"), + align.all.patients=TRUE, + period.in.days=30, + cex=0.5) > ``` Again, the output is an image (here, shown in the "Plots" panel in `RStudio`): <img src="plotting-r.jpg" alt="static plotting in R" style="width: 100%;"/> It can be seen that, except for the slightly different dimensions (and x/y ratio and quality) due to the actual plotting and exporting, the images show identical patterns. ##### Interactive plotting We will initate now an interactive plotting session from `Python`: ``` python In [12]: cma8.plot_interactive() ``` The output is represented by an interactive session in the default browser; below is a screenshot of this session in `Firefox`: <img src="plotting-interactive.jpg" alt="interactive plotting screenshot" style="width: 100%;"/> The interactive session ends by pressing the "Exit" button in the browser (and optinally also closing the browser tab/window), at which point the usual text output is provided to `Python` and a `True` value signalling success is returned: ``` python Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-05 18:01:28: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! Out[12]: True ``` Please note that it does not matter how the interactive session is started, as it only needs access to the base `CMA0` object and, more precisely, the raw dataset; all relevant parameters, including the CMA type can be changed interactively (this is why the CMA shown in the screenshot is `CMA1` even if the function `cma8.plot_interactive()` was initiated from a `CMA8` object). #### From a Jupyter Notebook `AdhereR` is very easy to use from within a [Jupyter Notebook](https://jupyter.org/) (the only tricky bit being making sure that `adherer` module is visible to the `Python` kernel, but this is explained in detail in section [Making the `adherer` module visible to Python (aka installation)](#making-the-adherer-module-visible-to-python-aka-installation)). A full example is provided in the `jupyter_notebook_python3_wrapper.ipynb` file accompanying the package in the same directory as the `adherer` module, but the code is reproduced below for convenience: ``` python # import the adherer python module (see above about how to make it findable) import adherer # load the test dataset: import pandas df = pandas.read_csv('./test-dataset.csv', sep='\t', header=0) # Change the column names: df.rename(columns={'ID': 'patientID', 'DATE': 'prescriptionDate', 'PERDAY': 'quantityPerDay', 'CLASS': 'medicationType', 'DURATION': 'prescriptionDuration'}, inplace=True) # check the file was read correctly type(df) # HTML printing of data frames import rpy2.ipython.html rpy2.ipython.html.init_printing() # print it df # create a CMA7 object cma7 = adherer.CMA7(df, id_colname='patientID', event_date_colname='prescriptionDate', event_duration_colname='prescriptionDuration', event_daily_dose_colname='quantityPerDay', medication_class_colname='medicationType', followup_window_start=230, followup_window_duration=705, observation_window_start=41, observation_window_duration=100, date_format="%m/%d/%Y", suppress_warnings=True) # print it for checking cma7 # show the plot directly in the notebook x ``` While this is very easy and transparent, some people might prefer to use the more generic mechanism provided by [`rpy2`](https://rpy2.github.io/index.html), which, in principle, allows the transparent call of `R` code from `Python`. In fact, `AdhereR` seems to play very nicely with `rpy2`, even within a [Jupyter Notebook](https://jupyter.org/), as shown by the code below (the full notebook is available in the `jupyter_notebook_python3_py2.ipynb` file accompanying the package in the same directory as the `adherer` module): ``` python # import ryp2 (please note that you might need to install it as per https://rpy2.github.io/doc.html) import rpy2 # check that all is ok rpy2.__path__ # import R's "AdhereR" package from rpy2.robjects.packages import importr adherer = importr('AdhereR') # access the internal R session import rpy2.robjects as robjects # access the med.events dataset med_events = robjects.r['med.events'] # check its type type(med_events) # HTML printing of data frames import rpy2.ipython.html rpy2.ipython.html.init_printing() # print it med_events # make some AdhereR functions available to Python CMA7 = robjects.r['CMA7'] getCMA = robjects.r['getCMA'] # create a CMA7 object cma7 = CMA7(med_events, ID_colname="PATIENT_ID", event_date_colname="DATE", event_duration_colname="DURATION", event_daily_dose_colname="PERDAY", medication_class_colname="CATEGORY", followup_window_start=230, followup_window_duration=705, observation_window_start=41, observation_window_duration=100, date_format="%m/%d/%Y") # print it for checking cma7 # print the estimated CMAs getCMA(cma7) # plot it # this is some clunky code involving do.call and named lists because # plot has lots of arguments with . that cannot be autmatically handeled by rpy2 # the idea is to use a TaggedList that associated values and argument names import rpy2.rlike.container as rlc # for TaggedList rcall = robjects.r['do.call'] # do.call() grdevices = importr('grDevices') # R graphics device # the actual plotting grdevices.jpeg(file="./cma7plot.jpg", width=512, height=512) rcall("plot", rlc.TaggedList([cma7, robjects.IntVector([1,2,3]), False, True], tags=('cma', 'patients.to.plot', 'show.legend', 'align.all.patients'))) grdevices.dev_off() ``` Arguably, the code is clunkier and, at least in this approach, needs an extra step for showing the plot: ``` Include the CMA7 plot using the Markdown syntax (there are several alternatives: https://stackoverflow.com/questions/32370281/how-to-embed-image-or-picture-in-jupyter-notebook-either-from-a-local-machine-o): ![The plot](./cma7plot.jpg) ``` #### Parallel processing (locally and on different machines) `AdhereR` uses `R`'s parallel processing capacities to split expensive computations and distribute them across multiple CPUs/cores in a single computer or even across a network of computers. As an example, we will compute here `CMA1` across sliding windows on the whole dataset, first in `R` and then in `Python 3`. ##### Single thread on the local machine The default mode of computation uses just a single CPU/core on the local machine. ###### `R` ``` R > # Sliding windows with CMA1 (single thread, locally): > cma1w.1l <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="none", + parallel.threads=1) > head(getCMA(cma1w.1l)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` ``` python In [13]: # Sliding windows with CMA1 (single thread, locally): ...: cma1w_1l = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="none", ...: parallel_threads=1) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-06 15:19:07: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [14]: cma1w_1l.get_cma().head(6) Out[14]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ##### Multi-threaded on the local machine If the local machine has multiple CPUs/cores (even with hyperthreading), it might make sense to use them for lengthy computations. `AdhereR` can use several backends (as provided by the `parallel` package in `R`), of which the most used are "multicore" (preffered on `Linux` and `macOS` but currently not available on `Windows`) and "SNOW" (on all three OS's). `AdhereR` is smart enough to use "SNOW" on `Windows` even if "multicore" was requested. ###### `R` ``` R > # Sliding windows with CMA1 (two threads, multicore, locally): > cma1w.2ml <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="multicore", # <--- multicore + parallel.threads=2) > head(getCMA(cma1w.2ml)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > > cma1w.2sl <- CMA_sliding_window(CMA.to.apply="CMA1", + data=med.events, + ID.colname='PATIENT_ID', + event.date.colname='DATE', + event.duration.colname='DURATION', + event.daily.dose.colname='PERDAY', + medication.class.colname='CATEGORY', + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="snow", # <--- SNOW + parallel.threads=2) > head(getCMA(cma1w.2sl)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` ``` python In [15]: # Sliding windows with CMA1 (two threads, multicore, locally): ...: cma1w_2ml = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="multicore", # <--- multicore ...: parallel_threads=2) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 11:44:49: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [16]: cma1w_2ml.get_cma().head(6) Out[16]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 In [17]: # Sliding windows with CMA1 (two threads, snow, locally): ...: cma1w_2sl = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="snow", # <--- SNOW ...: parallel_threads=2) ...: Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 11:44:49: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [18]: cma1w_2sl.get_cma().head(6) Out[18]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ##### Parallel on remote machines over a network Sometimes it is better to use one or more powerful machines over a network to do very expensive computations, usually, a `Linux` cluster from a `Windows`/`macos` laptop. `AdhereR` leverages the power of `R`'s [`snow`](https://CRAN.R-project.org/package=snow) package (as exposed through the `parallel` package) to distribute workloads across a network of computing nodes. There are several types of "Simple Network of Workstations" (`snow`), described in the package's manual. For example, one may use an already existing `MPI` ([Message Passing Interface](https://en.wikipedia.org/wiki/Message_Passing_Interface)) cluster, but an even simpler setup (and the one that we will illustrate here) involves a *collection of machines* running `Linux` and connected to a network (local or even over the Internet). The machines are called `workhorse1` and `workhorse2`, have differen hardware configurations (both sport quad-core i7 CPUs of different generations with 16Gb RAM) but run the same version of `Ubuntu 16.04` and `R 3.4.2` (not a requirement, as the architecture can be seriously heterogeneous, combining different OS's and versions of `R`). These two machines are connected to the same WiFi router (but they could be on different networks or even across the Internet). The "master" is the same `macOS` laptop used before, connected to the same WiFi router (not a requirement). As pre-requisites, the worker machines should allow [`SSH`](https://ubuntu.com/server/docs/service-openssh) access (for easiness, we use here *passwordless SSH access* from the "master"; see for example [here](http://www.linuxproblem.org/art_9.html) for this setup) and should have the `snow` package installed in `R`. Let's assume that the username allowing `ssh` into the workers is `user`, so that ``` bash laptop:~> ssh user@workhorse1 ``` works with no password needed. With these, we can distribute our processing to the two "workers" (two parallel threads for each, totalling 4 parallel threads): ###### `R` ``` R > # Sliding windows with CMA1 (two remote machines with two threads each): > # First, we need to specify the workers > # This is a list of lists! > # rep(,2) means that we generate two threads on each worker > workers <- c(rep(list(list(host="workhorse1", # hostname (make sure this works from the "master", otherwise use the IP-address) + user="user", # the username that can ssh into the worker (passwordless highly recommended) + rscript="/usr/local/bin/Rscript", # the location of Rscript on the worker + snowlib="/usr/local/lib64/R/library/")), # the location of the snow package on the worker + 2), + rep(list(list(host="workhorse2", + user="user", + rscript="/usr/local/bin/Rscript", + snowlib="/usr/local/lib64/R/library/")), + 2)); > > cma1w.2sw <- CMA_sliding_window(CMA="CMA1", + data=med.events, + ID.colname="PATIENT_ID", + event.date.colname="DATE", + event.duration.colname="DURATION", + event.daily.dose.colname="PERDAY", + medication.class.colname="CATEGORY", + carry.only.for.same.medication=FALSE, + consider.dosage.change=FALSE, + sliding.window.duration=30, + sliding.window.step.duration=30, + parallel.backend="snow", + parallel.threads=workers) > head(getCMA(cma1w.2sw)) PATIENT_ID window.ID window.start window.end CMA 1 1 1 2033-04-26 2033-05-26 NA 2 1 2 2033-05-26 2033-06-25 NA 3 1 3 2033-06-25 2033-07-25 NA 4 1 4 2033-07-25 2033-08-24 2.142857 5 1 5 2033-08-24 2033-09-23 NA 6 1 6 2033-09-23 2033-10-23 10.000000 > ``` ###### `Python 3` A quick for `Python` is that due to the communication protocol between the wrapper and `AdhereR`, the specification of the computer cluster must be a one-line string literally contaning the `R` code defining it, string that will be verbatim parsed and interpreted by `AdhereR`: ``` python In [19]: # Sliding windows with CMA1 (two remote machines with two threads each): ...: # The workers are defined as *literal R code* this is verbatim sent to AdhereR for parsing and interpretation ...: # Please note, however, that this string should not contain line breaks (i.e., it should be a one-liner): ...: workers = 'c(rep(list(list(host="workhorse1", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2), rep(list(list(host="workhorse2", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2))' In [20]: cma1w_2sw = ad.CMASlidingWindow(dataset=df, ...: cma_to_apply="CMA1", ...: id_colname='PATIENT_ID', ...: event_date_colname='DATE', ...: event_duration_colname='DURATION', ...: event_daily_dose_colname='PERDAY', ...: medication_class_colname='CATEGORY', ...: sliding_window_duration=30, ...: sliding_window_step_duration=30, ...: parallel_backend="snow", ...: parallel_threads=workers) Adherer returned code 0 and said: AdhereR 0.2.0 on R 3.4.3 started at 2018-06-07 13:22:21: OK: the results were exported successfully (but there might be warnings and messages above worth paying attention to)! In [21]: cma1w_2sw.get_cma().head(6) Out[21]: PATIENT_ID window.ID window.start window.end CMA 0 1 1 04/26/2033 05/26/2033 NaN 1 1 2 05/26/2033 06/25/2033 NaN 2 1 3 06/25/2033 07/25/2033 NaN 3 1 4 07/25/2033 08/24/2033 2.142857 4 1 5 08/24/2033 09/23/2033 NaN 5 1 6 09/23/2033 10/23/2033 10.000000 ``` ###### Some caveats for over-the-network distributed computation While this is a very good way to transparently distribute processing to more powerful nodes over a network, there are several (potential) issues one must be aware of: - *it may be very hard to debug failures*: failures of this might result from network issues, firewals blocking connections, incorrect `SSH` setup on the "workers" or errors in accesing the "workers" with the given user accounts; see, for examples, discussion [here](https://stackoverflow.com/q/17966055) and [here](https://stackoverflow.com/questions/17923256/r-making-cluster-in-doparallel-snowfall-hangs/17925618#17925618) in case you need to solve such problems; - *latency over the network*: starting the "workers" and especially transmitting the data to the "workers" and the results back to the "master" may take a non-negligible time, especially on slow networks (such as the Internet) and for large datasets; therefore, the best scenarios would involve relatively large computations (but not too large; see below) distributed to several nodes over a fast network; - *you need to wait for the results*: this process assumes that the "master" will wait for the "workers" to finish and return their results; thus, putting the "master" to sleep, shutting it down or disconnecting it from the network will probably result in not being able to collect the resuls back. If one needs very long computations (say 3+ hours), offline mobility or the network is unreliable, we would suggest setting up a separate compute process (that may itself parallelise computations) on the remote machines using, for example, [`screen`](https://www.howtoforge.com/linux_screen), [`nohup`](https://en.wikipedia.org/wiki/Nohup) or a more specialised cluster management platform such as [Son of a Grid Engine (SGE)](https://github.com/daimh/sge). ## Appendix I: the communication protocol ### Context All arguments are written to the text file `parameters.log`; the input data are in the TAB-separated no quotes file `dataset.csv`. The call returns any errors, warning and messages in the text file `Adherer-results.txt` file, and the actual results as TAB-separated no quotes files (not all necessarily produced, depending on the specific methods called) `CMA.csv`, `EVENTINFO.csv` and `TREATMENTEPISODES.csv`, and various image file(s). The argument values in the `parameters.log` are contained between single (`' '`) or double (`" "`) quotes. ### Protocol #### PARAMETERS[^1] Some are *required* and must be explicitly defined, but for most we can use implicit values (i.e., if the user doesn't set them explicitly, we may simply not specify them to the `parameters.log` file and the default values in `AdhereR` will be used). #### COMMENTS Everything on a line following `///` or `#` is considered a comment and ignored (except when included within quotes `" "` or `' '`). #### SPECIAL PARAMETERS[^2] | PARAMETER | MEANING | DEFAULT VALUE IF MISSING | PYHTON 3 | STATA | |------------|----------|--------------------------|----------|-------| | `NA.SYMBOL.NUMERIC` | the numeric missing data symbol | `NA` | `NA` | `.` | | `NA.SYMBOL.STRING` | the string missing data symbol | `NA` | `NA` | `""` | | `LOGICAL.SYMBOL.TRUE` | the logical `TRUE` symbol | `TRUE` | `TRUE` | `1` | | `LOGICAL.SYMBOL.FALSE` | the logical `FALSE` symbol | `FALSE` | `FALSE` | `0` | | `COLNAMES.DOT.SYMBOL` | can we use `.` in column names, and if not, what to replace it with? | `.` | `.` | `_` | | `COLNAMES.START.DOT` | can begin column names with `.` (or equivalent symbol), and if not, what to replace it with? | `.` | `.` | `internal_` | #### FUNCTIONS Possible values are: - `CMA0`, - `CMA1` ...`CMA9`, - `CMA_per_episode`, - `CMA_sliding_window`, - `compute.event.int.gaps`, - `compute.treatment.episodes` and - `plot_interactive_cma`. #### PLOTTING For all the `CMA` functions (i.e., `CMA0`, `CMA1` ...`CMA9`, `CMA_per_episode`, `CMA_sliding_window`) one can ask for a plot of (a subset) of the patients, in which case the parameter `plot.show` must be `TRUE`, and there are several plotting-specific parameters that can be set: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `function` | YES | `"CMA0"` | can also be `"CMA0"` for plotting! | | `plot.show` | NO | `"FALSE"` | [do the plotting? If `TRUE`, save the resulting dataset with a `"-plotted"` suffix to avoid overwriting previous results] | | `plot.save.to` | NO | `""` | [the folder where to save the plots (by default, same folder as the results)] | | `plot.save.as` | NO | `"jpg"` | `"jpg"`, `"png"`, `"tiff"`, `"eps"`, `"pdf"` [the type of image to save] | | `plot.width` | NO | `"7"` | [plot width in inches] | | `plot.height` | NO | `"7"` | [plot height in inches] | | `plot.quality` | NO | `"90"` | [plot quality (applies only to some types of plots] | | `plot.dpi` | NO | `"150"` | [plot DPI (applies only to some types of plots] | | `plot.patients.to.plot` | NO | `""` | [the patient IDs to plot (if missing, all patients) given as `"id1;id2; .. ;idn"`] | | `plot.duration` | NO | `""` | [duration to plot in days (if missing, determined from the data)] | | `plot.align.all.patients` | NO | `"FALSE"` | [should all patients be aligned? and, if so, place the first event as the horizontal 0?] | | `plot.align.first.event.at.zero` | NO | `"TRUE"` | | | `plot.show.period` | NO | `"days"` | `"dates"`, `"days"` [draw vertical bars at regular interval as dates or days?] | | `plot.period.in.days` | NO | `"90"` | [the interval (in days) at which to draw vertical lines] | | `plot.show.legend` | NO | `"TRUE"` | [legend params and position] | | `plot.legend.x` | NO | `"bottom right"` | | | `plot.legend.y` | NO | `""` | | | `plot.legend.bkg.opacity` | NO | `"0.5"` | [background opacity] | | `plot.legend.cex` | NO | `"0.75"` | | | `plot.legend.cex.title` | NO | `"1.0"` | | | `plot.cex` | NO | `"1.0"` | [various plotting font sizes] | | `plot.cex.axis` | NO | `"0.75"` | | | `plot.cex.lab` | NO | `"1.0"` | | | `plot.cex.title` | NO | `"1.5"` | | | `plot.show.cma` | NO | `"TRUE"` | [show the CMA type] | | `plot.xlab.dates` | NO | `"Date"` | [the x-label when showing the dates] | | `plot.xlab.days` | NO | `"Days"` | [the x-label when showing the number of days] | | `plot.ylab.withoutcma` | NO | `"patient"` | [the y-label when there's no CMA] | | `plot.ylab.withcma` | NO | `"patient (& CMA)"` | [the y-label when there's a CMA] | | `plot.title.aligned` | NO | `"Event patterns (all patients aligned)"` | [the title when patients are aligned] | | `plot.title.notaligned` | NO | `"Event patterns"` | [the title when patients are not aligned] | | `plot.col.cats` | NO | `"rainbow()"` | [single color or a function name (followed by "()", e.g., "rainbow()") mapping the categories to colors; for security reasons, the list of functions currently supported is: `rainbow`, `heat.colors`, `terrain.colors`, `topo.colors` and `cm.colors` from base `R`, and `viridis`, `magma`, `inferno`, `plasma`, `cividis`, `rocket`, `mako` and `turbo` from `viridisLite` (if installed)] | | `plot.unspecified.category.label` | NO | `"drug"` | [the label of the unspecified category of medication] | | `plot.medication.groups.to.plot` | NO | `""` | [the names of the medication groups to plot (by default, all)] | | `plot.medication.groups.separator.show` | NO | `"TRUE"` | [group medication events by patient?] | | `plot.medication.groups.separator.lty` | NO | `"solid"` | | | `plot.medication.groups.separator.lwd` | NO | `"2"` | | | `plot.medication.groups.separator.color` | NO | `"blue"` | | | `plot.medication.groups.allother.label` | NO | `"*"` | [the label to use for the \_\_ALL\_OTHERS\_\_ medication class (defaults to *)] | | `plot.lty.event` | NO | `"solid"` | [style parameters controlling the plotting of events] | | `plot.lwd.event` | NO | `"2"` | | | `plot.pch.start.event` | NO | `"15"` | | | `plot.pch.end.event` | NO | `"16"` | | | `plot.show.event.intervals` | NO | `"TRUE"` | [show the actual prescription intervals] | | `plot.show.overlapping.event.intervals` | NO | `"first"` | [how to plot overlapping event intervals (relevant for sliding windows and per episode); can be: "first", "last", "min gap", "max gap", "average"] | | `plot.plot.events.vertically.displaced` | NO | `"TRUE"` | [display the events on different lines (vertical displacement) or not (defaults to TRUE)?] | | `plot.print.dose` | NO | `"FALSE"` | [print daily dose] | | `plot.cex.dose` | NO | `"0.75"` | | | `plot.print.dose.col` | NO | `"black"` | | | `plot.print.dose.outline.col` | NO | `"white"` | | | `plot.print.dose.centered` | NO | `"FALSE"` | | | `plot.plot.dose` | NO | `"FALSE"` | [draw daily dose as line width] | | `plot.lwd.event.max.dose` | NO | `"8"` | | | `plot.plot.dose.lwd.across.medication.classes` | NO | `"FALSE"` | | | `plot.col.na` | NO | `"lightgray"` | [colour for missing data] | | `plot.col.continuation` | NO | `"black"` | [colour, style and width of the continuation lines connecting consecutive events] | | `plot.lty.continuation` | NO | `"dotted"` | | | `plot.lwd.continuation` | NO | `"1"` | | | `plot.print.CMA` | NO | `"TRUE"` | [print CMA next to the participant's ID?] | | `plot.CMA.cex` | NO | `"0.50"` | | | `plot.plot.CMA` | NO | `"TRUE"` | [plot the CMA next to the participant ID?] | | `plot.plot.CMA.as.histogram` | NO | `"TRUE"` | [plot CMA as a histogram or as a density plot?] | | `plot.plot.partial.CMAs.as` | NO | `"stacked"` | [can be "stacked", "overlapping" or "timeseries"] | | `plot.plot.partial.CMAs.as.stacked.col.bars` | NO | `"gray90"` | | | `plot.plot.partial.CMAs.as.stacked.col.border` | NO | `"gray30"` | | | `plot.plot.partial.CMAs.as.stacked.col.text` | NO | `"black"` | | | `plot.plot.partial.CMAs.as.timeseries.vspace` | NO | `"7"` | | | `plot.plot.partial.CMAs.as.timeseries.start.from.zero` | NO | `"TRUE"` | | | `plot.plot.partial.CMAs.as.timeseries.col.dot` | NO | `"darkblue"` | | | `plot.plot.partial.CMAs.as.timeseries.col.interval` | NO | `"gray70"` | | | `plot.plot.partial.CMAs.as.timeseries.col.text` | NO | `"firebrick"` | | | `plot.plot.partial.CMAs.as.timeseries.interval.type` | NO | `"segments"` | [can be "none", "segments", "arrows", "lines" or "rectangles"] | | `plot.plot.partial.CMAs.as.timeseries.lwd.interval` | NO | `"1"` | | | `plot.plot.partial.CMAs.as.timeseries.alpha.interval` | NO | `"0.25"` | | | `plot.plot.partial.CMAs.as.timeseries.show.0perc` | NO | `"TRUE"` | TRUE | | `plot.plot.partial.CMAs.as.timeseries.show.100perc` | NO | `"FALSE"` | | | `plot.plot.partial.CMAs.as.overlapping.alternate` | NO | `"TRUE"` | | | `plot.plot.partial.CMAs.as.overlapping.col.interval` | NO | `"gray70"` | | | `plot.plot.partial.CMAs.as.overlapping.col.text` | NO | `"firebrick"` | | | `plot.CMA.plot.ratio` | NO | `"0.10"` | [the proportion of the total horizontal plot to be taken by the CMA plot] | | `plot.CMA.plot.col` | NO | `"lightgreen"` | [attributes of the CMA plot] | | `plot.CMA.plot.border` | NO | `"darkgreen"` | | | `plot.CMA.plot.bkg` | NO | `"aquamarine"` | | | `plot.CMA.plot.text` | NO | `""` | [by default, the same as `plot.CMA.plot.border`] | | `plot.highlight.followup.window` | NO | `"TRUE"` | | | `plot.followup.window.col` | NO | `"green"` | | | `plot.highlight.observation.window` | NO | `"TRUE"` | | | `plot.observation.window.col` | NO | `"yellow"` | | | `plot.observation.window.density` | NO | `"35"` | | | `plot.observation.window.angle` | NO | `"-30"` | | | `plot.observation.window.opacity` | NO | `"0.3"` | | | `plot.show.real.obs.window.start` | NO | `"TRUE"` | [for some CMAs, the real observation window starts at a different date] | | `plot.real.obs.window.density` | NO | `"35"` | | | `plot.real.obs.window.angle` | NO | `"30"` | | | `plot.alternating.bands.cols` | NO | `["white", "gray95"]` | [the colors of the alternating vertical bands across patients; ''=don't draw any; if >= 1 color then a list of comma-separated strings] | | `plot.rotate.text` | NO | `"-60"` | [some text (e.g., axis labels) may be rotated by this much degrees] | | `plot.force.draw.text` | NO | `"FALSE"` | [if true, always draw text even if too big or too small] | | `plot.bw.plot` | NO | `"FALSE"` | [if `TRUE`, override all user-given colours and replace them with a scheme suitable for grayscale plotting] | | `plot.min.plot.size.in.characters.horiz` | NO | `"0"` | | | `plot.min.plot.size.in.characters.vert` | NO | `"0"` | | | `plot.max.patients.to.plot` | NO | `"100"` | | | `plot.suppress.warnings` | NO | `"FALSE"` | [suppress warnings?] | | `plot.do.not.draw.plot` | NO | `"FALSE"` | [if TRUE, don't draw the actual plot, but only the legend (if required)] | #### `CMA1`, `CMA2`, `CMA3`, `CMA4` The parameters for these functions are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `medication.groups` | NO | `""` | [a named vector of medication group definitions, the name of a column in the data that defines the groups, or ''; the medication groups are flattened into column __MED_GROUP_ID] | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` The parameters for these functions are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA_per_episode` The parameters for this function are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `CMA.to.apply ` | YES | | `CMA1`, `CMA2`, `CMA3`, `CMA4`, `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `medication.change.means.new.treatment.episode` | NO | `"TRUE"` | | | `maximum.permissible.gap` | NO | `"90"` | | | `maximum.permissible.gap.unit ` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"`, `"percent"` | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `CMA_sliding_window` The parameters for this function are (*N.B.*: the plotting parameters can also appear if plotting is required): | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `CMA.to.apply ` | YES | | `CMA1`, `CMA2`, `CMA3`, `CMA4`, `CMA5`, `CMA6`, `CMA7`, `CMA8`, `CMA9` | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | YES | | | `medication.class.colname ` | YES | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character'`, `"date'` | | `sliding.window.start` | NO | `0` | | | `sliding.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.duration.type ` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `sliding.window.duration` | NO | `"90"` | | | `sliding.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.step.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"` | | `sliding.window.step.duration ` | NO | `"30"` | | | `sliding.window.step.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `sliding.window.no.steps` | NO | `"-1"` | | | `date.format` | NO | `"%m/%d/%Y"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | `save.event.info` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The computed CMAs, as a TAB-separated no quotes CSV file | `CMA.csv` | Always generated in case of successful processing | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | Only by explicit request (i.e., `save.event.info = "TRUE"`) | #### `compute_event_int_gaps` This function is intended for advanced users only; the parameters for this function are: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | | `event.date.colname` | YES | | | | `event.duration.colname` | YES | | | | `event.daily.dose.colname ` | NO | | | | `medication.class.colname` | NO | | | | `carryover.within.obs.window` | NO | `"FALSE"` | | | `carryover.into.obs.window` | NO | `"FALSE"` | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `"0"` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2`" | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `"0"` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `keep.window.start.end.dates` | NO | `"FALSE"` | | | `remove.events.outside.followup.window` | NO | `"TRUE"` | | | `keep.event.interval.for.all.events` | NO | `"FALSE"` | | | `event.interval.colname` | NO | `"event.interval`" | | | `gap.days.colname ` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none "` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The gap days and event info data, as a TAB-separated no quotes CSV file | `EVENTINFO.csv` | In this case, always returned is successful | #### `compute_treatment_episodes` This function is intended for advanced users only; the parameters for this function are: | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | NO | | | `medication.class.colname ` | NO | | | `carryover.within.obs.window` | NO | `"FALSE"` | | | `carryover.into.obs.window` | NO | `"FALSE"` | | | `carry.only.for.same.medication` | NO | `"FALSE"` | | | `consider.dosage.change` | NO | `"FALSE"` | | | `medication.change.means.new.treatment.episode` | NO | `"TRUE"` | | | `maximum.permissible.gap` | NO | `"90"` | | | `maximum.permissible.gap.unit ` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"`, `"percent"` | | `followup.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.start` | NO | `0` | | | `followup.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `followup.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `followup.window.duration` | NO | `"365 * 2"` | | | `followup.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.start.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.start ` | NO | `0` | | | `observation.window.start.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `observation.window.duration.type` | NO | `"numeric"` | `"numeric"`, `"character"`, `"date"` | | `observation.window.duration` | NO | `"365 * 2"` | | | `observation.window.duration.unit` | NO | `"days"` | `"days"`, `"weeks"`, `"months"`, `"years"` | | `date.format` | NO | `"%m/%d/%Y"` | | | `keep.window.start.end.dates` | NO | `"FALSE"` | | | `remove.events.outside.followup.window` | NO | `"TRUE"` | | | `keep.event.interval.for.all.events` | NO | `"FALSE"` | | | `event.interval.colname` | NO | `"event.interval"` | | | `gap.days.colname` | NO | `"gap.days"` | | | `force.NA.CMA.for.failed.patients` | NO | `"TRUE"` | | | `parallel.backend ` | NO | `"none"` | `"none"`, `"multicore"`, `"snow"`, `"snow(SOCK)"`, `"snow(MPI)"`, `"snow(NWS)"` | | `parallel.threads` | NO | `"auto"` | | | `suppress.warnings` | NO | `"FALSE"` | | | RETURN VALUE(S) | FILE | OBSERVATIONS | |-----------------|------|--------------| | Errors, warnings and other messages | `Adherer-results.txt` | Possibly more than one line; if the processing was successful, the last line must begin with `OK:` | | The treatment episodes data, as a TAB-separated no quotes CSV file | `TREATMENTEPISODES.csv ` | Always if successful | #### `plot_interactive_cma` This function initiates the interactive plotting in `AdhereR` using `Shiny`: all the plotting will be done in the current internet browser and there are no results expected (except for errors, warnings and other messages). This function ignores the argument `plot.show = "TRUE"` and takes very few arguments of its own, as most of the relevant parameters can be set interactively through the `Shiny` interface. | PARAMETER | REQUIRED | DEFAULT_VALUE | POSSIBLE_VALUES | |------------|-----------|---------------|-----------------| | `patient_to_plot` | NO | | defaults to the first patient in the dataset | | `ID.colname` | YES | | | `event.date.colname` | YES | | | `event.duration.colname` | YES | | | `event.daily.dose.colname ` | NO | | | `medication.class.colname ` | NO | | | `date.format` | NO | `"%m/%d/%Y"` | | | `followup.window.start.max` | NO | | integer >0 | `followup.window.duration.max` | NO | | integer >0 | `observation.window.start.max` | NO | | integer >0 | `observation.window.duration.max ` | NO | | integer >0 | `maximum.permissible.gap.max ` | NO | | integer >0 | `sliding.window.start.max` | NO | | integer >0 | `sliding.window.duration.max ` | NO | | integer >0 | `sliding.window.step.duration.max` | NO | | integer >0 ## Appendix II: the `Python 3` code This annex lists the `Python 3` code included in this vignette in an easy-to-run form (i.e., no `In []`, `Out []` and prompts): ``` python # Import adherer as ad: import adherer as ad # Show the _DATA_SHARING_DIRECTORY (should be set automatically to a temporary location): ad._DATA_SHARING_DIRECTORY.name # Show the _RSCRIPT_PATH (should be dectedt automatically): ad._RSCRIPT_PATH # Import Pandas as pd: import pandas as pd # Load the test dataset df = pd.read_csv('~/Temp/med-events.csv', sep='\t', header=0) # Let's look at first 6 rows (it should match the R output above except for the row names): df.head(6) # Compute CMA8 as a test: cma8 = ad.CMA8(df, id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY') # Summary of cma8: cma8 # The return value and messages: cma8.get_computation_results() # The CMA (the first 6 rows out of all 100): cma8.get_cma().head(6) # Plot it (statically): cma8.plot(patients_to_plot=['1', '2', '3'], align_all_patients=True, period_in_days=30, cex=0.5) # Interactive plotting: cma8.plot_interactive() # Sliding windows with CMA1 (single thread, locally): cma1w_1l = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="none", parallel_threads=1) cma1w_1l.get_cma().head(6) # Sliding windows with CMA1 (two threads, multicore, locally): cma1w_2ml = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="multicore", # <--- multicore parallel_threads=2) cma1w_2ml.get_cma().head(6) # Sliding windows with CMA1 (two threads, snow, locally): cma1w_2sl = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="snow", # <--- SNOW parallel_threads=2) cma1w_2sl.get_cma().head(6) # Sliding windows with CMA1 (two remote machines with two threads each): # The workers are defined as *literal R code* this is verbatim sent to AdhereR for parsing and interpretation # Please note, however, that this string should not contain line breaks (i.e., it should be a one-liner): workers = 'c(rep(list(list(host="workhorse1", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2), rep(list(list(host="workhorse2", user="user", rscript="/usr/local/bin/Rscript", snowlib="/usr/local/lib64/R/library/")), 2))' cma1w_2sw = ad.CMASlidingWindow(dataset=df, cma_to_apply="CMA1", id_colname='PATIENT_ID', event_date_colname='DATE', event_duration_colname='DURATION', event_daily_dose_colname='PERDAY', medication_class_colname='CATEGORY', sliding_window_duration=30, sliding_window_step_duration=30, parallel_backend="snow", parallel_threads=workers) cma1w_2sw.get_cma().head(6) ``` ## Notes [^1]: For more info on the parameters and their values for all these functions please see the `AdhereR` documentation and vignette. [^2]: While this document concerns mainly `Python 3`, we also give the default values for other platforms, in particular `STATA`.
/scratch/gouwar.j/cran-all/cranData/AdhereR/vignettes/calling-AdhereR-from-python3.Rmd
############################################################################################### # # AdhereRViz: interactive visualisations for AdhereR. # Copyright (C) 2018-2019 Dan Dediu, Alexandra Dima & Samuel Allemann # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### #' @import AdhereR #' @import grDevices #' @import graphics #' @import stats #' @import data.table #' @import utils #' @importFrom shinyjs useShinyjs extendShinyjs hidden disabled toggle onclick js enable disable #' @importFrom shinyWidgets materialSwitch pickerInput updatePickerInput progressBar updateProgressBar #' @importFrom DBI dbConnect dbDisconnect dbWriteTable dbListTables dbGetQuery dbIsValid #' @importFrom RMariaDB MariaDB #' @importFrom RSQLite SQLite #' @import V8 #' @importFrom clipr clipr_available write_clip #' @importFrom colourpicker colourInput #' @importFrom highlight highlight renderer_html #' @import knitr # #' @importFrom readODS read_ods # #' @importFrom readxl read_excel # #' @importFrom haven read_spss read_xpt read_sas read_stata #' @importFrom viridisLite magma inferno plasma viridis cividis NULL # Declare some variables as global to avoid NOTEs during package building: globalVariables(c("patientID", "selectedCMA", "carry.only.for.same.medication", "consider.dosage.change", "followup.window.start", "followup.window.start", "followup.window.duration", "observation.window.start", "observation.window.duration", "show.legend", "medication.change.means.new.treatment.episode", "dosage.change.means.new.treatment.episode", "maximum.permissible.gap", "maximum.permissible.gap.as.percent", "plot.CMA.as.histogram", "sliding.window.start", "sliding.window.duration", "sliding.window.step.duration")); #' Interactive exploration and CMA computation. #' #' Interactively plots the data for one of more patients, allowing the real-time #' exploration of the various CMAs and their parameters. #' It can use \code{Rstudio}'s \code{manipulate} library (deprecated) or #' \code{Shiny} (recommended). #' #' The \code{manipulate} is kept for backward compatibility only, as it is much #' more limited than \code{Shiny} and will receive no new development in the #' future. #' \code{Shiny} currently allows the use of any other data source besides a #' default (and usual) \code{data.frame} (or derived), such a connection to an #' \code{SQL} database. In this case, the user \emph{must} redefine the three #' argument functions \code{get.colnames.fnc}, \code{get.patients.fnc} and #' \code{get.data.for.patients.fnc} which collectively define an interface for #' listing the column names, all the patient IDs, and for retreiving the actual #' data for a (set of) patient ID(s). A fully worked example is described in #' the vignette detailing the access to standard databases storaging the #' patient information. #' For more info please see the vignette. #' #' @param data Usually a \emph{\code{data.frame}} containing the events (prescribing #' or dispensing) used to compute the CMA. Must contain, at a minimum, the patient #' unique ID, the event date and duration, and might also contain the daily #' dosage and medication type (the actual column names are defined in the #' following four parameters). Alternatively, this can be any other data source #' (for example, a connection to a database), in which case the user must redefine #' the arguments \code{get.colnames.fnc}, \code{get.patients.fnc} and #' \code{get.data.for.patients.fnc} appropriately. Currently, this works only when #' using Shiny for interactive rendering. For a working example, please see #' the vignette describing the interfacing with databases. #' @param ID The ID (as given in the \code{ID.colname} column) of the patient #' whose data to interactively plot (if absent, pick the first one); please not #' that this an be interactively selected during plotting. #' @param cma.class The type of CMAs to plot; can be "simple" (CMA0 to CMA9), #' "per episode", or "sliding window". #' @param print.full.params A \emph{logical} specifying if the values of all the #' parameters used to generate the current plot should be printed in the console #' (if \emph{TRUE}, it can generate extremely verbose output!). #' @param ID.colname A \emph{string}, the name of the column in \code{data} #' containing the unique patient ID, or \code{NA} if not defined. #' @param event.date.colname A \emph{string}, the name of the column in #' \code{data} containing the start date of the event (in the format given in #' the \code{date.format} parameter), or \code{NA} if not defined. #' @param event.duration.colname A \emph{string}, the name of the column in #' \code{data} containing the event duration (in days), or \code{NA} if not #' defined. #' @param event.daily.dose.colname A \emph{string}, the name of the column in #' \code{data} containing the prescribed daily dose, or \code{NA} if not defined. #' @param medication.class.colname A \emph{string}, the name of the column in #' \code{data} containing the classes/types/groups of medication, or \code{NA} #' if not defined. #' @param medication.groups A \emph{named character vector} defining the #' medication classes, the name of a column in the data the defines the groups, #' or \code{NULL} if none (the default). #' @param date.format A \emph{string} giving the format of the dates used in the #' \code{data} and the other parameters; see the \code{format} parameters of the #' \code{\link[base]{as.Date}} function for details (NB, this concerns only the #' dates given as strings and not as \code{Date} objects). #' @param followup.window.start.max The maximum number of days when the #' follow-up window can start. #' @param followup.window.duration.max The maximum duration of the follow-up #' window in days. #' @param observation.window.start.max The maximum number of days when the #' observation window can start. #' @param observation.window.duration.max The maximum duration of the #' observation window in days. #' @param align.all.patients Should the patients be aligend? #' @param align.first.event.at.zero Should the first event be put at zero? #' @param maximum.permissible.gap.max The maximum permissible gap in days. #' @param sliding.window.start.max The maximum number of days when the sliding #' windows can start. #' @param sliding.window.duration.max The maximum duration of the sliding #' windows in days. #' @param sliding.window.step.duration.max The maximum sliding window step in #' days. #' @param backend The plotting backend to use; "shiny" (the default) tries to #' use the Shiny framework, while "rstudio" uses the manipulate RStudio #' capability. #' @param use.system.browser For shiny, use the system browser? #' @param get.colnames.fnc A \emph{function} taking as parameter the data source #' and returning the column names. Must be overridden when the data source is #' not derived from a \code{data.frame}. #' @param get.patients.fnc A \emph{function} taking as parameter the data source #' and the patient ID column name, and returns the list of all patient IDs. #' Must be overridden when the data source is not derived from a \code{data.frame}. #' @param get.data.for.patients.fnc A \emph{function} taking as parameter a (set #' of) patient ID(s), the data source, and the patient ID column name, and returns #' the list of all patient IDs. Must be overridden when the data source is not #' derived from a \code{data.frame}. #' @param ... Extra arguments. #' #' @seealso The vignette *AdhereR: Interactive plotting (and more) with Shiny*. #' #' @return Nothing #' @examples #' \dontrun{ #' library(AdhereR); #' plot_interactive_cma(med.events, #' ID.colname="PATIENT_ID", #' event.date.colname="DATE", #' event.duration.colname="DURATION", #' event.daily.dose.colname="PERDAY", #' medication.class.colname="CATEGORY");} #' @export plot_interactive_cma <- function( data=NULL, # the data used to compute the CMA on ID=NULL, # the ID of the patient to be plotted (automatically taken to be the first) cma.class=c("simple","per episode","sliding window")[1], # the CMA class to plot print.full.params=FALSE, # should the parameter values for the currently plotted plot be printed? # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) medication.groups=NULL, # definition of medication groups (NULL = undefined) # Date format: date.format="%m/%d/%Y", # the format of the dates used in this function (NA = undefined) # Parameter ranges: followup.window.start.max=5*365, # in days followup.window.duration.max=5*365, # in days observation.window.start.max=followup.window.start.max, # in days observation.window.duration.max=followup.window.duration.max, # in days align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? if so, place the first event as the horizontal 0? maximum.permissible.gap.max=2*365, # in days sliding.window.start.max=followup.window.start.max, # in days sliding.window.duration.max=2*365, # in days sliding.window.step.duration.max=2*365, # in days backend=c("shiny","rstudio")[1], # the interactive backend to use use.system.browser=FALSE, # if shiny backend, use the system browser? get.colnames.fnc=function(d) names(d), get.patients.fnc=function(d, idcol) unique(d[[idcol]]), get.data.for.patients.fnc=function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ], ... ) { # Clear any AdhereR errors, warning or messages, and start recording them: AdhereR:::.clear.ewms(); AdhereR:::.record.ewms(record=TRUE); if( backend == "shiny" ) { .plot_interactive_cma_shiny(data=data, ID=ID, medication.groups.to.plot=NULL, # plot all medication groups, by default cma.class=cma.class, print.full.params=print.full.params, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, medication.groups=medication.groups, date.format=date.format, followup.window.start.max=followup.window.start.max, followup.window.duration.max=followup.window.duration.max, observation.window.start.max=observation.window.start.max, observation.window.duration.max=observation.window.duration.max, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, maximum.permissible.gap.max=maximum.permissible.gap.max, sliding.window.start.max=sliding.window.start.max, sliding.window.duration.max=sliding.window.duration.max, sliding.window.step.duration.max=sliding.window.step.duration.max, use.system.browser=use.system.browser, get.colnames.fnc=get.colnames.fnc, get.patients.fnc=get.patients.fnc, get.data.for.patients.fnc=get.data.for.patients.fnc, ... ); } else if( backend == "rstudio" ) { .plot_interactive_cma_rstudio(data=data, ID=ID, cma.class=cma.class, print.full.params=print.full.params, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, date.format=date.format, followup.window.start.max=followup.window.start.max, followup.window.duration.max=followup.window.duration.max, observation.window.start.max=observation.window.start.max, observation.window.duration.max=observation.window.duration.max, #align.all.patients=align.all.patients, #align.first.event.at.zero=align.first.event.at.zero, maximum.permissible.gap.max=maximum.permissible.gap.max, sliding.window.start.max=sliding.window.start.max, sliding.window.duration.max=sliding.window.duration.max, sliding.window.step.duration.max=sliding.window.step.duration.max, ... ); } else { warning("Interactive plotting: dont' know backend '",backend,"'; only use 'shiny' or 'rstudio'.\n"); } # Clear any generated AdhereR errors, warning or messages, and stop recording them: AdhereR:::.clear.ewms(); AdhereR:::.record.ewms(record=FALSE); } # Auxiliary function: interactive plot using RStudio's manipulate: .plot_interactive_cma_rstudio <- function( data=NULL, # the data used to compute the CMA on ID=NULL, # the ID of the patient to be plotted (automatically taken to be the first) cma.class=c("simple","per episode","sliding window")[1], # the CMA class to plot print.full.params=FALSE, # should the parameter values for the currently plotted plot be printed? # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) # Date format: date.format=NA, # the format of the dates used in this function (NA = undefined) # Parameter ranges: followup.window.start.max=5*365, # in days followup.window.duration.max=5*365, # in days observation.window.start.max=followup.window.start.max, # in days observation.window.duration.max=followup.window.duration.max, # in days maximum.permissible.gap.max=2*365, # in days sliding.window.start.max=followup.window.start.max, # in days sliding.window.duration.max=2*365, # in days sliding.window.step.duration.max=2*365, # in days ... ) { # Check if manipulate can be run: if( !manipulate::isAvailable() ) { stop("Interactive plotting is currently only possible within RStudio (as we use the manipulate package)!\n"); return (NULL); } if( !(cma.class %in% c("simple","per episode","sliding window")) ) { warning(paste0("Only know how to interactively plot 'cma.class' of type 'simple', 'per episode' and 'sliding window', but you requested '",cma.class,"': assuming 'simple'.")); cma.class <- "simple" } # Preconditions: if( !is.null(data) ) { # data's class and dimensions: if( inherits(data, "matrix") || inherits(data, "data.table") ) data <- as.data.frame(data); # make it a data.frame if( !inherits(data, "data.frame") ) { stop("The 'data' must be of type 'data.frame'!\n"); return (NULL); } if( nrow(data) < 1 ) { stop("The 'data' must have at least one row!\n"); return (NULL); } # the column names must exist in data: if( !is.na(ID.colname) && !(ID.colname %in% names(data)) ) { stop(paste0("Column ID.colname='",ID.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(event.date.colname) && !(event.date.colname %in% names(data)) ) { stop(paste0("Column event.date.colname='",event.date.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(event.duration.colname) && !(event.duration.colname %in% names(data)) ) { stop(paste0("Column event.duration.colname='",event.duration.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(event.daily.dose.colname) && !(event.daily.dose.colname %in% names(data)) ) { stop(paste0("Column event.daily.dose.colname='",event.daily.dose.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(medication.class.colname) && !(medication.class.colname %in% names(data)) ) { stop(paste0("Column medication.class.colname='",medication.class.colname,"' must appear in the 'data'!\n")); return (NULL); } } else { stop("The 'data' cannot be empty!\n"); return (NULL); } # The function encapsulating the plotting: .plotting.fnc <- function(data=NULL, # the data used to compute the CMA on ID=NULL, # the ID of the patient to plot cma="none", # the CMA to use for plotting cma.to.apply="none", # cma to compute per episode or sliding window # Various types medhods of computing gaps: carryover.within.obs.window=NA, # if TRUE consider the carry-over within the observation window (NA = undefined) carryover.into.obs.window=NA, # if TRUE consider the carry-over from before the starting date of the observation window (NA = undefined) carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=NA, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.duration=NA, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=NA, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=NA, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Treatment episodes: medication.change.means.new.treatment.episode=TRUE, # does a change in medication automatically start a new treatment episode? dosage.change.means.new.treatment.episode=FALSE, # does a change in dosage automatically start a new treatment episode? maximum.permissible.gap=180, # if a number, is the duration in units of max. permissible gaps between treatment episodes maximum.permissible.gap.unit="days", # time units; can be "days", "weeks" (fixed at 7 days), "months" (fixed at 30 days) or "years" (fixed at 365 days) # Sliding window: sliding.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) sliding.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.duration=90, # the duration of the sliding window in time units (NA = undefined) sliding.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.step.duration=7, # the step ("jump") of the sliding window in time units (NA = undefined) sliding.window.step.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.no.steps=NA, # the number of steps to jump; if both sliding.win.no.steps & sliding.win.duration are NA, fill the whole observation window plot.CMA.as.histogram=TRUE, # plot the CMA as historgram or density plot? show.legend=TRUE # show the legend? ) { # Progress messages: cat(paste0("Plotting patient ID '",ID,"' with CMA '",cma,"'",ifelse(cma.to.apply != "none",paste0(" ('",cma.to.apply,"')"),""))); if( print.full.params ) { cat(paste0(" with params: ", "carryover.within.obs.window=",carryover.within.obs.window,", ", "carryover.into.obs.window=",carryover.into.obs.window,", ", "carry.only.for.same.medication=",carry.only.for.same.medication,", ", "consider.dosage.change=",consider.dosage.change,", ", "followup.window.start=",followup.window.start,", ", "followup.window.start.unit=",followup.window.start.unit,", ", "followup.window.duration=",followup.window.duration,", ", "followup.window.duration.unit=",followup.window.duration.unit,", ", "observation.window.start=",observation.window.start,", ", "observation.window.start.unit=",observation.window.start.unit,", ", "observation.window.duration=",observation.window.duration,", ", "observation.window.duration.unit=",observation.window.duration.unit,", ", "medication.change.means.new.treatment.episode=",medication.change.means.new.treatment.episode,", ", "dosage.change.means.new.treatment.episode=",dosage.change.means.new.treatment.episode,", ", "maximum.permissible.gap=",maximum.permissible.gap,", ", "maximum.permissible.gap.unit=",maximum.permissible.gap.unit,", ", "sliding.window.start=",sliding.window.start,", ", "sliding.window.start.unit=",sliding.window.start.unit,", ", "sliding.window.duration=",sliding.window.duration,", ", "sliding.window.duration.unit=",sliding.window.duration.unit,", ", "sliding.window.step.duration=",sliding.window.step.duration,", ", "sliding.window.step.unit=",sliding.window.step.unit,", ", "sliding.window.no.steps=",sliding.window.no.steps )); } cat("\n"); # Preconditions: if( is.null(ID) || is.null(data <- data[data[,ID.colname] %in% ID,]) || nrow(data)==0 ) { plot(-10:10,-10:10,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,paste0("Error: cannot display the data for patient '",ID,"'!"),col="red"); return (invisible(NULL)); } # Compute the CMA: cma.fnc <- switch(cma, "CMA1" = CMA1, "CMA2" = CMA2, "CMA3" = CMA3, "CMA4" = CMA4, "CMA5" = CMA5, "CMA6" = CMA6, "CMA7" = CMA7, "CMA8" = CMA8, "CMA9" = CMA9, "per episode" = CMA_per_episode, "sliding window" = CMA_sliding_window, CMA0); # by default, fall back to CMA0 # Try to catch errors and warnings for nice displaying: results <- NULL; full.results <- tryCatch( results <- cma.fnc( data, CMA=cma.to.apply, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, date.format=date.format, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, medication.change.means.new.treatment.episode=medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=dosage.change.means.new.treatment.episode, maximum.permissible.gap=maximum.permissible.gap, maximum.permissible.gap.unit=maximum.permissible.gap.unit, sliding.window.start=sliding.window.start, sliding.window.start.unit=sliding.window.start.unit, sliding.window.duration=sliding.window.duration, sliding.window.duration.unit=sliding.window.duration.unit, sliding.window.step.duration=sliding.window.step.duration, sliding.window.step.unit=sliding.window.step.unit, sliding.window.no.steps=sliding.window.no.steps), error =function(e) return(list(results=results,error=conditionMessage(e)))); if( is.null(results) ) { # Plot an error message: #plot(-10:10,-10:10,type="n",axes=FALSE,xlab="",ylab=""); #text(0,0,paste0("Error computing '",cma,"' for patient '",ID,"'\n(see console for possible warnings or errors)!"),col="red"); AdhereR:::plot.CMA.error(cma=cma, IDs=ID); if( !is.null(full.results$error) ) cat(paste0("Error(s): ",paste0(full.results$error,collapse="\n"))); } else { # Plot the results: plot(results, show.legend=show.legend, plot.CMA.as.histogram=plot.CMA.as.histogram); } } if( is.null(ID) ) ID <- data[1,ID.colname]; if( cma.class == "simple" ) { # CMA0 to CMA9: manipulate::manipulate(.plotting.fnc(data=data, ID=patientID, cma=selectedCMA, carryover.within.obs.window=NA, # carryover.within.obs.window, carryover.into.obs.window=NA, # carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit="days", # followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit="days", # followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit="days", # observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit="days", # observation.window.duration.unit, medication.change.means.new.treatment.episode=NA, #medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=NA, #dosage.change.means.new.treatment.episode maximum.permissible.gap=NA, #maximum.permissible.gap, maximum.permissible.gap.unit="days", # maximum.permissible.gap.unit, sliding.window.start=NA, #sliding.window.start, sliding.window.start.unit="days", # sliding.window.start.unit, sliding.window.duration=NA, #sliding.window.duration, sliding.window.duration.unit="days", # sliding.window.duration.unit, sliding.window.step.duration=NA, #sliding.window.step.duration, sliding.window.step.unit="days", # sliding.window.step.unit, sliding.window.no.steps=NA, # sliding.window.no.steps plot.CMA.as.histogram=NA, # plot CMA as historgram? show.legend=show.legend # show the legend? ), patientID = manipulate::picker(as.list(unique(data[,ID.colname])), initial=as.character(ID), label="Patient ID"), selectedCMA = manipulate::picker(list("CMA0", "CMA1", "CMA2", "CMA3", "CMA4", "CMA5", "CMA6", "CMA7", "CMA8", "CMA9"), initial="CMA1", label="CMA to compute"), #carryover.within.obs.window = manipulate::checkbox(FALSE, "Carry-over within obs. wnd.?"), #carryover.into.obs.window = manipulate::checkbox(FALSE, "Carry-over into obs. wnd.?"), carry.only.for.same.medication = manipulate::checkbox(FALSE, "Carry-over for same treat only? (CMAs 5-9)"), consider.dosage.change = manipulate::checkbox(FALSE, "Consider dosage changes? (CMAs 5-9)"), followup.window.start = manipulate::slider(0, followup.window.start.max, 0, "Follow-up wnd. start (days)", step=1), #followup.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. start unit"), followup.window.duration = manipulate::slider(0, followup.window.duration.max, 2*365, "Follow-up wnd. duration (days)", 1), #followup.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. duration unit"), observation.window.start = manipulate::slider(0, observation.window.start.max, 0, "Obs. wnd. start (days)", step=1), #observation.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. start unit"), observation.window.duration = manipulate::slider(0, observation.window.duration.max, 2*365, "Obs. wnd. duration (days)", 1), #observation.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. duration unit"), #medication.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Treat. change starts new episode?"), #dosage.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Dosage change starts new episode?"), #maximum.permissible.gap = manipulate::slider(0, 500, 0, "Max. permissible gap (days)", 1), #maximum.permissible.gap.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Max. permis. gap duration unit"), #maximum.permissible.gap.as.percent = manipulate::checkbox(FALSE, "Max. permissible gap as percent?"), #sliding.window.start = manipulate::slider(0, 5000, 0, "Sliding wnd. start (days)", step=1), #sliding.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding. wnd. start unit"), #sliding.window.duration = manipulate::slider(0, 2*365, 90, "Sliding wnd. duration (days)", 1), #sliding.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. duration unit"), #sliding.window.step.duration = manipulate::slider(0, 2*365, 7, "Sliding wnd. step (days)", 1) #sliding.window.step.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. step unit"), #sliding.window.no.steps = manipulate::slider(0, 100, 10, "# sliding wnd. steps", 1), show.legend = manipulate::checkbox(TRUE, "Show the legend?") ); } else if( cma.class == "per episode" ) { # per episode: manipulate::manipulate(.plotting.fnc(data=data, ID=patientID, cma="per episode", cma.to.apply=selectedCMA, carryover.within.obs.window=NA, # carryover.within.obs.window, carryover.into.obs.window=NA, # carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit="days", # followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit="days", # followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit="days", # observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit="days", # observation.window.duration.unit, medication.change.means.new.treatment.episode=medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=dosage.change.means.new.treatment.episode, maximum.permissible.gap=maximum.permissible.gap, maximum.permissible.gap.unit=ifelse(!maximum.permissible.gap.as.percent,"days","percent"), # maximum.permissible.gap.unit, sliding.window.start=NA, #sliding.window.start, sliding.window.start.unit="days", # sliding.window.start.unit, sliding.window.duration=NA, #sliding.window.duration, sliding.window.duration.unit="days", # sliding.window.duration.unit, sliding.window.step.duration=NA, #sliding.window.step.duration, sliding.window.step.unit="days", # sliding.window.step.unit, sliding.window.no.steps=NA, # sliding.window.no.steps plot.CMA.as.histogram=plot.CMA.as.histogram, # plot CMA as histogram? show.legend=show.legend # show the legend? ), patientID = manipulate::picker(as.list(unique(data[,ID.colname])), initial=as.character(ID), label="Patient ID"), selectedCMA = manipulate::picker(list("CMA1", "CMA2", "CMA3", "CMA4", "CMA5", "CMA6", "CMA7", "CMA8", "CMA9"), initial="CMA1", label="CMA to compute per episode"), #carryover.within.obs.window = manipulate::checkbox(FALSE, "Carry-over within obs. wnd.? (coupled)"), #carryover.into.obs.window = manipulate::checkbox(FALSE, "Carry-over into obs. wnd.? (coupled)"), carry.only.for.same.medication = manipulate::checkbox(FALSE, "Carry-over for same treat only? (coupled, CMAs 5-9)"), consider.dosage.change = manipulate::checkbox(FALSE, "Consider dosage changes? (coupled, CMAs 5-9)"), followup.window.start = manipulate::slider(0, followup.window.start.max, 0, "Follow-up wnd. start (days)", step=1), #followup.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. start unit"), followup.window.duration = manipulate::slider(0, followup.window.duration.max, 2*365, "Follow-up wnd. duration (days)", 1), #followup.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. duration unit"), observation.window.start = manipulate::slider(0, observation.window.start.max, 0, "Obs. wnd. start (days)", step=1), #observation.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. start unit"), observation.window.duration = manipulate::slider(0, observation.window.duration.max, 2*365, "Obs. wnd. duration (days)", 1), #observation.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. duration unit"), medication.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Treat. change starts new episode?"), dosage.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Dosage change starts new episode?"), maximum.permissible.gap = manipulate::slider(0, maximum.permissible.gap.max, 180, "Max. permissible gap (days or %)", 1), maximum.permissible.gap.as.percent = manipulate::checkbox(FALSE, "Max. permissible gap as percent?"), #maximum.permissible.gap.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Max. permis. gap duration unit"), #sliding.window.start = manipulate::slider(0, 5000, 0, "Sliding wnd. start (days)", step=1), #sliding.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding. wnd. start unit"), #sliding.window.duration = manipulate::slider(0, 2*365, 90, "Sliding wnd. duration (days)", 1), #sliding.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. duration unit"), #sliding.window.step.duration = manipulate::slider(0, 2*365, 7, "Sliding wnd. step (days)", 1) #sliding.window.step.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. step unit"), #sliding.window.no.steps = manipulate::slider(0, 100, 10, "# sliding wnd. steps", 1), plot.CMA.as.histogram = manipulate::checkbox(TRUE, "Plot CMA as histogram?"), show.legend = manipulate::checkbox(TRUE, "Show the legend?") ); } else if( cma.class == "sliding window" ) { # sliding window: manipulate::manipulate(.plotting.fnc(data=data, ID=patientID, cma="sliding window", cma.to.apply=selectedCMA, carryover.within.obs.window=NA, # carryover.within.obs.window, carryover.into.obs.window=NA, # carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit="days", # followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit="days", # followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit="days", # observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit="days", # observation.window.duration.unit, medication.change.means.new.treatment.episode=NA, dosage.change.means.new.treatment.episode=NA, maximum.permissible.gap=NA, #maximum.permissible.gap, maximum.permissible.gap.unit="days", # maximum.permissible.gap.unit, sliding.window.start=sliding.window.start, sliding.window.start.unit="days", # sliding.window.start.unit, sliding.window.duration=sliding.window.duration, sliding.window.duration.unit="days", # sliding.window.duration.unit, sliding.window.step.duration=sliding.window.step.duration, sliding.window.step.unit="days", # sliding.window.step.unit, sliding.window.no.steps=NA, # sliding.window.no.steps plot.CMA.as.histogram=plot.CMA.as.histogram, # plot CMA as histogram? show.legend=show.legend # show the legend? ), patientID = manipulate::picker(as.list(unique(data[,ID.colname])), initial=as.character(ID), label="Patient ID"), selectedCMA = manipulate::picker(list("CMA1", "CMA2", "CMA3", "CMA4", "CMA5", "CMA6", "CMA7", "CMA8", "CMA9"), initial="CMA1" , label="CMA to compute per sliding window"), #carryover.within.obs.window = manipulate::checkbox(FALSE, "Carry-over within obs. wnd.?"), #carryover.into.obs.window = manipulate::checkbox(FALSE, "Carry-over into obs. wnd.?"), carry.only.for.same.medication = manipulate::checkbox(FALSE, "Carry-over for same treat only? (CMAs 5-9)"), consider.dosage.change = manipulate::checkbox(FALSE, "Consider dosage changes? (CMAs 5-9)"), followup.window.start = manipulate::slider(0, followup.window.start.max, 0, "Follow-up wnd. start (days)", step=1), #followup.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. start unit"), followup.window.duration = manipulate::slider(0, followup.window.duration.max, 2*365, "Follow-up wnd. duration (days)", 1), #followup.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Follow-up wnd. duration unit"), observation.window.start = manipulate::slider(0, observation.window.start.max, 0, "Obs. wnd. start (days)", step=1), #observation.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. start unit"), observation.window.duration = manipulate::slider(0, observation.window.duration.max, 2*365, "Obs. wnd. duration (days)", 1), #observation.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Obs. wnd. duration unit"), #medication.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Treat. change starts new episode?"), #dosage.change.means.new.treatment.episode = manipulate::checkbox(TRUE, "Dosage change starts new episode?"), #maximum.permissible.gap = manipulate::slider(0, 500, 0, "Max. permissible gap (days)", 1), #maximum.permissible.gap.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Max. permis. gap duration unit"), #maximum.permissible.gap.as.percent = manipulate::checkbox(FALSE, "Max. permissible gap as percent?"), sliding.window.start = manipulate::slider(0, sliding.window.start.max, 0, "Sliding wnd. start (days)", step=1), #sliding.window.start.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding. wnd. start unit"), sliding.window.duration = manipulate::slider(0, sliding.window.duration.max, 90, "Sliding wnd. duration (days)", 1), #sliding.window.duration.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. duration unit"), sliding.window.step.duration = manipulate::slider(0, sliding.window.step.duration.max, 30, "Sliding wnd. step (days)", 1), #sliding.window.step.unit = manipulate::picker(list("days", "weeks", "months", "years"), initial="days", label="Sliding wnd. step unit"), #sliding.window.no.steps = manipulate::slider(0, 100, 10, "# sliding wnd. steps", 1), plot.CMA.as.histogram = manipulate::checkbox(FALSE, "Plot CMA as histogram?"), show.legend = manipulate::checkbox(TRUE, "Show the legend?") ); } } # Auxiliary functions for interactive plot using shiny: # The function encapsulating the actual plotting and CMA estimation: .plotting.fnc.shiny <- function(data=NULL, # the data used to compute the CMA on # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) medication.groups=NULL, # definition of medication groups (NULL = undefined) # Date format: date.format=NA, # the format of the dates used in this function (NA = undefined) ID=NULL, # the ID of the patient to plot # Medication groups: medication.groups.to.plot=NULL, # medication groups to plot medication.groups.separator.show=TRUE, # visuallt group medication groups within patient? medication.groups.separator.lty="solid", medication.groups.separator.lwd=2, medication.groups.separator.color="blue", medication.groups.allother.label="*", # CMA: cma="none", # the CMA to use for plotting cma.to.apply="none", # cma to compute per episode or sliding window # Various types medhods of computing gaps: carryover.within.obs.window=NA, # if TRUE consider the carry-over within the observation window (NA = undefined) carryover.into.obs.window=NA, # if TRUE consider the carry-over from before the starting date of the observation window (NA = undefined) carry.only.for.same.medication=NA, # if TRUE the carry-over applies only across medication of same type (NA = undefined) consider.dosage.change=NA, # if TRUE carry-over is adjusted to reflect changes in dosage (NA = undefined) # The follow-up window: followup.window.start=NA, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) followup.window.start.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) followup.window.duration=NA, # the duration of the follow-up window in the time units given below (NA = undefined) followup.window.duration.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # The observation window (embedded in the follow-up window): observation.window.start=NA, # the number of time units relative to followup.window.start (NA = undefined) observation.window.start.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) observation.window.duration=NA, # the duration of the observation window in time units (NA = undefined) observation.window.duration.unit=NA, # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) # Treatment episodes: medication.change.means.new.treatment.episode=TRUE, # does a change in medication automatically start a new treatment episode? dosage.change.means.new.treatment.episode=FALSE, # does a change in dosage automatically start a new treatment episode? maximum.permissible.gap=180, # if a number, is the duration in units of max. permissible gaps between treatment episodes maximum.permissible.gap.unit="days", # time units; can be "days", "weeks" (fixed at 7 days), "months" (fixed at 30 days) or "years" (fixed at 365 days) maximum.permissible.gap.append.to.episode=FALSE, # should the maximum permissible gap be appended at the end of an episode with a gap larger than the maximum permissible gap? FALSE = no addition (the default), TRUE = the full maximum permissible gap is added # Sliding window: sliding.window.start=0, # if a number is the earliest event per participant date + number of units, or a Date object, or a column name in data (NA = undefined) sliding.window.start.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.duration=90, # the duration of the sliding window in time units (NA = undefined) sliding.window.duration.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.step.duration=7, # the step ("jump") of the sliding window in time units (NA = undefined) sliding.window.step.unit=c("days", "weeks", "months", "years")[1], # the time units; can be "days", "weeks", "months" or "years" (if months or years, using an actual calendar!) (NA = undefined) sliding.window.no.steps=NA, # the number of steps to jump; if both sliding.win.no.steps & sliding.win.duration are NA, fill the whole observation window plot.CMA.as.histogram=TRUE, # plot the CMA as historgram or density plot? align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? if so, place first event the horizontal 0? # Legend: show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1.0, # legend # Labels and title: xlab=c("dates"="Date", "days"="Days"), ylab=c("withoutCMA"="patient", "withCMA"="patient (& CMA)"), title=c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns"), # Duration and period: duration=NA, # duration to plot show.period=c("dates","days")[2], period.in.days=90, # period on the x axis # Colors and fonts: force.draw.text=FALSE, bw.plot=FALSE, show.cma=TRUE, col.na="lightgray", col.cats=rainbow, unspecified.category.label="drug", lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, col.continuation="black", lty.continuation="dotted", lwd.continuation=1, cex=1.0, cex.axis=0.75, cex.lab=1.0, highlight.followup.window=TRUE, followup.window.col="green", highlight.observation.window=TRUE, observation.window.col="yellow", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, # Event intervals: show.event.intervals=!(cma %in% c("per episode", "sliding window")), show.overlapping.event.intervals="first", # CMAs: print.CMA=TRUE, CMA.cex=0.50, plot.CMA=TRUE, CMA.plot.ratio=0.10, CMA.plot.col="lightgreen", CMA.plot.border="darkgreen", CMA.plot.bkg="aquamarine", CMA.plot.text="darkgreen", plot.partial.CMAs.as=c("stacked"), plot.partial.CMAs.as.stacked.col.bars="gray90", plot.partial.CMAs.as.stacked.col.border="gray30", plot.partial.CMAs.as.stacked.col.text="black", plot.partial.CMAs.as.timeseries.vspace=7, plot.partial.CMAs.as.timeseries.start.from.zero=TRUE, plot.partial.CMAs.as.timeseries.col.dot="darkblue", plot.partial.CMAs.as.timeseries.interval.type=c("none", "segments", "arrows", "lines", "rectangles")[2], plot.partial.CMAs.as.timeseries.lwd.interval=1, plot.partial.CMAs.as.timeseries.alpha.interval=0.25, plot.partial.CMAs.as.timeseries.col.interval="gray70", plot.partial.CMAs.as.timeseries.col.text="firebrick", plot.partial.CMAs.as.timeseries.show.0perc=TRUE, plot.partial.CMAs.as.timeseries.show.100perc=FALSE, plot.partial.CMAs.as.overlapping.col.interval="gray70", plot.partial.CMAs.as.overlapping.col.text="firebrick", # Dose: print.dose=FALSE, cex.dose=0.75, print.dose.outline.col="white", print.dose.centered=FALSE, plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, # Minimum plot size: min.plot.size.in.characters.horiz=10, min.plot.size.in.characters.vert=0.5, # Data accessor functions: get.colnames.fnc=function(d) names(d), get.patients.fnc=function(d, idcol) unique(d[[idcol]]), get.data.for.patients.fnc=function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ], # Plot the results or only compute the CMA and return it: compute.cma.only=FALSE, # Debugging print.full.params=FALSE ) { # Clear any AdhereR messages: AdhereR:::.clear.ewms(); if( !compute.cma.only ) # for computing CMA only these messages are not very informative and positively distracting... { # Progress messages: AdhereR:::.report.ewms(paste0("Plotting patient ID '",ID,"' with CMA '",cma,"'",ifelse(cma.to.apply != "none",paste0(" ('",cma.to.apply,"')"),"")), "message", "plot_interactive_cma", "AdhereRViz"); if( print.full.params ) { cat(paste0(" with params: ", "carryover.within.obs.window=",carryover.within.obs.window,", ", "carryover.into.obs.window=",carryover.into.obs.window,", ", "carry.only.for.same.medication=",carry.only.for.same.medication,", ", "consider.dosage.change=",consider.dosage.change,", ", "followup.window.start=",followup.window.start,", ", "followup.window.start.unit=",followup.window.start.unit,", ", "followup.window.duration=",followup.window.duration,", ", "followup.window.duration.unit=",followup.window.duration.unit,", ", "observation.window.start=",observation.window.start,", ", "observation.window.start.unit=",observation.window.start.unit,", ", "observation.window.duration=",observation.window.duration,", ", "observation.window.duration.unit=",observation.window.duration.unit,", ", "medication.change.means.new.treatment.episode=",medication.change.means.new.treatment.episode,", ", "dosage.change.means.new.treatment.episode=",dosage.change.means.new.treatment.episode,", ", "maximum.permissible.gap=",maximum.permissible.gap,", ", "maximum.permissible.gap.unit=",maximum.permissible.gap.unit,", ", "maximum.permissible.gap.append.to.episode=",maximum.permissible.gap.append.to.episode,", ", "sliding.window.start=",sliding.window.start,", ", "sliding.window.start.unit=",sliding.window.start.unit,", ", "sliding.window.duration=",sliding.window.duration,", ", "sliding.window.duration.unit=",sliding.window.duration.unit,", ", "sliding.window.step.duration=",sliding.window.step.duration,", ", "sliding.window.step.unit=",sliding.window.step.unit,", ", "sliding.window.no.steps=",sliding.window.no.steps,", ", "align.all.patients=",align.all.patients,", ", "align.first.event.at.zero=",align.first.event.at.zero )); } cat("\n"); } # Do we need to recompute the CMA? recompute.CMA <- TRUE; # Check if anything really changed from the last time # (all the relevant stuff is stored in .GlobalEnv$.plotting.params$.recompute.CMA.old.params (which can be NULL or not defined the first time): if( compute.cma.only ) { # Explicit computation of CMAs (not for plotting): don't alter the saved parameter values or the cached CMA: recompute.CMA <- TRUE; } else if( # if not defined at all: is.null(pp <- .GlobalEnv$.plotting.params$.recompute.CMA.old.params) || # (and cache .GlobalEnv$.plotting.params$.recompute.CMA.old.params as "pp" for later use) # otherwise check if anything meaningful has changed: # check if the data or any of its important attributed have changed: (!identical(pp$data, data) || !identical(pp$ID.colname, ID.colname) || !identical(pp$event.date.colname, event.date.colname) || !identical(pp$event.duration.colname, event.duration.colname) || !identical(pp$event.daily.dose.colname, event.daily.dose.colname) || !identical(pp$medication.class.colname, medication.class.colname) || !identical(pp$date.format, date.format) || !identical(pp$get.colnames.fnc, get.colnames.fnc) || !identical(pp$get.patients.fnc, get.patients.fnc) || !identical(pp$get.data.for.patients.fnc, get.data.for.patients.fnc)) || # check if the patients have changed: (!identical(pp$ID, ID)) || # check if the medication groups have changed: (!identical(pp$medication.groups, medication.groups)) || # check if CMA or any of their relevant parameters have changed: (!identical(pp$cma, cma) || (cma == "per episode" && # per episode specifically (!identical(pp$cma.to.apply, cma.to.apply) || !identical(pp$medication.change.means.new.treatment.episode, medication.change.means.new.treatment.episode) || !identical(pp$dosage.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode) || !identical(pp$maximum.permissible.gap.unit, maximum.permissible.gap.unit) || !identical(pp$maximum.permissible.gap.append.to.episode, maximum.permissible.gap.append.to.episode) || !identical(pp$show.event.intervals, show.event.intervals) || !identical(pp$show.overlapping.event.intervals, show.overlapping.event.intervals))) || (cma == "siding window" && # sliding window specifically (!identical(pp$cma.to.apply, cma.to.apply) || !identical(pp$sliding.window.start, sliding.window.start) || !identical(pp$sliding.window.start.unit, sliding.window.start.unit) || !identical(pp$sliding.window.duration, sliding.window.duration) || !identical(pp$sliding.window.duration.unit, sliding.window.duration.unit) || !identical(pp$sliding.window.step.duration, sliding.window.step.duration) || !identical(pp$sliding.window.step.unit, sliding.window.step.unit) || !identical(pp$sliding.window.no.steps, sliding.window.no.steps) || !identical(pp$show.event.intervals, show.event.intervals) || !identical(pp$show.overlapping.event.intervals, show.overlapping.event.intervals))) || (!identical(pp$carryover.within.obs.window, carryover.within.obs.window) || !identical(pp$carryover.into.obs.window, carryover.into.obs.window) || !identical(pp$carry.only.for.same.medication, carry.only.for.same.medication) || !identical(pp$consider.dosage.change, consider.dosage.change))) || # check if the FUW or OW have changed: (!identical(pp$followup.window.start, followup.window.start) || !identical(pp$followup.window.start.unit, followup.window.start.unit) || !identical(pp$followup.window.duration, followup.window.duration) || !identical(pp$followup.window.duration.unit, followup.window.duration.unit) || !identical(pp$observation.window.start, observation.window.start) || !identical(pp$observation.window.start.unit, observation.window.start.unit) || !identical(pp$observation.window.duration, observation.window.duration) || !identical(pp$observation.window.duration.unit, observation.window.duration.unit)) ) { # Create this structure : recompute.CMA <- TRUE; .GlobalEnv$.plotting.params$.recompute.CMA.old.params <- list( # changes to these params force the recomputation of the CMA (the CMA itself is cached in this structure as well "cached.CMA"=NULL, "cached.CMA.messages"=NULL, # the previously computed CMA and associated messages (if any) # The data: "data"=data, # Important columns in the data: "ID.colname"=ID.colname, "event.date.colname"=event.date.colname, "event.duration.colname"=event.duration.colname, "event.daily.dose.colname"=event.daily.dose.colname, "medication.class.colname"=medication.class.colname, "medication.groups"=medication.groups, # Date format: "date.format"=date.format, # The IDs and CMAs: "ID"=ID, "cma"=cma, "cma.to.apply"=cma.to.apply, # Various types medhods of computing gaps: "carryover.within.obs.window"=carryover.within.obs.window, "carryover.into.obs.window"=carryover.into.obs.window, "carry.only.for.same.medication"=carry.only.for.same.medication, "consider.dosage.change"=consider.dosage.change, # The follow-up window: "followup.window.start"=followup.window.start, "followup.window.start.unit"=followup.window.start.unit, "followup.window.duration"=followup.window.duration, "followup.window.duration.unit"=followup.window.duration.unit, # The observation window: "observation.window.start"=observation.window.start, "observation.window.start.unit"=observation.window.start.unit, "observation.window.duration"=observation.window.duration, "observation.window.duration.unit"=observation.window.duration.unit, # Treatment episodes: "medication.change.means.new.treatment.episode"=medication.change.means.new.treatment.episode, "dosage.change.means.new.treatment.episode"=dosage.change.means.new.treatment.episode, "maximum.permissible.gap.unit"=maximum.permissible.gap.unit, "maximum.permissible.gap.append.to.episode"=maximum.permissible.gap.append.to.episode, # Sliding window "sliding.window.start"=sliding.window.start, "sliding.window.start.unit"=sliding.window.start.unit, "sliding.window.duration"=sliding.window.duration, "sliding.window.duration.unit"=sliding.window.duration.unit, "sliding.window.step.duration"=sliding.window.step.duration, "sliding.window.step.unit"=sliding.window.step.unit, "sliding.window.no.steps"=sliding.window.no.steps, # Event intervals: "show.event.intervals"=show.event.intervals, "show.overlapping.event.intervals"=show.overlapping.event.intervals, # Data accessor functions: "get.colnames.fnc"=get.colnames.fnc, "get.patients.fnc"=get.patients.fnc, "get.data.for.patients.fnc"=get.data.for.patients.fnc ); pp <- .GlobalEnv$.plotting.params$.recompute.CMA.old.params; #make sure it's easier to access with a shorter name } # Preconditions (and data extraction): if( is.null(ID) || is.null(data <- get.data.for.patients.fnc(ID, data, ID.colname)) || # extract the data for these IDs nrow(data)==0 || (!is.null(medication.groups.to.plot) && length(medication.groups.to.plot) < 1) ) { if( compute.cma.only ) { AdhereR:::.report.ewms(paste0("No data for patient ",ID), "error", "plot_interactive_cma", "AdhereRViz"); } else { plot(-10:10,-10:10,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,paste0("Error: cannot display the data for patient '",ID,"'!"),col="red"); AdhereR:::.report.ewms(paste0("Error: cannot display the data for patient '",ID,"'!"), "error", "plot_interactive_cma", "AdhereRViz"); AdhereR:::plot.CMA.error(); } return (invisible(NULL)); } # Compute the CMA: if( recompute.CMA ) { cma.fnc <- switch(cma, "CMA1" = CMA1, "CMA2" = CMA2, "CMA3" = CMA3, "CMA4" = CMA4, "CMA5" = CMA5, "CMA6" = CMA6, "CMA7" = CMA7, "CMA8" = CMA8, "CMA9" = CMA9, "per episode" = CMA_per_episode, "sliding window" = CMA_sliding_window, CMA0); # by default, fall back to CMA0 # Try to catch errors and warnings for nice displaying: results <- NULL; full.results <- tryCatch( results <- cma.fnc( data, CMA=cma.to.apply, ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, medication.groups=medication.groups, date.format=date.format, carryover.within.obs.window=carryover.within.obs.window, carryover.into.obs.window=carryover.into.obs.window, carry.only.for.same.medication=carry.only.for.same.medication, consider.dosage.change=consider.dosage.change, followup.window.start=followup.window.start, followup.window.start.unit=followup.window.start.unit, followup.window.duration=followup.window.duration, followup.window.duration.unit=followup.window.duration.unit, observation.window.start=observation.window.start, observation.window.start.unit=observation.window.start.unit, observation.window.duration=observation.window.duration, observation.window.duration.unit=observation.window.duration.unit, medication.change.means.new.treatment.episode=medication.change.means.new.treatment.episode, dosage.change.means.new.treatment.episode=dosage.change.means.new.treatment.episode, maximum.permissible.gap=maximum.permissible.gap, maximum.permissible.gap.unit=maximum.permissible.gap.unit, maximum.permissible.gap.append.to.episode=maximum.permissible.gap.append.to.episode, sliding.window.start=sliding.window.start, sliding.window.start.unit=sliding.window.start.unit, sliding.window.duration=sliding.window.duration, sliding.window.duration.unit=sliding.window.duration.unit, sliding.window.step.duration=sliding.window.step.duration, sliding.window.step.unit=sliding.window.step.unit, sliding.window.no.steps=sliding.window.no.steps, return.inner.event.info=show.event.intervals, arguments.that.should.not.be.defined=NULL # avoid spurious warnings about overridden arguments ), error =function(e) return(list(results=results,error=conditionMessage(e))), warning=function(w) return(list(results=results,warning=conditionMessage(w)))); if( !compute.cma.only ) { # Cache this new cma (and the associated messages, if any): pp$cached.CMA <- results; pp$cached.CMA.messages <- full.results; } } else { # Restore these from the case: results <- pp$cached.CMA; full.results <- pp$cached.CMA.messages; } if( is.null(results) ) { if( compute.cma.only ) { warning(paste0("Error computing '",cma,"' for patient '",ID,". ", if( !is.null(full.results$error) ) paste0("Error(s): ", paste0(full.results$error,collapse="; "),". "), if( !is.null(full.results$warning) ) paste0("Warning(s): ",paste0(full.results$warning,collapse="; "),". "))); return (invisible(NULL)); } else { # Plot an error message: #plot(-10:10,-10:10,type="n",axes=FALSE,xlab="",ylab=""); #text(0,0,paste0("Error computing '",cma,"' for patient '",ID,"'\n(see console for possible warnings or errors)!"),col="red"); AdhereR:::plot.CMA.error(cma=cma, patients.to.plot=ID); if( !is.null(full.results$error) ) cat(paste0("Error(s): ",paste0(full.results$error,collapse="\n"))); if( !is.null(full.results$warning) ) cat(paste0("Warning(s): ",paste0(full.results$warning,collapse="\n"))); } } else { if( compute.cma.only ) { return (invisible(results)); } else { # Plot the results: plot(results, medication.groups.to.plot=medication.groups.to.plot, medication.groups.separator.show=medication.groups.separator.show, medication.groups.separator.lty=medication.groups.separator.lty, medication.groups.separator.lwd=medication.groups.separator.lwd, medication.groups.separator.color=medication.groups.separator.color, medication.groups.allother.label=medication.groups.allother.label, show.legend=show.legend, legend.x=legend.x, legend.y=legend.y, legend.bkg.opacity=legend.bkg.opacity, legend.cex=legend.cex, legend.cex.title=legend.cex.title, duration=duration, bw.plot=bw.plot, show.cma=show.cma, col.na=col.na, col.cats=col.cats, unspecified.category.label=unspecified.category.label, lty.event=lty.event, lwd.event=lwd.event, pch.start.event=pch.start.event, pch.end.event=pch.end.event, col.continuation=col.continuation, lty.continuation=lty.continuation, lwd.continuation=lwd.continuation, cex=cex, cex.axis=cex.axis, cex.lab=cex.lab, force.draw.text=force.draw.text, highlight.followup.window=highlight.followup.window, followup.window.col=followup.window.col, highlight.observation.window=highlight.observation.window, observation.window.col=observation.window.col, observation.window.density=observation.window.density, observation.window.angle=observation.window.angle, observation.window.opacity=observation.window.opacity, show.real.obs.window.start=show.real.obs.window.start, real.obs.window.density=real.obs.window.density, real.obs.window.angle=real.obs.window.angle, show.event.intervals=show.event.intervals, print.CMA=print.CMA, CMA.cex=CMA.cex, plot.CMA=plot.CMA, CMA.plot.ratio=CMA.plot.ratio, CMA.plot.col=CMA.plot.col, CMA.plot.border=CMA.plot.border, CMA.plot.bkg=CMA.plot.bkg, CMA.plot.text=CMA.plot.text, plot.partial.CMAs.as=plot.partial.CMAs.as, plot.partial.CMAs.as.stacked.col.bars=plot.partial.CMAs.as.stacked.col.bars, plot.partial.CMAs.as.stacked.col.border=plot.partial.CMAs.as.stacked.col.border, plot.partial.CMAs.as.stacked.col.text=plot.partial.CMAs.as.stacked.col.text, plot.partial.CMAs.as.timeseries.vspace=plot.partial.CMAs.as.timeseries.vspace, plot.partial.CMAs.as.timeseries.start.from.zero=plot.partial.CMAs.as.timeseries.start.from.zero, plot.partial.CMAs.as.timeseries.col.dot=plot.partial.CMAs.as.timeseries.col.dot, plot.partial.CMAs.as.timeseries.interval.type=plot.partial.CMAs.as.timeseries.interval.type, plot.partial.CMAs.as.timeseries.lwd.interval=plot.partial.CMAs.as.timeseries.lwd.interval, plot.partial.CMAs.as.timeseries.alpha.interval=plot.partial.CMAs.as.timeseries.alpha.interval, plot.partial.CMAs.as.timeseries.col.interval=plot.partial.CMAs.as.timeseries.col.interval, plot.partial.CMAs.as.timeseries.col.text=plot.partial.CMAs.as.timeseries.col.text, plot.partial.CMAs.as.timeseries.show.0perc=plot.partial.CMAs.as.timeseries.show.0perc, plot.partial.CMAs.as.timeseries.show.100perc=plot.partial.CMAs.as.timeseries.show.100perc, plot.partial.CMAs.as.overlapping.col.interval=plot.partial.CMAs.as.overlapping.col.interval, plot.partial.CMAs.as.overlapping.col.text=plot.partial.CMAs.as.overlapping.col.text, min.plot.size.in.characters.horiz=min.plot.size.in.characters.horiz, min.plot.size.in.characters.vert=min.plot.size.in.characters.vert, show.period=show.period, period.in.days=period.in.days, plot.CMA.as.histogram=plot.CMA.as.histogram, xlab=xlab, ylab=ylab, title=title, align.all.patients=align.all.patients, align.first.event.at.zero=align.first.event.at.zero, print.dose=print.dose, cex.dose=cex.dose, print.dose.outline.col=print.dose.outline.col, print.dose.centered=print.dose.centered, show.overlapping.event.intervals=show.overlapping.event.intervals, plot.dose=plot.dose, lwd.event.max.dose=lwd.event.max.dose, plot.dose.lwd.across.medication.classes=plot.dose.lwd.across.medication.classes ); } } } # The shiny plotting itself: .plot_interactive_cma_shiny <- function(data=NULL, # the data used to compute the CMA on ID=NULL, # the ID of the patient to be plotted (automatically taken to be the first) medication.groups.to.plot=NULL, # which medication groups to plot cma.class=c("simple","per episode","sliding window")[1], # the CMA class to plot print.full.params=FALSE, # should the parameter values for the currently plotted plot be printed? # Important columns in the data ID.colname=NA, # the name of the column containing the unique patient ID (NA = undefined) event.date.colname=NA, # the start date of the event in the date.format format (NA = undefined) event.duration.colname=NA, # the event duration in days (NA = undefined) event.daily.dose.colname=NA, # the prescribed daily dose (NA = undefined) medication.class.colname=NA, # the classes/types/groups of medication (NA = undefined) medication.groups=NULL, # definition of medication groups (NULL = undefined) # Date format: date.format=NA, # the format of the dates used in this function (NA = undefined) align.all.patients=FALSE, align.first.event.at.zero=FALSE, # should all patients be aligned? if so, place first event the horizontal 0? use.system.browser=FALSE, # by default, don't necessarily use the system browser get.colnames.fnc=function(d) names(d), get.patients.fnc=function(d, idcol) unique(d[[idcol]]), get.data.for.patients.fnc=function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ], ... ) { # pass things to shiny using the global environment (as discussed at https://github.com/rstudio/shiny/issues/440): # checks: if( !(cma.class %in% c("simple","per episode","sliding window")) ) { warning(paste0("Only know how to interactively plot 'cma.class' of type 'simple', 'per episode' and 'sliding window', but you requested '",cma.class,"': assuming 'simple'.")); cma.class <- "simple"; } # Preconditions: if( !is.null(data) ) { # certain types of data must be coerced to data.frame: if( inherits(data, "matrix") || inherits(data, "data.table") ) data <- as.data.frame(data); # make it a data.frame ## Note: the following checks do not apply anymore as we could pass, for example, a database connection!!! # if( !inherits(data, "data.frame") ) # { # stop("The 'data' must be of type 'data.frame', 'matrix', or something derived from them!\n"); # return (NULL); # } # if( nrow(data) < 1 ) # { # stop("The 'data' must have at least one row!\n"); # return (NULL); # } # the column names must exist in data: column.names <- get.colnames.fnc(data); if( is.na(ID.colname) ) { stop(paste0("Column ID.colname cannot be NA!\n")); return (NULL); } if( !is.na(ID.colname) && !(ID.colname %in% column.names) ) { stop(paste0("Column ID.colname='",ID.colname,"' must appear in the 'data'!\n")); return (NULL); } # get the patients: all.IDs <- sort(get.patients.fnc(data, ID.colname)); if( length(all.IDs) < 1 ) { stop("The 'data' must contain at least one patient!\n"); return (NULL); } if( !is.na(event.date.colname) && !(event.date.colname %in% column.names) ) { stop(paste0("Column event.date.colname='",event.date.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(event.duration.colname) && !(event.duration.colname %in% column.names) ) { stop(paste0("Column event.duration.colname='",event.duration.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(event.daily.dose.colname) && !(event.daily.dose.colname %in% column.names) ) { stop(paste0("Column event.daily.dose.colname='",event.daily.dose.colname,"' must appear in the 'data'!\n")); return (NULL); } if( !is.na(medication.class.colname) && !(medication.class.colname %in% column.names) ) { stop(paste0("Column medication.class.colname='",medication.class.colname,"' must appear in the 'data'!\n")); return (NULL); } # Check the requested ID (if any): if( is.null(ID) || is.na(ID) || !(ID %in% all.IDs) ) ID <- all.IDs[1]; } else { #stop("The 'data' cannot be empty!\n"); #return (NULL); all.IDs <- c("[not defined]"); ID <- all.IDs[1]; cma.class <- "simple"; ID.colname <- event.date.colname <- event.duration.colname <- event.daily.dose.colname <- medication.class.colname <- NA; date.format <- NA; } # put things in the global environment for shiny: .GlobalEnv$.plotting.params <- list("data"=data, "cma.class"=cma.class, "ID.colname"=ID.colname, "event.date.colname"=event.date.colname, "event.duration.colname"=event.duration.colname, "event.daily.dose.colname"=event.daily.dose.colname, "medication.class.colname"=medication.class.colname, "medication.groups"=medication.groups, "date.format"=date.format, "align.all.patients"=align.all.patients, "align.first.event.at.zero"=align.first.event.at.zero, "ID"=ID, "all.IDs"=all.IDs, "medication.groups.to.plot"=medication.groups.to.plot, "max.number.patients.to.plot"=10, "max.number.events.to.plot"=500, "max.number.patients.to.compute"=100, "max.number.events.to.compute"=5000, "max.running.time.in.minutes.to.compute"=5, ".patients.to.compute"=NULL, "print.full.params"=print.full.params, "get.colnames.fnc"=get.colnames.fnc, "get.patients.fnc"=get.patients.fnc, "get.data.for.patients.fnc"=get.data.for.patients.fnc, ".plotting.fnc"=.plotting.fnc.shiny, ".dataset.type"=if(is.null(data)) NA else c("in memory", "from file", "SQL database")[2], ".dataset.comes.from.function.arguments"=!is.null(data), ".dataset.name"=NA, ".inmemory.dataset"=NULL, ".fromfile.dataset"=NULL, ".fromfile.dataset.filetype"=NULL, ".fromfile.dataset.header"=NULL, ".fromfile.dataset.sep"=NULL, ".fromfile.dataset.quote"=NULL, ".fromfile.dataset.dec"=NULL, ".fromfile.dataset.strip.white"=NULL, ".fromfile.dataset.na.strings"=NULL, ".fromfile.dataset.sheet"=NULL, ".db.connection.tables"=NULL, ".db.connection.selected.table"=NULL, ".db.connection"=NULL, ".mg.type"=if(is.null(medication.groups)) NA else c("in memory")[1], ".mg.comes.from.function.arguments"=!is.null(medication.groups), ".mg.name"=NA, ".inmemory.mg"=NULL ); # Make sure they are deleted on exit from shiny: on.exit({ .GlobalEnv$.plotting.params <- NULL; # Clear any AdhereR errors, warning or messages, and start recording them: AdhereR:::.clear.ewms(); AdhereR:::.record.ewms(record=FALSE); }, add=TRUE); #on.exit(rm(list=c(".plotting.params"), envir=.GlobalEnv)); # Clear any AdhereR errors, warning or messages, and start recording them: AdhereR:::.clear.ewms(); AdhereR:::.record.ewms(record=TRUE); shiny.app.launcher <- system.file('interactivePlotShiny', package='AdhereRViz'); # call shiny: if( use.system.browser ) { shiny::runApp(shiny.app.launcher, launch.browser=TRUE); } else { shiny::runApp(shiny.app.launcher); } }
/scratch/gouwar.j/cran-all/cranData/AdhereRViz/R/adhererviz.R
## ---- echo=FALSE, message=FALSE, warning=FALSE, results='hide'---------------- # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ## ----eval=FALSE--------------------------------------------------------------- # plot_interactive_cma() ## ----eval=FALSE--------------------------------------------------------------- # plot_interactive_cma(data=med.events, # included sample dataset # cma.class="simple", # simple cma, defaults to CMA0 # # The important column names: # ID.colname="PATIENT_ID", # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # # The format of dates in the "DATE" column: # date.format="%m/%d/%Y"); ## ----eval=FALSE--------------------------------------------------------------- # # The R code corresponding to the currently displayed Shiny plot: # # # # Extract the data for the selected 2 patient(s) with ID(s): # # "1", "2" # # # # We denote here by DATA the data you are using in the Shiny plot. # # This was manually defined as an object of class data.frame # # (or derived from it, such a data.table) that was already in # # memory under the name 'med.events'. # # Assuming this object still exists with the same name, then: # # DATA <- med.events; # # # These data has 5 columns, and contains info for 100 patients. # # # # To allow using data from other sources than a "data.frame" # # and other similar structures (for example, from a remote SQL # # database), we use a metchanism to request the data for the # # selected patients that uses a function called # # "get.data.for.patients.fnc()" which you may have redefined # # to better suit your case (chances are, however, that you are # # using its default version appropriate to the data source); # # in any case, the following is its definition: # get.data.for.patients.fnc <- function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ] # # Try to extract the data only for the selected patient ID(s): # .data.for.selected.patients. <- get.data.for.patients.fnc( # c("1", "2"), # DATA, ### don't forget to put here your REAL DATA! ### # "PATIENT_ID" # ); # # Compute the appropriate CMA: # cma <- CMA9(data=.data.for.selected.patients., # # (please note that even if some parameters are # # not relevant for a particular CMA type, we # # nevertheless pass them as they will be ignored) # ID.colname="PATIENT_ID", # event.date.colname="DATE", # event.duration.colname="DURATION", # event.daily.dose.colname="PERDAY", # medication.class.colname="CATEGORY", # carry.only.for.same.medication=FALSE, # consider.dosage.change=FALSE, # followup.window.start=0, # followup.window.start.unit="days", # followup.window.duration=730, # followup.window.duration.unit="days", # observation.window.start=0, # observation.window.start.unit="days", # observation.window.duration=730, # observation.window.duration.unit="days", # date.format="%m/%d/%Y" # ); # # if( !is.null(cma) ) # if the CMA was computed ok # { # # Try to plot it: # plot(cma, # # (same idea as for CMA: we send arguments even if # # they aren't used in a particular case) # align.all.patients=FALSE, # align.first.event.at.zero=FALSE, # show.legend=TRUE, # legend.x="right", # legend.y="bottom", # legend.bkg.opacity=0.5, # legend.cex=0.75, # legend.cex.title=1, # duration=NA, # show.period="days", # period.in.days=90, # bw.plot=FALSE, # col.na="#D3D3D3", # unspecified.category.label="drug", # col.cats=rainbow, # lty.event="solid", # lwd.event=2, # pch.start.event=15, # pch.end.event=16, # col.continuation="#000000", # lty.continuation="dotted", # lwd.continuation=1, # cex=1, # cex.axis=1, # cex.lab=1.25, # highlight.followup.window=TRUE, # followup.window.col="#00FF00", # highlight.observation.window=TRUE, # observation.window.col="#FFFF00", # observation.window.density=35, # observation.window.angle=-30, # observation.window.opacity=0.3, # show.real.obs.window.start=TRUE, # real.obs.window.density=35, # real.obs.window.angle=30, # print.CMA=TRUE, # CMA.cex=0.5, # plot.CMA=TRUE, # CMA.plot.ratio=0.1, # CMA.plot.col="#90EE90", # CMA.plot.border="#006400", # CMA.plot.bkg="#7FFFD4", # CMA.plot.text="#006400", # plot.CMA.as.histogram=TRUE, # show.event.intervals=TRUE, # print.dose=TRUE, # print.dose.outline.col="#FFFFFF", # print.dose.centered=FALSE, # plot.dose=FALSE, # lwd.event.max.dose=8, # plot.dose.lwd.across.medication.classes=FALSE, # min.plot.size.in.characters.horiz=10, # min.plot.size.in.characters.vert=0.5 # ); # }
/scratch/gouwar.j/cran-all/cranData/AdhereRViz/inst/doc/adherer_interctive_plots.R
--- title: "AdhereR: Interactive plotting (and more) with Shiny" author: "Dan Dediu <[email protected]>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: yes toc_depth: 4 fig_caption: yes vignette: > %\VignetteEncoding{UTF-8} %\VignetteIndexEntry{AdhereR: Interactive plotting (and more) with Shiny} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` ## Introduction [`AdhereR`](https://cran.r-project.org/package=AdhereR) is an [`R`](https://www.r-project.org/) package that implements, in an open and standardized manner, various methods linked to the estimation of *adherence to treatment* from a variety of data sources and formats (please see the other vignettes in the package, by involving, for example `browseVignettes(package="AdhereR")` or by visiting the package's site on [CRAN](https://cran.r-project.org/package=AdhereR)). One of the main aims of the package is to allow users to produce high quality, publication-ready and highly customizable *graphical representations* of both the patterns in the raw data and of the various estimates of adherence. This can be normally achieved from an `R` session or script using the `plot()` function applied to an estimated `CMA` object (the raw patterns are plotted by creating a basic `CMA0` object), as detailed in the [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) vignette. However, while allowing for a very fine-grained control over the resulting plots, this requires a certain level of familiarity with `R` (loading the source data, creating the appropriate `CMA` object, invoking the `plot()` function with the desired parameters, and the export of the resulting plot in the desired format at the quality and with the other desired characteristics), on the one hand, and the process is rather cumbersome when the user wants to explore and understand the data, or to try various types of plotting in search for the optimal visualization, on the other. These reasons prompted us to develop a *fully interactive user interface* that should hide the "gory details" of data loading, `CMA` computation and `plot()` invocation under an intuitive and easy to use point-and-click interface, while allowing fast exploration and customization of the plots. However, because this interactive user interface covers a rather particular set of use cases, tends to be rather "heavy" in terms of dependencies, and may not install or run properly in some environments (e.g., headless servers or older systems), we decided to implement it in a separate package, `AdhereRViz` that extends `AdhereR` (i.e., `AdhereRViz` requires `AdhereR`, but `AdhereR` cn happily run without `AdhereRViz`). ## Overview We use [`Shiny`](https://shiny.rstudio.com/), which allows us to build a *self-contained app* that can be run locally or remotely inside a standard *web browser* (such as [Firefox](https://www.mozilla.org/en-US/firefox/), [Google Chrome](https://www.google.com/chrome/), [Safari](https://www.apple.com/lae/safari/), [Internet Explorer](https://en.wikipedia.org/wiki/Internet_Explorer), [Edge](https://www.microsoft.com/en-us/edge) or [Opera](https://www.opera.com/)) on multiple *Operating Systems* (such as [Microsoft Windows](https://www.microsoft.com/en-us/windows), Apple's [macOS]https://en.wikipedia.org/wiki/MacOS) and [iOS](https://en.wikipedia.org/wiki/IOS), Google's [Android](https://www.android.com/), and several flavors of Linux -- e.g., [Debian](https://www.debian.org/), [Ubuntu](https://ubuntu.com/), [Fedora](https://getfedora.org/en/), [RedHat](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux), [CentOS](https://www.centos.org/), [Arch](https://archlinux.org/)... -- and BSD -- e.g., [FreeBSD](https://www.freebsd.org/)) and *devices* ranging from desktop and laptop computers to mobile phones and tablets. The app's interface uses *standard controls and paradigms*, ensuring a similar user experience across browsers, platforms and devices. ## Launching the app **Locally**, the app can be launched from a normal `R` session (including from within `RStudio`) or script with a single command; of course, the latest version of `AdhereR` and `AdhereRViz` must be *installed* on the system (using, for example, `install.packages("AdhereRViz", dep=TRUE)` or `RStudio`'s *Tools* → *Install Packages...* menu; or, in case it is already installed, updated using `update.packages()` or `RStudio`'s *Tools* → *Check for Package Updates...* menu), and *loaded* in the current session (using, for example, `library(AdhereRViz)` or `require(AdhereRViz)`). With these prerequisites in order, the app can be launched without any parameters with ```{r eval=FALSE} plot_interactive_cma() ``` or, if so desired, by specifying a data source and the important column names and optionally the desired `CMA`, as in the following example, where we use `CMA0` (i.e., the raw data) from the sample dataset `med.events` (see its structure in the **Table** below) included with the `AdhereR` package: ```{r eval=FALSE} plot_interactive_cma(data=med.events, # included sample dataset cma.class="simple", # simple cma, defaults to CMA0 # The important column names: ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", # The format of dates in the "DATE" column: date.format="%m/%d/%Y"); ``` | PATIENT_ID| DATE| PERDAY| CATEGORY| DURATION| |----------:|----------:|------:|--------:|--------:| | 1|03/22/2035 | 2|medB | 30| | 1|03/31/2035 | 2|medB | 30| | 2|01/20/2036 | 4|medA | 50| | 2|03/10/2036 | 4|medA | 50| | 2|08/01/2036 | 4|medA | 50| | 2|08/01/2036 | 4|medB | 60| | 2|09/21/2036 | 4|medB | 60| | 2|01/24/2037 | 4|medB | 60| | 2|04/16/2037 | 4|medB | 60| | 2|05/08/2037 | 4|medB | 60| | 3|04/13/2042 | 4|medA | 50| Table: The structure of the sample dataset `med.events` included in the `AdhereR` package. We shows the rows 23 to 33 (out of a total of 1080 rows), each row representing one *event* which is characterized **at the minimum** by: the *patient* it refers to (identified by the patient's unique ID in column `PATIENT_ID`), the *date* it happened (in column `DATE`, recorded in a uniform format, here MM/DD/YYYY), its *duration* in days (in column `DURATION`); **optionally** we can also have info concerning the prescribed daily quantity or *dose* (column `PERDAY`) and the class or type of treatment (column `CATEGORY`). We will use this dataset throughout this vignette. The app can also be launched in the "standard way" using `runApp()` or `RStudio`'s **<span style='color: green'>▶︎</span> Run app** button. Alternatively, the app may be made available on a **remote server**, such as on <https://www.shinyapps.io/>, in which case it can be accessed simply by pointing the web browser to the app's internet address. Please note that launching the App with no parameters, opens with a different screen (see the [**Selecting/changing the *data source***](#ui-datasource) section for details). Also note that there we provide a "stub" function `plot_interactive_cma()` in the package `AdhereR`, but this simply checks if `AdhereRViz` is installed and functional, and then tries to invoke `plot_interactive_cma()` from `AdhereRViz`. ## The App's User Interface (UI) {#ui-overview} The App's UI has several main elements which can be seen below. Most UI elements have **tooltips** that show up on hovering the mouse over the element and that offer specific information (but please note that these tooltips might need some time before showing up). ![**Overview of the User Interface.** Screenshot (App is running in Firefox on macOS 10.13) of some of the main UI elements (dotted black ellipses or rectangles identified with black numbers). **1** is a button that opens a box giving information about the App. **2** is a button that exist the App cleanly (i.e., stops and disconnects the session). **3** is the main plotting area which displays the current plot. **4** shows some of the UI elements controlling the plot (element 4) size. **5** is the area where various parameters can be modified. **6** opens UI elements specific for saving the current plot to file. **7** shows the `R` code that can be used to generate the current plot. **8** gives access to UI controls that allow the computation of the current CMA for many more patients and saving the results to file. **9** displays messages, warnings or errors that might have been geenrated while constructing the current plot.](shiny-overview.jpg) ### *About* the App Clicking on the **About** button (element **1** in [the overview figure](#ui-overview)) opens a box with info about the App, such as the version of the `AdhereR` package, and overview of the package and links to where more help (such as vignettes) can be found. ### Cleanly *exiting* the App It is recommended to cleanly exit the App by clicking the **Exit...** button (element **2** in [the overview figure](#ui-overview)), as simply closing the browser will *not* normally also stop the `R` process running in the background. Please note that currently, exiting the App will not also close the browser window or tab in which the App was running... ### The *plotting area* (and the *messages*) The current plot is displayed in the UI element **3** (in [the overview figure](#ui-overview)), a *canvas* that can be re-sized using the UI elements **4** in [the overview figure](#ui-overview) (see also below) and which, when too big, can be scrolled horizontally and vertically at will. This canvas is currently *passive* in the sense that it simply displays a plot which which interaction is possible only using the other elements of the UI, but almost all aspects of this plot can be tweaked using controls from the *left-hand side vertical panel* (element **5** in [the overview figure](#ui-overview); see details below). While the interpretation of these plots should be relatively intuitive, it is nevertheless detailed in the [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) vignette. Element **9** in [the overview figure](#ui-overview) displays most of the <span style='color: blue;'>information messages</span>, <span style='color: green;'>warnings</span> and <span style='color: red;'>errors</span> generated during the plotting process (please note that currently some messages, warnings and errors might not be captured and only shown in the `R` console). For example, here, the informational message <span style='color: blue;'>Plotting patient ID '1' with CMA 'CMA9' Plotting patient ID '2' with CMA 'CMA9'</span> means that the computation and plotting of `CMA9` for patients with IDs `1` and `2` was successful. Elements **4** in [the overview figure](#ui-overview) allow the control of the horizontal and vertical dimensions of the plot **3** either coupled (i.e., keeping the current width--to-height ratio), when the **Keep ratio** switch is **ON**, or independently of each other, when the switch is **OFF** (in which case a new slider controlling the plot height appears). The interaction with the slider(s) can be done either with mouse or with the arrow keys. Please note that there is a minimum size requirement for a plot to be displayed, otherwise an error of the type <span style='color: red;'>Plotting area is too small (it must be at least 10 x 0.5 characters per event, but now it is only 31.1 x 0.5)!</span> is thrown, in which case either the plotting area needs to be increased using the **Plot width** (and, if visible, **Plot height**) slider(s), or the number of patients or the duration to be shown need to be reduced. Alternatively, the <b style='color: darkblue'>Advanced</b> section (see Section **Setting *parameters*** for details) can be used to decrease these minimum requirements (but this not recommended in most cases). ### *Saving* the current plot to file The current plot can be exported to a variety of formats by turning the **Save plot!** switch **ON**: ![**Saving the current plot to file.** A zoom-in of the new controls (element **10**) revealed by turning the **Save plot!** switch (UI element **6**) **ON**. Also visible is an explanatory *tooltip* .](shiny-saveplot.jpg) These new UI elements (**10**) allow: - the definition of the exported plot's size (*width* and *height*) - in terms of the selected *unit*, currently *in* (inches), *cm* (centimeters), *mm* (millimeters) and *px* (pixels) - the type of image, currently *jpg* (JPEG), *png* (PNG), *tiff* (TIFF), *eps* (Encapsulated Postscript) and *pdf* (PDF) -- usually TIFF and EPS are accepted for publication - at a given *resultion* in dots-per-inch (DPI) -- used only by the raster formats JPEG, PNG and TIFF (usually a minimum of 300 DPI are needed for publication). By pressing the **Save plot** button, the user can select the location and file name (relative to the local machine) under which the plot will be exported. ### Viewing, copying and using the *`R` code* that would produce the current plot While the main use scenarios for this App are built around interactivity, the user may want to generate the same (or similar) plots as the one currently displayed (in element **3** in [the overview figure](#ui-overview)). To allow this, we provide the **Show R code...** button (element **7** in [the overview figure](#ui-overview)), which opens a box with the clearly commented `R` code: ![**Viewing the `R` code that can generates the current plot.**](shiny-rcode.jpg) Clicking the **Copy to clipboard** button copies the `R` code to the clipboard, from where it can be pasted into an editor of choice (such as `RStudio`). In particular, for the plot shown in [the overview figure](#ui-overview), the `R` code displayed is: ```{r eval=FALSE} # The R code corresponding to the currently displayed Shiny plot: # # Extract the data for the selected 2 patient(s) with ID(s): # "1", "2" # # We denote here by DATA the data you are using in the Shiny plot. # This was manually defined as an object of class data.frame # (or derived from it, such a data.table) that was already in # memory under the name 'med.events'. # Assuming this object still exists with the same name, then: DATA <- med.events; # These data has 5 columns, and contains info for 100 patients. # # To allow using data from other sources than a "data.frame" # and other similar structures (for example, from a remote SQL # database), we use a metchanism to request the data for the # selected patients that uses a function called # "get.data.for.patients.fnc()" which you may have redefined # to better suit your case (chances are, however, that you are # using its default version appropriate to the data source); # in any case, the following is its definition: get.data.for.patients.fnc <- function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ] # Try to extract the data only for the selected patient ID(s): .data.for.selected.patients. <- get.data.for.patients.fnc( c("1", "2"), DATA, ### don't forget to put here your REAL DATA! ### "PATIENT_ID" ); # Compute the appropriate CMA: cma <- CMA9(data=.data.for.selected.patients., # (please note that even if some parameters are # not relevant for a particular CMA type, we # nevertheless pass them as they will be ignored) ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, followup.window.start.unit="days", followup.window.duration=730, followup.window.duration.unit="days", observation.window.start=0, observation.window.start.unit="days", observation.window.duration=730, observation.window.duration.unit="days", date.format="%m/%d/%Y" ); if( !is.null(cma) ) # if the CMA was computed ok { # Try to plot it: plot(cma, # (same idea as for CMA: we send arguments even if # they aren't used in a particular case) align.all.patients=FALSE, align.first.event.at.zero=FALSE, show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1, duration=NA, show.period="days", period.in.days=90, bw.plot=FALSE, col.na="#D3D3D3", unspecified.category.label="drug", col.cats=rainbow, lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, col.continuation="#000000", lty.continuation="dotted", lwd.continuation=1, cex=1, cex.axis=1, cex.lab=1.25, highlight.followup.window=TRUE, followup.window.col="#00FF00", highlight.observation.window=TRUE, observation.window.col="#FFFF00", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, print.CMA=TRUE, CMA.cex=0.5, plot.CMA=TRUE, CMA.plot.ratio=0.1, CMA.plot.col="#90EE90", CMA.plot.border="#006400", CMA.plot.bkg="#7FFFD4", CMA.plot.text="#006400", plot.CMA.as.histogram=TRUE, show.event.intervals=TRUE, print.dose=TRUE, print.dose.outline.col="#FFFFFF", print.dose.centered=FALSE, plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, min.plot.size.in.characters.horiz=10, min.plot.size.in.characters.vert=0.5 ); } ``` This code is pretty much ready to be run, except for some issues that might surround accessing the actual data used for plotting: the user is reminded of these through the <span style="color: yellow; background-color: red; font-weight: bold; font-style: italic;">yellow-on-red bold italic</span> highlighting of `DATA` (not shown in the code listing above). In a nutshell (for details, see below), if (a) the user interactively uses the App to load or connect to a data source (such as an external file or an SQL database), then the identity of this data source is known (the file name or the database location), but if (b) the data source was passed to the `plot_interactive_cma()` function as the `data` argument, the App cannot know how this data source was named (and this "name" might not even exist if, for example, the data was created on-the-fly while calling the `plot_interactive_cma()` function). Wickedly, even in case (a), it is generally unsafe to assume that the data source will stay the same (or will be accessible in the same way) in the future. Thus, while we provide as much info about the data source used to produce the current plot as possible, we also warn the user to be careful when running this code! ### *Computing* the CMA for several patients By switching the UI element **8** (in [the overview figure](#ui-overview)) **Compute CMA for several patients...** to **ON**, the user unlocks a new set of UI elements that allow the computation of the currently defined `CMA` for more patients and the export of the results to an external file. First, it is important to highlight that the App is *not* intended for heavy computations, which explains why we are currently limiting this CMA computation to at most **100 patients**, at most **5000 events** across all patients (if more patients or events are selected, the computation will be done for only the first 100 and 5000, respectively) and for at most **5 minutes** of running time (after which the computation is automatically stopped). If seriously heavy computation is needed, we recommend the use of the appropriate `CMA()` functions from and `R` session or script, which allow many types of parallel processing and the use of several types of data sources with very fine-grained control, as described in the vignettes [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) and [Using AdhereR with various database technologies for processing very large datasets](https://cran.r-project.org/package=AdhereR/vignettes/adherer_with_databases.pdf). The `R` code needed to compute the current CMA can be accessed through the **Show R code** button (UI element **7**). The patients for which the computation of the CMA is to be performed can be done in two main ways: a. by **individually** selecting patients by their IDs, through a multiple selection dropdown list (element **11** in the figure below): ![**Selecting patients *individually* for the computation of CMA.**](shiny-computecma-individually.jpg) b. by selecting a continuous **range** of patients using two sliders (element **15** in the figure below) which define a set of *positions* in a list (element **14** in the figure below); this list can contain the patient IDs in their original order in the data source, or can have them sorted in ascending or descending order by ID (element **13** in the figure below). ![**Selecting patients *by range* of positions in a list for the computation of CMA.** In this example, we ordered the patients descreasingly by ID (using the combobox **13**), resulting in a mapping of positions (#) to ID as shown in the list **14**, where patient with ID "100" is on psition 1, patient "99" on position 2, etc. The sliders **15** define the range of positions (#) 3 to 24, which means that we selected patients with IDs "98", "97", "96" ... "78" and "77".](shiny-computecma-range.jpg) These two ways of selecting patients should be flexible enough for cover most cases of (semi-)interactive use; for more patients and/or the selection of patients based on more complex criteria, we suggest the use of the `R` code in a script. After patients have been selected, the user can press the **Compute CMA** button (UI element **12**) to access a specialized dialog box (see figure below) where the CMA computation can be started, its progress monitored, or stopped, and from where the results can be exported to file. ![**Starting, stopping and watchin the progress of CMA computation for several patients.** The list of patients is given in UI element **16**, and the progress of the computation is tracked by theprogress bar and individual success report (UI elements **17**). The button **Save results (as TSV)** allows the user to select a file where the results will be exported as a TAB-separated CSV file.](shiny-computecma-dialog.jpg) ### Setting *parameters* The left-hand panel has two tabs: *Params* and *Data*, and we are focusing here on *Params*, which contains various parameters customizing the computed CMA and the plotting of the results. UI element **5** in [the overview figure](#ui-overview) shows part of this panel, but the following principles apply: - the top **Dataset info** button gives access to information about the current data source such as its name, type, structure and the five important columns: ![**Basic information about the current dataset.** Here, `med.events`, showing also the five important columns.](shiny-infodataset.jpg) - there are several *sections* with <b style='color: darkblue'>dark blue bold headings</b> - the contents of most of sections can be hidden (by default, marked by the "...") or visible, the two states being toggled by clicking the mouse (see the figure below), the only exception being the first section, <b style='color: darkblue'>General settings</b>, whose contents is always visible ![**Folding and unfolding the contents of a section.** The section <b style='color: darkblue'>Follow-up window (FUW)</b> with content folded (hidden) on the left, and unfolded (visible) on the right.](shiny-foldsections.jpg) - some sections may appear or disappear depending on other circumstances, such as the type of CMA selected (e.g., <b style='color: darkblue'>Define episodes</b> exists only for *CMA per episodes*) or the optional columns being defined (e.g., <b style='color: darkblue'>Show dose</b> exists only if the daily dose column was defined and only for `CMA0`, `CMA5-9`, *per episodes*, and *sliding windows*). We will now go through all sections one by one. #### <b style='color: darkblue'>General settings</b> The <b style='color: darkblue'>General settings</b> section is always visible and allows the selection of: - **CMA type**: the type of CMA to compute, which can be (please see [Dima & Dediu, 2017](#Ref-Dima2017), and the vignette [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) for more details): - **simple**: one of the "simple" CMAs, currently `CMA0` tot `CMA9`, - **per episode**: computes one of the "simple" CMAs repeatedly for each treatment episode, - **sliding window**: computes one of the "simple" CMAs repeatedly for a set of sliding windows - **CMA to compute**: the "simple" CMA to compute, either by itself (for **CMA type** == **simple**) or iteratively (for the other two "complex" types); please note that by definition `CMA0` cannot be used with "complex" CMAs (which explains why it cannot be selected in these cases) - **Patient(s) to plot**: the list of patient IDs, selected from a drop-down list (which allows multiple selections) containing all the patient IDs in the current data source (at least one patient must be selected, otherwise an error is generated) Depending on these selections the plot may change or various types of errors or warnings may be thrown. #### <b style='color: darkblue'>Follow-up window (FUW)</b> and <b style='color: darkblue'>Observation window (OW)</b> These two sections are very similar and allow the definition of the follow-up (FUW) and observation (OW) windows by specifying: - their **start**: this can be either: - the number of **units** (days, weeks, months or years) relative to the first event (for FUW) and to the start of the FUW (for OW), or - an absolute **calendar date** - and their **duration** as a number of **units** (days, weeks, months or years). #### <b style='color: darkblue'>Carry over</b> This section is shown only for `CMA5` to `CMA9` and concerns the way carry over is considered: - **For same treat.only**: only for the treatment class or across classes - **Consider dosage changes**: should dosage changes be considered when computing the carry over? #### <b style='color: darkblue'>Define episodes</b> This section is shown only for **CMA per episodes** and concerns the way treatment episodes are defined: - **Treat. change starts new episode?**: does changing the treatment class trigger a new episode? - **Dose change starts new episode?**: does changing the dose trigger a new episode? - **Max. gap duration**: the duration of a gap above which a new episode is triggered; the gap can be in units (**Max. gap duration unit**) of days, weeks, months or years, or as a percent of the last prescription - **Append gap?**: should the maximum permissible gap be added to the episodes with a gap larger than this maximum? If "no" (the default), nothing is added, if "yes" then the maximum permissible gap is appended at the end of the episodes - **Plot CMA as histogram?**: should the distribution of CMA estimates across episodes for a given participant be plotted as a histogram or as a barplot #### <b style='color: darkblue'>Define sliding windows (SW)</b> This section is shown only for **sliding windows** and concerns the way this sequence of regularly spaced and uniform sliding windows is defined: - **SW start**: when is the first sliding window starting (relative to the start of the OW) in terms of units (**SW start unit**) that can be days, weeks, months or years - how long is one such sliding window **SW duration** in terms of **SW duration unit** (days, weeks, months or years) - the step between two consecutive sliding windows can be defined either in terms of: - **SW number of steps**: the total *number of steps* (i.e., sliding windows of the given duration covering the OW), or - the *duration of a setp* (i.e., one sliding window) in terms of how many (**SW step duration**) units (**SW step unit**; days, weeks, months or years) it lasts - **Plot CMA as histogram?**: should the distribution of CMA estimates across sliding windows for a given participant be plotted as a histogram or as a barplot ![**Defining sliding windows.** Here we show 90-days sliding windows lagging by 60 days and starting right at the begining of the observation window. The regularly spaced bars at the top of the plot represent the sliding window, each with its own CMA estimate (here, `CMA9`). The histogram on the left (which can be toggled to a barplot) shows the distribution of the CMA estimates across the sliding windows.](shiny-slidingwindows.jpg) #### <b style='color: darkblue'>Align patients</b> This section is shown only if there's more than one patient selected, and controls the way the plots of several patients are displayed vertically: - **Align patients?**: should all the patients be vertically aligned relative to their first event? - **Align 1st event at 0?**: should the first event (across patients) be considered as the origin of time? ![**Vertically aligning multiple patients.** The top panel shows two patients (with IDs '1' and '15') plotted using the actual dates of their events (as difference between the earilest event and their own) versus the same two patients aligned vertically relative to each other.](shiny-alignpatients.jpg) #### <b style='color: darkblue'>Duration & period</b> This section controls the amount of temporal information displayed (on the horizontal axis): - **Duration (in days)**: the period to show (in days); this is independent of the length of the FUW, OW or the events actually displayed and can be used to zoom-in or zoom-out; if `0` it is automatically computed so as all the events in the plot are shown - **Show period as**: if "days", it displays on the horizontal axis the number of days since the first plotted event on the horizontal axis; if "dates", it displays the actual calendar dates -- **Period (in days)**: the interval (in days) at which info is shown on the horizontal axis and vertical dashed lines are drawn on the plot #### <b style='color: darkblue'>CMA estimates</b> This section is shown for all CMAs except `CMA0` and controls how the CMA estimates are to be shown on the plot: - **Print CMA?**: this is visible only for the "simple" CMAs and controls whether the CMA estimates should be shown next to the participant's ID - **Plot CMA?**: should the CMA estimate be plotted next to the participant's ID? #### <b style='color: darkblue'>Show dose</b> This section is shown only a *daily dose* column is defined for the current data source, and only for `CMA0`, `CMA5`--`CMA9`, *per episodes*, and *sliding windows* (`CMA1`--`CMA4` by definition are unaware of dose and treatment categories) and controls how the dose is visually shown (if at all): - **Print it?**: print the dosage (i.e., the actual numeric values) next to each event; if so: - **Font size**: which font size[^1] to use - **Outline color**: which outline color to use - **Centered?**: should the text be centered or not? - **As line width?**: show the dose as the event line width; if so: - **Max dose width**: what is the line width of the maximum given dose? - **Global max?**: should this maximum dose be computed across all treatment classes or per class? Please see [the overview figure](#ui-overview) for an example where the dose is printed. #### <b style='color: darkblue'>Legend</b> This section controls the visual appearance of the legend: - **Show legend?**: should the legend be shown at all; if so: - **Legend x**: the legend's horizontal position ("left" or "right") - **Legend y**: the legend's vertical position ("bottom" or "top") - **Title font size**: the legend title's font size - **Text font size**: the legend text and symbols' font size - **Legend bkg. opacity**: the legend's background opacity, between 0.0 (fully transparent) and 1.0 (fully opaque) #### <b style='color: darkblue'>Aesthetics</b> This section controls many aspects of the visual presentation of the plots, including colors, font sizes and line styles; some of these depend on other factors, so may or may not be visible: - **Grayscale?**: when **ON**, it makes the plots use only shades of gray (and hides many other controls in this section), but when **OFF**, it allows various colors to be used - **Missing data color**: the colors of missing data - **Unspec. cat. label**: the label to use for an unspecified treatment class (free text) - **Treatment palette**: shown only if the *treatment class* column was defined, allows the selection of a *color palette* from which particular colors for the actual treatment classes will be picked[^2]; currently the available palettes are: *rainbow*, *heat.colors*, *terrain.colors*, *topo.colors*, *cm.colors*, *magma*, *inferno*, *plasma*, *viridis*, *cividis* (the last two are color-blind-friendly[^3]) - **Event line style**: controls the line style for plotting the events, and can be: ![**The possible line styles** used for the event lines.](shiny-linestyles.jpg) - **Event line width**: the width of the event lines - **Event start** and **Event end**: the symbols used to mark the start and end of an event, and can be: ![**The possible point symbols** used to mark the start and the end of an event.](shiny-pointsymbols.jpg) - attributes of the continuation lines between events (only for `CMA0`, per episode, and sliding windows): **Cont. line color**, **Cont. line style** and **Cont. line width** - **Show event interv.?**: should the event intervals be shown? (only for simple CMAs except `CMA0`) - the relative font size of various elements: **General font size**, **Axis font size** and **Axis labels font size** - follow-up window visual attributes: **Show FUW?** (should we show it or not), and if yes, **FUW color**, what color to use? - observation window visual attributes: **Show OW?** (should we show it or not), and if yes, with what color (**OW color**), line density (**OW hash dens.**) and angle (**OW hash angle**) and opacity (**OW opacity**) - `CMA8` uses a "real observation window", which ca be shown or not (**Show real OW?**) and whose attributes are the line density (**Real OW hash dens**) and angle (**Real OW hash angle**) - for all CMAs (except `CMA0`), we can control various attributes of the CMA estimate: the relative font size (**CMA font size**), the percent of the plotting area dedicated to plotting it (**CMA plot area %**), its color (**CMA plot color**), border color (**CMA border color**), background color (**CMA bkg. color**) and text color (**CMA text color**) #### <b style='color: darkblue'>Advanced</b> This section controls several advanced settings: - **Min plot size (horiz.)** and **Min plot size (vert.)**: the minimum plotting size (in characters) required for the whole duration to be plotted (horizontally) and for each event/episode/sliding window (vertically) ### Selecting/changing the *data source* {#ui-datasource} If the interactive App was *started with a given data source* passed through the parameters to the `plot_interactive_cma(...)` arguments, this data source (if valid and well-defined) is automatically used, but it can be changed at any time (as described below). However, if the App was starting *without any data source* (i.e., `plot_interactive_cma()`), the user is forced to select a valid data source before being able to plot anything. The actual processes of selecting an initial data source or changing it later are identical, so we discuss here the case of no initial data source: when `plot_interactive_cma()` was invoked, the App is opened without any plotting and messaging area at all and the **Data** tab in the left-hand panel is automatically selected and the **Params** tab contains only a warning message: ![**Starting the App with no data source.** The highlighted panel on the left (UI element **18**) is now open at the **Data** tab, which allows the interactive selection of various types of data sources.](shiny-data-empty.jpg) ![**Starting the App with no data source.** The **Params** tab on the left now contains only a warning message (and no settings).](shiny-data-empty-params.jpg) The **Data** panel allows us to interactively select and change on-the-fly the data set to be used; currently, this can be: - a data set **already in memory** -- basically, an object derived from `data.frame` (this includes, thus, things such as `data.tables`) that is already in the *global environment* of the current `R` session (please see for example, [here](http://adv-r.had.co.nz/Environments.html), for details about environments, but our purposes here, this contains the "stuff" currently loaded in `R`'s memory), - data stored in a (local) **file** -- the App can handle various file format, ranging from the ubiquitous Comma-Separated Values (CSV) to Excel, OpenDocument, SPSS, Stat and SAS files (within limits), or - a live connection to an **SQL database** -- the SQL server may be local or remote and, currently, can be [SQLite](https://www.sqlite.org/index.html) or [MySQL](https://www.mysql.com/)/[MariaDB](https://mariadb.org/) (but more relational database technologies/providers can be relatively easily added). The type of data source can be done with with list **Datasource type** at the top of the **Data** panel. We will go now through each of these types of data sources in turn. #### Data **already in memory** {#ui-inmemory} This is, in some respects, the simplest type of data source. When selected, the tab looks like: ![**Selecting and *in-memory* data source.**](shiny-data-inmemory.jpg) The **In-memory dataset** UI element contains the list of all objects in the current global environment derived from `data.table` that have at last 1 row and 3 columns, and they can be selected simply by clicking on their name (here, we select the `med.events` example dataset): ![**Selecting the `med.events` example dataset.** Please note that the selection ca be done by looking through the list, or by typing the `delete`/`backspace` key (⌫) and then starting to type the name of the dataset.](shiny-data-inmemory-select-medevents.jpg) After clicking on it, the dataset is selected and optionally available for inspection using the **Peek at dataset** button: ![**Peeking at (i.e., inspecting) the *in-memory* dataset `med.events`.** This box shows basic info about the dataset, including the number of rows and columns and, for each column, its name and type, plus the first few rows.](shiny-data-inmemory-peek.jpg) If the dataset is not the desired one, it can be replaced with anything else using the interface, but, if it is the one, we can continue by selecting the important columns and the format of the dates. ![**Selecting the "important" columns -- here, the one contaning the Patient IDs -- from the *in-memory* dataset `med.events`.** Please note that the list give extra summary info about the columns in the dataset (namely, its name, type, and first few values). The App automatically maps the first three columns in the dataset to the first three required columns (**Patient ID column**, **Event date column** and **Event duration column**) but this is most probably wrong and no type checks are done at this time. The "optional" columns (**Daily dose column** and **Treatment class column** may be left undefined by selecting the *[not defined]* value. **Date format** is different, being a free text field where the format of the dates in the dates column must be defined (please see, for example [here](https://www.statmethods.net/input/dates.html), for how this format looks like).](shiny-data-inmemory-selectcolumns.jpg) Please note that, at this time, the dataset is *not* selected to be used for plotting: this is an explicit action done by pressing the **Validate & use!** button at the bottom, which does perform various checks (such as that each column is used at most once and that the types more or less fit the expected type and format, among others) and, if OK, makes this dataset the one to be used for plotting. #### **Load from file** This is a very useful case, where the data is stored in an external file. When selecting *load from file* in the **Datasource type** list, the panel becomes: ![**Loading a dataset from file.**](shiny-data-fromfile.jpg) The App supports loading data from several file formats: - **Comma/TAB-separated (.csv; .tsv; .txt)**: this is the default format and refers to a class of open and flexible file formats where tabular data is stored as rows of values separated by a pre-defined delimiter; the best known are [Comma-Separated Values (CSV)](https://en.wikipedia.org/wiki/Comma-separated_values) and [TAB-Separated Values (TSV)](https://en.wikipedia.org/wiki/Tab-separated_values) formats, but the App allows a lot of flexibility by defining: - the **Field separator** can be: the *[`TAB`]* character (\\t), the *comma* (,), one or more *whitespaces*, the *semicolon* (;) or the *colon* (:) - the individual values can be quoted (or not) using the **Quote character**: *[none]* (no quoting of values), *single quotes* (') or *double quotes* (") - the **Decimal point** character: *dot* (.) or *comma* (,) - the **Missing data symbols**: a free text listing (within double quotes and separated by commas) the symbol(s) to be interpreted as *missing data* (by default, "NA") - if the 1^st^ row of the file represents the header (containing the column names) or not (**Header 1^st^ row**) - **Serialized R object (.rds)**: this loads data (such as objects derived from `data.frame`) previously exported from `R` using `readRDS()` (usually as ".rds") - **Open Document Spreadsheet (.ods)** and **Microsoft Excel (.xls; .xlsx)** loads data from these widespread formats, used by office suites such as [LibreOffice](https://www.libreoffice.org/)/[OpenOffice](https://www.openoffice.org/)'s `Calc` and [Micrsoft Office](https://www.office.com/)'s `Excel` programs, among others; for both these formats, the user can specify the particular sheet to be loaded for files containing more than one (**Which sheet to load?**) - **SPSS (.sav; .por)**, **SAS Transport data file (.xpt)**, **SAS sas7bdat data file (.sas7bdat)** and **Stata (.dta)**: these are file formats exported by the popular statistical platforms [IBM `SPSS`](https://www.ibm.com/analytics/spss-statistics-software), [`SAS`](https://www.sas.com) and [`Stata`](https://www.stata.com/) Please note that while **Comma/TAB-separated (.csv; .tsv; .txt)**, **Serialized R object (.rds)** and **Open Document Spreadsheet (.ods)** should be imported without issues, for the others there might limitations and fringe cases. After the file format has been selected, the user can use the **Load from file** control (its **Selecte** button) to browse for the desired file and upload it. Basic checks might be performed and a file might be rejected, but if the loading was successful, a new set of UI elements becomes visible. These elements are virtually identical to those used for [in-memory datasets](#ui-inmemory). #### Use an **SQL database** This allows the access to data stored in standard [Relational Database Management Systems (RDBMS's)](https://en.wikipedia.org/wiki/Relational_database_management_system) which use the [Structured Query Language (SQL)](https://en.wikipedia.org/wiki/SQL) -- for more info about the facilities offered by `AdhereR`, please see the [Using AdhereR with various database technologies for processing very large datasets](https://cran.r-project.org/package=AdhereR/vignettes/adherer_with_databases.pdf) vignette. Currently, the App supports [`SQLite`](https://sqlite.org/index.html), a small engine designed to be embedded in larger applications and which stored the data in normal files, and [`MySQL`](https://www.mysql.com/)/[`MariaDB`](https://mariadb.org/), which are widely-used, full-featured free and open-source RDBMSs. While **SQLite** is intended only as a demo of the App's capabilities and uses an in-memory database with a single table that contains a verbatim copy of the `med.events` example dataset, **MySQL/MariaDB** allows the use of actual databases, local or over the internet. Except for the selection of the database, the UI for the two is identical, so we will only discuss here the **MySQL/MariaDB** case We can connect to a local or remote server, and we can (optionally) define the following: - **Host name/address**: the fully qualified host name or IP address of the server (if *[none]* or *localhost*, the database is stored on the local machine) - **TCP/IP port number**: the port number (*0* for default) - **Database name**: the name of the database - **Username** and **Password**: the username and password for accessing the database (the password is hidden using *) ![**Inputting the info needed to connect to a remote MySQL server.** We use here a MySQL database contaning the `med.events` sample dataset hosted on the internet.](shiny-data-sql-mysql.jpg) When clicking the **Connect!** button, the App attempts to connect the server, authenticate and access the desired database: if everything's OK, it fetches basic information over all the tables/views in the database (avoiding thus unnecessary traffic) and displays it: ![**Basic information about an SQL database.** This shows, for each table/view in the database, the columns with their name, type and first few values. The same info is accessible by clicking on the **Peek at database...** button.](shiny-data-sql-mysql-peek.jpg) New UI elements become visible, most being virtually identical to those used for loading from file and [in-memory datasets](#ui-inmemory), but the specific ones being: - the **Disconnect!** button; this disconnects from the database cleanly (not required by nice to do) - **Which table/view** lists the tables and views in the database, also showing for each the number of rows and columns ![**UI elements for using an SQL database.**](shiny-data-sql-mysql-columns.jpg) For example, when using the `MySQL` database described in the vignette [*Using AdhereR with various database technologies for processing very large datasets*](https://CRAN.R-project.org/package=AdhereR/vignettes/AdhereR-overview.html) in package `AdhereR`, we can create, for example, a `view` (named `testview`) that brings together these data in the needed format with the following `SQL` commands in `MySQL Workbench`: ```{sql eval=FALSE} USE med_events; CREATE VIEW `testview` AS SELECT patients.`id`, `date`, `category`, `duration`, `perday` FROM event_date JOIN event_info ON event_info.`id` = event_date.`id` JOIN event_patients ON event_patients.`id` = event_info.`id` JOIN patients ON patients.`id` = event_patients.`patient_id`; ``` ### Defining and using *medication groups* {#ui-medicationgroups} Since `AdhereRViz` version 0.2/`AdhereR` version 0.7, *medication groups* can be defined and used for interactive plotting. For ore details about medication groups, please see the vignette "AdhereR: Adherence to Medications" in package `AdhereR`, but, fundamentally, they are named vectors of characters where the names are the unique names of groups of medication defined using `R`-like expressions that describe with of the events in the dataset are covered by a given medication group. Alternatively, one can use a *column* in the data itself to define the medication groups. Medication groups can be passed with the `medication.groups` argument to the `plot_interactive_cma()` function, or can be interactively loaded through a new panel `Groups` of the user interface (please note that a valid dataset must have already been loaded): ![**Loading medication groups.** The **Groups** tab allows the interactive selection of medication groups from already defined named character (or factor) vectors in memory (here, the pre-defined example `med.groups` from the `AdhereR` package). The switch allows us to instantly ignore or apply any medication groups that may have been defined.](shiny-groups-panel-1.jpg) ![**Inspecting medication groups.** Clicking on the "Check it!" button in the **Groups** tab allows the inspection of the currently selected vector contaning medication group definitions (here, the pre-defined example `med.groups` from the `AdhereR` package).](shiny-groups-panel-2.jpg) Pressing the "Use it!" button load the selected medication group definitions; please make sure they are correct and fit the currently loaded dataset! If the loading goes well, the plotting is automatically updated to reflect the medication groups: ![**Plotting medication groups.** `CMA1` for patients "1" and "2" in the example dataset `med.events.ATC` using the example medication groups `med.groups` from the `AdhereR` package.](shiny-medgroups-plot.jpg) The main differences to a plot without medication groups are: - any given patient may be "split" into several medication groups (here, patient "1" is split into "1 [NoVita]" and "1 [VitaResp]") - only those medication groups that have at least one event are shown, and only those patients with at least one medication group with at least one event are shown, - the medication groups belonging to a patient may be shown grouped using thick blue lines (but this can be changed at will). These apply not only to simple CMAs, but also to sliding windows and per episode (not shown). Various options related to plotting the medication groups can be changed in the using the new "Medication groups" user interface, probably the most important being the medication groups to be included in the plot: ![**Selecting which of the defined medication groups to plot.** We may plot only a subset of all the defined medication groups, including the implicitly defined `__ALL_OTHERS__` (here shown as "* (all others)*) that includes all events not selected by any of the explicitely defined groups. Don't forget to press the "Show them!" button to apply your changes.](shiny-medgroups-select.jpg) ## References <a name="Ref-Dima2017"></a>Dima A.L., Dediu D. (2017) [Computation of adherence to medication and visualization of medication histories in R with *AdhereR*: Towards transparent and reproducible use of electronic healthcare data](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0174426). *PLoS ONE* **12**(4): e0174426. [doi:10.1371/journal.pone.0174426](https://doi.org/10.1371/journal.pone.0174426). ## Notes [^1]: Please note that all font sizes are *relative*. Thus a font size of `1.0` means the default font size used for the plot (depending on resolution, etc.), while a value of `0.50` means half that and `1.25` means 25% bigger. [^2]: We have decided against directly mapping each class to a particular color and, instead, automatically mapping them using a palette, because this accommodates more flexibly a varying number (or grouping) of classes; the mapping classes → colors is based on the *alphabetic order* of the class names. [^3]: See for example [here](https://cran.r-project.org/package=viridis/vignettes/intro-to-viridis.html) for a comparison and discussion. <!-- Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format: --> <!-- - Never uses retina figures --> <!-- - Has a smaller default figure size --> <!-- - Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style --> <!-- ## Vignette Info --> <!-- Note the various macros within the `vignette` section of the metadata block above. These are required in order to instruct R how to build the vignette. Note that you should change the `title` field and the `\VignetteIndexEntry` to match the title of your vignette. --> <!-- ## Styles --> <!-- The `html_vignette` template includes a basic CSS theme. To override this theme you can specify your own CSS in the document metadata as follows: --> <!-- output: --> <!-- rmarkdown::html_vignette: --> <!-- css: mystyles.css --> <!-- ## More Examples --> <!-- You can write math expressions, e.g. $Y = X\beta + \epsilon$, footnotes^[A footnote here.] --> <!-- Also a quote using `>`: --> <!-- > "He who gives up [code] safety for [code] speed deserves neither." --> <!-- ([via](https://twitter.com/hadleywickham/status/504368538874703872)) -->
/scratch/gouwar.j/cran-all/cranData/AdhereRViz/inst/doc/adherer_interctive_plots.Rmd
############################################################################################### # # AdhereRViz: interactive visualisations for AdhereR. # This implements interactive plotting using shiny. # Copyright (C) 2018-2019 Dan Dediu, Alexandra Dima & Samuel Allemann # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################################### # Imports ---- #library(shiny) #' @import AdhereR #' @import AdhereRViz #' @import shiny #' @import colourpicker #' @import viridisLite #' @import highlight #' @import clipr #' @import shinyjs #' @import shinyWidgets #' @import knitr #' @import readODS #' @import readxl #' @import haven #' @import DBI #' @import RMariaDB #' @import RSQLite NULL # Symbols for lines and dots as images ---- line.types <- c("blank" ="symbols/lty-blank.png", "solid" ="symbols/lty-solid.png", "dashed" ="symbols/lty-dashed.png", "dotted" ="symbols/lty-dotted.png", "dotdash" ="symbols/lty-dotdash.png", "longdash"="symbols/lty-longdash.png", "twodash" ="symbols/lty-twodash.png"); point.types <- c("plus"=3, "times"=4, "star"=8, "square"=0, "circle"=1, "triangle"=2, "down triangle"=6, "diamond"=5, "fill square"=15, "fill small circle"=20, "fill med circle"=16, "fill big circle"=19, "fill triangle"=17, "fill diamond"=18, "square plus"=12, "square times"=7, "circle plus"=10, "circle times"=13, "two triangles"=11); # Define UI for app that draws a histogram ---- ui <- fluidPage( # JavaScript ---- shinyjs::useShinyjs(), shinyjs::extendShinyjs(text="shinyjs.scroll_cma_compute_log = function() {var x = document.getElementById('cma_computation_progress_log_container'); x.scrollTop = x.scrollHeight;}", #functions=c("shinyjs.scroll_cma_compute_log")), functions=c("scroll_cma_compute_log")), #shinyjs::extendShinyjs(text="shinyjs.show_hide_sections = function() {$('#follow_up_folding_bits').toggle();"), # APP TITLE ---- #titlePanel(windowTitle="AdhereR: Interactive plotting using Shiny..."), list(tags$head(HTML('<link rel="icon", href="adherer-logo.png", type="image/png" />'))), div(style="padding: 1px 0px; width: '100%'", titlePanel(title="", windowTitle="AdhereR: Shiny plot...")), fluidRow( # LOGO & ABOUT ---- column(12, div( img(src='adherer-logo.png', align = "left", style="font-size: x-large; font-weight: bold; height: 2em; vertical-align: baseline;"), div(style="width: 3em; display: inline-block; "), #h1("interactive plots with Shiny...", style="color:DarkBlue; font-size: x-large; font-weight: bold; margin: 0; display: inline-block;"), div(title="About AdhereR and AdhereRViz, and links to more info online and offline...", actionButton(inputId="about_button", label=strong("About"), icon=icon("question-sign", lib="glyphicon"), style="color: #3498db; border: none; background: none;"), style="float: right;") ), hr() ), #shinythemes::themeSelector(), # SIDEBAR PANEL ---- column(3, # PARAMS TAB ---- shinyjs::hidden(div(id="sidebar_tabpanel_container", # start with these hidden... tabsetPanel(id="sidebar-tabpanel", selected=ifelse(!is.null(.GlobalEnv$.plotting.params$data), "sidebar-params-tab", "sidebar-params-data"), tabPanel(span("Params", title="See the plot and adjust various parameters (type of CMA, patients, etc.)"), value="sidebar-params-tab", icon=icon("wrench", lib="glyphicon"), fluid=TRUE, conditionalPanel( condition="!(output.is_dataset_defined)", wellPanel(id = "tPanelnodataset", style = "overflow:scroll; max-height: 90vh;", div(h4("No datasource!"), style="color:DarkRed"), br(), div(span(span("There is no valid source of data defined (probably because the interactive Shiny plotting was invoked without passing a dataset).")), style="color: red;"), hr(), div(span("Please use the "), span(icon("hdd",lib="glyphicon"),strong("Data"), style="color: darkblue"), span(" tab to select a valid datesource!")) ) ), conditionalPanel( condition="(output.is_dataset_defined)", wellPanel(id = "tPanel", style = "overflow:scroll; max-height: 90vh;", # Dataset info ---- div(title="Info about the currently used dataset...", actionButton(inputId="about_dataset_button", label=strong("Dataset info..."), icon=icon("hdd", lib="glyphicon"), style="color: #3498db; border: none; background: none;")), # General settings ---- div(id='general_settings_section', style="cursor: pointer;", span(title='General setting that apply to all kinds of plots', # trick for adding tooltips: create a container div with the title the desired tootltip text... id = "general_settings", h4("General settings"), style="color:DarkBlue"), shinyjs::hidden(div(title='Click to unfold...', id="general_settings_unfold_icon", icon("option-horizontal", lib="glyphicon")))), div(id="general_settings_contents", # Select the CMA class ---- div(title='Select the type of CMA to plot: "simple", "per eipsode" or "sliding window"', selectInput(inputId="cma_class", label="CMA type", choices=c("simple", "per episode", "sliding window"), selected=.GlobalEnv$.plotting.params$cma.class)), # Select the simple CMA to compute conditionalPanel( condition = "(input.cma_class == 'simple')", div(title='The "simple" CMA to compute by itself', selectInput(inputId="cma_to_compute", label="CMA to compute", choices=paste0("CMA",0:9), selected="CMA0")) ), conditionalPanel( condition = "(input.cma_class != 'simple')", div(title='The "simple" CMA to compute for each episode/sliding window', selectInput(inputId="cma_to_compute_within_complex", label="CMA to compute", choices=paste0("CMA",1:9), selected="CMA1")) ), # Select the patients to plot ---- div(title='Select one (or more, by repeatedly selecting) patient(s) to plot', selectInput(inputId="patient", label="Patient(s) to plot", choices=.GlobalEnv$.plotting.params$all.IDs, selected=.GlobalEnv$.plotting.params$ID, multiple=TRUE)), hr() ), # Medication groups to plot ---- conditionalPanel( condition="(output.is_mg_defined && input.mg_use_medication_groups)", div(id='mg_section', style="cursor: pointer;", div(title='Chose which medication groups to plot', h4(id="medication_groups", "Medication groups"), style="color:DarkBlue;"), div(title='Click to unfold...', id="mg_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="mg_contents", # View the current medication groups definitions: conditionalPanel( condition="(input.mg_definitions_source == 'named vector')", div(title="Click here to view the medication groups...", actionButton("mg_view_button", label="View definitions!", icon=icon("eye-open", lib="glyphicon"))) ), # List the medication groups to show: div(title='Please select all the medication groups that should be plotted!', shinyWidgets::pickerInput(inputId="mg_to_plot_list", label="Groups to plot:", choices=c(names(.GlobalEnv$.plotting.params$medication.groups), "* (all others)"), #choices="<none>", options=list(`actions-box`=TRUE, `select-all-text` ="<b>ALL</b>", `deselect-all-text`="<b>NONE</b>"), multiple = TRUE, selected=c(names(.GlobalEnv$.plotting.params$medication.groups), "* (all others)"))), #selected="<none>")), conditionalPanel( condition="(input.mg_to_plot_list.length > 0)", div(title='Apply the selected medication groups!', actionButton(inputId="mg_plot_apply_button", label=strong("Show them!"), icon=icon("sunglasses", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="float: center;") ), hr(), div(title='Visually group the medication groups by patient?', shinyWidgets::materialSwitch(inputId="mg_plot_by_patient", label="Visually group by patient?", value=TRUE, status="primary", right=TRUE)), hr() )) ), # Follow-up window ---- div(id='follow_up_section', style="cursor: pointer;", div(title='Define the follow-up window (shortened to FUW)', h4(id="followup_window", "Follow-up window (FUW)"), style="color:DarkBlue;"), div(title='Click to unfold...', id="follow_up_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="follow_up_contents", # Follow-up window start div(title='The unit of the start of the follow-up window (can be "days", "weeks", "months", "years" or an actual "calendar date")', selectInput(inputId="followup_window_start_unit", label="FUW start unit", choices=c("days", "weeks", "months", "years", "calendar date"), # "column in dataset"), selected="days")), # If follow-up window unit is "calendar date" conditionalPanel( condition = "(input.followup_window_start_unit == 'calendar date')", # Select an actual date div(title='Select the actual start date of the follow-up window (possibly using a calendar widget in the format year-month-day)', dateInput(inputId="followup_window_start_date", label="FUW start", value=NULL, format="yyyy-mm-dd", startview="month", weekstart=1)) ), ## If follow-up window unit is "column in dataset" #conditionalPanel( # condition = "(input.followup_window_start_unit == 'column in dataset')", # selectInput(inputId="followup_window_start_column", # label="Follow-up wnd. start", # choices=names(.GlobalEnv$.plotting.params$data), # selected="") #), # If follow-up window unit is regular unit conditionalPanel( condition = "(input.followup_window_start_unit != 'calendar date')", # && input.followup_window_start_unit != 'column in dataset')", # Select the number of units div(title='Select the number of units defining the start of the follow-up window', numericInput(inputId="followup_window_start_no_units", label="FUW start", value=0, min=0, max=NA, step=30)) ), # Follow-up window duration div(title='The unit of the duration of the follow-up window (can be "days", "weeks", "months" or "years")', selectInput(inputId="followup_window_duration_unit", label="FUW duration unit", choices=c("days", "weeks", "months", "years"), selected="days")), # Select the number of units div(title='Select the number of units defining the duration of the follow-up window', numericInput(inputId="followup_window_duration", label="FUW duration", value=2*365, min=0, max=NA, step=30)), hr() )), # Observation window ---- div(id='observation_section', style="cursor: pointer;", span(title='Define the observation window (shortened to OW)', id="observation_window", h4("Observation window (OW)"), style="color:DarkBlue"), div(title='Click to unfold...', id="observation_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="observation_contents", # Observation window start div(title='The unit of the start of the observation window (can be "days", "weeks", "months", "years" or an actual "calendar date")', selectInput(inputId="observation_window_start_unit", label="OW start unit", choices=c("days", "weeks", "months", "years", "calendar date"), selected="days")), # If observation window unit is "calendar date" conditionalPanel( condition = "(input.observation_window_start_unit == 'calendar date')", # Select an actual date div(title='Select the actual start date of the observation window (possibly using a calendar widget in the format year-month-day)', dateInput(inputId="observation_window_start_date", label="OW start", value=NULL, format="yyyy-mm-dd", startview="month", weekstart=1)) ), # If observation window unit is not "calendar date" conditionalPanel( condition = "(input.observation_window_start_unit != 'calendar date')", # Select the number of units div(title='Select the number of units defining the start of the observation window', numericInput(inputId="observation_window_start_no_units", label="OW start", value=0, min=0, max=NA, step=30)) ), # Observation window duration div(title='The unit of the duration of the observation window (can be "days", "weeks", "months" or "years")', selectInput(inputId="observation_window_duration_unit", label="OW duration unit", choices=c("days", "weeks", "months", "years"), selected="days")), # Select the number of units div(title='Select the number of units defining the duration of the observation window', numericInput(inputId="observation_window_duration", label="OW duration", value=2*365, min=0, max=NA, step=30)), hr() )), # CMA5+ only ---- # carry_only_for_same_medication, consider_dosage_change conditionalPanel( condition = "((input.cma_class == 'simple' && (input.cma_to_compute == 'CMA5' || input.cma_to_compute == 'CMA6' || input.cma_to_compute == 'CMA7' || input.cma_to_compute == 'CMA8' || input.cma_to_compute == 'CMA9')) || (input.cma_class != 'simple' && (input.cma_to_compute_within_complex == 'CMA5' || input.cma_to_compute_within_complex == 'CMA6' || input.cma_to_compute_within_complex == 'CMA7' || input.cma_to_compute_within_complex == 'CMA8' || input.cma_to_compute_within_complex == 'CMA9')))", div(id='cma_plus_section', style="cursor: pointer;", span(title='What type of carry over to consider?', h4("Carry over"), style="color:DarkBlue"), div(title='Click to unfold...', id="cma_plus_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="cma_plus_contents", # Carry-over for same treat only? div(title='Carry over only across treatments of the same type?', shinyWidgets::materialSwitch(inputId="carry_only_for_same_medication", label="For same treat. only?", value=FALSE, status="primary", right=TRUE)), # Consider dosage changes? div(title='Consider dosage change when computing the carry over?', shinyWidgets::materialSwitch(inputId="consider_dosage_change", label="Consider dose changes?", value=FALSE, status="primary", right=TRUE)), hr() )) ), # Per episode only ---- conditionalPanel( condition = "(input.cma_class == 'per episode')", div(id='episodes_section', style="cursor: pointer;", span(title='Parameters defining treatment episodes', h4("Define episodes"), style="color:DarkBlue"), div(title='Click to unfold...', id="episodes_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="episodes_contents", # Does treat. change start new episode? conditionalPanel( condition="output.is_treat_class_defined", div(title='Does changing the treatment type trigger a new episode?', shinyWidgets::materialSwitch(inputId="medication_change_means_new_treatment_episode", label="Treat. change starts new episode?", value=FALSE, status="primary", right=TRUE)) ), # Does dosage change start new episode? conditionalPanel( condition="output.is_dose_defined", div(title='Does changing the dose trigger a new episode?', shinyWidgets::materialSwitch(inputId="dosage_change_means_new_treatment_episode", label="Dose change starts new episode?", value=FALSE, status="primary", right=TRUE)) ), # Max. permis. gap duration unit div(title='The unit of the maximum permissible gap after which a new episode is triggered: either absolute ("days", "weeks", "months" or "years") or relative ("percent")', selectInput(inputId="maximum_permissible_gap_unit", label="Max. gap duration unit", choices=c("days", "weeks", "months", "years", "percent"), selected="days")), # Max. permissible gap div(title='The maximum permissible gap after which a new episode is triggered (in the above-selected units)', numericInput(inputId="maximum_permissible_gap", label="Max. gap duration", value=0, min=0, max=NA, step=1)), # Append max gap duration? div(title='Append the maximum permissible gap to the episodes?', shinyWidgets::materialSwitch(inputId="maximum_permissible_gap_append", label="Append gap?", value=FALSE, status="primary", right=TRUE)), # Plot CMA as histogram div(title='Show the distribution of estimated CMAs across episodes as a histogram or barplot?', shinyWidgets::materialSwitch(inputId="plot_CMA_as_histogram_episodes", label="Plot CMA as histogram?", value=FALSE, status="primary", right=TRUE)), hr() )) ), # Sliding window only ---- conditionalPanel( condition = "(input.cma_class == 'sliding window')", div(id='sliding_windows_section', style="cursor: pointer;", span(title='Parameters defining the sliding windows (shortened to SW))', h4("Define sliding windows (SW)"), style="color:DarkBlue"), div(title='Click to unfold...', id="sliding_windows_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="sliding_windows_contents", # Sliding window start div(title='The unit of the start of the sliding windows ("days", "weeks", "months" or "years")', selectInput(inputId="sliding_window_start_unit", label="SW start unit", choices=c("days", "weeks", "months", "years"), selected="days")), # Select the number of units div(title='Select the number of units defining the start of the sliding windows', numericInput(inputId="sliding_window_start", label="SW start", value=0, min=0, max=NA, step=30)), # Sliding window duration div(title='The unit of the duration of the sliding windows ("days", "weeks", "months" or "years")', selectInput(inputId="sliding_window_duration_unit", label="SW duration unit", choices=c("days", "weeks", "months", "years"), selected="days")), # Select the number of units div(title='Select the number of units defining the duration of the sliding windows', numericInput(inputId="sliding_window_duration", label="SW duration", value=90, min=0, max=NA, step=30)), # Steps choice div(title='How is the step of the sliding windows defined: by giving their number or their duration?', selectInput(inputId="sliding_window_step_choice", label="Define SW steps by", choices=c("number of steps", "duration of a step"), selected="the duration of a step")), # Sliding window steps conditionalPanel( condition = "(input.sliding_window_step_choice == 'duration of a step')", div(title='The unit of the sliding windows step duration ("days", "weeks", "months" or "years")', selectInput(inputId="sliding_window_step_unit", label="SW step unit", choices=c("days", "weeks", "months", "years"), selected="days")), div(title='The sliding windows duration (in the units selected above)', numericInput(inputId="sliding_window_step_duration", label="SW step duration", value=60, min=0, max=NA, step=7)) ), conditionalPanel( condition = "(input.sliding_window_step_choice == 'number of steps')", div(title='The number of sliding windows steps', numericInput(inputId="sliding_window_no_steps", label="SW number of steps", value=10, min=0, max=NA, step=1)) ), # Plot CMA as histogram div(title='Show the distribution of estimated CMAs across sliding windows as a histogram or barplot?', shinyWidgets::materialSwitch(inputId="plot_CMA_as_histogram_sliding_window", label="Plot CMA as histogram?", value=TRUE, status="primary", right=TRUE)), hr() )) ), # Align all patients ---- conditionalPanel( condition="(input.patient.length > 1)", div(id='align_section', style="cursor: pointer;", span(title='Align patients for clearer plots?', h4("Align patients"), style="color:DarkBlue"), div(title='Click to unfold...', id="align_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="align_contents", div(title='Should all the patients be vertically aligned relative to their first event?', shinyWidgets::materialSwitch(inputId="plot_align_all_patients", label="Align patients?", value=FALSE, status="primary", right=TRUE)), # Align al patients conditionalPanel( condition="input.plot_align_all_patients", div(title='Should the first event (across patients) be considered as the origin of time?', shinyWidgets::materialSwitch(inputId="plot_align_first_event_at_zero", label="Align 1st event at 0?", value=FALSE, status="primary", right=TRUE)) ), hr() )) ), # Duration and period ---- div(id='duration_period_section', style="cursor: pointer;", span(title='Duration and period', h4("Duration & period"), style="color:DarkBlue"), div(title='Click to unfold...', id="duration_period_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="duration_period_contents", # Duration: div(title='The duration to plot (in days), or 0 to determine it from the data', numericInput(inputId="duration", label="Duration (in days)", value=0, min=0, max=NA, step=90)), # Period: conditionalPanel( condition="(input.patient.length > 1) && input.plot_align_all_patients", div(title='Draw vertical grid at regular interval as days since the earliest date', selectInput(inputId="show_period_align_patients", label="Show period as", choices=c("days"), # only days are possible when aligning the patients selected="days")) ), conditionalPanel( condition="!((input.patient.length > 1) && input.plot_align_all_patients)", # ELSE div(title='Draw vertical grid at regular interval as days since the earliest date or as actual dates?', selectInput(inputId="show_period", label="Show period as", choices=c("days", "dates"), selected="days")) ), div(title='The interval (in days) at which to draw the vertical grid (or 0 for no grid)', numericInput(inputId="period_in_days", label="Period (in days)", value=90, min=0, max=NA, step=30)), hr() )), # CMA estimate ---- conditionalPanel( condition="(input.cma_class == 'per episode') || (input.cma_class == 'sliding window') || (input.cma_class == 'simple' && input.cma_to_compute != 'CMA0')", div(id='cma_estimate_section', style="cursor: pointer;", span(title='How to show the CMA estimates', h4("CMA estimates"), style="color:DarkBlue"), div(title='Click to unfold...', id="cma_estimate_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="cma_estimate_contents", conditionalPanel( condition="input.cma_class == 'simple'", div(title='Print the CMA estimate next to the participant\'s ID?', shinyWidgets::materialSwitch(inputId="print_cma", label="Print CMA?", value=TRUE, status="primary", right=TRUE)) ), div(title='Plot the CMA estimate next to the participant\'s ID?', shinyWidgets::materialSwitch(inputId="plot_cma", label="Plot CMA?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_class != 'simple'", div(title='Show the "partial" CMA estimates as stacked bars?', shinyWidgets::materialSwitch(inputId="plot_cma_stacked", label="... as stacked bars?", value=TRUE, status="primary", right=TRUE)), div(title='Show the "partial" CMA estimates as overlapping segments?', shinyWidgets::materialSwitch(inputId="plot_cma_overlapping", label="... as overlapping lines?", value=FALSE, status="primary", right=TRUE)), div(title='Show the "partial" CMA estimates as time series?', shinyWidgets::materialSwitch(inputId="plot_cma_timeseries", label="... as time series?", value=FALSE, status="primary", right=TRUE)) ), hr() )) ), # Dose ---- conditionalPanel( condition="output.is_dose_defined && (input.cma_class == 'per episode' || input.cma_class == 'sliding window' || (input.cma_class == 'simple' && (input.cma_to_compute == 'CMA0' || input.cma_to_compute == 'CMA5' || input.cma_to_compute == 'CMA6' || input.cma_to_compute == 'CMA7' || input.cma_to_compute == 'CMA8' || input.cma_to_compute == 'CMA9')))", div(id='dose_section', style="cursor: pointer;", span(title='Show dose', h4("Show dose"), style="color:DarkBlue"), div(title='Click to unfold...', id="dose_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="dose_contents", # Print dose? div(title='Print the dosage (i.e., the actual numeric values)?', shinyWidgets::materialSwitch(inputId="print_dose", label="Print it?", value=FALSE, status="primary", right=TRUE)), # Print dose attributes conditionalPanel( condition="input.print_dose", div(title='Relative font size (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="cex_dose", label="Font size", value=0.75, min=0.0, max=NA, step=0.25)), div(title='Dose text outline color', colourpicker::colourInput(inputId="print_dose_outline_col", label="Outline color", value="white")), div(title='Print the dose centered on the event?', shinyWidgets::materialSwitch(inputId="print_dose_centered", label="Centered?", value=FALSE, status="primary", right=TRUE)), hr() ), # Plot dose? div(title='Represent the dose as event line width?', shinyWidgets::materialSwitch(inputId="plot_dose", label="As line width?", value=FALSE, status="primary", right=TRUE)), # Plot dose attributes conditionalPanel( condition="input.plot_dose", div(title='What line width corresponds to the maximum dose?', numericInput(inputId="lwd_event_max_dose", label="Max dose width", value=8, min=1, max=NA, step=1)), div(title='Consider maximum dose globally or per each medication class separately?', shinyWidgets::materialSwitch(inputId="plot_dose_lwd_across_medication_classes", label="Global max?", value=FALSE, status="primary", right=TRUE)) ), hr() )) ), # Legend ---- div(id='legend_section', style="cursor: pointer;", span(title='The legend', h4("Legend"), style="color:DarkBlue"), div(title='Click to unfold...', id="legend_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="legend_contents", # Show legend? div(title='Display the plot legend?', shinyWidgets::materialSwitch(inputId="show_legend", label="Show legend?", value=TRUE, status="primary", right=TRUE)), # Legend attributes conditionalPanel( condition="input.show_legend", div(title='The legend\'s x position', selectInput(inputId="legend_x", label="Legend x", choices=c("left", "right"), selected="right")), div(title='The legend\'s y position', selectInput(inputId="legend_y", label="Legend y", choices=c("bottom", "top"), selected="bottom")), div(title='Relative font size of legend title (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="legend_cex_title", label="Title font size", value=1.0, min=0.0, max=NA, step=0.25)), div(title='Relative font size of legend text and symbols (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="legend_cex", label="Text font size", value=0.75, min=0.0, max=NA, step=0.25)), div(title='The legend\'s background opacity (between 0.0=fully transparent and 1.0=fully opaque)', sliderInput(inputId="legend_bkg_opacity", label="Legend bkg. opacity", min=0.0, max=1.0, value=0.5, step=0.1, round=TRUE)) ), hr() )), # Aesthetics ---- div(id='aesthetics_section', style="cursor: pointer;", span(title='Colors, fonts, line style...', h4("Aesthetics"), style="color:DarkBlue"), div(title='Click to unfold...', id="aesthetics_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="aesthetics_contents", ## Show CMA type in the title? #div(title='Show CMA type in the plot title?', # checkboxInput(inputId="show_cma", # label="Show CMA in title?", # value=TRUE)), div(title='Colors or grayscale?', span(p("Color or grayscale"), style="color:RoyalBlue; font-weight: bold;")), # Draw grayscale? div(title='Draw using only grayscales? (overrides everything else)', shinyWidgets::materialSwitch(inputId="bw_plot", label="Grayscale?", value=FALSE, status="primary", right=TRUE)), hr(), conditionalPanel( condition="!(input.bw_plot)", div(title='Colors for catgories of treatment', span(p("Treatment colors"), style="color:RoyalBlue; font-weight: bold;")), # Colors for categories: div(title='The color for missing data', colourpicker::colourInput(inputId="col_na", label="Missing data color", value="lightgray")), # Unspecified category name: div(title='The label of the unspecified (generic) treatment category', textInput(inputId="unspecified_category_label", label="Unspec. cat. label", value="drug")), # The colour palette for treatment types: conditionalPanel( condition="output.is_treat_class_defined", div(title='Color palette for mapping treatment categories to colors (the last two are colour-blind-friendly and provided by ).\nPlease see R\'s help for more info about each palette (first 5 are provided by the standard library, and the last 5 are in package "viridisLight").\nThe mapping is done automatically based on the alphabetic ordering of the category names.', selectInput(inputId="col_cats", label="Treatment palette", choices=c("rainbow", "heat.colors", "terrain.colors", "topo.colors", "cm.colors", "magma", "inferno", "plasma", "viridis", "cividis"), selected="rainbow")) ), hr() ), div(title='Event visual attributes', span(p("Events"), style="color:RoyalBlue; font-weight: bold;")), # Event style: div(title='Event line style', #selectInput(inputId="lty_event", # using UNICODE character # label="Event line style", # choices=c("\U00A0\U00A0\U00A0\U00A0\U00A0 blank"="blank", # "\U2E3B solid"="solid", # "\U2012\U2009\U2012\U2009\U2012\U2009\U2012 dashed"="dashed", # "\U00B7\U00B7\U00B7\U00B7\U00B7\U00B7\U00B7 dotted"="dotted", # "\U00B7\U2012\U00B7\U2012\U00B7\U2012 dotdash"="dotdash", # "\U2014\U2014\U2009\U2014\U2014 longdash"="longdash", # "\U2012\U2009\U2014\U2009\U2012\U2009\U2014 twodash"="twodash"), # selected="solid")), shinyWidgets::pickerInput(inputId="lty_event", # using actual images label="Event line style", multiple=FALSE, choices=names(line.types), choicesOpt=list(content=lapply(1:length(line.types), function(i) HTML(paste0("<img src='", line.types[i], "' width=50 height=10/>", names(line.types[i]))))), selected="solid")), div(title='Event line width', numericInput(inputId="lwd_event", label="Event line width", value=2, min=0, max=NA, step=1)), div(title='Event start symbol (most commonly used)...', #selectInput(inputId="pch_start_event", # label="Event start", # choices=c("none"=NA, # using UNICODE characters # "\UFF0B plus"=3, # "\U00D7times"=4, # "\U2733\UFE0E star"=8, # "\U25FB\UFE0E square"=0, # "\U25CB circle"=1, # "\U25B3 up triangle"=2, # "\U25BD down triangle"=6, # "\U25C7 diamond"=5, # "\U25A0 fill square"=15, # "\U25CF fill small circle"=20, # "\U26AB\UFE0E fill med circle"=16, # "\U2B24 fill big circle"=19, # "\U25B2 fill triangle"=17, # "\U25C6 fill diamond"=18, # "\U229E square plus"=12, # "\U22A0 square times"=7, # "\U2A01 circle plus"=10, # "\U2A02 circle times"=13, # "\U2721 David star"=11), # selected=15)), shinyWidgets::pickerInput(inputId="pch_start_event", # using actual images label="Event start", multiple=FALSE, choices=point.types, choicesOpt=list(content=lapply(1:length(point.types), function(i) HTML(paste0("<img src='symbols/pch-", point.types[i], ".png' width=15 height=15/>", names(point.types[i]))))), selected=15)), div(title='Event end symbol (most commonly used)...', # selectInput(inputId="pch_end_event", # label="Event end", # choices=c("none"=NA, # "\UFF0B plus"=3, # "\U00D7times"=4, # "\U2733\UFE0E star"=8, # "\U25FB\UFE0E square"=0, # "\U25CB circle"=1, # "\U25B3 up triangle"=2, # "\U25BD down triangle"=6, # "\U25C7 diamond"=5, # "\U25A0 fill square"=15, # "\U25CF fill small circle"=20, # "\U26AB\UFE0E fill med circle"=16, # "\U2B24 fill big circle"=19, # "\U25B2 fill triangle"=17, # "\U25C6 fill diamond"=18, # "\U229E square plus"=12, # "\U22A0 square times"=7, # "\U2A01 circle plus"=10, # "\U2A02 circle times"=13, # "\U2721 David star"=11), # selected=16)), shinyWidgets::pickerInput(inputId="pch_end_event", # using actual images label="Event end", multiple=FALSE, choices=point.types, choicesOpt=list(content=lapply(1:length(point.types), function(i) HTML(paste0("<img src='symbols/pch-", point.types[i], ".png' width=15 height=15/>", names(point.types[i]))))), selected=16)), hr(), # Continuation (CMA0 and complex only): conditionalPanel( condition="(input.cma_class == 'per eipsode') || (input.cma_class == 'sliding window') || (input.cma_class == 'simple' && input.cma_to_compute == 'CMA0')", div(title='Continuation visual attributes', span(p("Continuation"), style="color:RoyalBlue; font-weight: bold;")), conditionalPanel( condition="!(input.bw_plot)", div(title='The color of continuation lines connecting consecutive events', colourpicker::colourInput(inputId="col_continuation", label="Cont. line color", value="black")) ), div(title='The line style of continuation lines connecting consecutive events', #selectInput(inputId="lty_continuation", # label="Cont. line style", # choices=c("\U00A0\U00A0\U00A0\U00A0\U00A0 blank"="blank", # "\U2E3B solid"="solid", # "\U2012\U2009\U2012\U2009\U2012\U2009\U2012 dashed"="dashed", # "\U00B7\U00B7\U00B7\U00B7\U00B7\U00B7\U00B7 dotted"="dotted", # "\U00B7\U2012\U00B7\U2012\U00B7\U2012 dotdash"="dotdash", # "\U2014\U2014\U2009\U2014\U2014 longdash"="longdash", # "\U2012\U2009\U2014\U2009\U2012\U2009\U2014 twodash"="twodash"), # selected="dotted")), shinyWidgets::pickerInput(inputId="lty_continuation", # using actual images label="Cont. line style", multiple=FALSE, choices=names(line.types), choicesOpt=list(content=lapply(1:length(line.types), function(i) HTML(paste0("<img src='", line.types[i], "' width=50 height=10/>", names(line.types[i]))))), selected="dotted")), div(title='The line width of continuation lines connecting consecutive events', numericInput(inputId="lwd_continuation", label="Cont. line width", value=1, min=0, max=NA, step=1)), hr() ), # Show event intervals: conditionalPanel( condition="(input.cma_class == 'simple' && input.cma_to_compute != 'CMA0') || (input.cma_class == 'per episode' || input.cma_class == 'sliding window')", div(title='Event intervals', span(p("Event intervals"), style="color:RoyalBlue; font-weight: bold;")), div(title='Show the event intervals?', shinyWidgets::materialSwitch(inputId="show_event_intervals", label="Show event interv.?", value=TRUE, status="primary", right=TRUE)), # What to do with overlapping event interval estimates (for sliding windows and per episode only)? conditionalPanel( condition="input.show_event_intervals && (input.cma_class == 'per episode' || input.cma_class == 'sliding window')", div(title='For sliding windows and per episode, for the overlapping event interval estimates, which one to show?', selectInput(inputId="overlapping_evint", label="The estimate for which windows/episode?", choices=c("first"="first", "last"="last", "minimizes gap"="min gap", "maximizes gap"="max gap", "average"="average"), selected="first")) ), hr() ), # Font sizes: div(title='Font sizes', span(p("Font sizes"), style="color:RoyalBlue; font-weight: bold;")), div(title='Relative font size of general plotting text (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="cex", label="General font size", value=1.0, min=0.0, max=NA, step=0.25)), div(title='Relative font size of axis text (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="cex_axis", label="Axis font size", value=0.75, min=0.0, max=NA, step=0.25)), div(title='Relative font size of axis labels text (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="cex_lab", label="Axis labels font size", value=1.0, min=0.0, max=NA, step=0.25)), div(title='Force showing text elements, even if they might be too small or ulgy?', shinyWidgets::materialSwitch(inputId="force_draw_text", label="Force drawing text?", value=FALSE, status="primary", right=TRUE)), hr(), # Follow-up window: div(title='Follow-up window visual attributes', span(p("FUW visuals"), style="color:RoyalBlue; font-weight: bold;")), div(title='Show the follow-up window?', shinyWidgets::materialSwitch(inputId="highlight_followup_window", label="Show FUW?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.highlight_followup_window && !(input.bw_plot)", div(title='The color of the follow-up window', colourpicker::colourInput(inputId="followup_window_col", label="FUW color", value="green")) ), hr(), # Observation window: div(title='Observation window visual attributes', span(p("OW visuals"), style="color:RoyalBlue; font-weight: bold;")), div(title='Show the observation window?', shinyWidgets::materialSwitch(inputId="highlight_observation_window", label="Show OW?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.highlight_observation_window", conditionalPanel( condition="!(input.bw_plot)", div(title='The color of the observation window', colourpicker::colourInput(inputId="observation_window_col", label="OW color", value="yellow")) ), #div(title='The density of the hashing lines (number of lines per inch) used to draw the observation window', # numericInput(inputId="observation_window_density", # label="OW hash dens.", # value=35, min=0, max=NA, step=5)), #div(title='The orientation of the hashing lines (in degrees) used to draw the observation window', # sliderInput(inputId="observation_window_angle", # label="OW hash angle", # min=-90.0, max=90.0, value=-30, step=15, round=TRUE)), div(title='The observation window\'s background opacity (between 0.0=fully transparent and 1.0=fully opaque)', sliderInput(inputId="observation_window_opacity", label="OW opacity", min=0.0, max=1.0, value=0.3, step=0.1, round=TRUE)) ), hr(), # Real observation window: conditionalPanel( condition="(input.cma_class == 'simple' && input.cma_to_compute == 'CMA8')", div(title='Real observation window visual attributes', span(p("Real OW visuals"), style="color:RoyalBlue; font-weight: bold;")), div(title='Show the real observation window (the color and transparency are the same as for the theoretial observation window but the hasing pattern can be different)?', shinyWidgets::materialSwitch(inputId="show_real_obs_window_start", label="Show real OW?", value=TRUE, status="primary", right=TRUE)), #conditionalPanel( # condition="input.show_real_obs_window_start", # # div(title='The density of the hashing lines (number of lines per inch) used to draw the real observation window', # numericInput(inputId="real_obs_window_density", # label="Real OW hash dens.", # value=35, min=0, max=NA, step=5)), # div(title='The orientation of the hashing lines (in degrees) used to draw the real observation window', # sliderInput(inputId="real_obs_window_angle", # label="Real OW hash angle", # min=-90.0, max=90.0, value=30, step=15, round=TRUE)) #), hr() ), # Axis labels & title div(title='Axis labels and title', span(p("Axis labels and title"), style="color:RoyalBlue; font-weight: bold;")), div(title='Show to main title?', shinyWidgets::materialSwitch(inputId="show_plot_title", label="Show title?", value=TRUE, status="primary", right=TRUE)), div(title='Show to x axis label?', shinyWidgets::materialSwitch(inputId="show_xlab", label="Show x label?", value=TRUE, status="primary", right=TRUE)), div(title='Show to y axis label?', shinyWidgets::materialSwitch(inputId="show_ylab", label="Show y label?", value=TRUE, status="primary", right=TRUE)), hr(), # CMA estimate aesthetics: conditionalPanel( condition="(input.cma_class == 'per episode') || (input.cma_class == 'sliding window') || (input.cma_class == 'simple' && input.cma_to_compute != 'CMA0')", div(title='CMA estimate visual attributes', span(p("CMA estimate"), style="color:RoyalBlue; font-weight: bold;")), conditionalPanel( condition="input.plot_cma", div(title='Relative font size of CMA estimate for per episode and sliding windows (please note that a size of 0 is autmatically forced to 0.01)', numericInput(inputId="cma_cex", label="CMA font size", value=0.5, min=0.0, max=NA, step=0.25)), hr() ), conditionalPanel( condition="input.plot_cma", div(title='The horizontal percent of the total plotting area to be taken by the CMA plot', sliderInput(inputId="cma_plot_ratio", label="CMA plot area %", min=0, max=100, value=10, step=5, round=TRUE)), conditionalPanel( condition="!(input.bw_plot)", div(title='The color of the CMA plot', colourpicker::colourInput(inputId="cma_plot_col", label="CMA plot color", value="lightgreen")), div(title='The color of the CMA plot border', colourpicker::colourInput(inputId="cma_plot_border", label="CMA border color", value="darkgreen")), div(title='The color of the CMA plot background', colourpicker::colourInput(inputId="cma_plot_bkg", label="CMA bkg. color", value="aquamarine")), div(title='The color of the CMA plot text', colourpicker::colourInput(inputId="cma_plot_text", label="CMA text color", value="darkgreen")), conditionalPanel( condition="input.cma_class != 'simple'", conditionalPanel( condition="input.plot_cma_timeseries", hr(), div(title='Plotting the "partial" CMAs as time series...', span(p("Showing CMAs as time series"), style="color:RoyalBlue; font-weight: italic;")), div(title='The vertical space (in text lines) taken by the time series plot of the "partial" CMAs', numericInput(inputId="cma_as_timeseries_vspace", label="Time series vertical space", value=10, min=5, max=NA, step=1)), div(title='Show the 0% mark?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_show_0perc", label="Show 0% mark?", value=TRUE, status="primary", right=TRUE)), div(title='Show the 100% mark?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_show_100perc", label="Show 100% mark?", value=FALSE, status="primary", right=TRUE)), div(title='Should the vertical axis of the time series plot start at 0 or at the minimum actually observed value?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_start_from_zero", label="Start plot from 0?", value=TRUE, status="primary", right=TRUE)), div(title='Show time series values as points and lines?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_show_dots", label="Show dots and lines?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_as_timeseries_show_dots", div(title='The color of the time series dots and lines', colourpicker::colourInput(inputId="cma_as_timeseries_color_dots", label="Dots and lines color", value="#422CD1"))), # dark blue div(title='Show time series interval?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_show_interval", label="Show intervals?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_as_timeseries_show_interval", div(title='Which way to show the intervals?', selectInput(inputId="cma_as_timeseries_show_interval_type", label="Show intervals as", choices=c("none", "segments", "arrows", "lines", "rectangles"), selected="segments")), div(title='The color of the time series intervals', colourpicker::colourInput(inputId="cma_as_timeseries_color_intervals", label="Intervals color", value="blue")), conditionalPanel( condition="input.cma_as_timeseries_show_interval_type == 'segments' || input.cma_as_timeseries_show_interval_type == 'arrows' || input.cma_as_timeseries_show_interval_type == 'lines'", div(title='Line width', numericInput(inputId="cma_as_timeseries_lwd_intervals", label="Intervals line width", value=1.0, min=0.01, max=NA, step=0.25))), conditionalPanel( condition="input.cma_as_timeseries_show_interval_type == 'rectangles'", div(title='Rectangle transparency (0=fully transparent to 1=fully opaque)', sliderInput(inputId="cma_as_timeseries_alpha_intervals", label="Intervals transparency", value=0.25, min=0.00, max=1.00, step=0.05))) ), div(title='Show time series text?', shinyWidgets::materialSwitch(inputId="cma_as_timeseries_show_text", label="Show text values?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_as_timeseries_show_text", div(title='The color of the time series text values', colourpicker::colourInput(inputId="cma_as_timeseries_color_text", label="Text values color", value="firebrick"))) ), conditionalPanel( condition="input.plot_cma_overlapping", hr(), div(title='Plotting the "partial" CMAs as overlapping segments...', span(p("Showing CMAs as overlapping segments"), style="color:RoyalBlue; font-weight: italic;")), div(title='Show the overlapping intervals?', shinyWidgets::materialSwitch(inputId="cma_as_overlapping_show_interval", label="Show intervals?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_as_overlapping_show_interval", div(title='The color of the overlapping intervals', colourpicker::colourInput(inputId="cma_as_overlapping_color_intervals", label="Intervals color", value="gray70"))), div(title='Show overlapping text?', shinyWidgets::materialSwitch(inputId="cma_as_overlapping_show_text", label="Show text values?", value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition="input.cma_as_overlapping_show_text", div(title='The color of the overlapping text values', colourpicker::colourInput(inputId="cma_as_overlapping_color_text", label="Text values color", value="firebrick"))) ), conditionalPanel( condition="input.plot_cma_stacked", hr(), div(title='Plotting the "partial" CMAs as stacked bars...', span(p("Showing CMAs as stacked bars"), style="color:RoyalBlue; font-weight: italic;")), div(title='The color of the bar', colourpicker::colourInput(inputId="plot_partial_cmas_as_stacked_col_bars", label="Bar color", value="gray90")), div(title='The color of the border', colourpicker::colourInput(inputId="plot_partial_cmas_as_stacked_col_border", label="Border color", value="gray30")), div(title='The color of the text', colourpicker::colourInput(inputId="plot_partial_cmas_as_stacked_col_text", label="text color", value="black")) ) ) ), hr() ) ), conditionalPanel( condition="(output.is_mg_defined && input.mg_use_medication_groups)", div(title='Visually grouping medication groups within patients', span(p("Medication groups"), style="color:RoyalBlue; font-weight: bold;")), div(title='The separator color', colourpicker::colourInput(inputId="plot_mg_separator_color", label="Separator color", value="blue")), div(title='The line style of the separator', shinyWidgets::pickerInput(inputId="plot_mg_separator_lty", # using actual images label="Separator line style", multiple=FALSE, choices=names(line.types), choicesOpt=list(content=lapply(1:length(line.types), function(i) HTML(paste0("<img src='", line.types[i], "' width=50 height=10/>", names(line.types[i]))))), selected="solid")), div(title='The line width of the separator', numericInput(inputId="plot_mg_separator_lwd", label="Separator line width", value=2, min=0, max=NA, step=1)), div(title='The label of the __ALL_OTHERS__ implicit medication group', textInput(inputId="plot_mg_allothers_label", label="__ALL_OTHERS__ label", value="*")) ) )), # Advanced ---- div(id='advanced_section', style="cursor: pointer;", span(title='Advanced stuff...', h4("Advanced"), style="color:DarkBlue"), div(title='Click to unfold...', id="advanced_unfold_icon", icon("option-horizontal", lib="glyphicon"))), shinyjs::hidden(div(id="advanced_contents", div(title='The minimum horizontal plot size (in characters, for the whole duration to plot)', numericInput(inputId="min_plot_size_in_characters_horiz", label="Min plot size (horiz.)", value=0, min=0, max=NA, step=1.0)), # should be 10 div(title='The minimum vertical plot size (in characters, per event)', numericInput(inputId="min_plot_size_in_characters_vert", label="Min plot size (vert.)", value=0.0, min=0.0, max=NA, step=0.25)) # should be 0.5 )), # Allow last comma: NULL ) ) ), # DATA TAB ---- tabPanel(span("Data", title="Select the data source (in-memory data frame, file, SQL database)..."), value="sidebar-params-data", icon=icon("hdd", lib="glyphicon"), fluid=TRUE, wellPanel(id = "tPanel2", style = "overflow:scroll; max-height: 90vh; min-height: 50vh", # Datasource ---- span(title='The data source to use...', h4("Data source"), style="color:DarkBlue"), div(title='Select the type of data source (currently supported: in-memory data.frame, flat files or SQL connection)', selectInput(inputId="datasource_type", label="Datasource type", choices=c("already in memory", "load from file", "SQL database"), selected="already in memory")), # Use in-memory dataset ---- conditionalPanel( condition = "(input.datasource_type == 'already in memory')", # Obligatory stuff: div(title='Required: select the name of the dataset to use from those available in memory', selectInput(inputId="dataset_from_memory", label="In-memory dataset", choices=c("[none]"), selected="[none]")), div(title="Click here to peek at the selected dataset...", actionButton("dataset_from_memory_peek_button", label="Peek at dataset...", icon=icon("eye-open", lib="glyphicon"))), hr(), div(title='Required: select the name of the column containing the patient IDs', shinyWidgets::pickerInput(inputId="dataset_from_memory_patient_id", label="Patient ID column", choices=c("[none]"), selected="[none]")), div(title='Required: give the date format.\nBasic codes are:\n "%d" (day of the month as decimal number),\n "%m" (month as decimal number),\n "%b" (Month in abbreviated form),\n "%B" (month full name),\n "%y" (year in 2 digit format) and\n "%Y" (year in 4 digit format).\nSome examples are %m/%d/%Y or %Y%m%d.\nPlease see help entry for "strptime()".', textInput(inputId="dataset_from_memory_event_format", label="Date format", value="%m/%d/%Y", placeholder="%m/%d/%Y")), div(title='Required: select the name of the column containing the event dates (in the format defined above)', shinyWidgets::pickerInput(inputId="dataset_from_memory_event_date", label="Event date column", choices=c("[none]"), selected="[none]")), div(title='Required: select the name of the column containing the event duration (in days)', shinyWidgets::pickerInput(inputId="dataset_from_memory_event_duration", label="Event duration column", choices=c("[none]"), selected="[none]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the daily dose', shinyWidgets::pickerInput(inputId="dataset_from_memory_daily_dose", label="Daily dose column", choices=c("[not defined]"), selected="[not defined]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the treatment class', shinyWidgets::pickerInput(inputId="dataset_from_memory_medication_class", label="Treatment class column", choices=c("[not defined]"), selected="[not defined]")), hr(), div(title='Validate choices and use the dataset!', actionButton(inputId="dataset_from_memory_button_use", label=strong("Validate & use!"), icon=icon("sunglasses", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="float: center;") ), # Use dataset from file ---- conditionalPanel( condition = "(input.datasource_type == 'load from file')", # Obligatory stuff: div(title='Required: which type of file to load?\n.csv and .tsv are prefered, .RData and .rds should pose no problems, but for the others there might be limitations (please see the help for packages "readODS", "SASxport", "readxl" and "heaven").\nPlease note that readling very big files might be very slow and need quite a bit of RAM.', selectInput(inputId="dataset_from_file_filetype", label="Type of file", choices=c("Comma/TAB-separated (.csv; .tsv; .txt)", #"R objects from save() (.RData)", "Serialized R object (.rds)", "Open Document Spreadsheet (.ods)", "Microsoft Excel (.xls; .xlsx)", "SPSS (.sav; .por)", "SAS Transport data file (.xpt)", "SAS sas7bdat data file (.sas7bdat)", "Stata (.dta)"), selected="Comma/TAB-separated (.csv; .tsv; .txt)")), conditionalPanel( condition = "(input.dataset_from_file_filetype == 'Comma/TAB-separated (.csv; .tsv; .txt)')", div(title='The filed separator (or delimiter); usually, a comma (,) for .csv files and a [TAB] for .tsv files...', selectInput(inputId="dataset_from_file_csv_separator", label="Filed separator", choices=c("[TAB] (\\t)", "comma (,)", "white spaces (1+)", "semicolon (;)", "colon (:)"), selected="[TAB] (\\t)")), div(title='The quote character (if any); usually, single (\' \') or double quotes (" ")...', selectInput(inputId="dataset_from_file_csv_quotes", label="Quote character", choices=c("[none] ()", "singe quotes (' ')", "double quotes (\" \")"), selected="[none] ()")), div(title='The decimal point symbol; usually, the dot (.) or the comma (,)...', selectInput(inputId="dataset_from_file_csv_decimal", label="Decimal point", choices=c("dot (.)", "comma (,)"), selected="dot (.)")), div(title='Should the first row to be considered as the header?', shinyWidgets::materialSwitch(inputId="dataset_from_file_csv_header", label=HTML("Header 1<sup>st</sup> row"), value=TRUE, status="primary", right=TRUE)), conditionalPanel( condition = "(input.dataset_from_file_csv_quotes != '[none] ()')", div(title='Should the leading and trailing white spaces from unquoted fields be deleted?', shinyWidgets::materialSwitch(inputId="dataset_from_file_csv_strip_white", label="Strip white spaces", value=FALSE, status="primary", right=TRUE))), div(title='Which strings in the file should be considered as missing data?\nPlease include the value(s) within double quotes and, if multiple values, separate them with commas (e.g. "NA", " ", "9999", "?").', textInput(inputId="dataset_from_file_csv_na_strings", label="Missing data symbols", value='"NA"')) ), conditionalPanel( condition = "(input.dataset_from_file_filetype == 'Open Document Spreadsheet (.ods)') || (input.dataset_from_file_filetype == 'Microsoft Excel (.xls; .xlsx)')", div(title='Which sheet to load (if there are several sheets)?', numericInput(inputId="dataset_from_file_sheet", label="Which sheet to load?", value=1, min=1, max=NA, step=1)) ), #conditionalPanel( # condition = "(input.dataset_from_file_filetype == 'SAS Transport data file (.xpt)')", # # div(title='Which dataset to load (if there are several of them)?', # numericInput(inputId="dataset_from_file_sheet_sas", # label="Which dataset to load?", # value=1, min=1, max=NA, step=1)) #), div(title='Required: select and load a file...', fileInput(inputId="dataset_from_file_filename", label="Load from file", multiple=FALSE, buttonLabel="Select")), conditionalPanel( #condition="(typeof(input.dataset_from_file_filename) != 'undefined') && (input.dataset_from_file_filename != null)", condition="(output.is_file_loaded == true)", div(title="Click here to peek at the selected dataset...", actionButton("dataset_from_file_peek_button", label="Peek at file...", icon=icon("eye-open", lib="glyphicon"))), hr(), div(title='Required: select the name of the column containing the patient IDs', shinyWidgets::pickerInput(inputId="dataset_from_file_patient_id", label="Patient ID column", choices=c("[none]"), selected="[none]")), div(title='Required: give the date format.\nBasic codes are:\n "%d" (day of the month as decimal number),\n "%m" (month as decimal number),\n "%b" (Month in abbreviated form),\n "%B" (month full name),\n "%y" (year in 2 digit format) and\n "%Y" (year in 4 digit format).\nSome examples are %m/%d/%Y or %Y%m%d.\nPlease see help entry for "strptime()".', textInput(inputId="dataset_from_file_event_format", label="Date format", value="%m/%d/%Y", placeholder="%m/%d/%Y")), div(title='Required: select the name of the column containing the event dates (in the format defined above)', shinyWidgets::pickerInput(inputId="dataset_from_file_event_date", label="Event date column", choices=c("[none]"), selected="[none]")), div(title='Required: select the name of the column containing the event duration (in days)', shinyWidgets::pickerInput(inputId="dataset_from_file_event_duration", label="Event duration column", choices=c("[none]"), selected="[none]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the daily dose', shinyWidgets::pickerInput(inputId="dataset_from_file_daily_dose", label="Daily dose column", choices=c("[not defined]"), selected="[not defined]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the treatment class', shinyWidgets::pickerInput(inputId="dataset_from_file_medication_class", label="Treatment class column", choices=c("[not defined]"), selected="[not defined]")), hr(), div(title='Validate choices and use the dataset!', actionButton(inputId="dataset_from_file_button_use", label=strong("Validate & use!"), icon=icon("sunglasses", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="float: center;") ) ), # Use dataset from SQL database ---- conditionalPanel( condition = "(input.datasource_type == 'SQL database')", # Obligatory stuff: div(title=HTML('Required: connection to SQL database (please note that the credentials are <b>not</b> stored! What RDBMS/SQL server type/vendor/solution to connect to?'), selectInput(inputId="dataset_from_sql_server_type", label="What RDBMS solution?", choices=c("SQLite", "MySQL/MariaDB"), selected="SQLite")), conditionalPanel( condition="(input.dataset_from_sql_server_type == 'SQLite')", div(title=HTML('This is intended as an example of using SQL with SQLite, and uses an in-memory "med_events" database that contains the example dataset included in the package.\nFor security reasons, we do not allow at this time the use of a user-given SQLite database, but this is easy to do.\nDespite its limitations, SQLite could be a fully working solution in specific scenarios involving, for example, local applications or a pre-defined databasestored in a file on the server.'), shinyjs::disabled(textInput(inputId="dataset_from_sqlite_database_name", label=HTML("Database name <span style='color: red'>(fixed example)</span>"), value=c("med_events")))) ), conditionalPanel( condition="(input.dataset_from_sql_server_type == 'MySQL/MariaDB')", div(title=HTML('Required: the address (name or IP) of the host database (if on the local machine, use "localhost" or "[none]").'), textInput(inputId="dataset_from_sql_server_host", label="Host name/address", value=c("[none]"))), div(title=HTML('Required: the database server TCP/IP port number.'), numericInput(inputId="dataset_from_sql_server_port", label="TCP/IP port number", value=c(0), min=0, max=NA, step=1)), div(title=HTML('Required: the name of the database.'), textInput(inputId="dataset_from_sql_database_name", label="Database name", value=c("[none]"))), div(title=HTML('Required: the username.'), textInput(inputId="dataset_from_sql_username", label="Username", value=c(""), placeholder="user")), div(title=HTML('Required: the password'), passwordInput(inputId="dataset_from_sql_password", label="Password", value=c(""), placeholder="password")) ), div(title='Connect to datadase and fetch tables!', actionButton(inputId="dataset_from_sql_button_connect", label=strong("Connect!"), icon=icon("transfer", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="padding-bottom: 10px;"), conditionalPanel( condition="(output.is_database_connected == true)", div(title='Disconnect from datadase (not really necessary, as the disconnection is automatic when closing the application, but nice to do))', actionButton(inputId="dataset_from_sql_button_disconnect", label=strong("Disconnect!"), icon=icon("ban-circle", lib="glyphicon"), style="color:red; border-color:red;"), style="padding-bottom: 20px;"), div(title='Peek at database!', actionButton(inputId="dataset_from_sql_button_peek", label=strong("Peek at database..."), icon=icon("eye-open", lib="glyphicon"))), hr(), div(title=HTML('Required: the table or view to use...'), shinyWidgets::pickerInput(inputId="dataset_from_sql_table", label="Which table/view", choices=c("[none]"), selected="[none]")), div(title='Required: select the name of the column containing the patient IDs', shinyWidgets::pickerInput(inputId="dataset_from_sql_patient_id", label="Patient ID column", choices=c("[none]"), selected="[none]")), div(title='Required: give the date format.\nBasic codes are:\n "%d" (day of the month as decimal number),\n "%m" (month as decimal number),\n "%b" (Month in abbreviated form),\n "%B" (month full name),\n "%y" (year in 2 digit format) and\n "%Y" (year in 4 digit format).\nSome examples are %m/%d/%Y or %Y%m%d.\nPlease see help entry for "strptime()".\nFor SQL, the standard format is %Y-%m-%d (i.e., YYYY-MM-DD).', textInput(inputId="dataset_from_sql_event_format", label="Date format", value="%Y-%m-%d", placeholder="%Y-%m-%d")), div(title='Required: select the name of the column containing the event dates (please note the the format is the standard SQL YYYY-MM-DD)', shinyWidgets::pickerInput(inputId="dataset_from_sql_event_date", label="Event date column", choices=c("[none]"), selected="[none]")), div(title='Required: select the name of the column containing the event duration (in days)', shinyWidgets::pickerInput(inputId="dataset_from_sql_event_duration", label="Event duration column", choices=c("[none]"), selected="[none]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the daily dose', shinyWidgets::pickerInput(inputId="dataset_from_sql_daily_dose", label="Daily dose column", choices=c("[not defined]"), selected="[not defined]")), div(title='Optional (potentially used by CMA5+): select the name of the column containing the treatment class', shinyWidgets::pickerInput(inputId="dataset_from_sql_medication_class", label="Treatment class column", choices=c("[not defined]"), selected="[not defined]")), hr(), div(title='Validate choices and use the dataset!', actionButton(inputId="dataset_from_sql_button_use", label=strong("Validate & use!"), icon=icon("sunglasses", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="float: center;") ) ), # Allow last comma: NULL ) ), # MEDICATION GROUPS TAB ---- tabPanel(span("Groups", title="Define medication groups..."), value="sidebar-params-data", icon=icon("list", lib="glyphicon"), fluid=TRUE, conditionalPanel( condition="!(output.is_dataset_defined)", wellPanel(id = "tPanelnomg", style = "overflow:scroll; max-height: 90vh;", div(h4("No datasource!"), style="color:DarkRed"), br(), div(span(span("There is no valid source of data defined (probably because the interactive Shiny plotting was invoked without passing a dataset).")), style="color: red;"), hr(), div(span("Please use the "), span(icon("hdd",lib="glyphicon"),strong("Data"), style="color: darkblue"), span(" tab to select a valid datesource!")) ) ), conditionalPanel( condition="(output.is_dataset_defined)", wellPanel(id = "tPanel3", style = "overflow:scroll; max-height: 90vh; min-height: 50vh", # Source of medication groups ---- span(title='Define medication groups...', h4("Medication groups"), style="color:DarkBlue"), div(title='Are there medication groups or not?', shinyWidgets::materialSwitch(inputId="mg_use_medication_groups", label=HTML("Use medication groups?"), value=!is.null(.GlobalEnv$.plotting.params$medication.groups), status="primary", right=TRUE)), conditionalPanel( condition="(input.mg_use_medication_groups)", div(title='How to define the medication groups?', selectInput(inputId="mg_definitions_source", label="Medication groups from:", choices=c("named vector", "column in data"), selected="named vector")), conditionalPanel( condition="(input.mg_definitions_source == 'named vector')", div(title='Load the medication groups from a named vector in memory', # From in-memory vector ---- selectInput(inputId="mg_from_memory", label="Load named vector", choices=c("[none]"), selected="[none]")), div(style="height: 0.50em;"), div(title="Click here to check the selected vector...", actionButton("mg_from_memory_peek_button", label="Check it!", icon=icon("eye-open", lib="glyphicon"))) ), conditionalPanel( condition="(input.mg_definitions_source == 'column in data')", div(title='The medication groups are defined by a column in the data', # From column in the data ---- shinyWidgets::pickerInput(inputId="mg_from_column", label="Medication groups column", choices=c("[none]"), selected="[none]")), div(style="height: 0.50em;") ), hr(), div(title='Validate and use the medication groups!', actionButton(inputId="mg_from_memory_button_use", label=strong("Use it!"), icon=icon("sunglasses", lib="glyphicon"), style="color:DarkBlue; border-color:DarkBlue;"), style="float: center;"), hr() ) ) ) ) )))), # OUTPUT PANEL ---- #mainPanel( column(9, #shinyjs::hidden(checkboxInput(inputId="output_panel_container_show", label="", value=FALSE)), shinyjs::hidden(div(id="output_panel_container", # start with these hidden... #conditionalPanel( # condition="(input.output_panel_container_show == true)", conditionalPanel( condition="(output.is_dataset_defined == true)", # Plot dimensions ---- column(3, div(title='The width of the plotting area (in pixles)', sliderInput(inputId="plot_width", label="Plot width", min=100, max=5000, value=500, step=20, round=TRUE)) ), conditionalPanel( condition = "(!input.plot_keep_ratio)", column(3, div(title='The height of the plotting area (in pixels)', sliderInput(inputId="plot_height", label="height", min=60, max=5000, value=300, step=20, round=TRUE)) ) ), conditionalPanel( condition = "(input.plot_keep_ratio)", column(3, p("") ) ), column(3, div(title='Freeze the width/height ratio of the plotting area (or make the width and height independent of each other)?', shinyWidgets::materialSwitch(inputId="plot_keep_ratio", label="Keep ratio", value=TRUE, status="primary", right=TRUE)), #checkboxInput(inputId="plot_auto_size", # label="auto size", # value=TRUE) #), #column(2, # Save image to file: div(title='Export this plot to an image file?', shinyWidgets::materialSwitch(inputId="save_to_file_info", label="Save plot!", value=FALSE, status="primary", right=TRUE)) #shinyWidgets::checkboxGroupButtons(inputId="save_to_file_info", # label=NULL, # choices=c(`<span><i class='fa fa-bar-chart'></i>&nbsp; Save plot!</span>` = "Save it!"))) # #choices=c(`<i class='fa fa-bar-chart'></i>` = "Save it!"))) ) ), conditionalPanel( condition="!(output.is_dataset_defined)", column(9, div(p(" ")) ) ), column(3, # Close shop: div(title='Exit this Shiny plotting app? (The plot will NOT be automatically saved!)', actionButton(inputId="close_shop", label=strong("Exit..."), icon=icon("remove-circle", lib="glyphicon"), style="color: #C70039 ; border-color: #C70039")) ), # Export to file ---- column(12, conditionalPanel( condition="(input.save_to_file_info)", div(title='Save the plot using the same size as currently displayed or pick a new size?', checkboxInput(inputId="save_plot_displayed_size", label="Save plot using current size?", value=TRUE)), conditionalPanel( condition="(!input.save_plot_displayed_size)", column(2, div(title='The width of the exported plot (in the selected units)', numericInput(inputId="save_plot_width", label="width", value=5))), column(2, div(title='The height of the exported plot (in the selected units)', numericInput(inputId="save_plot_height", label="height", value=5))), conditionalPanel( # EPS + PDF condition="(input.save_plot_type == 'eps' || save_plot_type == 'pdf')", column(2, div(title='For EPS and PDF, only inches are available', selectInput(inputId="save_plot_dim_unit", label="unit", choices=c("in"), selected="in"))) # only inches ), conditionalPanel( # JPEG + PNG + TIFF condition="(input.save_plot_type != 'eps' && save_plot_type != 'pdf')", column(2, div(title='The unit of exported plot', selectInput(inputId="save_plot_dim_unit", label="unit", choices=c("in","cm","px"), selected="in"))) ) ), conditionalPanel( condition="(input.save_plot_displayed_size)", column(6, div()) ), column(2, div(title='The type of the exported image', selectInput(inputId="save_plot_type", label="type", choices=c("jpg","png","tiff","eps","pdf"), selected="jpg"))), #column(2,numericInput(inputId="save_plot_quality", label="quality", value=75, min=0, max=100, step=1)), conditionalPanel( condition="(input.save_plot_type != 'eps' && input.save_plot_type != 'pdf')", column(2, div(title='The resolution of the exported image (not useful for EPS and PDF)', numericInput(inputId="save_plot_resolution", label="resolution", value=72, min=0))) ), conditionalPanel( condition="(input.save_plot_type == 'eps' || input.save_plot_type == 'pdf')", column(2, div()) ), column(2, style="margin-top: 25px;", div(title='Export the plot now!', downloadButton(outputId="save_to_file", label="Save plot"))) ) ), conditionalPanel( condition="(output.is_dataset_defined)", # Messages ---- column(12, tags$head(tags$style("#container * { display: inline; }")), div(id="container", title="Various messages (in blue), warnings (in green) and errors (in red) generated during plotting...", span(" Messages:", style="color:DarkBlue; font-weight: bold;"), span(htmlOutput(outputId = "messages")), style="height: 4em; resize: vertical; overflow: auto") ), # The actual plot ---- column(12, wellPanel(id = "tPlot", style="resize: none; overflow:scroll; max-height: 75vh; max-width: 80vw", plotOutput(outputId = "distPlot", inline=TRUE))), # Export R code for plot ---- column(12, # Show the R code: div(title='Show the R code that would generate the current plot', actionButton(inputId="show_r_code", label=strong("Show R code..."), icon=icon("eye-open", lib="glyphicon"))) ), column(12, div(p(" ")) ), hr(), # Compute CMA for a (larger) set of patients using the same parameters as for the current plot: column(12, conditionalPanel( condition="!(input.cma_class == 'simple' && input.cma_to_compute == 'CMA0')", div(title='Compute the same CMA with the same parameters as those used to generate the current plot but for (possible) more patients and export the results', # actionButton(inputId="compute_cma_for_larger_sample", label=strong("Compute CMA for (more) patients..."), icon=icon("play", lib="glyphicon"))) shinyWidgets::materialSwitch(inputId="compute_cma_for_larger_sample", label=strong("Compute CMA for several patients..."), value=FALSE, status="primary", right=TRUE)) ) ), # Compute CMA and export results and R code ---- column(12, conditionalPanel( condition="!(input.cma_class == 'simple' && input.cma_to_compute == 'CMA0') && (input.compute_cma_for_larger_sample)", column(12, div(HTML(paste0('Please select the patients for which to compute the <code>CMA</code>.<br/>', 'Please note that, due to the potentially high computational costs associated, we limit the <b>maximum number of patients</b> to ', .GlobalEnv$.plotting.params$max.number.patients.to.compute, ', the <b>maximum number of events</b> across all patients to ', .GlobalEnv$.plotting.params$max.number.events.to.compute, ', and the <b>running time</b> to a maximum of ', .GlobalEnv$.plotting.params$max.running.time.in.minutes.to.compute, ' minutes.<br/>', 'For larger computations, we provide the <code>R</code> code, ', 'which we recommend running from a <b>dedicated <code>R</code> session</b> on appropriately powerful hardware...' ))), #div(title="TEST!", # radioButtons(inputId="compute_cma_patient_selection_method", # label="You can select the patients either:", # choices=c("individually by their ID"="by_id", # "or as a range based on their position in a list"="by_position"), # inline=TRUE)), hr(), div(title="Compue the CMA for the selected patients...", actionButton(inputId="compute_cma_for_larger_sample_button", label=strong("Compute CMA..."), icon=icon("play", lib="glyphicon"), style="color: darkblue ; border-color: darkblue")), hr(), div(HTML('<b>You can select the patients:</b>')), #hr(), tabsetPanel(id="compute_cma_patient_selection_method", #conditionalPanel( # condition="(input.compute_cma_patient_selection_method == 'by_id'", tabPanel(title=HTML("<b>individually</b>, using their IDs"), value="by_id", column(12,div(title="Please select one or more patient IDs to process...", selectInput(inputId="compute_cma_patient_by_id", label="Select the IDs of the patients to include", choices=.GlobalEnv$.plotting.params$all.IDs, selected=.GlobalEnv$.plotting.params$all.IDs[1], multiple=TRUE))) ), #conditionalPanel( # condition="(input.compute_cma_patient_selection_method == 'by_position'", tabPanel(title=HTML("as a <b>range</b>, based on their position in a list"), value="by_position", column(12, div(title="Define the range of positions (#) corresponding to the selected IDs...", sliderInput(inputId="compute_cma_patient_by_group_range", label="Select range of ID positions (#)", min=1, max=100, step=1, value=c(1,1), round=TRUE, width="100%")) ), column(3, div(title="Order the patients by..."), selectInput(inputId="compute_cma_patient_by_group_sorting", label="Sort patients by", choices=c("original order", "by ID (↑)", "by ID (↓)")) ), column(9, div(div("The patient IDs with their position (#):"), dataTableOutput(outputId="show_patients_as_list")) ) ) ) ) ) ) ), conditionalPanel( condition="!(output.is_dataset_defined)", column(12, align="center", div(br(),br(),br(), span("Please use the "), span(icon("hdd",lib="glyphicon"),strong("Data"), style="color: darkblue"), span(" tab to select a valid datesource!"))) ) )))#) ) ) # THE SERVER LOGIC ---- server <- function(input, output, session) { # Initialisation of the Shiny app ---- isolate({showModal(modalDialog("Adherer", title=div(icon("hourglass", lib="glyphicon"), "Please wait while initializing the App..."), easyClose=FALSE, footer=NULL))}) # Reactive value to allow UI updating on dataset changes: rv <- reactiveValues(toggle.me = FALSE); isolate( { options(shiny.sanitize.errors=FALSE); # Initialisation for a directly-launched Shiny App or for a new session: if( is.null(.GlobalEnv$.plotting.params) || (is.logical(.GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments) && !is.na(.GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments) && !.GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments) ) { # Ok, seem we've been launched directly as a "normal" Shiny app: # make sure things are set to their default in the .plotting.params global list: .GlobalEnv$.plotting.params <- list("data"=NULL, "cma.class"="simple", "ID.colname"=NA, "event.date.colname"=NA, "event.duration.colname"=NA, "event.daily.dose.colname"=NA, "medication.class.colname"=NA, "medication.groups"=NULL, "date.format"=NA, "align.all.patients"=FALSE, "align.first.event.at.zero"=FALSE, "ID"="[not defined]", "all.IDs"=c("[not defined]"), "max.number.patients.to.plot"=10, "max.number.events.to.plot"=500, "max.number.patients.to.compute"=100, "max.number.events.to.compute"=5000, "max.running.time.in.minutes.to.compute"=5, ".patients.to.compute"=NULL, "print.full.params"=FALSE, "get.colnames.fnc"=NULL, "get.patients.fnc"=NULL, "get.data.for.patients.fnc"=NULL, ".plotting.fnc"=AdhereRViz:::.plotting.fnc.shiny, ".dataset.type"=NA, ".dataset.comes.from.function.arguments"=FALSE, ".dataset.name"=NA, ".inmemory.dataset"=NULL, ".fromfile.dataset"=NULL, ".fromfile.dataset.filetype"=NULL, ".fromfile.dataset.header"=NULL, ".fromfile.dataset.sep"=NULL, ".fromfile.dataset.quote"=NULL, ".fromfile.dataset.dec"=NULL, ".fromfile.dataset.strip.white"=NULL, ".fromfile.dataset.na.strings"=NULL, ".fromfile.dataset.sheet"=NULL, ".db.connection.tables"=NULL, ".db.connection.selected.table"=NULL, ".db.connection"=NULL ); # Make sure the med.events data is loaded as well: data("medevents", package="AdhereR"); } }) # Show/hide UI elements based on various conditions: output$is_dataset_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$data)}); outputOptions(output, "is_dataset_defined", suspendWhenHidden = FALSE); output$is_file_loaded <- reactive({!is.null(.GlobalEnv$.plotting.params$.fromfile.dataset)}); outputOptions(output, "is_file_loaded", suspendWhenHidden = FALSE); output$is_database_connected <- reactive({!is.null(.GlobalEnv$.plotting.params$.db.connection)}); outputOptions(output, "is_database_connected", suspendWhenHidden = FALSE); output$is_dose_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$event.daily.dose.colname) && !is.na(.GlobalEnv$.plotting.params$event.daily.dose.colname)}); outputOptions(output, "is_dose_defined", suspendWhenHidden = FALSE); output$is_treat_class_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$medication.class.colname) && !is.na(.GlobalEnv$.plotting.params$medication.class.colname)}); outputOptions(output, "is_treat_class_defined", suspendWhenHidden = FALSE); output$is_mg_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$medication.groups)}); outputOptions(output, "is_mg_defined", suspendWhenHidden = FALSE); #outputOptions(output, 'save_to_file', suspendWhenHidden=FALSE); # Clean up at session end ---- session$onSessionEnded(function() { # Disconnect any open database connections... if( !is.null(.GlobalEnv$.plotting.params$.db.connection) ) { try(DBI::dbDisconnect(.GlobalEnv$.plotting.params$.db.connection), silent=TRUE); } # Clean up stuff from the previous session: .GlobalEnv$.plotting.params <- NULL; collected.results <<- NULL; cma.computation.progress.log.text <<- NULL; }) # The plotting function ---- .renderPlot <- function() { patients.to.plot <- input$patient; # Checks concerning the maximum number of patients and events to plot: if( length(patients.to.plot) > .GlobalEnv$.plotting.params$max.number.patients.to.plot ) { patients.to.plot <- patients.to.plot[ 1:.GlobalEnv$.plotting.params$max.number.patients.to.plot ]; #updateSelectInput(session, inputId="patient", selected=patients.to.plot); cat(paste0("Warning: a maximum of ",.GlobalEnv$.plotting.params$max.number.patients.to.plot, " patients can be shown in an interactive plot: we kept only the first ",.GlobalEnv$.plotting.params$max.number.patients.to.plot, " from those you selected!\n")); } ## This check can be too costly during plotting (especially for database connections), so we don't do it for now assuming there's not too many events per patient anyway: #if( !is.null(n.events <- .GlobalEnv$.plotting.params$get.data.for.patients.fnc(patients.to.plot, .GlobalEnv$.plotting.params$data, .GlobalEnv$.plotting.params$ID.colname)) && # nrow(n.events) > .GlobalEnv$.plotting.params$max.number.events.to.plot ) #{ # n.events.per.patient <- cumsum(table(n.events[,.GlobalEnv$.plotting.params$ID.colname])); # n <- min(which(n.events.per.patient > .GlobalEnv$.plotting.params$max.number.events.to.plot)); # if( n > 1 ) n <- n-1; # patients.to.plot <- patients.to.plot[ 1:n ]; # cat(paste0("Warning: a maximum of ",.GlobalEnv$.plotting.params$max.number.events.to.plot, # " events across all patients can be shown in an interactive plot: we kept only the first ",length(patients.to.plot), # " patients from those you selected (totalling ",n.events.per.patient[n]," events)!\n")); #} res <- NULL; try(res <- .GlobalEnv$.plotting.params$.plotting.fnc(data=.GlobalEnv$.plotting.params$data, ID.colname=.GlobalEnv$.plotting.params$ID.colname, event.date.colname=.GlobalEnv$.plotting.params$event.date.colname, event.duration.colname=.GlobalEnv$.plotting.params$event.duration.colname, event.daily.dose.colname=.GlobalEnv$.plotting.params$event.daily.dose.colname, medication.class.colname=.GlobalEnv$.plotting.params$medication.class.colname, date.format=.GlobalEnv$.plotting.params$date.format, ID=patients.to.plot, medication.groups=if( input$mg_use_medication_groups ){ .GlobalEnv$.plotting.params$medication.groups }else{ NULL }, medication.groups.separator.show=input$mg_plot_by_patient, medication.groups.to.plot=.GlobalEnv$.plotting.params$medication.groups.to.plot, medication.groups.separator.lty=input$plot_mg_separator_lty, medication.groups.separator.lwd=input$plot_mg_separator_lwd, medication.groups.separator.color=input$plot_mg_separator_color, medication.groups.allother.label=input$plot_mg_allothers_label, cma=ifelse(input$cma_class == "simple", input$cma_to_compute, input$cma_class), cma.to.apply=ifelse(input$cma_class == "simple", "none", ifelse(input$cma_to_compute_within_complex == "CMA0", "CMA1", input$cma_to_compute_within_complex)), # don't use CMA0 for complex CMAs #carryover.within.obs.window=FALSE, #carryover.into.obs.window=FALSE, carry.only.for.same.medication=input$carry_only_for_same_medication, consider.dosage.change=input$consider_dosage_change, followup.window.start=if(input$followup_window_start_unit == "calendar date"){as.Date(input$followup_window_start_date, format="%Y-%m-%d")} else {as.numeric(input$followup_window_start_no_units)}, followup.window.start.unit=ifelse(input$followup_window_start_unit == "calendar date", "days", input$followup_window_start_unit), followup.window.duration=as.numeric(input$followup_window_duration), followup.window.duration.unit=input$followup_window_duration_unit, observation.window.start=if(input$observation_window_start_unit == "calendar date"){as.Date(input$observation_window_start_date, format="%Y-%m-%d")} else {as.numeric(input$observation_window_start_no_units)}, observation.window.start.unit=ifelse(input$observation_window_start_unit == "calendar date", "days", input$observation_window_start_unit), observation.window.duration=as.numeric(input$observation_window_duration), observation.window.duration.unit=input$observation_window_duration_unit, medication.change.means.new.treatment.episode=input$medication_change_means_new_treatment_episode, dosage.change.means.new.treatment.episode=input$dosage_change_means_new_treatment_episode, maximum.permissible.gap=as.numeric(input$maximum_permissible_gap), maximum.permissible.gap.unit=input$maximum_permissible_gap_unit, maximum.permissible.gap.append.to.episode=input$maximum_permissible_gap_append, sliding.window.start=as.numeric(input$sliding_window_start), sliding.window.start.unit=input$sliding_window_start_unit, sliding.window.duration=as.numeric(input$sliding_window_duration), sliding.window.duration.unit=input$sliding_window_duration_unit, sliding.window.step.duration=as.numeric(input$sliding_window_step_duration), sliding.window.step.unit=input$sliding_window_step_unit, sliding.window.no.steps=ifelse(input$sliding_window_step_choice == "number of steps" ,as.numeric(input$sliding_window_no_steps), NA), plot.CMA.as.histogram=ifelse(input$cma_class == "sliding window", !input$plot_CMA_as_histogram_sliding_window, !input$plot_CMA_as_histogram_episodes), align.all.patients=input$plot_align_all_patients, align.first.event.at.zero=input$plot_align_first_event_at_zero, show.legend=input$show_legend, legend.x=input$legend_x, legend.y=input$legend_y, legend.bkg.opacity=input$legend_bkg_opacity, legend.cex=max(0.01,input$legend_cex), legend.cex.title=max(0.01,input$legend_cex_title), duration=ifelse(input$duration==0, NA, input$duration), # duration to plot show.period=ifelse(length(input$patient) > 1 && input$plot_align_all_patients, "days", input$show_period), period.in.days=input$period_in_days, # period bw.plot=input$bw_plot, # grayscale plotting #show.cma=input$show_cma, col.na=input$col_na, unspecified.category.label=input$unspecified_category_label, col.cats=list("rainbow" =grDevices::rainbow, "heat.colors" =grDevices::heat.colors, "terrain.colors"=grDevices::terrain.colors, "topo.colors" =grDevices::topo.colors, "cm.colors" =grDevices::cm.colors, "magma" =viridisLite::magma, "inferno" =viridisLite::inferno, "plasma" =viridisLite::plasma, "viridis" =viridisLite::viridis, "cividis" =viridisLite::cividis)[[input$col_cats]], lty.event=input$lty_event, lwd.event=input$lwd_event, pch.start.event=as.numeric(input$pch_start_event), pch.end.event=as.numeric(input$pch_end_event), col.continuation=input$col_continuation, lty.continuation=input$lty_continuation, lwd.continuation=input$lwd_continuation, cex=max(0.01,input$cex), cex.axis=max(0.01,input$cex_axis), cex.lab=max(0.01,input$cex_lab), force.draw.text=input$force_draw_text, highlight.followup.window=input$highlight_followup_window, followup.window.col=input$followup_window_col, highlight.observation.window=input$highlight_observation_window, observation.window.col=input$observation_window_col, #observation.window.density=input$observation_window_density, observation.window.angle=input$observation_window_angle, observation.window.opacity=input$observation_window_opacity, show.real.obs.window.start=input$show_real_obs_window_start, #real.obs.window.density=input$real_obs_window_density, real.obs.window.angle=input$real_obs_window_angle, print.CMA=input$print_cma, CMA.cex=max(0.01,input$cma_cex), plot.CMA=input$plot_cma, CMA.plot.ratio=input$cma_plot_ratio / 100.0, CMA.plot.col=input$cma_plot_col, CMA.plot.border=input$cma_plot_border, CMA.plot.bkg=input$cma_plot_bkg, CMA.plot.text=input$cma_plot_text, plot.partial.CMAs.as=c(if(input$plot_cma_stacked){"stacked"}else{NULL}, if(input$plot_cma_overlapping){"overlapping"}else{NULL}, if(input$plot_cma_timeseries){"timeseries"}else{NULL}), plot.partial.CMAs.as.stacked.col.bars=input$plot_partial_cmas_as_stacked_col_bars, plot.partial.CMAs.as.stacked.col.border=input$plot_partial_cmas_as_stacked_col_border, plot.partial.CMAs.as.stacked.col.text=input$plot_partial_cmas_as_stacked_col_text, plot.partial.CMAs.as.timeseries.vspace=input$cma_as_timeseries_vspace, plot.partial.CMAs.as.timeseries.start.from.zero=input$cma_as_timeseries_start_from_zero, plot.partial.CMAs.as.timeseries.col.dot=if(!input$cma_as_timeseries_show_dots){NA}else{input$cma_as_timeseries_color_dots}, plot.partial.CMAs.as.timeseries.interval.type=input$cma_as_timeseries_show_interval_type, plot.partial.CMAs.as.timeseries.lwd.interval=input$cma_as_timeseries_lwd_intervals, plot.partial.CMAs.as.timeseries.alpha.interval=input$cma_as_timeseries_alpha_intervals, plot.partial.CMAs.as.timeseries.col.interval=if(!input$cma_as_timeseries_show_interval){NA}else{input$cma_as_timeseries_color_intervals}, plot.partial.CMAs.as.timeseries.col.text=if(!input$cma_as_timeseries_show_text){NA}else{input$cma_as_timeseries_color_text}, plot.partial.CMAs.as.timeseries.show.0perc=input$cma_as_timeseries_show_0perc, plot.partial.CMAs.as.timeseries.show.100perc=input$cma_as_timeseries_show_100perc, plot.partial.CMAs.as.overlapping.col.interval=if(!input$cma_as_overlapping_show_interval){NA}else{input$cma_as_overlapping_color_intervals}, plot.partial.CMAs.as.overlapping.col.text=if(!input$cma_as_overlapping_show_text){NA}else{input$cma_as_overlapping_color_text}, show.event.intervals=input$show_event_intervals, print.dose=input$print_dose, cex.dose=max(0.01,input$cex_dose), print.dose.outline.col=input$print_dose_outline_col, print.dose.centered=input$print_dose_centered, plot.dose=input$plot_dose, lwd.event.max.dose=input$lwd_event_max_dose, plot.dose.lwd.across.medication.classes=input$plot_dose_lwd_across_medication_classes, show.overlapping.event.intervals=input$overlapping_evint, xlab=if(input$show_xlab) {c("dates"="Date", "days"="Days")} else {NULL}, ylab=if(input$show_ylab) {c("withoutCMA"="patient", "withCMA"="patient (& CMA)")} else {NULL}, title=if(input$show_plot_title) {c("aligned"="Event patterns (all patients aligned)", "notaligned"="Event patterns")} else {NULL}, min.plot.size.in.characters.horiz=input$min_plot_size_in_characters_horiz, min.plot.size.in.characters.vert=input$min_plot_size_in_characters_vert, get.colnames.fnc=.GlobalEnv$.plotting.params$get.colnames.fnc, get.patients.fnc=.GlobalEnv$.plotting.params$get.patients.fnc, get.data.for.patients.fnc=.GlobalEnv$.plotting.params$get.data.for.patients.fnc ), silent=FALSE); return (res); } # renderPlot() ---- output$distPlot <- renderPlot({ rv$toggle.me; # make the plot aware of forced updates to the UI (for example, when changing the dataset) msgs <- ""; # the output messages res <- NULL; # the result of plotting if( is.null(.GlobalEnv$.plotting.params$data) ) { # Switch to the Data tab: updateTabsetPanel(session=session, inputId="sidebar-tabpanel", selected="sidebar-params-data"); ## Display a warning urging the user to select a data source: #showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR..."), # div(span(code("plot_interactive_cma()"), # span("was called without a dataset!\nPlease use the ")), # span(icon("hdd",lib="glyphicon")), # span("Data"), # span(" tab to select a datesource!"), style="color: red;"), # footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } else { # Depeding on the CMA class we might do things differently: if( input$cma_class %in% c("simple", "per episode", "sliding window") ) { # Call the workhorse plotting function with the appropriate argumens: #msgs <- capture.output(res <- .renderPlot()); res <- .renderPlot(); } else { # Quitting.... showModal(modalDialog(title="AdhereR interactive plotting...", paste0("Unknwon CMA class '",input$cma_class,"'."), easyClose=TRUE)); } # Show the messages (if any): ewms <- AdhereR:::.get.ewms(); if( !is.null(ewms) && nrow(ewms) > 0 ) { msgs <- vapply(1:nrow(ewms), function(i) { switch(as.character(ewms$type[i]), "error"= paste0("<b>&gt;</b> <font color=\"red\"><b>",as.character(ewms$text[i]),"</b></font>"), "warning"=paste0("<b>&gt;</b> <font color=\"green\"><i>",as.character(ewms$text[i]),"</i></font>"), "message"=paste0("<b>&gt;</b> <font color=\"blue\">",as.character(ewms$text[i]),"</font>"), paste0("<b>&gt;</b> ",as.character(ewms$text[i]))); }, character(1)); output$messages <- renderText(paste0(paste0("<font color=\"red\"><b>", sum(ewms$type=="error",na.rm=TRUE), " error(s)</b></font>, ", "<font color=\"green\"><i>",sum(ewms$type=="warning",na.rm=TRUE)," warning(s)</i></font> & ", "<font color=\"blue\">", sum(ewms$type=="message",na.rm=TRUE)," message(s)</font>:<br>"), paste0(msgs,collapse="<br>"))); } #if( is.null(res) || length(grep("error", msgs, ignore.case=TRUE)) > 0 ) #{ # # Errors: # output$messages <- renderText({ paste0("<font color=\"red\"><b>",msgs,"</b></font>"); }) #} else if( length(grep("warning", msgs, ignore.case=TRUE)) > 0 ) #{ # # Warnings: # output$messages <- renderText({ paste0("<font color=\"green\"><i>",msgs,"</i></font>"); }) #} else #{ # # Normal output: # output$messages <- renderText({ paste0("<font color=\"blue\">",msgs,"</font>"); }) #} } }, width=function() # plot width { return (input$plot_width); }, height=function() # plot height { if( !is.numeric(.GlobalEnv$.plotting.params$plot.ratio) ) .GlobalEnv$.plotting.params$plot.ratio <- (input$plot_width / input$plot_height); # define the ratio if( input$plot_keep_ratio ) { return (input$plot_width / .GlobalEnv$.plotting.params$plot.ratio); } else { return (input$plot_height); } }, execOnResize=TRUE # force redrawing on resize ) # The text messages ---- output$messages <- renderText({ "" }) # Keep ratio toggle event ---- observeEvent(input$plot_keep_ratio, { if( input$plot_keep_ratio ) { .GlobalEnv$.plotting.params$plot.ratio <- (input$plot_width / input$plot_height); # save the ratio } else { updateSliderInput(session, "plot_height", value = round(input$plot_width / .GlobalEnv$.plotting.params$plot.ratio)); } }) # Export plot to file ---- output$save_to_file <- downloadHandler( filename = function() { paste0("adherer-plot-", input$cma_class,"-", ifelse(input$cma_class=="simple", input$cma_to_compute, input$cma_to_compute_within_complex), "-", "ID-",input$patient, ".", input$save_plot_type) }, content = function(file) { # Plot dimensions: if( input$save_plot_displayed_size ) { if( input$save_plot_type %in% c("eps", "pdf") ) { # Cairo PS and PDF only understand inches, so make sure we convert right: plot.dims.width <- input$plot_width / 72; # by default 72 DPI if( !is.numeric(.GlobalEnv$.plotting.params$plot.ratio) ) .GlobalEnv$.plotting.params$plot.ratio <- (input$plot_width / input$plot_height); # define the ratio plot.dims.height <- ifelse(input$plot_keep_ratio, input$plot_width / .GlobalEnv$.plotting.params$plot.ratio, input$plot_height) / 72; # by default 72 DPI plot.dims.unit <- "in"; } else { # The others work in pixels: plot.dims.width <- input$plot_width; if( !is.numeric(.GlobalEnv$.plotting.params$plot.ratio) ) .GlobalEnv$.plotting.params$plot.ratio <- (input$plot_width / input$plot_height); # define the ratio plot.dims.height <- ifelse(input$plot_keep_ratio, input$plot_width / .GlobalEnv$.plotting.params$plot.ratio, input$plot_height); plot.dims.unit <- "px"; } } else { plot.dims.width <- input$save_plot_width; plot.dims.height <- input$save_plot_height; plot.dims.unit <- input$save_plot_dim_unit; } # The type of plot to save: if( input$save_plot_type == "png" ) { png(file, width=plot.dims.width, height=plot.dims.height, units=plot.dims.unit, res=input$save_plot_resolution, type="cairo"); } else if( input$save_plot_type == "tiff" ) { tiff(file, width=plot.dims.width, height=plot.dims.height, units=plot.dims.unit, res=input$save_plot_resolution, compression="zip", type="cairo"); } else if( input$save_plot_type == "eps" ) { cairo_ps(file, width=plot.dims.width, height=plot.dims.height, onefile=FALSE); } else if( input$save_plot_type == "pdf" ) { cairo_pdf(file, width=plot.dims.width, height=plot.dims.height, onefile=FALSE); } else # default to JPEG { jpeg(file, width=plot.dims.width, height=plot.dims.height, units=plot.dims.unit, res=input$save_plot_resolution); } # Plot it: .renderPlot(); # Close the device: dev.off(); } ) # Make sure by default the event intervals are not shown for complex CMAs ---- observeEvent(input$cma_class, { shinyWidgets::updateMaterialSwitch(session, inputId="show_event_intervals", value=(input$cma_class == "simple" && input$cma_to_compute != "CMA0")); # by default, it is TRUE for simple (non-CMA0) CMAs and FALSE otherwise }) observeEvent(input$cma_to_compute, { shinyWidgets::updateMaterialSwitch(session, inputId="show_event_intervals", value=(input$cma_class == "simple" && input$cma_to_compute != "CMA0")); # by default, it is TRUE for simple (non-CMA0) CMAs and FALSE otherwise }) # About and help box ---- observeEvent(input$about_button, { # Get most of the relevant info from the DESCRIPTION file: descr.adherer <- utils::packageDescription("AdhereR"); descr.adhererviz <- utils::packageDescription("AdhereRViz"); msg <- paste0(# Logo: "<img src='adherer-logo.png', align = 'left', style='font-size: x-large; font-weight: bold; height: 2em; vertical-align: baseline;'/>", #"<div style='width: 1em; display: inline-block;'/>", "<div style='display: inline-block;'/>", "<hr/>", # AdhereR: "<div style='max-height: 50vh; overflow: auto;'>", "<h2>AdhereR</h1>", "<p><b>Version</b> ",descr.adherer$Version,"</p>", "<p><b>Authors:</b> ",descr.adherer$Author,"</p>", "<p><b>Maintainer:</b> ",descr.adherer$Maintainer,"</p>", "<p align='justify'>",descr.adherer$Description,"</p>", "<p><b>Website:</b> <a href='",descr.adherer$URL,"' target='_blank'>",descr.adherer$URL,"</a></p>", "<p><b>Released under:</b> ",descr.adherer$License,"</p>", "<p><b>Citation:</b></p>",paste0(format(citation(package="AdhereR"),style="html"),collapse=" "), "<hr/>", # AdhereRViz: "<h2>AdhereRViz</h1>", "<p><b>Version</b> ",descr.adhererviz$Version,"</p>", "<p><b>Authors:</b> ",descr.adhererviz$Author,"</p>", "<p><b>Maintainer:</b> ",descr.adhererviz$Maintainer,"</p>", "<p align='justify'>",descr.adhererviz$Description,"</p>", "<p><b>Website:</b> <a href='",descr.adhererviz$URL,"' target='_blank'>",descr.adhererviz$URL,"</a></p>", "<p><b>Released under:</b> ",descr.adhererviz$License,"</p>", "<p><b>Citation:</b></p>",paste0(format(citation(package="AdhereRViz"),style="html"),collapse=" "), "<hr/>", # More info: "<h2>More info</h1>", "<p>For more info <b>online</b> please visit the project's <a href='http://www.adherer.eu' target='_blank'>homepage</a> (<a href='http://www.adherer.eu' target='_blank'>www.adherer.eu</a>) and its source code repository on <a href='https://github.com/ddediu/AdhereR' target='_blank'>GitHub</a> (<a href='https://github.com/ddediu/AdhereR' target='_blank'>github.com/ddediu/AdhereR</a>). ", "The official releases are hosted on <a href='https://cran.r-project.org/package=AdhereR' target='_blank'>CRAN</a> (<a href='https://cran.r-project.org/package=AdhereR' target='_blank'>https://cran.r-project.org/package=AdhereR</a>).", "<p><b>Offline</b> help is available within R (and RStudio):</p>", "<ul>", "<li>running <code>help(package='AdhereR')</code> in the R cosole displayes the <i>main documentation</i> for the package with links to detailed help for particular topics;</li>", "<li>running <code>help('CMA0')</code> (or the equivalent <code>?CMA0</code>) in the R cosole displayes the <i>detailed documentation</i> the particular topic (here, CMA0); in RStudio, selecting the keyword ('CMA0') in the script editor and pressing <code>F1</code> has the same effect. Please note that to obtain help for <i>overloaded</i> functions (such as <code>plot</code>) for, say, sliding windows, one must use the fully qualified function name (here, <code>?plot.CMA_sliding_window</code>);</li>", "<li>the various <i>vignettes</i> contain a lot of information about selected topics. To list all available vignettes for AdhereR, run <code>browseVignettes(package='AdhereR')</code> in the R console. Currently, the main vignettes concern:</li>", "<ul>", "<li><i><a href='https://CRAN.R-project.org/package=AdhereR/vignettes/AdhereR-overview.html' target='_blank'>AdhereR: Adherence to Medications</a></i> gives an overview of what AdhereR can do;</li>", "<li><i><a href='https://CRAN.R-project.org/package=AdhereR/vignettes/calling-AdhereR-from-python3.html' target='_blank'>Calling AdhereR from Python 3</a></i> describes a mechanism that allows AdhereR to be used from programming languages and platforms other than R (in particular, from Python 3);</li>", "<li><i><a href='https://CRAN.R-project.org/package=AdhereR/vignettes/adherer_with_databases.pdf' target='_blank'>Using AdhereR with various database technologies for processing very large datasets</a></i> described how to use AdhereR to process data stored in 'classic' SQL Relational Databases Management Systems (RDBMSs) or in Apache's Hadoop;</li>", "<li><i><b><a href='https://CRAN.R-project.org/package=AdhereRViz/vignettes/adherer_interctive_plots.html' target='_blank'>AdhereR: Interactive plotting (and more) with Shiny</a></b></i> is probably the most relevant here.</li>", "</ul>", "</ul>", "</div>"); tryCatch(showModal(modalDialog(HTML(msg), title=NULL, footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))), error = function(e) showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Cannot display the About message!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))) ); }) # Show the R code box ---- r_code <- ""; # must be global because we need to access it form other functions as well (and it's not a big object anyway) observeEvent(input$show_r_code, { if( is.na(.GlobalEnv$.plotting.params$.dataset.type) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), HTML("No dataset (or a NULL one) was given through the <code>data</code> argument to the <code>plot_interactive_cma()</code> function call, and no datasource was manually selected either: please select one using the <b>Data</b> tab!"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( is.null(input$patient) || length(input$patient) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("No patients selected, so nothing to do!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Create the R code: r_code <<- ""; # Initial comments: r_code <<- paste0(r_code, "# The R code corresponding to the currently displayed Shiny plot:\n"); r_code <<- paste0(r_code, "# \n"); # The selected patients: r_code <<- paste0(r_code, "# Extract the data for the selected ", length(input$patient), " patient(s) with ID(s):\n"); r_code <<- paste0(r_code, "# ",paste0('"',input$patient,'"',collapse=", "),"\n"); r_code <<- paste0(r_code, "# \n"); # The datasource: r_code <<- paste0(r_code, "# We denote here by DATA the data you are using in the Shiny plot.\n"); if( .GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments ) { # The dataset came as the `data` argument to `plot_interactive_cam()`, so we don't know it's "name": r_code <<- paste0(r_code, "# For reasons to do with how R works, we cannot display the name\n"); r_code <<- paste0(r_code, "# you used for it (if any), but we can tell you that it is of type\n"); r_code <<- paste0(r_code, "# \"", paste0(class(.GlobalEnv$.plotting.params$data),collapse=","), "\", and it has the structure:\n"); r_code <<- paste0(r_code, paste0("# ",capture.output(str(.GlobalEnv$.plotting.params$data, vec.len=3, width=60)),collapse="\n"),"\n"); } else { # The dataset was manually selected, so we know quite a bit about it: r_code <<- paste0(r_code, "# This was manually defined as "); r_code <<- paste0(r_code, switch(.GlobalEnv$.plotting.params$.dataset.type, "in memory"= paste0("an object of class data.frame\n", "# (or derived from it, such a data.table) that was already in\n", "# memory under the name '",.GlobalEnv$.plotting.params$.dataset.name,"'.\n", "# Assuming this object still exists with the same name, then:\n\n", "DATA <- ",.GlobalEnv$.plotting.params$.dataset.name,";\n\n"), "from file"= paste0("a data.frame object loaded from the\n", "# file '",.GlobalEnv$.plotting.params$.dataset.name,"'\n", "# of type '",.GlobalEnv$.plotting.params$.fromfile.dataset.filetype,"'\n", "# (unfortunately, the full path to the original file cannot be recovered)\n", "# Assuming this file still exists with the same name, then:\n\n", switch(.GlobalEnv$.plotting.params$.fromfile.dataset.filetype, "Comma/TAB-separated (.csv; .tsv; .txt)"= paste0("DATA <- read.table(\"",.GlobalEnv$.plotting.params$.dataset.name,"\",\n", " header=",.GlobalEnv$.plotting.params$.fromfile.dataset.header,",\n", " sep=\"",if(.GlobalEnv$.plotting.params$.fromfile.dataset.sep=="\t") "\\t" else .GlobalEnv$.plotting.params$.fromfile.dataset.sep,"\",\n", " quote=",if(.GlobalEnv$.plotting.params$.fromfile.dataset.quote=='"') "'\"'" else paste0('"',.GlobalEnv$.plotting.params$.fromfile.dataset.quote,'"'),",\n", " dec=\"",.GlobalEnv$.plotting.params$.fromfile.dataset.dec,"\",\n", " strip.white=",.GlobalEnv$.plotting.params$.fromfile.dataset.strip.white,",\n", " na.strings=c(",paste0('"',.GlobalEnv$.plotting.params$.fromfile.dataset.na.strings,'"',collapse=","),")\n", ");\n"), "R objects from save() (.RData)"= paste0("# load the .RData file that contains the object using load() and\n", "DATA <- ",.GlobalEnv$.plotting.params$.dataset.name,";\n"), "Serialized R object (.rds)"= paste0("DATA <- readRDS(\"",.GlobalEnv$.plotting.params$.dataset.name,"\");\n"), "Open Document Spreadsheet (.ods)"= paste0("DATA <- readODS::read_ods(\"",.GlobalEnv$.plotting.params$.dataset.name,"\",\n", " sheet=",.GlobalEnv$.plotting.params$.fromfile.dataset.sheet,");\n"), "Microsoft Excel (.xls; .xlsx)"= paste0("DATA <- readxl::read_excel(\"",.GlobalEnv$.plotting.params$.dataset.name,"\",\n", " sheet=",.GlobalEnv$.plotting.params$.fromfile.dataset.sheet,");\n"), "SPSS (.sav; .por)"= paste0("DATA <- haven::read_spss(\"",.GlobalEnv$.plotting.params$.dataset.name,"\");\n"), "SAS Transport data file (.xpt)"= paste0("DATA <- haven::read_xpt(\"",.GlobalEnv$.plotting.params$.dataset.name,"\");\n"), "SAS sas7bdat data file (.sas7bdat)"= paste0("DATA <- haven::read_sas(\"",.GlobalEnv$.plotting.params$.dataset.name,"\");\n"), "Stata (.dta)"= paste0("DATA <- haven::read_stata(\"",.GlobalEnv$.plotting.params$.dataset.name,"\");\n"), "NULL; # please make sure you load this file manually!!!\n"), "\n"), "SQL database"=paste0("a connection to the SQL database\n# '",.GlobalEnv$.plotting.params$.dataset.name,"'\n")), ""); r_code <<- paste0(r_code, "# These data has ", length(.GlobalEnv$.plotting.params$get.colnames.fnc(.GlobalEnv$.plotting.params$data)), " columns, ", "and contains info for ", length(unique(.GlobalEnv$.plotting.params$get.patients.fnc(.GlobalEnv$.plotting.params$data, .GlobalEnv$.plotting.params$ID.colname))), " patients.\n"); } # The medication group: if( !is.null(.GlobalEnv$.plotting.params$medication.groups) && input$mg_use_medication_groups ) { # Defined: r_code <<- paste0(r_code, "# \n", "# There are medication groups defined: we denote them here as MGs.\n"); if( input$mg_definitions_source == 'named vector' && (length(.GlobalEnv$.plotting.params$medication.groups) > 1 || (length(.GlobalEnv$.plotting.params$medication.groups) == 1 && !(.GlobalEnv$.plotting.params$medication.groups %in% .GlobalEnv$.plotting.params$get.colnames.fnc(.GlobalEnv$.plotting.params$data)))) ) { # Vector defining the medication groups: if( .GlobalEnv$.plotting.params$.mg.comes.from.function.arguments ) { # The medication groups came as the `medication.groups` argument to `plot_interactive_cam()`, so we don't know it's "name": r_code <<- paste0(r_code, "# For reasons to do with how R works, we cannot display the name\n"); r_code <<- paste0(r_code, "# you used for it (if any), but we can tell you that it is of type\n"); r_code <<- paste0(r_code, "# \"", paste0(class(.GlobalEnv$.plotting.params$medication.groups),collapse=","), "\", and has ",length(.GlobalEnv$.plotting.params$medication.groups)," elements:\n"); } else { # The medication groups were manually selected, so we know quite a bit about them: r_code <<- paste0(r_code, "# The medication groups are defined using an object already\n", "# in memory under the name '",.GlobalEnv$.plotting.params$.mg.name,"'.\n", "# Assuming this object still exists with the same name, then:\n"); r_code <<- paste0(r_code, "# it is of type \"", paste0(class(.GlobalEnv$.plotting.params$medication.groups),collapse=","), "\"\n", "# and has ",length(.GlobalEnv$.plotting.params$medication.groups)," elements:\n"); } # The elements are the same: r_code <<- paste0(r_code, "# c(\n"); r_code <<- paste0(r_code, paste0("# '",names(.GlobalEnv$.plotting.params$medication.groups),"' = '",.GlobalEnv$.plotting.params$medication.groups,"'",collapse=",\n"), "\n"); r_code <<- paste0(r_code, "# );\n", "# \n"); } else { # Column name: r_code <<- paste0(r_code, "# The medication groups are defined by column\n"); r_code <<- paste0(r_code, "# '",.GlobalEnv$.plotting.params$medication.groups,"'\n"); r_code <<- paste0(r_code, "# in the data.\n"); r_code <<- paste0(r_code, "# \n"); } } # The accessor functions: r_code <<- paste0(r_code, "# \n"); r_code <<- paste0(r_code, "# To allow using data from other sources than a \"data.frame\"\n"); r_code <<- paste0(r_code, "# and other similar structures (for example, from a remote SQL\n"); r_code <<- paste0(r_code, "# database), we use a metchanism to request the data for the\n"); r_code <<- paste0(r_code, "# selected patients that uses a function called\n"); r_code <<- paste0(r_code, "# \"get.data.for.patients.fnc()\" which you may have redefined\n"); r_code <<- paste0(r_code, "# to better suit your case (chances are, however, that you are\n"); r_code <<- paste0(r_code, "# using its default version appropriate to the data source);\n"); r_code <<- paste0(r_code, "# in any case, the following is its definition:\n"); fnc.code <- capture.output(print(.GlobalEnv$.plotting.params$get.data.for.patients.fnc)); if( is.null(fnc.code) || length(fnc.code) == 0 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Cannot display the R code for plot!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( length(grep("<environment", fnc.code[length(fnc.code)], fixed=TRUE)) == 1 ){ fnc.code <- fnc.code[-length(fnc.code)]; } if( length(grep("<bytecode", fnc.code[length(fnc.code)], fixed=TRUE)) == 1 ){ fnc.code <- fnc.code[-length(fnc.code)]; } if( is.null(fnc.code) || length(fnc.code) == 0 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Cannot display the R code for plot!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( length(fnc.code) == 1 ) { r_code <<- paste0(r_code, "get.data.for.patients.fnc <- ",fnc.code,"\n"); } else { r_code <<- paste0(r_code, "get.data.for.patients.fnc <- ",fnc.code[1],"\n"); r_code <<- paste0(r_code, paste0(fnc.code[-1],collapse="\n"), "\n\n"); } r_code <<- paste0(r_code, "# Try to extract the data only for the selected patient ID(s):\n"); r_code <<- paste0(r_code, ".data.for.selected.patients. <- get.data.for.patients.fnc(\n"); r_code <<- paste0(r_code, " c(", paste0('"',input$patient,'"',collapse=", "),"),\n"); r_code <<- paste0(r_code, " DATA, ### don't forget to put here your REAL DATA! ###\n"); r_code <<- paste0(r_code, " \"",.GlobalEnv$.plotting.params$ID.colname,"\"\n"); r_code <<- paste0(r_code, ");\n"); r_code <<- paste0(r_code, "# Compute the appropriate CMA:\n"); # The CMA function name: cma_fnc_name <- switch(input$cma_class, "simple"=input$cma_to_compute, "per episode"="CMA_per_episode", "sliding window"="CMA_sliding_window"); r_code <<- paste0(r_code, "cma <- ",cma_fnc_name,"("); # the CMA function call cma_fnc_body_indent <- paste0(rep(" ",nchar(cma_fnc_name) + nchar("cma <- ")),collapse=""); # the CMA function body indent # The parameters: r_code <<- paste0(r_code, "data=.data.for.selected.patients.,\n"); if( input$cma_class != "simple" ) r_code <<- paste0(r_code, cma_fnc_body_indent, " ", 'CMA="',input$cma_to_compute_within_complex,'",\n'); if( !is.null(.GlobalEnv$.plotting.params$medication.groups) && input$mg_use_medication_groups ) { # Medication groups defined: r_code <<- paste0(r_code, cma_fnc_body_indent, " medication.groups=MGs, ### don't forget to put here your REAL medication groups! ###\n"); } r_code <<- paste0(r_code, cma_fnc_body_indent, " # (please note that even if some parameters are\n"); r_code <<- paste0(r_code, cma_fnc_body_indent, " # not relevant for a particular CMA type, we\n"); r_code <<- paste0(r_code, cma_fnc_body_indent, " # nevertheless pass them as they will be ignored)\n"); params.cma <- list("all"=c("ID.colname"=if(!is.na(.GlobalEnv$.plotting.params$ID.colname)) paste0('"',.GlobalEnv$.plotting.params$ID.colname,'"') else "NA", "event.date.colname"=if(!is.na(.GlobalEnv$.plotting.params$event.date.colname)) paste0('"',.GlobalEnv$.plotting.params$event.date.colname,'"') else "NA", "event.duration.colname"=if(!is.na(.GlobalEnv$.plotting.params$event.duration.colname)) paste0('"',.GlobalEnv$.plotting.params$event.duration.colname,'"') else "NA", "event.daily.dose.colname"=if(!is.na(.GlobalEnv$.plotting.params$event.daily.dose.colname)) paste0('"',.GlobalEnv$.plotting.params$event.daily.dose.colname,'"') else "NA", "medication.class.colname"=if(!is.na(.GlobalEnv$.plotting.params$medication.class.colname)) paste0('"',.GlobalEnv$.plotting.params$medication.class.colname,'"') else "NA", #"carryover.within.obs.window"=NA, #"carryover.into.obs.window"=NA, "carry.only.for.same.medication"=input$carry_only_for_same_medication, "consider.dosage.change"=input$consider_dosage_change, "followup.window.start"=ifelse(input$followup_window_start_unit=="calendar date", paste0('"',as.character(as.Date(input$followup_window_start_date, format="%Y-%m-%d"), format=.GlobalEnv$.plotting.params$date.format),'"'), input$followup_window_start_no_units), "followup.window.start.unit"=ifelse(input$followup_window_start_unit=="calendar date", '"days"', paste0('"',input$followup_window_start_unit,'"')), "followup.window.duration"=input$followup_window_duration, "followup.window.duration.unit"=paste0('"',input$followup_window_duration_unit,'"'), "observation.window.start"=ifelse(input$observation_window_start_unit=="calendar date", paste0('"',as.character(as.Date(input$observation_window_start_date, format="%Y-%m-%d"), format=.GlobalEnv$.plotting.params$date.format),'"'), input$observation_window_start_no_units), "observation.window.start.unit"=ifelse(input$observation_window_start_unit=="calendar date", '"days"', paste0('"',input$observation_window_start_unit,'"')), "observation.window.duration"=input$observation_window_duration, "observation.window.duration.unit"=paste0('"',input$observation_window_duration_unit,'"')), "per.episode"=c("medication.change.means.new.treatment.episode"=input$medication_change_means_new_treatment_episode, "dosage.change.means.new.treatment.episode"=input$dosage_change_means_new_treatment_episode, "maximum.permissible.gap"=input$maximum_permissible_gap, "maximum.permissible.gap.unit"=paste0('"',input$maximum_permissible_gap_unit,'"'), "maximum.permissible.gap.append.to.episode"=input$maximum_permissible_gap_append), "sliding.window"=c("sliding.window.start"=as.numeric(input$sliding_window_start), "sliding.window.start.unit"=paste0('"',input$sliding_window_start_unit,'"'), "sliding.window.duration"=input$sliding_window_duration, "sliding.window.duration.unit"=paste0('"',input$sliding_window_duration_unit,'"'), "sliding.window.step.duration"=input$sliding_window_step_duration, "sliding.window.step.unit"=paste0('"',input$sliding_window_step_unit,'"'), "sliding.window.no.steps"=ifelse(input$sliding_window_step_choice=="number of steps", input$sliding_window_no_steps, NA)), "date.format"=paste0('"',.GlobalEnv$.plotting.params$date.format,'"') # keep date.format as last to avoid issues with dangling commas ); r_code <<- paste0(r_code, paste0(cma_fnc_body_indent, " ", names(params.cma$all), "=", params.cma$all, collapse=",\n"), ",\n"); if( input$cma_class == "per episode" ) r_code <<- paste0(r_code, paste0(cma_fnc_body_indent, " ", names(params.cma$per.episode), "=", params.cma$per.episode, collapse=",\n"), ",\n"); if( input$cma_class == "sliding window" ) r_code <<- paste0(r_code, paste0(cma_fnc_body_indent, " ", names(params.cma$sliding.window), "=", params.cma$sliding.window, collapse=",\n"), ",\n"); r_code <<- paste0(r_code, cma_fnc_body_indent, " date.format=", params.cma$date.format, "\n"); # End end of CMA function call: r_code <<- paste0(r_code, cma_fnc_body_indent,");\n\n"); # The plotting: r_code <<- paste0(r_code, "if( !is.null(cma) ) # if the CMA was computed ok\n"); r_code <<- paste0(r_code, "{\n"); r_code <<- paste0(r_code, " # Try to plot it:\n"); r_code <<- paste0(r_code, " plot(cma,\n"); r_code <<- paste0(r_code, " # (same idea as for CMA: we send arguments even if\n"); r_code <<- paste0(r_code, " # they aren't used in a particular case)\n"); params.plot <- c("align.all.patients"=input$plot_align_all_patients, "align.first.event.at.zero"=input$plot_align_first_event_at_zero, "show.legend"=input$show_legend, "legend.x"=ifelse( is.numeric(input$legend_x), input$legend_x, paste0('"',input$legend_x,'"')), "legend.y"=ifelse( is.numeric(input$legend_y), input$legend_y, paste0('"',input$legend_y,'"')), "legend.bkg.opacity"=input$legend_bkg_opacity, "legend.cex"=max(0.01,input$legend_cex), "legend.cex.title"=max(0.01,input$legend_cex_title), "duration"=ifelse(input$duration==0, NA, input$duration), "show.period"=ifelse(length(input$patient) > 1 && input$plot_align_all_patients, '"days"', paste0('"',input$show_period,'"')), "period.in.days"=input$period_in_days, "bw.plot"=input$bw_plot, #show.cma=input$show_cma, "col.na"=paste0('"',input$col_na,'"'), "unspecified.category.label"=paste0('"',input$unspecified_category_label,'"'), "col.cats"=input$col_cats, "lty.event"=paste0('"',input$lty_event,'"'), "lwd.event"=input$lwd_event, "pch.start.event"=input$pch_start_event, "pch.end.event"=input$pch_end_event, "col.continuation"=paste0('"',input$col_continuation,'"'), "lty.continuation"=paste0('"',input$lty_continuation,'"'), "lwd.continuation"=input$lwd_continuation, "cex"=max(0.01,input$cex), "cex.axis"=max(0.01,input$cex_axis), "cex.lab"=max(0.01,input$cex_lab), "force.draw.text"=input$force.draw.text, "highlight.followup.window"=input$highlight_followup_window, "followup.window.col"=paste0('"',input$followup_window_col,'"'), "highlight.observation.window"=input$highlight_observation_window, "observation.window.col"=paste0('"',input$observation_window_col,'"'), #"observation.window.density"=input$observation_window_density, #"observation.window.angle"=input$observation_window_angle, "observation.window.opacity"=input$observation_window_opacity, "show.real.obs.window.start"=input$show_real_obs_window_start, #"real.obs.window.density"=input$real_obs_window_density, #"real.obs.window.angle"=input$real_obs_window_angle, "print.CMA"=input$print_cma, "CMA.cex"=max(0.01,input$cma_cex), "plot.CMA"=input$plot_cma, "CMA.plot.ratio"=input$cma_plot_ratio / 100.0, "CMA.plot.col"=paste0('"',input$cma_plot_col,'"'), "CMA.plot.border"=paste0('"',input$cma_plot_border,'"'), "CMA.plot.bkg"=paste0('"',input$cma_plot_bkg,'"'), "CMA.plot.text"=paste0('"',input$cma_plot_text,'"'), "plot.CMA.as.histogram"=ifelse(input$cma_class=="sliding window", !input$plot_CMA_as_histogram_sliding_window, !input$plot_CMA_as_histogram_episodes), "show.event.intervals"=input$show_event_intervals, "print.dose"=input$print_dose, "cex.dose"=max(0.01,input$cex.dose), "print.dose.outline.col"=paste0('"',input$print_dose_outline_col,'"'), "print.dose.centered"=input$print_dose_centered, "plot.dose"=input$plot_dose, "lwd.event.max.dose"=input$lwd_event_max_dose, "plot.dose.lwd.across.medication.classes"=input$plot_dose_lwd_across_medication_classes, "show.overlapping.event.intervals"=input$overlapping_evint, "min.plot.size.in.characters.horiz"=input$min_plot_size_in_characters_horiz, "min.plot.size.in.characters.vert"=input$min_plot_size_in_characters_vert, "medication.groups.to.plot"=ifelse(!is.null(.GlobalEnv$.plotting.params$medication.groups) && input$mg_use_medication_groups, paste0("c(", paste0('"', ifelse(input$mg_to_plot_list=="* (all others)","__ALL_OTHERS__",input$mg_to_plot_list), '"',collapse=","), ")"), "NULL"), "medication.groups.separator.show"=input$mg_plot_by_patient, "medication.groups.separator.lty"=paste0('"',input$plot_mg_separator_lty,'"'), "medication.groups.separator.lwd"=input$plot_mg_separator_lwd, "medication.groups.separator.color"=paste0('"',input$plot_mg_separator_color,'"'), "medication.groups.allother.label"=paste0('"',input$plot_mg_allothers_label,'"') ); r_code <<- paste0(r_code, paste0(" ", names(params.plot), "=", params.plot, collapse=",\n"), "\n"); r_code <<- paste0(r_code, " );\n"); r_code <<- paste0(r_code, "}\n"); ## DEBUG: #cat(r_code); tryCatch(showModal(modalDialog(div(div(HTML("<p>This is the <code>R</code> that would generate the plot currently seen. You can copy it to the clipboard using the <i>Copy to clipboard</i> button.</p> <p>Please note that the parameter values <b><code>DATA</code></b> and <b><code>MGs</code></b> <i>must be replaced</i> by the actual data and medication groups (if the case) you passed to the Shiny interactive plot function!</p>")), div(HTML(gsub('<span class="symbol">MGs</span>','<span class="symbol_data">MGs</span>', gsub('<span class="symbol">DATA</span>','<span class="symbol_data">DATA</span>', highlight::highlight(parse.output=parse(text=r_code), renderer=highlight::renderer_html(document=TRUE, stylesheet=file.path(system.file('interactivePlotShiny', package='AdhereRViz'), "r-code-highlight.css")), show_line_numbers=FALSE, output=NULL), fixed=TRUE), fixed=TRUE)), #div(HTML(highlight::external_highlight(code=r_code, theme="acid", lang="r", type="HTML", doc=TRUE, file=NULL, outfile=NULL)), style="max-height: 50vh; overflow-x: scroll; overflow-y: scroll; white-space: nowrap;")), # overflow: auto; title=HTML("The <code>R</code> code for the current plot..."), footer = tagList(actionButton("copy_code", "Copy to clipboard", icon=icon("copy", lib="glyphicon")), modalButton("Close", icon=icon("ok", lib="glyphicon"))))), error = function(e) showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Cannot display the R code for plot!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))) ); }) observeEvent(input$copy_code, { if( clipr::clipr_available() ) clipr::write_clip(r_code, object_type="character"); }) # Close shop nicely ---- observeEvent(input$close_shop, { showModal(modalDialog(title="AdhereR interactive plotting...", "Are you sure you want to close the interactive plotting?", footer = tagList(modalButton("No", icon=icon("remove-circle", lib="glyphicon")), actionButton("ok", "Yes", icon=icon("ok-circle", lib="glyphicon"))))) }) observeEvent(input$ok, { removeModal(); stopApp(); }) # Show/hide panel sections ---- .toggle.all.sections <- function(id=c("follow_up"), anim=TRUE, animType=c("slide","fade")[1]) { shinyjs::toggle(id=paste0(id,"_unfold_icon"), anim=anim, animType=animType); # the unfolding icon shinyjs::toggle(id=paste0(id,"_contents"), anim=anim, animType=animType); # the section content } shinyjs::onclick("mg_section", function(e){.toggle.all.sections("mg");}) shinyjs::onclick("follow_up_section", function(e){.toggle.all.sections("follow_up");}) shinyjs::onclick("general_settings_section", function(e){.toggle.all.sections("general_settings");}) shinyjs::onclick("observation_section", function(e){.toggle.all.sections("observation");}) shinyjs::onclick("cma_plus_section", function(e){.toggle.all.sections("cma_plus");}) shinyjs::onclick("episodes_section", function(e){.toggle.all.sections("episodes");}) shinyjs::onclick("sliding_windows_section", function(e){.toggle.all.sections("sliding_windows");}) shinyjs::onclick("align_section", function(e){.toggle.all.sections("align");}) shinyjs::onclick("duration_period_section", function(e){.toggle.all.sections("duration_period");}) shinyjs::onclick("cma_estimate_section", function(e){.toggle.all.sections("cma_estimate");}) shinyjs::onclick("dose_section", function(e){.toggle.all.sections("dose");}) shinyjs::onclick("legend_section", function(e){.toggle.all.sections("legend");}) shinyjs::onclick("aesthetics_section", function(e){.toggle.all.sections("aesthetics");}) shinyjs::onclick("advanced_section", function(e){.toggle.all.sections("advanced");}) # Recursively list objects in memory ---- .recursively.list.objects.in.memory <- function(..., # inspired from http://adv-r.had.co.nz/Environments.html#env-recursion env = parent.frame(), of.class="data.frame", # if NULL, no type testing (all go) min.nrow=1, min.ncol=3, # NA if not relevant return.dimensions=TRUE, consider.derived.classes=TRUE) { if( identical(env, emptyenv()) ) { # No objects in the empty environment return (NULL); } else { # List all objects in this environment: all.objects <- objects(envir=env, all.names=TRUE); # Check each objects' class: if( !is.null(of.class) ) { # Do type testing: objects.to.keep <- vapply(all.objects, function(s) { x <- get(s, envir=env); # get the actual object if( (!consider.derived.classes && (of.class %in% class(x))) || (consider.derived.classes && inherits(x, of.class)) ) { if( !is.na(min.nrow) && !is.na(min.ncol) ) { return (nrow(x) >= min.nrow && ncol(x) >= min.ncol); } else { return (TRUE); } } else { return (FALSE); } }, logical(1)); all.objects <- all.objects[ objects.to.keep ]; } # Recursive processing: all.objects <- c(all.objects, .recursively.list.objects.in.memory(..., env = parent.env(env), of.class=of.class, min.nrow=min.nrow, min.ncol=min.ncol, return.dimensions=return.dimensions, consider.derived.classes=consider.derived.classes)); # Return the list of objects: return (all.objects); } } # In-memory dataset: update the list of data.frame-derived objects all the way to the base environment ---- observeEvent(input$datasource_type, { if( input$datasource_type == "already in memory" ) { # List all the data.frame-derived objects currently in memory: x <- sort(.recursively.list.objects.in.memory()); # If defined, add the data.frame sent to the Shiny plotting function: if( !is.null(.GlobalEnv$.plotting.params) && !is.null(.GlobalEnv$.plotting.params$data) && inherits(.GlobalEnv$.plotting.params$data, "data.frame")) { if( .GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments ) { # Add the function argument as well: x <- c("<<'data' argument to plot_interactive_cma() call>>", x); } } updateSelectInput(session, "dataset_from_memory", choices=x, selected=head(x,1)); } }) # In-memory dataset: list the columns and update the selections ---- observeEvent(input$dataset_from_memory, { # Disconnect any pre-existing database connections: if( !is.null(.GlobalEnv$.plotting.params$.db.connection) ) { try(DBI::dbDisconnect(.GlobalEnv$.plotting.params$.db.connection), silent=TRUE); .GlobalEnv$.plotting.params$.db.connection <- NULL; } # Set the data.frame: .GlobalEnv$.plotting.params$.inmemory.dataset <- NULL; if( input$dataset_from_memory == "[none]" || input$dataset_from_memory == "" ) { # Initialisation: return (invisible(NULL)); } else if( input$dataset_from_memory == "<<'data' argument to plot_interactive_cma() call>>" ) { # The special value pointing to the argument to plot_interactive_cma(): .GlobalEnv$.plotting.params$.inmemory.dataset <- .GlobalEnv$.plotting.params$data; } else { # Try to find it memory: try(.GlobalEnv$.plotting.params$.inmemory.dataset <- get(input$dataset_from_memory), silent=TRUE); } # Sanity checks: if( (input$dataset_from_memory != "[none]") && (is.null(.GlobalEnv$.plotting.params$.inmemory.dataset) || !inherits(.GlobalEnv$.plotting.params$.inmemory.dataset, "data.frame") || ncol(.GlobalEnv$.plotting.params$.inmemory.dataset) < 1 || nrow(.GlobalEnv$.plotting.params$.inmemory.dataset) < 1 )) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected dataset '",input$dataset_from_memory, "' from memory!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( (input$dataset_from_memory != "[none]") && nrow(.GlobalEnv$.plotting.params$.inmemory.dataset) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Dataset '",input$dataset_from_memory, "' must have at least three distinct columns (patient ID, event date and duration)!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } n.vals.to.show <-3; d <- as.data.frame(.GlobalEnv$.plotting.params$.inmemory.dataset); x <- names(d); x.info <- vapply(1:ncol(d), function(i) paste0("(", paste0(class(d[,i]),collapse=","), ": ", paste0(d[1:min(n.vals.to.show,nrow(d)),i],collapse=", "), if(nrow(d)>n.vals.to.show) "...", ")"), character(1)); # Required columns: shinyWidgets::updatePickerInput(session, "dataset_from_memory_patient_id", choices=x, selected=x[1], choicesOpt=list(subtext=x.info)); shinyWidgets::updatePickerInput(session, "dataset_from_memory_event_date", choices=x, selected=x[2], choicesOpt=list(subtext=x.info)); shinyWidgets::updatePickerInput(session, "dataset_from_memory_event_duration", choices=x, selected=x[3], choicesOpt=list(subtext=x.info)); # Optional columns (possibly used by CMA5+): shinyWidgets::updatePickerInput(session, "dataset_from_memory_medication_class", choices=c("[not defined]", x), selected="[not defined]", choicesOpt=list(subtext=c("", x.info))); shinyWidgets::updatePickerInput(session, "dataset_from_memory_daily_dose", choices=c("[not defined]", x), selected="[not defined]", choicesOpt=list(subtext=c("", x.info))); # Medication groups: shinyWidgets::updatePickerInput(session, "mg_from_column", choices=x, selected=x[1], choicesOpt=list(subtext=x.info)); }) # Display a data.frame as a nice HTML table ---- .show.data.frame.as.HTML <- function(d, # the data.frame-derived object to show max.rows=50, # if NA, show all escape=TRUE) { if( is.null(d) || !inherits(d, "data.frame") || nrow(d) < 1 || ncol(d) < 3 ) { return ("<b>The given dataset is empty, of the wrong type, or too small!</b>"); } # This is a pretty basic thing thet tweaks the output of knitr::kable... d.as.html <- knitr::kable(d[1:min(max.rows,nrow(d),na.rm=TRUE),], format="html", align="c", col.names=names(d), #col.names=paste0("\U2007\U2007",names(d),"\U2007\U2007"), row.names=FALSE); # The data.frame info in a nice HTML format: d.info <- paste0("An object of type", ifelse(length(class(d))>1,"s "," "), paste0("<i>",class(d),"</i>", collapse=", "), ". It has ", nrow(d), " rows × ", ncol(d), " columns [with type(s)]: <br/>", paste0(vapply(1:ncol(d),function(i) paste0("<b>",names(d)[i], "</b> [", paste0("<i>",class(d[,i]),"</i>",collapse=", "), "]"), character(1)), collapse=", "), "."); if( length(s <- strsplit(d.as.html, "<table", fixed=TRUE)[[1]]) > 1 ) { # Found the <table> tag: add its class and caption: d.as.html <- paste0(s[1], paste0("<table class='peekAtTable'", "<caption style='caption-side: top;'>", d.info,"</caption", # > is already in s[2] because of <table s[-1])); # Add the CSS: d.as.html <- paste0(d.as.html, "\n\n <style> table.peekAtTable { border: 1px solid #1C6EA4; background-color: #EEEEEE; #width: 100%; text-align: left; border-collapse: collapse; white-space: nowrap; } table.peekAtTable td, table.peekAtTable th { border: 1px solid #AAAAAA; padding: 0.2em 0.5em; } table.peekAtTable tbody td { font-size: 13px; } table.peekAtTable tr:nth-child(even) { background: #D0E4F5; } table.peekAtTable thead { background: #1C6EA4; background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%); background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%); background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%); border-bottom: 2px solid #444444; } table.peekAtTable thead th { font-size: 15px; font-weight: bold; color: #FFFFFF; border-left: 2px solid #D0E4F5; } table.peekAtTable thead th:first-child { border-left: none; } </style>\n"); } return (d.as.html); } # In-memory dataset: peek ---- observeEvent(input$dataset_from_memory_peek_button, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.inmemory.dataset) || !inherits(.GlobalEnv$.plotting.params$.inmemory.dataset, "data.frame") || ncol(.GlobalEnv$.plotting.params$.inmemory.dataset) < 1 || nrow(.GlobalEnv$.plotting.params$.inmemory.dataset) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected dataset '",input$dataset_from_memory, "' from memory!\nPlease make sure you selected a valid data.frame (or derived object) with at least 3 columns and 1 row..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } showModal(modalDialog(title="AdhereR: peeking at the selected in-memory dataset ...", div(HTML(.show.data.frame.as.HTML(.GlobalEnv$.plotting.params$.inmemory.dataset)), style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); }) # Validate a given dataset and possibly load it ---- .validate.and.load.dataset <- function(d, # the dataset get.colnames.fnc, get.patients.fnc, get.data.for.patients.fnc, # getter functions appropriate for the dataset min.npats=1, min.ncol=3, # minimum number of patients and columns ID.colname, event.date.colname, event.duration.colname, event.daily.dose.colname, medication.class.colname, # column names date.format # date format ) { # Check dataset dimensions: all.IDs <- get.patients.fnc(d, ID.colname); if( length(all.IDs) < min.npats || length(get.colnames.fnc(d)) < min.ncol ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected dataset!\nPlease make sure your selection is valid and has at least ",min.ncol," column(s) and data for at least ",min.npats," patient(s)..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Check if the column names refer to existing columns in the dataset: if( is.na(ID.colname) || length(ID.colname) != 1 || ID.colname=="" || !(ID.colname %in% get.colnames.fnc(d)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Patient ID column '",ID.colname, "' must be a string and a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( is.na(event.date.colname) || length(event.date.colname) != 1 || event.date.colname=="" || !(event.date.colname %in% get.colnames.fnc(d)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Event date column '",event.date.colname, "' must be a string and a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( is.na(event.duration.colname) || length(event.duration.colname) != 1 || event.duration.colname=="" || !(event.duration.colname %in% get.colnames.fnc(d)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Event duration column '",event.duration.colname, "' must be a string and a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( is.na(event.daily.dose.colname) || length(event.daily.dose.colname) != 1 || event.daily.dose.colname=="" ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Event duration column '",event.daily.dose.colname, "' must be a non-empty string..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else if( event.daily.dose.colname == "[not defined]" ) { event.daily.dose.colname <- NA; # not defined } else if( !(event.daily.dose.colname %in% get.colnames.fnc(d)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Event duration column '",event.daily.dose.colname, "' if given, must be either '[not defined]' or a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( is.na(medication.class.colname) || length(medication.class.colname) != 1 || medication.class.colname=="" ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Treatment class column '",medication.class.colname, "' must be a non-empty string..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else if( medication.class.colname == "[not defined]" ) { medication.class.colname <- NA; # not defined } else if( !(medication.class.colname %in% get.colnames.fnc(d)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Treatment class column '",medication.class.colname, "' if given, must be either '[not defined]' or a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Check if the column names are unique (i.e., do not repeat): if( anyDuplicated(na.omit(c(ID.colname, event.date.colname, event.duration.colname, event.daily.dose.colname, medication.class.colname))) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("The selected column names must be unique!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # More advanced checks of the column types: if( inherits(d, "data.frame") ) # for data.frame's { d <- as.data.frame(d); # force it to a data.frame to avoid unexpected behaviours from derived classes if( inherits(d[,event.date.colname], "Date") ) { # It's a column of Dates: perfect! } else if( is.factor(d[,event.date.colname]) || is.character(d[,event.date.colname]) ) { # It's a factor or string: check if it conforms to the given date.format: s <- na.omit(as.character(d[,event.date.colname])); if( length(s) == 0 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("There are no non-missing dates in the '",event.date.colname,"' column!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } tmp <- as.Date(s, format=input$dataset_from_memory_event_format); if( all(is.na(tmp)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Please check if the date format is correct and fits the actual dates in the '",event.date.colname,"' column: all conversions failed!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else if( any(is.na(tmp)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Please check if the date format is correct and fits the actual dates in the '",event.date.colname,"' column: ", length(is.na(tmp))," conversions failed!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } } else { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("The event date column '",event.date.colname,"' must contain either objects of class 'Date' or correctly-formatted strings (or factor levels)!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( !is.na(event.duration.colname) && (!is.numeric(d[,event.duration.colname]) || any(d[,event.duration.colname] < 0, na.rm=TRUE)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("If given, the event duration column '",event.duration.colname,"' must contain non-negative numbers!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } if( !is.na(event.daily.dose.colname) && (!is.numeric(d[,event.daily.dose.colname]) || any(d[,event.daily.dose.colname] < 0, na.rm=TRUE)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("If given, the daily dose column '",event.daily.dose.colname,"' must contain non-negative numbers!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } } # Even more complex check: try to compute CMA0 on the first patient: test.cma <- NULL; test.res <- tryCatch(test.cma <- AdhereR::CMA0(data=get.data.for.patients.fnc(all.IDs[1], d, ID.colname), ID.colname=ID.colname, event.date.colname=event.date.colname, event.duration.colname=event.duration.colname, event.daily.dose.colname=event.daily.dose.colname, medication.class.colname=medication.class.colname, date.format=date.format), error=function(e) e, warning=function(w) w); if( is.null(test.cma) || inherits(test.res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with these data!\nI tried to create a CMA0 object and this is what I got back:\n"), div(as.character(test.res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(test.res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("These data seem ok, but when I tried to create a CMA0 object I got some warnings:\n"), div(as.character(test.res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } ### Now, really load the data! ### # Place the data in the .GlobalEnv$.plotting.params list: .GlobalEnv$.plotting.params$data <- d; .GlobalEnv$.plotting.params$ID.colname <- ID.colname; .GlobalEnv$.plotting.params$event.date.colname <- event.date.colname; .GlobalEnv$.plotting.params$event.duration.colname <- event.duration.colname; .GlobalEnv$.plotting.params$event.daily.dose.colname <- event.daily.dose.colname; .GlobalEnv$.plotting.params$medication.class.colname <- medication.class.colname; .GlobalEnv$.plotting.params$date.format <- date.format; # This is a data.frame, so use the appropriate getters: .GlobalEnv$.plotting.params$get.colnames.fnc <- get.colnames.fnc; .GlobalEnv$.plotting.params$get.patients.fnc <- get.patients.fnc; .GlobalEnv$.plotting.params$get.data.for.patients.fnc <- get.data.for.patients.fnc; # CMA class: .GlobalEnv$.plotting.params$cma.class <- "simple"; # Patient IDs and selected ID: .GlobalEnv$.plotting.params$all.IDs <- all.IDs; .GlobalEnv$.plotting.params$ID <- all.IDs[1]; # Force UI updating... .force.update.UI(); } # In-memory dataset: validate and use ---- observeEvent(input$dataset_from_memory_button_use, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.inmemory.dataset) || !inherits(.GlobalEnv$.plotting.params$.inmemory.dataset, "data.frame") || ncol(.GlobalEnv$.plotting.params$.inmemory.dataset) < 1 || nrow(.GlobalEnv$.plotting.params$.inmemory.dataset) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected dataset '",input$dataset_from_memory, "' from memory!\nPlease make sure you selected a valid data.frame (or derived object) with at least 3 columns and 1 row..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Checks: .validate.and.load.dataset(.GlobalEnv$.plotting.params$.inmemory.dataset, get.colnames.fnc=function(d) names(d), get.patients.fnc=function(d, idcol) unique(d[[idcol]]), get.data.for.patients.fnc=function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ], ID.colname=input$dataset_from_memory_patient_id, event.date.colname=input$dataset_from_memory_event_date, event.duration.colname=input$dataset_from_memory_event_duration, event.daily.dose.colname=input$dataset_from_memory_daily_dose, medication.class.colname=input$dataset_from_memory_medication_class, date.format=input$dataset_from_memory_event_format); # Let the world know this: .GlobalEnv$.plotting.params$.dataset.type <- "in memory"; .GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments <- FALSE; if( input$dataset_from_memory == "[none]" ) { # How did we get here??? return (invisible(NULL)); } else if( input$dataset_from_memory == "<<'data' argument to plot_interactive_cma() call>>" ) { # The special value pointing to the argument to plot_interactive_cma(): .GlobalEnv$.plotting.params$.dataset.name <- NA; } else { .GlobalEnv$.plotting.params$.dataset.name <- input$dataset_from_memory; } }) # Force updating the Shiny UI using the new data ---- .force.update.UI <- function() { updateSelectInput(session, "cma_class", selected=.GlobalEnv$.plotting.params$cma.class); #updateSelectInput(session, "cma_to_compute", selected=.GlobalEnv$.plotting.params$cma.class); updateSelectInput(session, "patient", choices=.GlobalEnv$.plotting.params$all.IDs, selected=.GlobalEnv$.plotting.params$ID); updateSelectInput(session, "compute_cma_patient_by_id", choices=.GlobalEnv$.plotting.params$all.IDs, selected=.GlobalEnv$.plotting.params$all.IDs[1]); if( input$mg_definitions_source == 'named vector' ) { shinyWidgets::updatePickerInput(session, "mg_to_plot_list", choices=c(names(.GlobalEnv$.plotting.params$medication.groups), "* (all others)"), selected=c(names(.GlobalEnv$.plotting.params$medication.groups), "* (all others)")); } else if( input$mg_definitions_source == 'column in data' ) { if( !is.null(.GlobalEnv$.plotting.params$data) ) { mg_vals <- .GlobalEnv$.plotting.params$get.data.for.patients.fnc(.GlobalEnv$.plotting.params$all.IDs, .GlobalEnv$.plotting.params$data, idcol=.GlobalEnv$.plotting.params$ID.colname); if( !is.null(mg_vals) && length(mg_vals) > 0 ) { mg_vals <- unique(mg_vals[, input$mg_from_column]); mg_vals <- mg_vals[ !is.na(mg_vals) ]; if( !is.null(mg_vals) && length(mg_vals) > 0 ) { mg_vals <- sort(mg_vals); } } } else { mg_vals <- NULL; } shinyWidgets::updatePickerInput(session, "mg_to_plot_list", choices=c(mg_vals, "* (all others)"), selected=c(mg_vals, "* (all others)")); } #if( is.na(.GlobalEnv$.plotting.params$event.daily.dose.colname) ) shinyjs::hide(id="dose_is_defined") else shinyjs::show(id="dose_is_defined"); output$is_dose_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$event.daily.dose.colname) && !is.na(.GlobalEnv$.plotting.params$event.daily.dose.colname)}); output$is_treat_class_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$medication.class.colname) && !is.na(.GlobalEnv$.plotting.params$medication.class.colname)}); rv$toggle.me <- !rv$toggle.me; # make the plotting aware of a change (even if we did not change any UI elements) output$is_dataset_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$data)}); # now a dataset is defined! output$is_mg_defined <- reactive({!is.null(.GlobalEnv$.plotting.params$medication.groups)}); # and medication groups! } # Dataset from file: load it, list the columns and upate the selections ---- observeEvent(input$dataset_from_file_filename, { # Disconnect any pre-existing database connections: if( !is.null(.GlobalEnv$.plotting.params$.db.connection) ) { try(DBI::dbDisconnect(.GlobalEnv$.plotting.params$.db.connection), silent=TRUE); .GlobalEnv$.plotting.params$.db.connection <- NULL; } if( is.null(input$dataset_from_file_filename) || nrow(input$dataset_from_file_filename) < 1 ) { # No file loaded, nothing to do: return (invisible(NULL)); } # Try to parse and load it: d <- NULL; #.GlobalEnv$.plotting.params$.fromfile.dataset <- NULL; #output$is_file_loaded <- reactive({FALSE}); # Update UI if( input$dataset_from_file_filetype == "Comma/TAB-separated (.csv; .tsv; .txt)" ) { # Load CSV/TSV: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- read.table(input$dataset_from_file_filename$datapath[1], header=input$dataset_from_file_csv_header, sep=switch(input$dataset_from_file_csv_separator, "[TAB] (\\t)"="\t", "comma (,)"=",", "white spaces (1+)"="", "semicolon (;)"=";", "colon (:)"=":"), quote=switch(input$dataset_from_file_csv_quotes, "[none] ()"="", "singe quotes (' ')"="'", "double quotes (\" \")"='"'), dec=switch(input$dataset_from_file_csv_decimal, "dot (.)"=".", "comma (,)"=","), strip.white=input$dataset_from_file_csv_strip_white, na.strings=gsub('["\']','',trimws(strsplit(input$dataset_from_file_csv_na_strings,",",fixed=TRUE)[[1]], "both"))), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given CSV/TSV file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This CSV/TSV file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } else if( input$dataset_from_file_filetype == "R objects from save() (.RData)" ) { # Use load to recover them but then ask the user to use "load from memory" UI to continue... showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(read.objs <- load(input$dataset_from_file_filename$datapath[1]), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(read.objs) || length(read.objs) == 0 || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given R datasets file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This R datasets file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } # Show the user the objects that were read and redirect them to load them from memory: showModal(modalDialog(title="AdhereR R datasets file loaded!", HTML(paste0("The R datasets file was successfully loaded and the following objects are now in memory: ",paste0("'",read.objs,"'",collapse=", "),".<br/>Please use the <b>load from memory</b> option to load the desired object from memory...")), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); # don't continue... } else if( input$dataset_from_file_filetype == "Serialized R object (.rds)" ) { # Load them with readRDS: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- readRDS(input$dataset_from_file_filename$datapath[1]), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given serialized single R object file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This serialized single R object file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } } else if( input$dataset_from_file_filetype == "Open Document Spreadsheet (.ods)" ) { # Use readODS::read.ods to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- readODS::read_ods(input$dataset_from_file_filename$datapath[1], sheet=input$dataset_from_file_sheet), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given ODS file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This ODS file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } else if( input$dataset_from_file_filetype == "Microsoft Excel (.xls; .xlsx)" ) { # Use readxl::read_excel to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- readxl::read_excel(input$dataset_from_file_filename$datapath[1], sheet=input$dataset_from_file_sheet), #d <- openxlsx::read.xlsx(input$dataset_from_file_filename$datapath[1], sheet=input$dataset_from_file_sheet), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given XLS/XLSX file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This XLS/XLSX file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } else if( input$dataset_from_file_filetype == "SPSS (.sav; .por)" ) { # Use haven::read_spss to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- haven::read_spss(input$dataset_from_file_filename$datapath[1]), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given SPSS file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This SPSS file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } else if( input$dataset_from_file_filetype == "SAS Transport data file (.xpt)" ) { # Use haven::read_xpt to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- haven::read_xpt(input$dataset_from_file_filename$datapath[1]), #d <- SASxport::read.xport(input$dataset_from_file_filename$datapath[1], as.list=TRUE), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given SAS Transport file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This SAS Transport file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); #if( length(d) < input$dataset_from_file_sheet_sas ) #{ # showModal(modalDialog(title="AdhereR warning!", # paste0("This SAS Transport file contains only ",length(d)," datasets, so I can't load the ",input$dataset_from_file_sheet_sas,"th: loading the first instead!"), # footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); # d <- d[[1]]; #} else #{ # d <- d[[input$dataset_from_file_sheet_sas]]; #} } else if( input$dataset_from_file_filetype == "SAS sas7bdat data file (.sas7bdat)" ) { # Use haven::read_sas to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- haven::read_sas(input$dataset_from_file_filename$datapath[1]), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given SAS sas7bdat file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This SAS sas7bdat file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } else if( input$dataset_from_file_filetype == "Stata (.dta)" ) { # Use haven::read_stata to read the first sheet: showModal(modalDialog("Loading and processing data...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)); res <- tryCatch(d <- haven::read_stata(input$dataset_from_file_filename$datapath[1]), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There's something wrong with the given Stata file: I tried reading it and this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("This Stata file seems ok, but when reading it I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } d <- as.data.frame(d); } # Set it as the from-file dataset and update columns: if( !is.null(d) && inherits(d, "data.frame") ) { if( nrow(d) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("The selected file must have at least three distinct columns (patient ID, event date and duration)!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } n.vals.to.show <-3; x <- names(d); x.info <- vapply(1:ncol(d), function(i) paste0("(", paste0(class(d[,i]),collapse=","), ": ", paste0(d[1:min(n.vals.to.show,nrow(d)),i],collapse=", "), if(nrow(d)>n.vals.to.show) "...", ")"), character(1)); # Required columns: shinyWidgets::updatePickerInput(session, "dataset_from_file_patient_id", choices=x, selected=x[1], choicesOpt=list(subtext=x.info)); shinyWidgets::updatePickerInput(session, "dataset_from_file_event_date", choices=x, selected=x[2], choicesOpt=list(subtext=x.info)); shinyWidgets::updatePickerInput(session, "dataset_from_file_event_duration", choices=x, selected=x[3], choicesOpt=list(subtext=x.info)); # Optional columns (possibly used by CMA5+): shinyWidgets::updatePickerInput(session, "dataset_from_file_medication_class", choices=c("[not defined]", x), selected="[not defined]", choicesOpt=list(subtext=c("",x.info))); shinyWidgets::updatePickerInput(session, "dataset_from_file_daily_dose", choices=c("[not defined]", x), selected="[not defined]", choicesOpt=list(subtext=c("",x.info))); # set the dataset and various parameters used to read it: .GlobalEnv$.plotting.params$.fromfile.dataset <- d; .GlobalEnv$.plotting.params$.fromfile.dataset.filetype <- input$dataset_from_file_filetype; .GlobalEnv$.plotting.params$.fromfile.dataset.header <- input$dataset_from_file_csv_header; .GlobalEnv$.plotting.params$.fromfile.dataset.sep <- switch(input$dataset_from_file_csv_separator, "[TAB] (\\t)"="\t", "comma (,)"=",", "white spaces (1+)"="", "semicolon (;)"=";", "colon (:)"=":"); .GlobalEnv$.plotting.params$.fromfile.dataset.quote <- switch(input$dataset_from_file_csv_quotes, "[none] ()"="", "singe quotes (' ')"="'", "double quotes (\" \")"='"'); .GlobalEnv$.plotting.params$.fromfile.dataset.dec <- switch(input$dataset_from_file_csv_decimal, "dot (.)"=".", "comma (,)"=","); .GlobalEnv$.plotting.params$.fromfile.dataset.strip.white <- input$dataset_from_file_csv_strip_white; .GlobalEnv$.plotting.params$.fromfile.dataset.na.strings <- gsub('["\']','',trimws(strsplit(input$dataset_from_file_csv_na_strings,",",fixed=TRUE)[[1]], "both")); .GlobalEnv$.plotting.params$.fromfile.dataset.sheet <- input$dataset_from_file_sheet; output$is_file_loaded <- reactive({TRUE}); # Update UI to reflect this change } }) # Dataset from file: peek ---- observeEvent(input$dataset_from_file_peek_button, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.fromfile.dataset) || !inherits(.GlobalEnv$.plotting.params$.fromfile.dataset, "data.frame") || ncol(.GlobalEnv$.plotting.params$.fromfile.dataset) < 1 || nrow(.GlobalEnv$.plotting.params$.fromfile.dataset) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Could not load the selected file '",input$dataset_from_file_filename$name[1], "' in memory!\nPlease make sure you selected a valid file contaning at least 3 columns and 1 row...", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } showModal(modalDialog(title="AdhereR: peeking at the selected file ...", div(HTML(.show.data.frame.as.HTML(.GlobalEnv$.plotting.params$.fromfile.dataset)), style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); }) # Dataset from file: validate and use ---- observeEvent(input$dataset_from_file_button_use, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.fromfile.dataset) || !inherits(.GlobalEnv$.plotting.params$.fromfile.dataset, "data.frame") || ncol(.GlobalEnv$.plotting.params$.fromfile.dataset) < 1 || nrow(.GlobalEnv$.plotting.params$.fromfile.dataset) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected file '",input$dataset_from_file_filename$name[1], "'!\nPlease make sure you selected a valid file with at least 3 columns and 1 row..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Checks: .validate.and.load.dataset(.GlobalEnv$.plotting.params$.fromfile.dataset, get.colnames.fnc=function(d) names(d), get.patients.fnc=function(d, idcol) unique(d[[idcol]]), get.data.for.patients.fnc=function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ], ID.colname=input$dataset_from_file_patient_id, event.date.colname=input$dataset_from_file_event_date, event.duration.colname=input$dataset_from_file_event_duration, event.daily.dose.colname=input$dataset_from_file_daily_dose, medication.class.colname=input$dataset_from_file_medication_class, date.format=input$dataset_from_file_event_format); # Let the world know this: .GlobalEnv$.plotting.params$.dataset.type <- "from file"; .GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments <- FALSE; .GlobalEnv$.plotting.params$.dataset.name <- input$dataset_from_file_filename$name[1]; }) # SQL database: connect and fetch tables ---- observeEvent(input$dataset_from_sql_button_connect, { # Disconnect any pre-existing database connections: if( !is.null(.GlobalEnv$.plotting.params$.db.connection) ) { try(DBI::dbDisconnect(.GlobalEnv$.plotting.params$.db.connection), silent=TRUE); } updateSelectInput(session, inputId="dataset_from_sql_table", choices="[none]", selected="[none]"); .GlobalEnv$.plotting.params$.db.connection <- NULL; output$is_database_connected <- reactive({FALSE}); # update UI if( input$dataset_from_sql_server_type == "SQLite" ) { d <- NULL; res <- NULL; if( input$dataset_from_sqlite_database_name == "med_events" ) { # Create this one on-the-fly in memory: res <- tryCatch(d <- DBI::dbConnect(RSQLite::SQLite(), ":memory:", bigint="numeric"), error=function(e) e, warning=function(w) w); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't create the example in-memory SQLite database: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("Creating the example in-memory SQLite database seems ok, but when connecting I got some warnings:\n"), div(as.character(res, style="color: blue;")), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } # Put the data in: tmp <- AdhereR::med.events; tmp$DATE <- as.character(as.Date(tmp$DATE,format="%m/%d/%Y"),format="%Y-%m-%d"); # make sure the dates are in the YYYY-MM-DD SQL format res <- tryCatch(DBI::dbWriteTable(d, "med_events", tmp, overwrite=TRUE), error=function(e) e, warning=function(w) w); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't put med.events in the example in-memory SQLite database: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("Putting med.events in the example in-memory SQLite database seems ok, but when connecting I got some warnings:\n"), div(as.character(res, style="color: blue;")), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } } else { # Simply connect to the table: res <- tryCatch(d <- DBI::dbConnect(RSQLite::SQLite(), input$dataset_from_sqlite_database_name), error=function(e) e, warning=function(w) w); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't access the SQLite database: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("Accessing the SQLite database seems ok, but when connecting I got some warnings:\n"), div(as.character(res, style="color: blue;")), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } } # Fetch the tables: db_tables <- NULL; res <- tryCatch(db_tables <- DBI::dbListTables(d), error=function(e) e, warning=function(w) w); if( is.null(db_tables) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't read tables from the SQL server: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); removeModal(); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("Could read tables from SQL server, but I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } # Build a list of columns for each table: d.tables.columns <- do.call(rbind, lapply(db_tables, function(s) { x <- NULL; try(x <- DBI::dbGetQuery(d, paste0("PRAGMA table_info(",s,");")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") ) { n <- NULL; try(n <- DBI::dbGetQuery(d, paste0("SELECT COUNT(*) FROM ",s,";")), silent=TRUE); if( is.null(n) || !inherits(n, "data.frame") || nrow(n) != 1 || ncol(n) != 1 ) { # Error retreiving the number of rows: n <- NA; } else { n <- as.numeric(n[1,1]); } # Get first X values for each column: fr <- NULL; try(fr <- DBI::dbGetQuery(d, paste0("SELECT * FROM ",s," LIMIT 3;")), silent=TRUE); if( is.null(fr) || !inherits(fr, "data.frame") || nrow(fr) < 1 || ncol(fr) != nrow(x) ) { fr <- rep(nrow(x),""); } else { fr <- vapply(1:ncol(fr), function(i) paste0(as.character(fr[,i]),collapse=", "), character(1)); } return (data.frame("table"=s, "nrow"=n, "column"=x$name, "type"=x$type, "null"=(x$notnull == 0), "key"=(x$pk != 0), "firstvals"=fr)); } else { return (NULL); } })); } else if( input$dataset_from_sql_server_type == "MySQL/MariaDB" ) { d <- NULL; showModal(modalDialog("Connecting to SQL database...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)) res <- tryCatch(d <- DBI::dbConnect(RMariaDB::MariaDB(), # works also for MySQL user=input$dataset_from_sql_username, # the username password=input$dataset_from_sql_password, # and password dbname=if( input$dataset_from_sql_database_name == "[none]" ) NULL else input$dataset_from_sql_database_name, # which database host=if( input$dataset_from_sql_server_host == "[none]" ) NULL else input$dataset_from_sql_server_host, # on which host port=input$dataset_from_sql_server_port, # the TCP/IP port bigint="numeric" # force bigint to numeric to avoid weird problems down the line ), error=function(e) e, warning=function(w) w); removeModal(); if( is.null(d) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't connect to the SQL server: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("The SQL server seems ok, but when connecting I got some warnings:\n"), div(as.character(res, style="color: blue;")), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } # Fetch the tables: db_tables <- NULL; showModal(modalDialog("Reading tables from the SQL database...", title=div(icon("hourglass", lib="glyphicon"), "Please wait..."), easyClose=FALSE, footer=NULL)) res <- tryCatch(db_tables <- DBI::dbListTables(d), error=function(e) e, warning=function(w) w); if( is.null(db_tables) || inherits(res, "error") ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Can't read tables from the SQL server: this is what I got back:\n"), div(as.character(res), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); removeModal(); return (invisible(NULL)); } else { if( inherits(res, "warning") ) { showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("Could read tables from SQL server, but I got some warnings:\n"), div(as.character(res), style="color: blue;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } } # Build a list of columns for each table: d.tables.columns <- do.call(rbind, lapply(db_tables, function(s) { x <- NULL; # Get columns: try(x <- DBI::dbGetQuery(d, paste0("SHOW COLUMNS FROM ",s,";")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") ) { n <- NULL; # Get number of rows: try(n <- DBI::dbGetQuery(d, paste0("SELECT COUNT(*) FROM ",s,";")), silent=TRUE); if( is.null(n) || !inherits(n, "data.frame") || nrow(n) != 1 || ncol(n) != 1 ) { # Error retreiving the number of rows: n <- NA; } else { n <- as.numeric(n[1,1]); } # Get first X values for each column: fr <- NULL; try(fr <- DBI::dbGetQuery(d, paste0("SELECT * FROM ",s," LIMIT 3;")), silent=TRUE); if( is.null(fr) || !inherits(fr, "data.frame") || nrow(fr) < 1 || ncol(fr) != nrow(x) ) { fr <- rep(nrow(x),""); } else { fr <- vapply(1:ncol(fr), function(i) paste0(as.character(fr[,i]),collapse=", "), character(1)); } return (data.frame("table"=s, "nrow"=n, "column"=x$Field, "type"=x$Type, "null"=x$Null, "key"=x$Key, "firstvals"=fr)); } else { return (NULL); } })); removeModal(); } if( is.null(d.tables.columns) ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Could not fetch any info from the database!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Set it as the current SQL databse: .GlobalEnv$.plotting.params$.db.connection.tables <- d.tables.columns; .GlobalEnv$.plotting.params$.db.connection <- d; # Update the list of tables/views: x <- aggregate(column ~ nrow + table, d.tables.columns, length); x.eligible <- which(x$column >= 3); # which are the eligible tables/views x.to.pick <- 1; if( length(x.eligible) == 0 ) { # Warning: showModal(modalDialog(title=div(icon("warning-sign", lib="glyphicon"), "AdhereR warning!"), div("There doesn't seem to be any tables/views with at least 3 columns in this database: picking the first (but this will generate an error)!\n"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); x.to.pick <- 1; } else { x.to.pick <- x.eligible[1]; } shinyWidgets::updatePickerInput(session, "dataset_from_sql_table", choices=as.character(x$table), selected=as.character(x$table)[x.to.pick], choicesOpt=list(subtext=paste0(x$nrow," x ",x$column))); # Update UI: output$is_database_connected <- reactive({TRUE}); # Show the info: .show.db.info(); }) # SQL database: disconnect ---- observeEvent(input$dataset_from_sql_button_disconnect, { if( !is.null(.GlobalEnv$.plotting.params$.db.connection) ) { try(DBI::dbDisconnect(.GlobalEnv$.plotting.params$.db.connection), silent=TRUE); .GlobalEnv$.plotting.params$.db.connection <- NULL; } # Update UI: updateSelectInput(session, inputId="dataset_from_sql_table", choices="[none]", selected="[none]"); output$is_database_connected <- reactive({FALSE}); }) # SQL database: peek ---- observeEvent(input$dataset_from_sql_button_peek, { .show.db.info(); }) # SQL database: show info ---- .show.db.info <- function() { if( is.null(.GlobalEnv$.plotting.params$.db.connection.tables) || !inherits(.GlobalEnv$.plotting.params$.db.connection.tables, "data.frame") || nrow(.GlobalEnv$.plotting.params$.db.connection.tables) < 1 || is.null(.GlobalEnv$.plotting.params$.db.connection) || !DBI::dbIsValid(.GlobalEnv$.plotting.params$.db.connection) ) { # Some error occured! showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Error accessing the database!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Display the info: showModal(modalDialog(title="AdhereR SQL database connection...", div(style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;", HTML(paste0("Successfully connected to SQL server <i>", if( input$dataset_from_sql_server_host == "[none]" ) "localhost" else input$dataset_from_sql_server_host, "</i>", if( input$dataset_from_sql_server_port > 0 ) paste0(":",input$dataset_from_sql_server_port)," and fetched data from ", length(unique(.GlobalEnv$.plotting.params$.db.connection.tables$table))," tables.<br/><hl/><br/>", "Please note that, currently, this interactive Shiny User Interface <b style='color: red'>requires that all the data</b> (namely, patient ID, event date and duration,(and possibly dosage and type)) are in <b style='color: red'>ONE TABLE or VIEW</b>! ", "If this is not the case, please create a <i>temporary table</i> or a <i>view</i> and reconnect to the database. ", "(Please see the vignette for more details.) ", # "For example, using the <code>MySQL</code> database described in the vignette <i>Using AdhereR with various database technologies for processing very large datasets</i>, named <code>med_events</code> and consisting of 4 tables containing information about the patients (<code>patients</code>), the events (<code>event_info</code> and <code>event_date</code>), and the connections between the two (<code>event_patients</code>), we can create a <i>view</i> named <code>all_info_view</code> with the <code>SQL</code> commands:<br/>", # "<pre> # CREATE VIEW `all_info_view` AS # SELECT event_date.id, # event_date.date, # event_info.category, # event_info.duration, # event_info.perday, # event_patients.patient_id, # patients.sex # FROM event_date # JOIN event_info # ON event_info.id = event_date.id # JOIN event_patients # ON event_patients.id = event_info.id # JOIN patients # ON patients.id = event_patients.patient_id;</pre>", "<br/><hl/><br/>", "We list below, for each <b style='color: DarkBlue'>table</b>, the <b style='color: blue'>columns</b> [with their <span style='color: green'>types</span> and other <i>relevant info</i>], possibly followed by the first few values:<br/>", "<ul>", paste0(vapply(unique(.GlobalEnv$.plotting.params$.db.connection.tables$table), function(table_name) { s <- which(.GlobalEnv$.plotting.params$.db.connection.tables$table == table_name); if( length(s) > 0 ) { paste0("<li><b style='color: DarkBlue'>", table_name, "</b>", ": ", if( is.na(.GlobalEnv$.plotting.params$.db.connection.tables$nrow[s[1]]) ) "<span style='color: red'>ERROR RETREIVING NUMBER OF ROWS</span>" else paste0("with ", .GlobalEnv$.plotting.params$.db.connection.tables$nrow[s[1]]," row(s)"), "<ul>", paste0(vapply(s, function(i) paste0("<li><b style='color: blue'>", .GlobalEnv$.plotting.params$.db.connection.tables$column[i], "</b>", " [<span style='color: green'>", .GlobalEnv$.plotting.params$.db.connection.tables$type[i], "</span>", if( .GlobalEnv$.plotting.params$.db.connection.tables$key[i] == "PRI" ) ", <i>primary key</i>", "]", " ",.GlobalEnv$.plotting.params$.db.connection.tables$firstvals[i], "</li>"), character(1)), collapse="\n"), "</ul>", "</li>") } }, character(1)), collapse="\n"), "</ul>" ))), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } # SQL database: update columns depending on the selected table ---- observeEvent(input$dataset_from_sql_table, { if( input$dataset_from_sql_table != "[none]" && !is.null(.GlobalEnv$.plotting.params$.db.connection) && !is.null(.GlobalEnv$.plotting.params$.db.connection.tables) && sum((s <- (.GlobalEnv$.plotting.params$.db.connection.tables$table == input$dataset_from_sql_table)), na.rm=TRUE) > 0 ) { if( sum(s) < 3 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("The table/view must have at least three columns!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Save this as the selected table: .GlobalEnv$.plotting.params$.db.connection.selected.table <- input$dataset_from_sql_table; # Update them: column.names <- as.character(.GlobalEnv$.plotting.params$.db.connection.tables$column[s]); column.info <- paste0("(",.GlobalEnv$.plotting.params$.db.connection.tables$type[s],": ",.GlobalEnv$.plotting.params$.db.connection.tables$firstvals[s],")"); shinyWidgets::updatePickerInput(session, "dataset_from_sql_patient_id", choices=column.names, selected=column.names[1], choicesOpt=list(subtext=column.info)); shinyWidgets::updatePickerInput(session, "dataset_from_sql_event_date", choices=column.names, selected=column.names[2], choicesOpt=list(subtext=column.info)); shinyWidgets::updatePickerInput(session, "dataset_from_sql_event_duration", choices=column.names, selected=column.names[3], choicesOpt=list(subtext=column.info)); shinyWidgets::updatePickerInput(session, "dataset_from_sql_daily_dose", choices=c("[not defined]", column.names), selected="[not defined]", choicesOpt=list(subtext=c("",column.info))); shinyWidgets::updatePickerInput(session, "dataset_from_sql_medication_class", choices=c("[not defined]", column.names), selected="[not defined]", choicesOpt=list(subtext=c("",column.info))); } }) # SQL database: validate and use ---- observeEvent(input$dataset_from_sql_button_use, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.db.connection) || !DBI::dbIsValid(.GlobalEnv$.plotting.params$.db.connection) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot use the selected database and table/view!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Check and load: .validate.and.load.dataset(.GlobalEnv$.plotting.params$.db.connection, get.colnames.fnc= if(input$dataset_from_sql_server_type == "SQLite") { function(d) { if( is.null(d) || !DBI::dbIsValid(d) ){ warning("Connection to database lost!"); return (NULL); } x <- NULL; try(x <- DBI::dbGetQuery(d, paste0("PRAGMA table_info(",.GlobalEnv$.plotting.params$.db.connection.selected.table,");")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") && nrow(x) > 0 ) return (as.character(x$name)) else { warning("Cannot fetch DB column names!"); return (NULL); } } } else if(input$dataset_from_sql_server_type == "MySQL/MariaDB") { function(d) { if( is.null(d) || !DBI::dbIsValid(d) ){ warning("Connection to database lost!"); return (NULL); } x <- NULL; try(x <- DBI::dbGetQuery(d, paste0("SHOW COLUMNS FROM ",.GlobalEnv$.plotting.params$.db.connection.selected.table,";")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") && nrow(x) > 0 ) return (as.character(x$Field)) else { warning("Cannot fetch DB column names!"); return (NULL); } } }, get.patients.fnc= function(d, idcol) { if( is.null(d) || !DBI::dbIsValid(d) ){ warning("Connection to database lost!"); return (NULL); } x <- NULL; try(x <- DBI::dbGetQuery(d, paste0("SELECT DISTINCT ",idcol," FROM ",.GlobalEnv$.plotting.params$.db.connection.selected.table,";")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") && nrow(x) > 0 ) return (x[,1]) else { warning("Cannot fetch patients from DB!"); return (NULL); } }, get.data.for.patients.fnc= function(patientid, d, idcol, cols=NA, maxrows=NA) { if( is.null(d) || !DBI::dbIsValid(d) ){ warning("Connection to database lost!"); return (NULL); } x <- NULL; try(x <- DBI::dbGetQuery(d, paste0("SELECT ", if(is.na(cols)) "*" else paste0(cols,collapse=","), " FROM ",.GlobalEnv$.plotting.params$.db.connection.selected.table, " WHERE ",idcol, " IN (",paste0(patientid,collapse=","),")", if(!is.na(maxrows)) paste0("LIMIT ",maxrows), ";")), silent=TRUE); if( !is.null(x) && inherits(x, "data.frame") && nrow(x) > 0 ) return (x) else { warning("Cannot fetch data for patient(s) from DB!"); return (NULL); } }, ID.colname=input$dataset_from_sql_patient_id, event.date.colname=input$dataset_from_sql_event_date, event.duration.colname=input$dataset_from_sql_event_duration, event.daily.dose.colname=input$dataset_from_sql_daily_dose, medication.class.colname=input$dataset_from_sql_medication_class, date.format=input$dataset_from_sql_event_format); # Let the world know this: .GlobalEnv$.plotting.params$.dataset.type <- "SQL database"; .GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments <- FALSE; .GlobalEnv$.plotting.params$.dataset.name <- paste0({if( input$dataset_from_sql_username != "" ) paste0(input$dataset_from_sql_username," @ ")}, {if( input$dataset_from_sql_server_host == "[none]" ) "localhost" else input$dataset_from_sql_server_host}, {if( input$dataset_from_sql_server_port > 0 ) paste0(":",input$dataset_from_sql_server_port)}, " :: ",.GlobalEnv$.plotting.params$.db.connection.selected.table); }) # Show info about the curent dataset ---- observeEvent(input$about_dataset_button, { showModal(modalDialog(title=div(icon("hdd", lib="glyphicon"), "AdhereR: info over the current dataset..."), div(style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;", HTML(if( .GlobalEnv$.plotting.params$.dataset.type %in% c("in memory", "from file", "SQL database") ) { paste0("The dataset currently used ", {if(.GlobalEnv$.plotting.params$.dataset.comes.from.function.arguments) { paste0("was given as the <code>data</code> argument to the <code>plot_interactive_cma()</code> function called by the user.<br/>", "Therefore, we cannot know its name outside the function call (and there might not be such a \"name\" as the data might have been created on-the-fly in the function call), and instead we identify it as the <b style='color:darkblue'><<'data' argument to plot_interactive_cma() call>></b> of class <i>", paste0(class(.GlobalEnv$.plotting.params$data),collapse=","), "</i>." ) } else { paste0("was manualy defined as ", switch(.GlobalEnv$.plotting.params$.dataset.type, "in memory"=paste0("an object of class <i>data.frame</i> (or derived from it, such a <i>data.table</i>) that was already <b>in-memory</b> under the name <b style='color:darkblue'>",.GlobalEnv$.plotting.params$.dataset.name,"</b>"), "from file"=paste0("a <i>data.frame</i> object loaded <b>from the file</b> <b style='color:darkblue'>",.GlobalEnv$.plotting.params$.dataset.name,"</b>"), "SQL database"=paste0("a connection to the <b>SQL database</b> <b style='color:darkblue'>",.GlobalEnv$.plotting.params$.dataset.name,"</b>") ), ".") } }, "<br/><hr/>", "These data has <b>", length(.GlobalEnv$.plotting.params$get.colnames.fnc(.GlobalEnv$.plotting.params$data)), " columns</b>, ", "and contains info for <b>", length(unique(.GlobalEnv$.plotting.params$get.patients.fnc(.GlobalEnv$.plotting.params$data, .GlobalEnv$.plotting.params$ID.colname))), " patients</b>.<br/>", "The relevant information is distributed as:</br>", "<ul>", "<li>the <i>patient IDs</i> are in column <b>", .GlobalEnv$.plotting.params$ID.colname, "</b></li>", "<li>the event <i>dates</i> are in column <b>", .GlobalEnv$.plotting.params$event.date.colname, "</b></li>", "<li>the event <i>durations</i> are in column <b>", .GlobalEnv$.plotting.params$event.duration.colname, "</b></li>", {if(!is.na(.GlobalEnv$.plotting.params$event.daily.dose.colname)) paste0("<li>the <i>doses</i> are in column <b>", .GlobalEnv$.plotting.params$event.daily.dose.colname, "</b></li>")}, {if(!is.na(.GlobalEnv$.plotting.params$medication.class.colname)) paste0("<li>the <i>treatment types</i> are in column <b>", .GlobalEnv$.plotting.params$medication.class.colname, "</b></li>")}, "</ul>" ) } else { "There was no argument (or a NULL) passed as the <code>data</code> argument to the <code>plot_interactive_cma()</code>, which means that there's no dataset defined: please define one using the <b>Data</b> tab!" } )), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); }) # Update the patient IDs table ---- .update.patients.IDs.table <- function(reset.slider=TRUE) { if( is.null(.GlobalEnv$.plotting.params$all.IDs) || length(.GlobalEnv$.plotting.params$all.IDs) < 1 ) { .GlobalEnv$.plotting.params$all.IDs <- c("[not defined]"); } tmp <- data.frame("#"= 1:length(.GlobalEnv$.plotting.params$all.IDs), "ID"= if( input$compute_cma_patient_by_group_sorting == "by ID (↑)" ) { sort(.GlobalEnv$.plotting.params$all.IDs, decreasing=FALSE) } else if( input$compute_cma_patient_by_group_sorting == "by ID (↓)" ) { sort(.GlobalEnv$.plotting.params$all.IDs, decreasing=TRUE) } else { .GlobalEnv$.plotting.params$all.IDs }, check.names=FALSE); .GlobalEnv$.plotting.params$.patients.to.compute <- tmp; output$show_patients_as_list <- renderDataTable(.GlobalEnv$.plotting.params$.patients.to.compute, options=list(pageLength=10)); if( reset.slider ) updateSliderInput(session, inputId="compute_cma_patient_by_group_range", max=nrow(tmp), value=c(1,1)); } observeEvent(input$compute_cma_patient_selection_method, { if( input$compute_cma_patient_selection_method == "by_position" ) { .update.patients.IDs.table(); } }) observeEvent(input$compute_cma_patient_by_group_sorting, { .update.patients.IDs.table(); }) # Basic checks for a putative vector containing medication group definitions: .check.basic.mg.definition <- function(v) { return (!( is.null(v) || # must be non-NULL (!is.character(v) && !is.factor(v)) || # must be a vector of characters or factors length(v) == 0 || # of at least length 1 length(v <- v[!is.na(v)]) == 0 || # and with at least 1 non-NA element is.null(names(v)) || # must have names "" %in% names(v) || # that are non-empty any(duplicated(names(v))) )); # and unique } # In-memory medication groups: get the list of appropriate vectors objects all the way to the base environment ---- .list.mg.from.memory <- function() { # List all the character or factor vectors currently in memory: x <- sort(c(.recursively.list.objects.in.memory(of.class="character", min.nrow=NA, min.ncol=NA, return.dimensions=FALSE), .recursively.list.objects.in.memory(of.class="factor", min.nrow=NA, min.ncol=NA, return.dimensions=FALSE))); if( is.null(x) || length(x) == 0 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There are no fitting medication group definitions in memory!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } else { # Check that they meet the basic requirements for medication group definitions: s <- vapply(x, function(v) .check.basic.mg.definition(get(v)), logical(1)); if( !any(s) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("There are no fitting medication group definitions in memory!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } else { # Keep only these: x <- x[s]; # If defined, add the medication groups sent to the Shiny plotting function: if( !is.null(.GlobalEnv$.plotting.params) && !is.null(.GlobalEnv$.plotting.params$medication.groups) && (is.character(.GlobalEnv$.plotting.params$medication.groups) || is.factor(.GlobalEnv$.plotting.params$medication.groups))) { if( .GlobalEnv$.plotting.params$.mg.comes.from.function.arguments ) { # Add the function argument as well: x <- c("<<'medication.groups' argument to plot_interactive_cma() call>>", x); } } updateSelectInput(session, "mg_from_memory", choices=x, selected=x[1]); .update.mg.inmemory(); } } } # In-memory vector: update the selections ---- .update.mg.inmemory <- function() { # Set the vector: .GlobalEnv$.plotting.params$.inmemory.mg <- NULL; if( input$mg_from_memory == "[none]" || input$mg_from_memory == "" ) { # Initialisation: .GlobalEnv$.plotting.params$.inmemory.mg <- NULL; } else if( input$mg_from_memory == "<<'medication.groups' argument to plot_interactive_cma() call>>" ) { # The special value pointing to the argument to plot_interactive_cma(): .GlobalEnv$.plotting.params$.inmemory.mg <- .GlobalEnv$.plotting.params$medication.groups; } else { try(.GlobalEnv$.plotting.params$.inmemory.mg <- get(input$mg_from_memory), silent=TRUE); if( inherits(.GlobalEnv$.plotting.params$.inmemory.mg, "try-error") ) .GlobalEnv$.plotting.params$.inmemory.mg <- NULL; } # Sanity checks: if( (input$mg_from_memory != "[none]") && (is.null(.GlobalEnv$.plotting.params$.inmemory.mg) || (!is.character(.GlobalEnv$.plotting.params$.inmemory.mg) && !is.factor(.GlobalEnv$.plotting.params$.inmemory.mg)) || length(.GlobalEnv$.plotting.params$.inmemory.mg) < 1 )) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected medication group definitions '",input$mg_from_memory, "' from memory!"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Update the relevant UI elements: updateRadioButtons(session, "mg_list_of_groups", choices=if( is.null(.GlobalEnv$.plotting.params$.inmemory.mg) ) {"<EMPTY>"} else {names(.GlobalEnv$.plotting.params$.inmemory.mg)}, selected=NULL); } observeEvent(input$mg_from_memory, { .update.mg.inmemory(); }) # Display a vector of medication groups nicely as HTML ---- .show.medication.groups.as.HTML <- function(mg, # the vector to show max.entries=200, # if NA, show all escape=TRUE) { if( !.check.basic.mg.definition(mg) ) { return ("<b>The given medication group definitions are empty of the wrong type!</b>"); } # Highlight things in the definitions using HTML tags: # The calls: for( s in names(mg) ) { mg <- gsub(paste0("{",s,"}"), paste0("{<b><i>",s,"</i></b>}"), mg, fixed=TRUE); } # The names: names(mg) <- paste0("<b><i>",names(mg),"</i></b>"); # This is a pretty basic thing that tweaks the output of knitr::kable... d <- data.frame("Name"=names(mg), "Definition"=mg); d.as.html <- knitr::kable(d[1:min(max.entries,nrow(d),na.rm=TRUE),], format="html", align="l", col.names=names(d), #col.names=paste0("\U2007\U2007",names(d),"\U2007\U2007"), row.names=FALSE); # Put back the HTML tags: d.as.html <- gsub("&lt;/i&gt;", "</i>", gsub("&lt;i&gt;", "<i>", gsub("&lt;/b&gt;", "</b>", gsub("&lt;b&gt;", "<b>", d.as.html, fixed=TRUE), fixed=TRUE), fixed=TRUE), fixed=TRUE); # The data.frame info in a nice HTML format: d.info <- paste0("There are ", nrow(d), " medication groups defined."); if( length(s <- strsplit(d.as.html, "<table", fixed=TRUE)[[1]]) > 1 ) { # Found the <table> tag: add its class and caption: d.as.html <- paste0(s[1], paste0("<table class='peekAtMGTable'", "<caption style='caption-side: top;'>", d.info,"</caption", # > is already in s[2] because of <table s[-1])); # Add the CSS: d.as.html <- paste0(d.as.html, "\n\n <style> table.peekAtMGTable { border: 1px solid #1C6EA4; background-color: #fbfcfc; #width: 100%; text-align: left; border-collapse: collapse; #white-space: nowrap; } table.peekAtMGTable td, table.peekAtMGTable th { border: 1px solid #AAAAAA; padding: 0.2em 0.5em; } table.peekAtMGTable tbody td { font-size: 13px; } table.peekAtMGTable tr:nth-child(even) { background: #f0f3f4; } table.peekAtMGTable thead { background: #1C6EA4; background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%); background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%); background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%); border-bottom: 2px solid #444444; } table.peekAtMGTable thead th { font-size: 15px; font-weight: bold; color: #FFFFFF; border-left: 2px solid #D0E4F5; } table.peekAtMGTable thead th:first-child { border-left: none; } </style>\n"); } return (d.as.html); } # In-memory medication groups: peek ---- observeEvent(input$mg_from_memory_peek_button, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.inmemory.mg) || (!is.character(.GlobalEnv$.plotting.params$.inmemory.mg) && !is.factor(.GlobalEnv$.plotting.params$.inmemory.mg)) || length(.GlobalEnv$.plotting.params$.inmemory.mg) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected medication group definitions '",input$mg_from_memory, "' from memory!\nPlease make sure you selected a valid vector of definitions..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } showModal(modalDialog(title="AdhereR: the selected in-memory medication group definitions ...", div(HTML(.show.medication.groups.as.HTML(.GlobalEnv$.plotting.params$.inmemory.mg)), style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); }) # View the currently selected medication group definitions ---- observeEvent(input$mg_view_button, { # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$medication.groups) || (!is.character(.GlobalEnv$.plotting.params$medication.groups) && !is.factor(.GlobalEnv$.plotting.params$medication.groups)) || length(.GlobalEnv$.plotting.params$medication.groups) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("The medication group definitions seems to be of the wrong type or empty!\n"), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } showModal(modalDialog(title="AdhereR: the medication group definitions ...", div(HTML(.show.medication.groups.as.HTML(.GlobalEnv$.plotting.params$medication.groups)), style="max-height: 50vh; max-width: 90vw; overflow: auto; overflow-x:auto;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); }) # Validate a given medication groups definition and possibly load it ---- .validate.and.load.medication.groups <- function(mg, # the vector of definitions or column name d=NULL # the data.frame to which these definitions refer to (or NULL for no such checks) ) { # Place the data in the .GlobalEnv$.plotting.params list: .GlobalEnv$.plotting.params$medication.groups <- mg; .GlobalEnv$.plotting.params$medication.groups.to.plot <- NULL; # Force UI updating... .force.update.UI(); } # In-memory medication group definitions: validate and use ---- observeEvent(input$mg_from_memory_button_use, { if( input$mg_definitions_source == 'named vector' ) { # From a named vector in memory: # Sanity checks: if( is.null(.GlobalEnv$.plotting.params$.inmemory.mg) || (!is.character(.GlobalEnv$.plotting.params$.inmemory.mg) && !is.factor(.GlobalEnv$.plotting.params$.inmemory.mg)) || length(.GlobalEnv$.plotting.params$.inmemory.mg) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("Cannot load the selected medication group definitions '",input$mg_from_memory, "' from memory!\nPlease make sure you selected a valid vector of definitions..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Checks: .validate.and.load.medication.groups(.GlobalEnv$.plotting.params$.inmemory.mg, .GlobalEnv$.plotting.params$data); # Let the world know this: .GlobalEnv$.plotting.params$.mg.type <- "in memory"; .GlobalEnv$.plotting.params$.mg.comes.from.function.arguments <- FALSE; if( input$mg_from_memory == "[none]" ) { # How did we get here??? return (invisible(NULL)); } else if( input$mg_from_memory == "<<'medication.groups' argument to plot_interactive_cma() call>>" ) { # The special value pointing to the argument to plot_interactive_cma(): .GlobalEnv$.plotting.params$.mg.name <- NA; } else { .GlobalEnv$.plotting.params$.mg.name <- input$mg_from_memory; } } else if( input$mg_definitions_source == 'column in data' ) { # From column in the data: # Check if the column name refers to an existing column in the dataset: if( is.na(input$mg_from_column) || length(input$mg_from_column) != 1 || input$mg_from_column=="" || !(input$mg_from_column %in% .GlobalEnv$.plotting.params$get.colnames.fnc(.GlobalEnv$.plotting.params$data)) ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div(paste0("The medication groups column '",ID.colname, "' must be a string and a valid column name in the selected dataset..."), style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); return (invisible(NULL)); } # Validate and load the medication groups .validate.and.load.medication.groups(input$mg_from_column, .GlobalEnv$.plotting.params$data); # Let the world know this: .GlobalEnv$.plotting.params$.mg.type <- "column in data"; .GlobalEnv$.plotting.params$.mg.comes.from.function.arguments <- FALSE; if( input$mg_from_column == "[none]" ) { # How did we get here??? return (invisible(NULL)); } else if( input$mg_from_column == "<<'medication.groups' argument to plot_interactive_cma() call>>" ) { # The special value pointing to the argument to plot_interactive_cma(): .GlobalEnv$.plotting.params$.mg.name <- NA; } else { .GlobalEnv$.plotting.params$.mg.name <- input$mg_from_column; } } }) # Show selected medication groups ---- observeEvent(input$mg_plot_apply_button, { # Sanity checks: # Let the world know this: .GlobalEnv$.plotting.params$medication.groups.to.plot <- input$mg_to_plot_list; # Re-plot things: rv$toggle.me <- !rv$toggle.me; # make the plotting aware of the changes }) # CMA computation for multiple patients ---- # Allow the user to break it and show progress (inspired by https://gist.github.com/jcheng5/1659aff15904a0c4ffcd4d0c7788f789 ) # The CMA computation main UI ---- observeEvent(input$compute_cma_for_larger_sample_button, { # Get the selected patient IDs: if( input$compute_cma_patient_selection_method == "by_id" ) { patients.to.compute <- input$compute_cma_patient_by_id; } else if( input$compute_cma_patient_selection_method == "by_position" ) { if( is.null(.GlobalEnv$.plotting.params$.patients.to.compute) || !inherits(.GlobalEnv$.plotting.params$.patients.to.compute, "data.frame") ) { .update.patients.IDs.table(reset.slider=FALSE); # for re-udating this table (there were left-over from previous computations that result in an ugly crash (but keep range)... } patients.to.compute <- .GlobalEnv$.plotting.params$.patients.to.compute$ID[ .GlobalEnv$.plotting.params$.patients.to.compute$`#` %in% input$compute_cma_patient_by_group_range[1]:input$compute_cma_patient_by_group_range[2] ]; } # Checks concerning the maximum number of patients and events to plot: msgs <- NULL; if( length(patients.to.compute) > .GlobalEnv$.plotting.params$max.number.patients.to.compute ) { patients.to.compute <- patients.to.compute[ 1:.GlobalEnv$.plotting.params$max.number.patients.to.compute ]; msgs <- c(msgs, paste0("Warning: a maximum of ",.GlobalEnv$.plotting.params$max.number.patients.to.compute, " patients can be shown in an interactive plot: we kept only the first ",.GlobalEnv$.plotting.params$max.number.patients.to.compute, " from those you selected!\n")); } data.for.patients <- .GlobalEnv$.plotting.params$get.data.for.patients.fnc(patients.to.compute, .GlobalEnv$.plotting.params$data, .GlobalEnv$.plotting.params$ID.colname) n.events.per.patient <- cumsum(table(data.for.patients[,.GlobalEnv$.plotting.params$ID.colname])); if( !is.null(data.for.patients) && nrow(data.for.patients) > .GlobalEnv$.plotting.params$max.number.events.to.compute ) { n <- min(which(n.events.per.patient > .GlobalEnv$.plotting.params$max.number.events.to.compute)); if( n > 1 ) n <- n-1; patients.to.compute <- patients.to.compute[ 1:n ]; msgs <- c(msgs, paste0("Warning: a maximum of ",.GlobalEnv$.plotting.params$max.number.events.to.compute, " events across all patients can be shown in an interactive plot: we kept only the first ",length(patients.to.compute), " patients from those you selected (totalling ",n.events.per.patient[n]," events)!\n")); } .GlobalEnv$.plotting.params$.patients.to.compute <- patients.to.compute; # Where there any messages or anyhting else wrong? Ask the user if they are sure they want to start this... r.ver.info <- sessionInfo(); cma.computation.progress.log.text <<- ""; try(output$cma_computation_progress_log <- renderText(cma.computation.progress.log.text), silent=TRUE); showModal(modalDialog(title=div(icon("play", lib="glyphicon"), "AdhereR..."), div(div(if(!is.null(msgs)) paste0("There ",ifelse(length(msgs)==1,"was a warning",paste0("were ",length(msgs)," warnings")),":\n") else ""), div(HTML(paste0(msgs,collapse="<br/>")), style="color: red;"), div(HTML(paste0("We will compute the selected CMA for the <b>",length(patients.to.compute)," patients</b>:"))), div(paste0(patients.to.compute,collapse=", "), style="overflow: auto; max-height: 10em; color: blue;"), div(HTML(paste0("totalling <b>",n.events.per.patient[length(patients.to.compute)]," events</b>."))), div(HTML(paste0("The running time is limited to <b>",.GlobalEnv$.plotting.params$max.running.time.in.minutes.to.compute," minutes</b>."))), div(HTML("The actual <code>R</code> code needed to compute the selected CMA for any set of patients and data source can be accessed through the "), span(icon("eye-open", lib="glyphicon"), strong("Show R code..."), style="border: 1px solid darkblue; border-radius: 5px; color: darkblue; background-color: lightblue"), HTML(" button in the main window (please ignore the plotting code).<br/>")), hr(), div(HTML(paste0("We are using ",R.version.string, " and AdhereR version ",descr <- utils::packageDescription("AdhereR")$Version, " on ",r.ver.info$running,"."))), hr(), shinyWidgets::progressBar(id="cma_computation_progress", value=0, display_pct=TRUE, status="info", title="Progress:"), div(title="Progress long...", strong("Progress log:"), br(), div(htmlOutput(outputId="cma_computation_progress_log", inline=FALSE), id="cma_computation_progress_log_container", style="height: 5em; overflow: auto; border-radius: 5px; border-style: solid; border-width: 2px; background-color: #f0f0f0;")) ), footer = tagList(span(title="Close this dialog box", actionButton(inputId="close_compute_cma_dialog", label="Close", icon=icon("remove", lib="glyphicon"))), span(title="Start computation...", actionButton(inputId="start_computation_now", label="Start!", icon=icon("play", lib="glyphicon"))), span(title="Stop computation...", shinyjs::disabled(actionButton(inputId="cancel_cma_computation", label="Stop!", icon=icon("stop", lib="glyphicon")))), span(title="Save the results to a TAB-separated (no quotes) CSV file...", shinyjs::disabled(downloadButton(outputId="save_cma_computation_results", label="Save results (as TSV)", icon=icon("floppy-save", lib="glyphicon")))) ))); }) # Close the CMA computation main UI ---- observeEvent(input$close_compute_cma_dialog, { removeModal(); }) # observeEvent(input$start_computation_now, # { # session=shiny::getDefaultReactiveDomain(); # # Show up the progress bar and stopping button: # #showModal(modalDialog(title=div(icon("hourglass", lib="glyphicon"), paste0("Computing CMA for ",length(.GlobalEnv$.plotting.params$.patients.to.compute)," patients: please wait...")), # # #div(checkboxInput(inputId="stop_cma_computation", label="STOP!", value=FALSE)), # # actionButton("stop","Stop",class="btn-danger", onclick="Shiny.onInputChange('stopThis',true)"), # # footer=NULL)); # # cat(session$input$cma_class); # cat('Computing CMA for patient: '); # withProgress(message="", detail="", # min=0, max=length(.GlobalEnv$.plotting.params$.patients.to.compute), value=0, # { # start.time <- Sys.time(); # for(i in seq_along(.GlobalEnv$.plotting.params$.patients.to.compute) ) # { # # Show the patient currently processed: # cur.time <- Sys.time(); # time.left <- difftime(cur.time, start.time, units="sec"); # incProgress(0, # message=paste0("Computing patient ",.GlobalEnv$.plotting.params$.patients.to.compute[i]), # detail=paste0(" (",round(difftime(cur.time, start.time, units="sec"),1),"s)")); # cat(paste0(.GlobalEnv$.plotting.params$.patients.to.compute[i]," (",round(difftime(cur.time, start.time, units="sec"),1),"s)",", ")); # # # The computation: # Sys.sleep(1); # # # Increment the progress: # incProgress(1); # # # Stop? # httpuv:::service(); # invalidateLater(1); # cat(input$cma_class); # if( !is.null(session$input$stopThis) && session$input$stopThis ) # { # cat("\nCancelled....\n") # break; # } # } # incProgress(0, # message=paste0("Completed in ",round(difftime(cur.time, start.time, units="sec"),1)," seconds!"), detail=""); # cat("DONE in ",round(difftime(cur.time, start.time, units="sec"),1)," seconds\n"); # Sys.sleep(2); # wait a bit for the message to be (possibly) seen... # }); # # removeModal(); # }) # Compute CMA for one patient ---- .compute.cma.for.patient <- function(i, start.time) { # Show the patient currently processed: cur.time <- Sys.time(); #cat(paste0(.GlobalEnv$.plotting.params$.patients.to.compute[i]," (",round(difftime(cur.time, start.time, units="sec"),1),"s)",", ")); shinyWidgets::updateProgressBar(session, id="cma_computation_progress", value=(i/length(.GlobalEnv$.plotting.params$.patients.to.compute))*100, title=paste0("Progress: computing CMA for patient '", .GlobalEnv$.plotting.params$.patients.to.compute[i],"' (", i," of ",length(.GlobalEnv$.plotting.params$.patients.to.compute),"); time: ", round(difftime(cur.time, start.time, units="sec"),1)," seconds.")); # The computation: res <- NULL; compute.start.time <- Sys.time(); msgs <- capture.output(res <- .GlobalEnv$.plotting.params$.plotting.fnc(data=.GlobalEnv$.plotting.params$data, ID.colname=.GlobalEnv$.plotting.params$ID.colname, event.date.colname=.GlobalEnv$.plotting.params$event.date.colname, event.duration.colname=.GlobalEnv$.plotting.params$event.duration.colname, event.daily.dose.colname=.GlobalEnv$.plotting.params$event.daily.dose.colname, medication.class.colname=.GlobalEnv$.plotting.params$medication.class.colname, date.format=.GlobalEnv$.plotting.params$date.format, ID=.GlobalEnv$.plotting.params$.patients.to.compute[i], medication.groups=if( input$mg_use_medication_groups ){ .GlobalEnv$.plotting.params$medication.groups }else{ NULL }, medication.groups.separator.show=input$mg_plot_by_patient, medication.groups.to.plot=.GlobalEnv$.plotting.params$medication.groups.to.plot, medication.groups.separator.lty=input$plot_mg_separator_lty, medication.groups.separator.lwd=input$plot_mg_separator_lwd, medication.groups.separator.color=input$plot_mg_separator_color, medication.groups.allother.label=input$plot_mg_allothers_label, cma=ifelse(input$cma_class == "simple", input$cma_to_compute, input$cma_class), cma.to.apply=ifelse(input$cma_class == "simple", "none", ifelse(input$cma_to_compute_within_complex == "CMA0", "CMA1", input$cma_to_compute_within_complex)), # don't use CMA0 for complex CMAs #carryover.within.obs.window=FALSE, #carryover.into.obs.window=FALSE, carry.only.for.same.medication=input$carry_only_for_same_medication, consider.dosage.change=input$consider_dosage_change, followup.window.start=ifelse(input$followup_window_start_unit== "calendar date", as.Date(input$followup_window_start_date, format="%Y-%m-%d"), as.numeric(input$followup_window_start_no_units)), followup.window.start.unit=ifelse(input$followup_window_start_unit== "calendar date", "days", input$followup_window_start_unit), followup.window.duration=as.numeric(input$followup_window_duration), followup.window.duration.unit=input$followup_window_duration_unit, observation.window.start=ifelse(input$observation_window_start_unit== "calendar date", as.Date(input$observation_window_start_date, format="%Y-%m-%d"), as.numeric(input$observation_window_start_no_units)), observation.window.start.unit=ifelse(input$observation_window_start_unit== "calendar date", "days", input$observation_window_start_unit), observation.window.duration=as.numeric(input$observation_window_duration), observation.window.duration.unit=input$observation_window_duration_unit, medication.change.means.new.treatment.episode=input$medication_change_means_new_treatment_episode, dosage.change.means.new.treatment.episode=input$dosage_change_means_new_treatment_episode, maximum.permissible.gap=as.numeric(input$maximum_permissible_gap), maximum.permissible.gap.unit=input$maximum_permissible_gap_unit, sliding.window.start=as.numeric(input$sliding_window_start), sliding.window.start.unit=input$sliding_window_start_unit, sliding.window.duration=as.numeric(input$sliding_window_duration), sliding.window.duration.unit=input$sliding_window_duration_unit, sliding.window.step.duration=as.numeric(input$sliding_window_step_duration), sliding.window.step.unit=input$sliding_window_step_unit, sliding.window.no.steps=ifelse(input$sliding_window_step_choice == "number of steps" , as.numeric(input$sliding_window_no_steps), NA), get.colnames.fnc=.GlobalEnv$.plotting.params$get.colnames.fnc, get.patients.fnc=.GlobalEnv$.plotting.params$get.patients.fnc, get.data.for.patients.fnc=.GlobalEnv$.plotting.params$get.data.for.patients.fnc, compute.cma.only=TRUE # just compute the CMA, no plotting please! )); # Display result summary and return full info (including any messages/warnings/errors): if( is.null(res) || length(grep("error", msgs, ignore.case=TRUE)) > 0 ) { # Errors: cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<span style='color: red;'>Patient <b>", .GlobalEnv$.plotting.params$.patients.to.compute[i], "</b> <b>failed</b> after ", round(difftime(Sys.time(),compute.start.time,units="sec"),2)," seconds", if(length(msgs)>1) paste0(" with error(s): ", paste0("'",msgs,"'",collapse="; ")), ".</span><br/>"); } else if( length(grep("warning", msgs, ignore.case=TRUE)) > 0 ) { # Warnings: cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<span style='color: blue;'>Patient <b>", .GlobalEnv$.plotting.params$.patients.to.compute[i], "</b> finished <b>successfully</b> after ", round(difftime(Sys.time(),compute.start.time,units="sec"),2)," seconds", if(length(msgs)>1) paste0(", but with warning(s): ", paste0("'",msgs,"'",collapse="; ")), ".</span><br/>"); } else { # Normal output: cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<span style='color: black;'>Patient <b>", .GlobalEnv$.plotting.params$.patients.to.compute[i], "</b> finished <b>successfully</b> after ", round(difftime(Sys.time(),compute.start.time,units="sec"),2)," seconds", if(length(msgs)>1) paste0(" with message(s): ", paste0("'",msgs,"'",collapse="; ")), ".</span><br/>"); } # Print progress so far... output$cma_computation_progress_log <- renderText(cma.computation.progress.log.text); shinyjs::js$scroll_cma_compute_log(); # make sure the last message is in view # Return the results: if( !input$mg_use_medication_groups ) { # No medication groups: return (AdhereR::getCMA(res)); } else { # Medication groups: return (AdhereR::getCMA(res, flatten.medication.groups=TRUE)); } } # Collect computed CMA for several patients ---- collected.results <<- list(); cma.computation.progress.log.text <<- ""; workQueue <- function(start.time = Sys.time(), max.time = Inf, # max run time (in seconds, Inf == forever) cancel = cancelFunc, onSuccess = NULL, onError = stop) { i <- 1; if (is.null(onSuccess)) { onSuccess <- function(...) NULL } result <- list(); makeReactiveBinding("result"); observe( { if( i > length(.GlobalEnv$.plotting.params$.patients.to.compute) ) # natural finishing { #message("Finished naturally"); result <<- i; #removeModal(); shinyjs::enable('start_computation_now'); shinyjs::disable('cancel_cma_computation'); shinyjs::enable('close_compute_cma_dialog'); if( !is.null(collected.results) && length(collected.results) > 0 ) shinyjs::enable('save_cma_computation_results'); shinyWidgets::updateProgressBar(session, id="cma_computation_progress", value=100, title=paste0("Finished for all ",length(.GlobalEnv$.plotting.params$.patients.to.compute)," patients, took ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds.")); cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<br/>Finished for all ",length(.GlobalEnv$.plotting.params$.patients.to.compute)," patients, took ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds."); output$cma_computation_progress_log <- renderText(cma.computation.progress.log.text); shinyjs::js$scroll_cma_compute_log(); # make sure the last message is in view return(); } time.spent <- difftime(Sys.time(), start.time, units="sec"); if( time.spent > max.time ) # finished because the time ran out { #message("Ran out of time"); result <<- Inf; # ran out of time #removeModal(); shinyjs::enable('start_computation_now'); shinyjs::disable('cancel_cma_computation'); shinyjs::enable('close_compute_cma_dialog'); if( !is.null(collected.results) && length(collected.results) > 0 ) shinyjs::enable('save_cma_computation_results'); shinyWidgets::updateProgressBar(session, id="cma_computation_progress", value=(i/length(.GlobalEnv$.plotting.params$.patients.to.compute))*100, title=paste0("Stopped after ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds, succesfully computed for ",i," patients.")); cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<br/>Stopped after ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds, succesfully computed for ",i," patients."); output$cma_computation_progress_log <- renderText(cma.computation.progress.log.text); shinyjs::js$scroll_cma_compute_log(); # make sure the last message is in view return(); } if( isolate(cancel()) ) { #message("Cancelled by user"); #collected.results <<- list(); # erase the results collected so far... result <- NA; # cancelled by user #removeModal(); shinyjs::enable('start_computation_now'); shinyjs::disable('cancel_cma_computation'); shinyjs::enable('close_compute_cma_dialog'); if( !is.null(collected.results) && length(collected.results) > 0 ) shinyjs::enable('save_cma_computation_results'); shinyWidgets::updateProgressBar(session, id="cma_computation_progress", value=(i/length(.GlobalEnv$.plotting.params$.patients.to.compute))*100, title=paste0("Manually cancelled after ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds, succesfully computed for ",i," patients.")); cma.computation.progress.log.text <<- paste0(cma.computation.progress.log.text, "<br/>Manually cancelled after ",round(difftime(Sys.time(), start.time, units="sec"),1)," seconds, succesfully computed for ",i," patients."); output$cma_computation_progress_log <- renderText(cma.computation.progress.log.text); shinyjs::js$scroll_cma_compute_log(); # make sure the last message is in view return(); } tryCatch( { collected.results[[length(collected.results) + 1]] <<- isolate(.compute.cma.for.patient(i, start.time)); names(collected.results)[length(collected.results)] <- .GlobalEnv$.plotting.params$.patients.to.compute[i]; result <<- i; }, error = onError) i <<- i + 1; invalidateLater(1); }); reactive(req(result)); } # observeEvent(input$go, # { # isCancelled <- local( # { # origCancel <- isolate(input$cancel_cma_computation); # function() { !identical(origCancel, input$cancel_cma_computation) } # }); # # cat('Computing CMA for patient: '); # collected.results <<- list(); # result <- workQueue(patients=.GlobalEnv$.plotting.params$.patients.to.compute, # cancel=isCancelled); # # #observe( # #{ # # val <- result(); # # message("The result was ", val); # #}); # }) # Start CMA computation ---- observeEvent(input$start_computation_now, { # Show up the progress bar and stopping button: #showModal(modalDialog(title=div(icon("hourglass", lib="glyphicon"), paste0("Computing CMA for ",length(.GlobalEnv$.plotting.params$.patients.to.compute)," patients: please wait...")), # #div(checkboxInput(inputId="stop_cma_computation", label="STOP!", value=FALSE)), # #actionButton("go", "Go"), # actionButton("cancel_cma_computation", "Stop"), # footer=NULL)); shinyjs::disable('start_computation_now'); shinyjs::enable('cancel_cma_computation'); shinyjs::disable('close_compute_cma_dialog'); shinyjs::disable('save_cma_computation_results'); shinyWidgets::updateProgressBar(session, id="cma_computation_progress", value=0); isCancelled <- local( { origCancel <- isolate(input$cancel_cma_computation); function() { !identical(origCancel, input$cancel_cma_computation) } }); #cat('Computing CMA for patient: '); collected.results <<- list(); cma.computation.progress.log.text <<- ""; result <- workQueue(cancel=isCancelled); #observe( #{ # val <- result(); # message("The result was ", val); #}); }) # observeEvent(input$save_cma_computation_results, # { # if( is.null(collected.results) || length(collected.results) < 1 ) # { # showModal(modalDialog(title="Adherer warning...", "No results to export...")); # return (invisible(NULL)); # } # # # Assemble the results as a single data.frame: # d <- NULL; # try(d <- do.call(rbind, collected.results), silent=TRUE); # if( !is.null(d) || !inherits(d, "data.frame") || nrow(d) < 1 || ncol(d) < 1 ) # { # showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), # div("Error collecting the results of the CMA computation: nothing to save to file!", style="color: red;"), # footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); # return (invisible(NULL)); # } # # # Ask the user for a file to save them to: # # }) # Export results to file ---- output$save_cma_computation_results <- downloadHandler( filename = function() paste0("adherer-compute-",input$cma_class,"-",ifelse(input$cma_class=="simple", input$cma_to_compute, input$cma_to_compute_within_complex),"-results.tsv"), content = function(file) { if( is.null(collected.results) || length(collected.results) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "Adherer warning..."), "No results to export...")); } else { # Assemble the results as a single data.frame: d <- NULL; try(d <- do.call(rbind, collected.results), silent=FALSE); if( is.null(d) || !inherits(d, "data.frame") || nrow(d) < 1 || ncol(d) < 1 ) { showModal(modalDialog(title=div(icon("exclamation-sign", lib="glyphicon"), "AdhereR error!"), div("Error collecting the results of the CMA computation: nothing to save to file!", style="color: red;"), footer = tagList(modalButton("Close", icon=icon("ok", lib="glyphicon"))))); } else { # Write them to file: write.table(d, file=file, col.names=TRUE, row.names=FALSE, quote=FALSE, sep="\t"); } } } ) # Make sure the UI is properly updated for each new session ---- isolate( { .list.mg.from.memory(); .force.update.UI(); removeModal(); shinyjs::show(id="sidebar_tabpanel_container"); #updateCheckboxInput(session, inputId="output_panel_container_show", value=TRUE); shinyjs::show(id="output_panel_container"); }) } # Call shiny ---- shinyApp(ui=ui, server=server);
/scratch/gouwar.j/cran-all/cranData/AdhereRViz/inst/interactivePlotShiny/app.R
--- title: "AdhereR: Interactive plotting (and more) with Shiny" author: "Dan Dediu <[email protected]>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: yes toc_depth: 4 fig_caption: yes vignette: > %\VignetteEncoding{UTF-8} %\VignetteIndexEntry{AdhereR: Interactive plotting (and more) with Shiny} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'} # Various Rmarkdown output options: # center figures and reduce their file size: knitr::opts_chunk$set(fig.align = "center", dpi=100, dev="jpeg"); ``` ## Introduction [`AdhereR`](https://cran.r-project.org/package=AdhereR) is an [`R`](https://www.r-project.org/) package that implements, in an open and standardized manner, various methods linked to the estimation of *adherence to treatment* from a variety of data sources and formats (please see the other vignettes in the package, by involving, for example `browseVignettes(package="AdhereR")` or by visiting the package's site on [CRAN](https://cran.r-project.org/package=AdhereR)). One of the main aims of the package is to allow users to produce high quality, publication-ready and highly customizable *graphical representations* of both the patterns in the raw data and of the various estimates of adherence. This can be normally achieved from an `R` session or script using the `plot()` function applied to an estimated `CMA` object (the raw patterns are plotted by creating a basic `CMA0` object), as detailed in the [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) vignette. However, while allowing for a very fine-grained control over the resulting plots, this requires a certain level of familiarity with `R` (loading the source data, creating the appropriate `CMA` object, invoking the `plot()` function with the desired parameters, and the export of the resulting plot in the desired format at the quality and with the other desired characteristics), on the one hand, and the process is rather cumbersome when the user wants to explore and understand the data, or to try various types of plotting in search for the optimal visualization, on the other. These reasons prompted us to develop a *fully interactive user interface* that should hide the "gory details" of data loading, `CMA` computation and `plot()` invocation under an intuitive and easy to use point-and-click interface, while allowing fast exploration and customization of the plots. However, because this interactive user interface covers a rather particular set of use cases, tends to be rather "heavy" in terms of dependencies, and may not install or run properly in some environments (e.g., headless servers or older systems), we decided to implement it in a separate package, `AdhereRViz` that extends `AdhereR` (i.e., `AdhereRViz` requires `AdhereR`, but `AdhereR` cn happily run without `AdhereRViz`). ## Overview We use [`Shiny`](https://shiny.rstudio.com/), which allows us to build a *self-contained app* that can be run locally or remotely inside a standard *web browser* (such as [Firefox](https://www.mozilla.org/en-US/firefox/), [Google Chrome](https://www.google.com/chrome/), [Safari](https://www.apple.com/lae/safari/), [Internet Explorer](https://en.wikipedia.org/wiki/Internet_Explorer), [Edge](https://www.microsoft.com/en-us/edge) or [Opera](https://www.opera.com/)) on multiple *Operating Systems* (such as [Microsoft Windows](https://www.microsoft.com/en-us/windows), Apple's [macOS]https://en.wikipedia.org/wiki/MacOS) and [iOS](https://en.wikipedia.org/wiki/IOS), Google's [Android](https://www.android.com/), and several flavors of Linux -- e.g., [Debian](https://www.debian.org/), [Ubuntu](https://ubuntu.com/), [Fedora](https://getfedora.org/en/), [RedHat](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux), [CentOS](https://www.centos.org/), [Arch](https://archlinux.org/)... -- and BSD -- e.g., [FreeBSD](https://www.freebsd.org/)) and *devices* ranging from desktop and laptop computers to mobile phones and tablets. The app's interface uses *standard controls and paradigms*, ensuring a similar user experience across browsers, platforms and devices. ## Launching the app **Locally**, the app can be launched from a normal `R` session (including from within `RStudio`) or script with a single command; of course, the latest version of `AdhereR` and `AdhereRViz` must be *installed* on the system (using, for example, `install.packages("AdhereRViz", dep=TRUE)` or `RStudio`'s *Tools* → *Install Packages...* menu; or, in case it is already installed, updated using `update.packages()` or `RStudio`'s *Tools* → *Check for Package Updates...* menu), and *loaded* in the current session (using, for example, `library(AdhereRViz)` or `require(AdhereRViz)`). With these prerequisites in order, the app can be launched without any parameters with ```{r eval=FALSE} plot_interactive_cma() ``` or, if so desired, by specifying a data source and the important column names and optionally the desired `CMA`, as in the following example, where we use `CMA0` (i.e., the raw data) from the sample dataset `med.events` (see its structure in the **Table** below) included with the `AdhereR` package: ```{r eval=FALSE} plot_interactive_cma(data=med.events, # included sample dataset cma.class="simple", # simple cma, defaults to CMA0 # The important column names: ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", # The format of dates in the "DATE" column: date.format="%m/%d/%Y"); ``` | PATIENT_ID| DATE| PERDAY| CATEGORY| DURATION| |----------:|----------:|------:|--------:|--------:| | 1|03/22/2035 | 2|medB | 30| | 1|03/31/2035 | 2|medB | 30| | 2|01/20/2036 | 4|medA | 50| | 2|03/10/2036 | 4|medA | 50| | 2|08/01/2036 | 4|medA | 50| | 2|08/01/2036 | 4|medB | 60| | 2|09/21/2036 | 4|medB | 60| | 2|01/24/2037 | 4|medB | 60| | 2|04/16/2037 | 4|medB | 60| | 2|05/08/2037 | 4|medB | 60| | 3|04/13/2042 | 4|medA | 50| Table: The structure of the sample dataset `med.events` included in the `AdhereR` package. We shows the rows 23 to 33 (out of a total of 1080 rows), each row representing one *event* which is characterized **at the minimum** by: the *patient* it refers to (identified by the patient's unique ID in column `PATIENT_ID`), the *date* it happened (in column `DATE`, recorded in a uniform format, here MM/DD/YYYY), its *duration* in days (in column `DURATION`); **optionally** we can also have info concerning the prescribed daily quantity or *dose* (column `PERDAY`) and the class or type of treatment (column `CATEGORY`). We will use this dataset throughout this vignette. The app can also be launched in the "standard way" using `runApp()` or `RStudio`'s **<span style='color: green'>▶︎</span> Run app** button. Alternatively, the app may be made available on a **remote server**, such as on <https://www.shinyapps.io/>, in which case it can be accessed simply by pointing the web browser to the app's internet address. Please note that launching the App with no parameters, opens with a different screen (see the [**Selecting/changing the *data source***](#ui-datasource) section for details). Also note that there we provide a "stub" function `plot_interactive_cma()` in the package `AdhereR`, but this simply checks if `AdhereRViz` is installed and functional, and then tries to invoke `plot_interactive_cma()` from `AdhereRViz`. ## The App's User Interface (UI) {#ui-overview} The App's UI has several main elements which can be seen below. Most UI elements have **tooltips** that show up on hovering the mouse over the element and that offer specific information (but please note that these tooltips might need some time before showing up). ![**Overview of the User Interface.** Screenshot (App is running in Firefox on macOS 10.13) of some of the main UI elements (dotted black ellipses or rectangles identified with black numbers). **1** is a button that opens a box giving information about the App. **2** is a button that exist the App cleanly (i.e., stops and disconnects the session). **3** is the main plotting area which displays the current plot. **4** shows some of the UI elements controlling the plot (element 4) size. **5** is the area where various parameters can be modified. **6** opens UI elements specific for saving the current plot to file. **7** shows the `R` code that can be used to generate the current plot. **8** gives access to UI controls that allow the computation of the current CMA for many more patients and saving the results to file. **9** displays messages, warnings or errors that might have been geenrated while constructing the current plot.](shiny-overview.jpg) ### *About* the App Clicking on the **About** button (element **1** in [the overview figure](#ui-overview)) opens a box with info about the App, such as the version of the `AdhereR` package, and overview of the package and links to where more help (such as vignettes) can be found. ### Cleanly *exiting* the App It is recommended to cleanly exit the App by clicking the **Exit...** button (element **2** in [the overview figure](#ui-overview)), as simply closing the browser will *not* normally also stop the `R` process running in the background. Please note that currently, exiting the App will not also close the browser window or tab in which the App was running... ### The *plotting area* (and the *messages*) The current plot is displayed in the UI element **3** (in [the overview figure](#ui-overview)), a *canvas* that can be re-sized using the UI elements **4** in [the overview figure](#ui-overview) (see also below) and which, when too big, can be scrolled horizontally and vertically at will. This canvas is currently *passive* in the sense that it simply displays a plot which which interaction is possible only using the other elements of the UI, but almost all aspects of this plot can be tweaked using controls from the *left-hand side vertical panel* (element **5** in [the overview figure](#ui-overview); see details below). While the interpretation of these plots should be relatively intuitive, it is nevertheless detailed in the [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) vignette. Element **9** in [the overview figure](#ui-overview) displays most of the <span style='color: blue;'>information messages</span>, <span style='color: green;'>warnings</span> and <span style='color: red;'>errors</span> generated during the plotting process (please note that currently some messages, warnings and errors might not be captured and only shown in the `R` console). For example, here, the informational message <span style='color: blue;'>Plotting patient ID '1' with CMA 'CMA9' Plotting patient ID '2' with CMA 'CMA9'</span> means that the computation and plotting of `CMA9` for patients with IDs `1` and `2` was successful. Elements **4** in [the overview figure](#ui-overview) allow the control of the horizontal and vertical dimensions of the plot **3** either coupled (i.e., keeping the current width--to-height ratio), when the **Keep ratio** switch is **ON**, or independently of each other, when the switch is **OFF** (in which case a new slider controlling the plot height appears). The interaction with the slider(s) can be done either with mouse or with the arrow keys. Please note that there is a minimum size requirement for a plot to be displayed, otherwise an error of the type <span style='color: red;'>Plotting area is too small (it must be at least 10 x 0.5 characters per event, but now it is only 31.1 x 0.5)!</span> is thrown, in which case either the plotting area needs to be increased using the **Plot width** (and, if visible, **Plot height**) slider(s), or the number of patients or the duration to be shown need to be reduced. Alternatively, the <b style='color: darkblue'>Advanced</b> section (see Section **Setting *parameters*** for details) can be used to decrease these minimum requirements (but this not recommended in most cases). ### *Saving* the current plot to file The current plot can be exported to a variety of formats by turning the **Save plot!** switch **ON**: ![**Saving the current plot to file.** A zoom-in of the new controls (element **10**) revealed by turning the **Save plot!** switch (UI element **6**) **ON**. Also visible is an explanatory *tooltip* .](shiny-saveplot.jpg) These new UI elements (**10**) allow: - the definition of the exported plot's size (*width* and *height*) - in terms of the selected *unit*, currently *in* (inches), *cm* (centimeters), *mm* (millimeters) and *px* (pixels) - the type of image, currently *jpg* (JPEG), *png* (PNG), *tiff* (TIFF), *eps* (Encapsulated Postscript) and *pdf* (PDF) -- usually TIFF and EPS are accepted for publication - at a given *resultion* in dots-per-inch (DPI) -- used only by the raster formats JPEG, PNG and TIFF (usually a minimum of 300 DPI are needed for publication). By pressing the **Save plot** button, the user can select the location and file name (relative to the local machine) under which the plot will be exported. ### Viewing, copying and using the *`R` code* that would produce the current plot While the main use scenarios for this App are built around interactivity, the user may want to generate the same (or similar) plots as the one currently displayed (in element **3** in [the overview figure](#ui-overview)). To allow this, we provide the **Show R code...** button (element **7** in [the overview figure](#ui-overview)), which opens a box with the clearly commented `R` code: ![**Viewing the `R` code that can generates the current plot.**](shiny-rcode.jpg) Clicking the **Copy to clipboard** button copies the `R` code to the clipboard, from where it can be pasted into an editor of choice (such as `RStudio`). In particular, for the plot shown in [the overview figure](#ui-overview), the `R` code displayed is: ```{r eval=FALSE} # The R code corresponding to the currently displayed Shiny plot: # # Extract the data for the selected 2 patient(s) with ID(s): # "1", "2" # # We denote here by DATA the data you are using in the Shiny plot. # This was manually defined as an object of class data.frame # (or derived from it, such a data.table) that was already in # memory under the name 'med.events'. # Assuming this object still exists with the same name, then: DATA <- med.events; # These data has 5 columns, and contains info for 100 patients. # # To allow using data from other sources than a "data.frame" # and other similar structures (for example, from a remote SQL # database), we use a metchanism to request the data for the # selected patients that uses a function called # "get.data.for.patients.fnc()" which you may have redefined # to better suit your case (chances are, however, that you are # using its default version appropriate to the data source); # in any case, the following is its definition: get.data.for.patients.fnc <- function(patientid, d, idcol, cols=NA, maxrows=NA) d[ d[[idcol]] %in% patientid, ] # Try to extract the data only for the selected patient ID(s): .data.for.selected.patients. <- get.data.for.patients.fnc( c("1", "2"), DATA, ### don't forget to put here your REAL DATA! ### "PATIENT_ID" ); # Compute the appropriate CMA: cma <- CMA9(data=.data.for.selected.patients., # (please note that even if some parameters are # not relevant for a particular CMA type, we # nevertheless pass them as they will be ignored) ID.colname="PATIENT_ID", event.date.colname="DATE", event.duration.colname="DURATION", event.daily.dose.colname="PERDAY", medication.class.colname="CATEGORY", carry.only.for.same.medication=FALSE, consider.dosage.change=FALSE, followup.window.start=0, followup.window.start.unit="days", followup.window.duration=730, followup.window.duration.unit="days", observation.window.start=0, observation.window.start.unit="days", observation.window.duration=730, observation.window.duration.unit="days", date.format="%m/%d/%Y" ); if( !is.null(cma) ) # if the CMA was computed ok { # Try to plot it: plot(cma, # (same idea as for CMA: we send arguments even if # they aren't used in a particular case) align.all.patients=FALSE, align.first.event.at.zero=FALSE, show.legend=TRUE, legend.x="right", legend.y="bottom", legend.bkg.opacity=0.5, legend.cex=0.75, legend.cex.title=1, duration=NA, show.period="days", period.in.days=90, bw.plot=FALSE, col.na="#D3D3D3", unspecified.category.label="drug", col.cats=rainbow, lty.event="solid", lwd.event=2, pch.start.event=15, pch.end.event=16, col.continuation="#000000", lty.continuation="dotted", lwd.continuation=1, cex=1, cex.axis=1, cex.lab=1.25, highlight.followup.window=TRUE, followup.window.col="#00FF00", highlight.observation.window=TRUE, observation.window.col="#FFFF00", observation.window.density=35, observation.window.angle=-30, observation.window.opacity=0.3, show.real.obs.window.start=TRUE, real.obs.window.density=35, real.obs.window.angle=30, print.CMA=TRUE, CMA.cex=0.5, plot.CMA=TRUE, CMA.plot.ratio=0.1, CMA.plot.col="#90EE90", CMA.plot.border="#006400", CMA.plot.bkg="#7FFFD4", CMA.plot.text="#006400", plot.CMA.as.histogram=TRUE, show.event.intervals=TRUE, print.dose=TRUE, print.dose.outline.col="#FFFFFF", print.dose.centered=FALSE, plot.dose=FALSE, lwd.event.max.dose=8, plot.dose.lwd.across.medication.classes=FALSE, min.plot.size.in.characters.horiz=10, min.plot.size.in.characters.vert=0.5 ); } ``` This code is pretty much ready to be run, except for some issues that might surround accessing the actual data used for plotting: the user is reminded of these through the <span style="color: yellow; background-color: red; font-weight: bold; font-style: italic;">yellow-on-red bold italic</span> highlighting of `DATA` (not shown in the code listing above). In a nutshell (for details, see below), if (a) the user interactively uses the App to load or connect to a data source (such as an external file or an SQL database), then the identity of this data source is known (the file name or the database location), but if (b) the data source was passed to the `plot_interactive_cma()` function as the `data` argument, the App cannot know how this data source was named (and this "name" might not even exist if, for example, the data was created on-the-fly while calling the `plot_interactive_cma()` function). Wickedly, even in case (a), it is generally unsafe to assume that the data source will stay the same (or will be accessible in the same way) in the future. Thus, while we provide as much info about the data source used to produce the current plot as possible, we also warn the user to be careful when running this code! ### *Computing* the CMA for several patients By switching the UI element **8** (in [the overview figure](#ui-overview)) **Compute CMA for several patients...** to **ON**, the user unlocks a new set of UI elements that allow the computation of the currently defined `CMA` for more patients and the export of the results to an external file. First, it is important to highlight that the App is *not* intended for heavy computations, which explains why we are currently limiting this CMA computation to at most **100 patients**, at most **5000 events** across all patients (if more patients or events are selected, the computation will be done for only the first 100 and 5000, respectively) and for at most **5 minutes** of running time (after which the computation is automatically stopped). If seriously heavy computation is needed, we recommend the use of the appropriate `CMA()` functions from and `R` session or script, which allow many types of parallel processing and the use of several types of data sources with very fine-grained control, as described in the vignettes [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) and [Using AdhereR with various database technologies for processing very large datasets](https://cran.r-project.org/package=AdhereR/vignettes/adherer_with_databases.pdf). The `R` code needed to compute the current CMA can be accessed through the **Show R code** button (UI element **7**). The patients for which the computation of the CMA is to be performed can be done in two main ways: a. by **individually** selecting patients by their IDs, through a multiple selection dropdown list (element **11** in the figure below): ![**Selecting patients *individually* for the computation of CMA.**](shiny-computecma-individually.jpg) b. by selecting a continuous **range** of patients using two sliders (element **15** in the figure below) which define a set of *positions* in a list (element **14** in the figure below); this list can contain the patient IDs in their original order in the data source, or can have them sorted in ascending or descending order by ID (element **13** in the figure below). ![**Selecting patients *by range* of positions in a list for the computation of CMA.** In this example, we ordered the patients descreasingly by ID (using the combobox **13**), resulting in a mapping of positions (#) to ID as shown in the list **14**, where patient with ID "100" is on psition 1, patient "99" on position 2, etc. The sliders **15** define the range of positions (#) 3 to 24, which means that we selected patients with IDs "98", "97", "96" ... "78" and "77".](shiny-computecma-range.jpg) These two ways of selecting patients should be flexible enough for cover most cases of (semi-)interactive use; for more patients and/or the selection of patients based on more complex criteria, we suggest the use of the `R` code in a script. After patients have been selected, the user can press the **Compute CMA** button (UI element **12**) to access a specialized dialog box (see figure below) where the CMA computation can be started, its progress monitored, or stopped, and from where the results can be exported to file. ![**Starting, stopping and watchin the progress of CMA computation for several patients.** The list of patients is given in UI element **16**, and the progress of the computation is tracked by theprogress bar and individual success report (UI elements **17**). The button **Save results (as TSV)** allows the user to select a file where the results will be exported as a TAB-separated CSV file.](shiny-computecma-dialog.jpg) ### Setting *parameters* The left-hand panel has two tabs: *Params* and *Data*, and we are focusing here on *Params*, which contains various parameters customizing the computed CMA and the plotting of the results. UI element **5** in [the overview figure](#ui-overview) shows part of this panel, but the following principles apply: - the top **Dataset info** button gives access to information about the current data source such as its name, type, structure and the five important columns: ![**Basic information about the current dataset.** Here, `med.events`, showing also the five important columns.](shiny-infodataset.jpg) - there are several *sections* with <b style='color: darkblue'>dark blue bold headings</b> - the contents of most of sections can be hidden (by default, marked by the "...") or visible, the two states being toggled by clicking the mouse (see the figure below), the only exception being the first section, <b style='color: darkblue'>General settings</b>, whose contents is always visible ![**Folding and unfolding the contents of a section.** The section <b style='color: darkblue'>Follow-up window (FUW)</b> with content folded (hidden) on the left, and unfolded (visible) on the right.](shiny-foldsections.jpg) - some sections may appear or disappear depending on other circumstances, such as the type of CMA selected (e.g., <b style='color: darkblue'>Define episodes</b> exists only for *CMA per episodes*) or the optional columns being defined (e.g., <b style='color: darkblue'>Show dose</b> exists only if the daily dose column was defined and only for `CMA0`, `CMA5-9`, *per episodes*, and *sliding windows*). We will now go through all sections one by one. #### <b style='color: darkblue'>General settings</b> The <b style='color: darkblue'>General settings</b> section is always visible and allows the selection of: - **CMA type**: the type of CMA to compute, which can be (please see [Dima & Dediu, 2017](#Ref-Dima2017), and the vignette [AdhereR: Adherence to Medications](https://cran.r-project.org/package=AdhereR/vignettes/AdhereR-overview.html) for more details): - **simple**: one of the "simple" CMAs, currently `CMA0` tot `CMA9`, - **per episode**: computes one of the "simple" CMAs repeatedly for each treatment episode, - **sliding window**: computes one of the "simple" CMAs repeatedly for a set of sliding windows - **CMA to compute**: the "simple" CMA to compute, either by itself (for **CMA type** == **simple**) or iteratively (for the other two "complex" types); please note that by definition `CMA0` cannot be used with "complex" CMAs (which explains why it cannot be selected in these cases) - **Patient(s) to plot**: the list of patient IDs, selected from a drop-down list (which allows multiple selections) containing all the patient IDs in the current data source (at least one patient must be selected, otherwise an error is generated) Depending on these selections the plot may change or various types of errors or warnings may be thrown. #### <b style='color: darkblue'>Follow-up window (FUW)</b> and <b style='color: darkblue'>Observation window (OW)</b> These two sections are very similar and allow the definition of the follow-up (FUW) and observation (OW) windows by specifying: - their **start**: this can be either: - the number of **units** (days, weeks, months or years) relative to the first event (for FUW) and to the start of the FUW (for OW), or - an absolute **calendar date** - and their **duration** as a number of **units** (days, weeks, months or years). #### <b style='color: darkblue'>Carry over</b> This section is shown only for `CMA5` to `CMA9` and concerns the way carry over is considered: - **For same treat.only**: only for the treatment class or across classes - **Consider dosage changes**: should dosage changes be considered when computing the carry over? #### <b style='color: darkblue'>Define episodes</b> This section is shown only for **CMA per episodes** and concerns the way treatment episodes are defined: - **Treat. change starts new episode?**: does changing the treatment class trigger a new episode? - **Dose change starts new episode?**: does changing the dose trigger a new episode? - **Max. gap duration**: the duration of a gap above which a new episode is triggered; the gap can be in units (**Max. gap duration unit**) of days, weeks, months or years, or as a percent of the last prescription - **Append gap?**: should the maximum permissible gap be added to the episodes with a gap larger than this maximum? If "no" (the default), nothing is added, if "yes" then the maximum permissible gap is appended at the end of the episodes - **Plot CMA as histogram?**: should the distribution of CMA estimates across episodes for a given participant be plotted as a histogram or as a barplot #### <b style='color: darkblue'>Define sliding windows (SW)</b> This section is shown only for **sliding windows** and concerns the way this sequence of regularly spaced and uniform sliding windows is defined: - **SW start**: when is the first sliding window starting (relative to the start of the OW) in terms of units (**SW start unit**) that can be days, weeks, months or years - how long is one such sliding window **SW duration** in terms of **SW duration unit** (days, weeks, months or years) - the step between two consecutive sliding windows can be defined either in terms of: - **SW number of steps**: the total *number of steps* (i.e., sliding windows of the given duration covering the OW), or - the *duration of a setp* (i.e., one sliding window) in terms of how many (**SW step duration**) units (**SW step unit**; days, weeks, months or years) it lasts - **Plot CMA as histogram?**: should the distribution of CMA estimates across sliding windows for a given participant be plotted as a histogram or as a barplot ![**Defining sliding windows.** Here we show 90-days sliding windows lagging by 60 days and starting right at the begining of the observation window. The regularly spaced bars at the top of the plot represent the sliding window, each with its own CMA estimate (here, `CMA9`). The histogram on the left (which can be toggled to a barplot) shows the distribution of the CMA estimates across the sliding windows.](shiny-slidingwindows.jpg) #### <b style='color: darkblue'>Align patients</b> This section is shown only if there's more than one patient selected, and controls the way the plots of several patients are displayed vertically: - **Align patients?**: should all the patients be vertically aligned relative to their first event? - **Align 1st event at 0?**: should the first event (across patients) be considered as the origin of time? ![**Vertically aligning multiple patients.** The top panel shows two patients (with IDs '1' and '15') plotted using the actual dates of their events (as difference between the earilest event and their own) versus the same two patients aligned vertically relative to each other.](shiny-alignpatients.jpg) #### <b style='color: darkblue'>Duration & period</b> This section controls the amount of temporal information displayed (on the horizontal axis): - **Duration (in days)**: the period to show (in days); this is independent of the length of the FUW, OW or the events actually displayed and can be used to zoom-in or zoom-out; if `0` it is automatically computed so as all the events in the plot are shown - **Show period as**: if "days", it displays on the horizontal axis the number of days since the first plotted event on the horizontal axis; if "dates", it displays the actual calendar dates -- **Period (in days)**: the interval (in days) at which info is shown on the horizontal axis and vertical dashed lines are drawn on the plot #### <b style='color: darkblue'>CMA estimates</b> This section is shown for all CMAs except `CMA0` and controls how the CMA estimates are to be shown on the plot: - **Print CMA?**: this is visible only for the "simple" CMAs and controls whether the CMA estimates should be shown next to the participant's ID - **Plot CMA?**: should the CMA estimate be plotted next to the participant's ID? #### <b style='color: darkblue'>Show dose</b> This section is shown only a *daily dose* column is defined for the current data source, and only for `CMA0`, `CMA5`--`CMA9`, *per episodes*, and *sliding windows* (`CMA1`--`CMA4` by definition are unaware of dose and treatment categories) and controls how the dose is visually shown (if at all): - **Print it?**: print the dosage (i.e., the actual numeric values) next to each event; if so: - **Font size**: which font size[^1] to use - **Outline color**: which outline color to use - **Centered?**: should the text be centered or not? - **As line width?**: show the dose as the event line width; if so: - **Max dose width**: what is the line width of the maximum given dose? - **Global max?**: should this maximum dose be computed across all treatment classes or per class? Please see [the overview figure](#ui-overview) for an example where the dose is printed. #### <b style='color: darkblue'>Legend</b> This section controls the visual appearance of the legend: - **Show legend?**: should the legend be shown at all; if so: - **Legend x**: the legend's horizontal position ("left" or "right") - **Legend y**: the legend's vertical position ("bottom" or "top") - **Title font size**: the legend title's font size - **Text font size**: the legend text and symbols' font size - **Legend bkg. opacity**: the legend's background opacity, between 0.0 (fully transparent) and 1.0 (fully opaque) #### <b style='color: darkblue'>Aesthetics</b> This section controls many aspects of the visual presentation of the plots, including colors, font sizes and line styles; some of these depend on other factors, so may or may not be visible: - **Grayscale?**: when **ON**, it makes the plots use only shades of gray (and hides many other controls in this section), but when **OFF**, it allows various colors to be used - **Missing data color**: the colors of missing data - **Unspec. cat. label**: the label to use for an unspecified treatment class (free text) - **Treatment palette**: shown only if the *treatment class* column was defined, allows the selection of a *color palette* from which particular colors for the actual treatment classes will be picked[^2]; currently the available palettes are: *rainbow*, *heat.colors*, *terrain.colors*, *topo.colors*, *cm.colors*, *magma*, *inferno*, *plasma*, *viridis*, *cividis* (the last two are color-blind-friendly[^3]) - **Event line style**: controls the line style for plotting the events, and can be: ![**The possible line styles** used for the event lines.](shiny-linestyles.jpg) - **Event line width**: the width of the event lines - **Event start** and **Event end**: the symbols used to mark the start and end of an event, and can be: ![**The possible point symbols** used to mark the start and the end of an event.](shiny-pointsymbols.jpg) - attributes of the continuation lines between events (only for `CMA0`, per episode, and sliding windows): **Cont. line color**, **Cont. line style** and **Cont. line width** - **Show event interv.?**: should the event intervals be shown? (only for simple CMAs except `CMA0`) - the relative font size of various elements: **General font size**, **Axis font size** and **Axis labels font size** - follow-up window visual attributes: **Show FUW?** (should we show it or not), and if yes, **FUW color**, what color to use? - observation window visual attributes: **Show OW?** (should we show it or not), and if yes, with what color (**OW color**), line density (**OW hash dens.**) and angle (**OW hash angle**) and opacity (**OW opacity**) - `CMA8` uses a "real observation window", which ca be shown or not (**Show real OW?**) and whose attributes are the line density (**Real OW hash dens**) and angle (**Real OW hash angle**) - for all CMAs (except `CMA0`), we can control various attributes of the CMA estimate: the relative font size (**CMA font size**), the percent of the plotting area dedicated to plotting it (**CMA plot area %**), its color (**CMA plot color**), border color (**CMA border color**), background color (**CMA bkg. color**) and text color (**CMA text color**) #### <b style='color: darkblue'>Advanced</b> This section controls several advanced settings: - **Min plot size (horiz.)** and **Min plot size (vert.)**: the minimum plotting size (in characters) required for the whole duration to be plotted (horizontally) and for each event/episode/sliding window (vertically) ### Selecting/changing the *data source* {#ui-datasource} If the interactive App was *started with a given data source* passed through the parameters to the `plot_interactive_cma(...)` arguments, this data source (if valid and well-defined) is automatically used, but it can be changed at any time (as described below). However, if the App was starting *without any data source* (i.e., `plot_interactive_cma()`), the user is forced to select a valid data source before being able to plot anything. The actual processes of selecting an initial data source or changing it later are identical, so we discuss here the case of no initial data source: when `plot_interactive_cma()` was invoked, the App is opened without any plotting and messaging area at all and the **Data** tab in the left-hand panel is automatically selected and the **Params** tab contains only a warning message: ![**Starting the App with no data source.** The highlighted panel on the left (UI element **18**) is now open at the **Data** tab, which allows the interactive selection of various types of data sources.](shiny-data-empty.jpg) ![**Starting the App with no data source.** The **Params** tab on the left now contains only a warning message (and no settings).](shiny-data-empty-params.jpg) The **Data** panel allows us to interactively select and change on-the-fly the data set to be used; currently, this can be: - a data set **already in memory** -- basically, an object derived from `data.frame` (this includes, thus, things such as `data.tables`) that is already in the *global environment* of the current `R` session (please see for example, [here](http://adv-r.had.co.nz/Environments.html), for details about environments, but our purposes here, this contains the "stuff" currently loaded in `R`'s memory), - data stored in a (local) **file** -- the App can handle various file format, ranging from the ubiquitous Comma-Separated Values (CSV) to Excel, OpenDocument, SPSS, Stat and SAS files (within limits), or - a live connection to an **SQL database** -- the SQL server may be local or remote and, currently, can be [SQLite](https://www.sqlite.org/index.html) or [MySQL](https://www.mysql.com/)/[MariaDB](https://mariadb.org/) (but more relational database technologies/providers can be relatively easily added). The type of data source can be done with with list **Datasource type** at the top of the **Data** panel. We will go now through each of these types of data sources in turn. #### Data **already in memory** {#ui-inmemory} This is, in some respects, the simplest type of data source. When selected, the tab looks like: ![**Selecting and *in-memory* data source.**](shiny-data-inmemory.jpg) The **In-memory dataset** UI element contains the list of all objects in the current global environment derived from `data.table` that have at last 1 row and 3 columns, and they can be selected simply by clicking on their name (here, we select the `med.events` example dataset): ![**Selecting the `med.events` example dataset.** Please note that the selection ca be done by looking through the list, or by typing the `delete`/`backspace` key (⌫) and then starting to type the name of the dataset.](shiny-data-inmemory-select-medevents.jpg) After clicking on it, the dataset is selected and optionally available for inspection using the **Peek at dataset** button: ![**Peeking at (i.e., inspecting) the *in-memory* dataset `med.events`.** This box shows basic info about the dataset, including the number of rows and columns and, for each column, its name and type, plus the first few rows.](shiny-data-inmemory-peek.jpg) If the dataset is not the desired one, it can be replaced with anything else using the interface, but, if it is the one, we can continue by selecting the important columns and the format of the dates. ![**Selecting the "important" columns -- here, the one contaning the Patient IDs -- from the *in-memory* dataset `med.events`.** Please note that the list give extra summary info about the columns in the dataset (namely, its name, type, and first few values). The App automatically maps the first three columns in the dataset to the first three required columns (**Patient ID column**, **Event date column** and **Event duration column**) but this is most probably wrong and no type checks are done at this time. The "optional" columns (**Daily dose column** and **Treatment class column** may be left undefined by selecting the *[not defined]* value. **Date format** is different, being a free text field where the format of the dates in the dates column must be defined (please see, for example [here](https://www.statmethods.net/input/dates.html), for how this format looks like).](shiny-data-inmemory-selectcolumns.jpg) Please note that, at this time, the dataset is *not* selected to be used for plotting: this is an explicit action done by pressing the **Validate & use!** button at the bottom, which does perform various checks (such as that each column is used at most once and that the types more or less fit the expected type and format, among others) and, if OK, makes this dataset the one to be used for plotting. #### **Load from file** This is a very useful case, where the data is stored in an external file. When selecting *load from file* in the **Datasource type** list, the panel becomes: ![**Loading a dataset from file.**](shiny-data-fromfile.jpg) The App supports loading data from several file formats: - **Comma/TAB-separated (.csv; .tsv; .txt)**: this is the default format and refers to a class of open and flexible file formats where tabular data is stored as rows of values separated by a pre-defined delimiter; the best known are [Comma-Separated Values (CSV)](https://en.wikipedia.org/wiki/Comma-separated_values) and [TAB-Separated Values (TSV)](https://en.wikipedia.org/wiki/Tab-separated_values) formats, but the App allows a lot of flexibility by defining: - the **Field separator** can be: the *[`TAB`]* character (\\t), the *comma* (,), one or more *whitespaces*, the *semicolon* (;) or the *colon* (:) - the individual values can be quoted (or not) using the **Quote character**: *[none]* (no quoting of values), *single quotes* (') or *double quotes* (") - the **Decimal point** character: *dot* (.) or *comma* (,) - the **Missing data symbols**: a free text listing (within double quotes and separated by commas) the symbol(s) to be interpreted as *missing data* (by default, "NA") - if the 1^st^ row of the file represents the header (containing the column names) or not (**Header 1^st^ row**) - **Serialized R object (.rds)**: this loads data (such as objects derived from `data.frame`) previously exported from `R` using `readRDS()` (usually as ".rds") - **Open Document Spreadsheet (.ods)** and **Microsoft Excel (.xls; .xlsx)** loads data from these widespread formats, used by office suites such as [LibreOffice](https://www.libreoffice.org/)/[OpenOffice](https://www.openoffice.org/)'s `Calc` and [Micrsoft Office](https://www.office.com/)'s `Excel` programs, among others; for both these formats, the user can specify the particular sheet to be loaded for files containing more than one (**Which sheet to load?**) - **SPSS (.sav; .por)**, **SAS Transport data file (.xpt)**, **SAS sas7bdat data file (.sas7bdat)** and **Stata (.dta)**: these are file formats exported by the popular statistical platforms [IBM `SPSS`](https://www.ibm.com/analytics/spss-statistics-software), [`SAS`](https://www.sas.com) and [`Stata`](https://www.stata.com/) Please note that while **Comma/TAB-separated (.csv; .tsv; .txt)**, **Serialized R object (.rds)** and **Open Document Spreadsheet (.ods)** should be imported without issues, for the others there might limitations and fringe cases. After the file format has been selected, the user can use the **Load from file** control (its **Selecte** button) to browse for the desired file and upload it. Basic checks might be performed and a file might be rejected, but if the loading was successful, a new set of UI elements becomes visible. These elements are virtually identical to those used for [in-memory datasets](#ui-inmemory). #### Use an **SQL database** This allows the access to data stored in standard [Relational Database Management Systems (RDBMS's)](https://en.wikipedia.org/wiki/Relational_database_management_system) which use the [Structured Query Language (SQL)](https://en.wikipedia.org/wiki/SQL) -- for more info about the facilities offered by `AdhereR`, please see the [Using AdhereR with various database technologies for processing very large datasets](https://cran.r-project.org/package=AdhereR/vignettes/adherer_with_databases.pdf) vignette. Currently, the App supports [`SQLite`](https://sqlite.org/index.html), a small engine designed to be embedded in larger applications and which stored the data in normal files, and [`MySQL`](https://www.mysql.com/)/[`MariaDB`](https://mariadb.org/), which are widely-used, full-featured free and open-source RDBMSs. While **SQLite** is intended only as a demo of the App's capabilities and uses an in-memory database with a single table that contains a verbatim copy of the `med.events` example dataset, **MySQL/MariaDB** allows the use of actual databases, local or over the internet. Except for the selection of the database, the UI for the two is identical, so we will only discuss here the **MySQL/MariaDB** case We can connect to a local or remote server, and we can (optionally) define the following: - **Host name/address**: the fully qualified host name or IP address of the server (if *[none]* or *localhost*, the database is stored on the local machine) - **TCP/IP port number**: the port number (*0* for default) - **Database name**: the name of the database - **Username** and **Password**: the username and password for accessing the database (the password is hidden using *) ![**Inputting the info needed to connect to a remote MySQL server.** We use here a MySQL database contaning the `med.events` sample dataset hosted on the internet.](shiny-data-sql-mysql.jpg) When clicking the **Connect!** button, the App attempts to connect the server, authenticate and access the desired database: if everything's OK, it fetches basic information over all the tables/views in the database (avoiding thus unnecessary traffic) and displays it: ![**Basic information about an SQL database.** This shows, for each table/view in the database, the columns with their name, type and first few values. The same info is accessible by clicking on the **Peek at database...** button.](shiny-data-sql-mysql-peek.jpg) New UI elements become visible, most being virtually identical to those used for loading from file and [in-memory datasets](#ui-inmemory), but the specific ones being: - the **Disconnect!** button; this disconnects from the database cleanly (not required by nice to do) - **Which table/view** lists the tables and views in the database, also showing for each the number of rows and columns ![**UI elements for using an SQL database.**](shiny-data-sql-mysql-columns.jpg) For example, when using the `MySQL` database described in the vignette [*Using AdhereR with various database technologies for processing very large datasets*](https://CRAN.R-project.org/package=AdhereR/vignettes/AdhereR-overview.html) in package `AdhereR`, we can create, for example, a `view` (named `testview`) that brings together these data in the needed format with the following `SQL` commands in `MySQL Workbench`: ```{sql eval=FALSE} USE med_events; CREATE VIEW `testview` AS SELECT patients.`id`, `date`, `category`, `duration`, `perday` FROM event_date JOIN event_info ON event_info.`id` = event_date.`id` JOIN event_patients ON event_patients.`id` = event_info.`id` JOIN patients ON patients.`id` = event_patients.`patient_id`; ``` ### Defining and using *medication groups* {#ui-medicationgroups} Since `AdhereRViz` version 0.2/`AdhereR` version 0.7, *medication groups* can be defined and used for interactive plotting. For ore details about medication groups, please see the vignette "AdhereR: Adherence to Medications" in package `AdhereR`, but, fundamentally, they are named vectors of characters where the names are the unique names of groups of medication defined using `R`-like expressions that describe with of the events in the dataset are covered by a given medication group. Alternatively, one can use a *column* in the data itself to define the medication groups. Medication groups can be passed with the `medication.groups` argument to the `plot_interactive_cma()` function, or can be interactively loaded through a new panel `Groups` of the user interface (please note that a valid dataset must have already been loaded): ![**Loading medication groups.** The **Groups** tab allows the interactive selection of medication groups from already defined named character (or factor) vectors in memory (here, the pre-defined example `med.groups` from the `AdhereR` package). The switch allows us to instantly ignore or apply any medication groups that may have been defined.](shiny-groups-panel-1.jpg) ![**Inspecting medication groups.** Clicking on the "Check it!" button in the **Groups** tab allows the inspection of the currently selected vector contaning medication group definitions (here, the pre-defined example `med.groups` from the `AdhereR` package).](shiny-groups-panel-2.jpg) Pressing the "Use it!" button load the selected medication group definitions; please make sure they are correct and fit the currently loaded dataset! If the loading goes well, the plotting is automatically updated to reflect the medication groups: ![**Plotting medication groups.** `CMA1` for patients "1" and "2" in the example dataset `med.events.ATC` using the example medication groups `med.groups` from the `AdhereR` package.](shiny-medgroups-plot.jpg) The main differences to a plot without medication groups are: - any given patient may be "split" into several medication groups (here, patient "1" is split into "1 [NoVita]" and "1 [VitaResp]") - only those medication groups that have at least one event are shown, and only those patients with at least one medication group with at least one event are shown, - the medication groups belonging to a patient may be shown grouped using thick blue lines (but this can be changed at will). These apply not only to simple CMAs, but also to sliding windows and per episode (not shown). Various options related to plotting the medication groups can be changed in the using the new "Medication groups" user interface, probably the most important being the medication groups to be included in the plot: ![**Selecting which of the defined medication groups to plot.** We may plot only a subset of all the defined medication groups, including the implicitly defined `__ALL_OTHERS__` (here shown as "* (all others)*) that includes all events not selected by any of the explicitely defined groups. Don't forget to press the "Show them!" button to apply your changes.](shiny-medgroups-select.jpg) ## References <a name="Ref-Dima2017"></a>Dima A.L., Dediu D. (2017) [Computation of adherence to medication and visualization of medication histories in R with *AdhereR*: Towards transparent and reproducible use of electronic healthcare data](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0174426). *PLoS ONE* **12**(4): e0174426. [doi:10.1371/journal.pone.0174426](https://doi.org/10.1371/journal.pone.0174426). ## Notes [^1]: Please note that all font sizes are *relative*. Thus a font size of `1.0` means the default font size used for the plot (depending on resolution, etc.), while a value of `0.50` means half that and `1.25` means 25% bigger. [^2]: We have decided against directly mapping each class to a particular color and, instead, automatically mapping them using a palette, because this accommodates more flexibly a varying number (or grouping) of classes; the mapping classes → colors is based on the *alphabetic order* of the class names. [^3]: See for example [here](https://cran.r-project.org/package=viridis/vignettes/intro-to-viridis.html) for a comparison and discussion. <!-- Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format: --> <!-- - Never uses retina figures --> <!-- - Has a smaller default figure size --> <!-- - Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style --> <!-- ## Vignette Info --> <!-- Note the various macros within the `vignette` section of the metadata block above. These are required in order to instruct R how to build the vignette. Note that you should change the `title` field and the `\VignetteIndexEntry` to match the title of your vignette. --> <!-- ## Styles --> <!-- The `html_vignette` template includes a basic CSS theme. To override this theme you can specify your own CSS in the document metadata as follows: --> <!-- output: --> <!-- rmarkdown::html_vignette: --> <!-- css: mystyles.css --> <!-- ## More Examples --> <!-- You can write math expressions, e.g. $Y = X\beta + \epsilon$, footnotes^[A footnote here.] --> <!-- Also a quote using `>`: --> <!-- > "He who gives up [code] safety for [code] speed deserves neither." --> <!-- ([via](https://twitter.com/hadleywickham/status/504368538874703872)) -->
/scratch/gouwar.j/cran-all/cranData/AdhereRViz/vignettes/adherer_interctive_plots.Rmd
ci.mult.ref <- function(k,n,A.ref,A.follow,alpha=0.1,p.target=1,prec=2,tailcut=1e-08,tol=1e-12){ if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){ return<-"Input error: check alpha and/or p.target!" }else if(A.follow<=0){ return<-"Input error: A.follow has to be larger than 0!" }else{ r<-length(k) scale<-phi.mult.ref(k,n,A.ref,prec,tailcut) if(is.character(scale)){ return<-scale }else{ phi<-scale$phi A.gcd<-scale$A.gcd A.prec<-round(A.ref,prec) A.prec[A.prec-A.ref>0]<-A.prec[A.prec-A.ref>0]-10^(-prec) A.ref<-A.prec n.gcd<-sum(n*A.ref/A.gcd) f.p.gcd<-function(p.gcd){as.numeric(phi$prob%*%pbinom(phi$k.gcd,n.gcd,p.gcd))-alpha} p.gcd.hat<-uniroot(f.p.gcd,lower=0,upper=1,tol=tol)$root p.ref<-qbeta(1-alpha,k+1,n-k) p.mm<-1-(1-p.gcd.hat)^(1/A.gcd) p.follow<-1-(1-p.mm)^A.follow if(p.follow>p.target){ n.add<-NULL for(i in c(1:r)){ f.n<-function(n.add.i){ vec<-rep(0,r);vec[i]<-floor(n.add.i) n.new<-n+vec scale<-phi.mult.ref(k,n.new,A.ref,prec,tailcut) phi<-scale$phi A.gcd<-scale$A.gcd n.gcd<-sum(n.new*A.ref/A.gcd) f.p.gcd<-function(p.gcd){as.numeric(phi$prob%*%pbinom(phi$k.gcd,n.gcd,p.gcd))-alpha} p.gcd.hat<-uniroot(f.p.gcd,lower=0,upper=1,tol=tol)$root p.fol<-1-(1-p.gcd.hat)^(A.follow/A.gcd) p.fol-p.target } n.add.i<-ceiling(uniroot(f.n,lower=0,upper=100*n[i],extendInt="yes")$root) n.add<-c(n.add,n.add.i) } }else{ n.add<-0 } return<-list(p.ref=p.ref,p.mm=p.mm,p.follow=p.follow,n.add=n.add) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.mult.ref.R
ci.mult.ref.cm <- function(k,n,A.ref,A.follow,K,theta,alpha=0.1,p.target=1,prec=2,tailcut=1e-08,tol=1e-12){ if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){ return<-"Input error: check alpha and/or p.target!" }else if(A.follow<=0){ return<-"Input error: A.follow has to be larger than 0!" }else{ scale<-phi.mult.ref.cm(k,n,A.ref,K,theta,prec,tailcut) if(is.character(scale)){ return<-scale }else{ A.prec<-round(A.ref,prec) A.prec[A.prec-A.ref>0]<-A.prec[A.prec-A.ref>0]-10^(-prec) A.ref<-A.prec phi<-scale$phi.cm A.gcd<-scale$A.gcd r<-length(k) n.gcd<-sum(n*A.ref/A.gcd) f.p.gcd.cm<-function(p.gcd.cm){as.numeric(phi$prob%*%pbinom(phi$k.gcd,n.gcd,p.gcd.cm))-alpha} p.gcd.cm.hat<-uniroot(f.p.gcd.cm,lower=0,upper=1,tol=tol)$root p.ref.cm<-NULL for(j in c(1:r)){ if(k[j]>0){ p.ref.cm<-c(p.ref.cm,cm.clopper.pearson.ci(n[j],c(K[j,],k[j]-sum(K[j,])),c(theta,0),alpha,uniroot.tol=tol)$Upper.limit) }else{ p.ref.cm<-c(p.ref.cm,qbeta(1-alpha,1,n[j])) } } p.mm.cm<-1-(1-p.gcd.cm.hat)^(1/A.gcd) p.follow.cm<-1-(1-p.mm.cm)^A.follow if(p.follow.cm>p.target){ n.add<-NULL for(i in c(1:r)){ f.n<-function(n.add.i){ vec<-rep(0,r);vec[i]<-floor(n.add.i) n.new<-n+vec scale<-phi.mult.ref.cm(k,n.new,A.ref,K,theta,prec,tailcut) phi<-scale$phi.cm A.gcd<-scale$A.gcd n.gcd<-sum(n.new*A.ref/A.gcd) f.p.gcd.cm<-function(p.gcd.cm){as.numeric(phi$prob%*%pbinom(phi$k.gcd,n.gcd,p.gcd.cm))-alpha} p.gcd.cm.hat<-uniroot(f.p.gcd.cm,lower=0,upper=1,tol=tol)$root p.fol<-1-(1-p.gcd.cm.hat)^(A.follow/A.gcd) p.fol-p.target } n.add.i<-ceiling(uniroot(f.n,lower=0,upper=100*n[i],extendInt="yes")$root) n.add<-c(n.add,n.add.i) } }else{ n.add<-0 } return<-list(p.ref.cm=p.ref.cm,p.mm.cm=p.mm.cm,p.follow.cm=p.follow.cm,n.add.cm=n.add) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.mult.ref.cm.R
ci.sas <- function(k, n, A.ref, A.follow, alpha=0.1, p.target=1, atol=1e-08){ if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){return<-"Input error: check alpha and/or p.target!" }else if((length(k)!=length(A.ref))||(length(A.ref)!=length(A.follow))){return<-"Input error: dimensions of k, A.ref and A.follow do not match!" }else if(n-sum(k)<0){return<-"Input error: total number of failures has to be <= n!" }else if(n<=0){return<-"Input error: n has to be > 0!" }else if(min(A.ref)<=0){return<-"Input error: A.ref has to be > 0!" }else if(min(A.follow)<0){return<-"Input error: A.follow has to be >= 0!" }else{ r <- length(k) k.tot<-sum(k) A.ref.tot <- sum(A.ref) A.follow.tot <- sum(A.follow) p<-qbeta(1-alpha,k.tot+1,n-k.tot) #CAS p.cas<-1-(1-p)^(A.ref/A.ref.tot) p.follow.cas<-1-(1-p)^(A.follow.tot/A.ref.tot) if(p.follow.cas>p.target){ f.n<-function(n.new){pbinom(k.tot,floor(n.new),1-(1-p.target)^(A.ref.tot/A.follow.tot))-alpha} n.add.cas<-ceiling(uniroot(f.n,lower=n,upper=100*n,extendInt="yes")$root)-n }else{ n.add.cas<-0 } if(r>1){ #delta delta.ij<-NULL for(i in c(1:(r-1))){ for(j in c((i+1):r)){ if(k[i]>=k[j]){ if((k[j]==0)||(A.ref[i]<=A.ref[j])){ delta.ij<-c(delta.ij,pbinom(k[i],n,p.cas[i])/pbinom(k[j],n,p.cas[j])) }else{ delta.ij<-c(delta.ij,pbinom(k[j],n,p.cas[j])/pbinom(k[i],n,p.cas[i])) } }else{ if((k[i]==0)||(A.ref[j]<=A.ref[i])){ delta.ij<-c(delta.ij,pbinom(k[j],n,p.cas[j])/pbinom(k[i],n,p.cas[i])) }else{ delta.ij<-c(delta.ij,pbinom(k[i],n,p.cas[i])/pbinom(k[j],n,p.cas[j])) } } } } delta<-max(delta.ij) #SAS f.sas<-function(p.sas){c((1-p)-prod(1-p.sas),pbinom(k[-r],n,p.sas[-r])-pbinom(k[-1],n,p.sas[-1]))} start.val<-1-(1-p)^((k+1)/sum(k+1)) p.sas<-multiroot(f.sas,start.val,positive=TRUE,atol=atol,ctol=0,rtol=0) if(max(abs(p.sas$f.root))>atol){ p.sas<-rep(NA,r) p.follow.sas<-NA n.add.sas<-NA }else{ p.sas<-p.sas$root p.follow.sas<-1-prod((1-p.sas)^(A.follow/A.ref)) if(p.follow.sas>p.target){ f.n<-function(n.new){ p<-qbeta(1-alpha,k.tot+1,floor(n.new)-k.tot) start.val<-1-(1-p)^((k+1)/sum(k+1)) f.sas<-function(p.sas){c((1-p)-prod(1-p.sas),pbinom(k[-r],floor(n.new),p.sas[-r])-pbinom(k[-1],floor(n.new),p.sas[-1]))} p.sas<-multiroot(f.sas,start.val,positive=TRUE,atol=atol,ctol=0,rtol=0)$root p.follow.sas<-1-prod((1-p.sas)^(A.follow/A.ref)) p.follow.sas-p.target } n.add.sas<-ceiling(uniroot(f.n,lower=n,upper=100*n,extendInt="yes")$root)-n }else{ n.add.sas<-0 } } }else{ p.sas<-p.cas p.follow.sas<-p.follow.cas delta<-1 n.add.sas<-n.add.cas } return<-list(p.cas=p.cas, p.sas=p.sas, p.follow.cas=p.follow.cas, p.follow.sas=p.follow.sas, delta=delta, n.add.cas=n.add.cas,n.add.sas=n.add.sas) } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.sas.R
ci.sas.cm <- function(k, n, A.ref, A.follow, K, theta, alpha=0.1, p.target=1, atol=1e-08){ r<-length(k) if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){return<-"Input error: check alpha and/or p.target!" }else if((length(k)!=length(A.ref))||(length(A.ref)!=length(A.follow))){return<-"Input error: dimensions of k, n, A.ref and A.follow do not match!" }else if(n-sum(k)<0){return<-"Input error: total number of failures has to be <= n!" }else if(n<=0){return<-"Input error: n has to be > 0!" }else if(min(A.ref)<=0){return<-"Input error: A.ref has to be > 0!" }else if(min(A.follow)<0){return<-"Input error: A.follow has to be >= 0!" }else if(!is.matrix(K)){return<-"Input error: K has to be a matrix!" }else if((r!=dim(K)[1])||(length(theta)!=dim(K)[2])){return<-"Input error: dimensions of k and K and/or theta and K do not match!" }else if((min(theta)<0)||(max(theta)>1)){return<-"Input error: theta has to be in [0,1]!" }else{ k.tot<-sum(k) if(k.tot==0){ return<-ci.sas(k,n,A.ref,A.follow,alpha,p.target,atol) }else{ A.ref.tot<-sum(A.ref) A.follow.tot<-sum(A.follow) k.with.cm<-apply(K,1,sum) k.without.cm<-k-k.with.cm K<-cbind(K,k.without.cm) theta<-c(theta,0) if(min(K[,length(theta)])<0){ return<-"Input error: arguments in k and K do not match!" }else{ p.cm<-cm.clopper.pearson.ci(n,apply(K,2,sum),theta,alpha,uniroot.tol=1e-12)$Upper.limit #CAS p.cas.cm<-1-(1-p.cm)^(A.ref/A.ref.tot) p.follow.cas.cm<-1-(1-p.cm)^(A.follow.tot/A.ref.tot) if(p.follow.cas.cm>p.target){ f.n<-function(n.new){ p.cm<-cm.clopper.pearson.ci(floor(n.new),apply(K,2,sum),theta,alpha,uniroot.tol=1e-12)$Upper.limit (1-(1-p.cm)^(A.follow.tot/A.ref.tot))-p.target } n.add.cas.cm<-ceiling(uniroot(f.n,lower=n,upper=100*n,extendInt="yes")$root)-n }else{ n.add.cas.cm<-0 } if(r>1){ #delta delta.ij.cm<-NULL for(i in c(1:(r-1))){ for(j in c((i+1):r)){ if(k[i]>0){xi.i<-dgbinom(c(0:k[i]),K[i,],1-theta)}else{xi.i<-1} if(k[j]>0){xi.j<-dgbinom(c(0:k[j]),K[j,],1-theta)}else{xi.j<-1} if(k[i]>=k[j]){ if((k[j]==0)||(A.ref[i]<=A.ref[j])){ delta.ij.cm<-c(delta.ij.cm,xi.i%*%pbinom(c(0:k[i]),n,p.cas.cm[i])/xi.j%*%pbinom(c(0:k[j]),n,p.cas.cm[j])) }else{ delta.ij.cm<-c(delta.ij.cm,xi.j%*%pbinom(c(0:k[j]),n,p.cas.cm[j])/xi.i%*%pbinom(c(0:k[i]),n,p.cas.cm[i])) } }else{ if((k[i]==0)||(A.ref[j]<=A.ref[i])){ delta.ij.cm<-c(delta.ij.cm,xi.j%*%pbinom(c(0:k[j]),n,p.cas.cm[j])/xi.i%*%pbinom(c(0:k[i]),n,p.cas.cm[i])) }else{ delta.ij.cm<-c(delta.ij.cm,xi.i%*%pbinom(c(0:k[i]),n,p.cas.cm[i])/xi.j%*%pbinom(c(0:k[j]),n,p.cas.cm[j])) } } } } delta.cm<-max(delta.ij.cm) #SAS f.sas.cm<-function(p.sas.cm){ eq<-numeric(r) eq[1]<-(1-p.cm)-prod(1-p.sas.cm) for(j in c(2:r)){ if(k[j-1]>0){xi.jminus1<-dgbinom(c(0:k[j-1]),K[j-1,],1-theta)}else{xi.jminus1<-1} if(k[j]>0){xi.j<-dgbinom(c(0:k[j]),K[j,],1-theta)}else{xi.j<-1} eq[j]<-xi.jminus1%*%pbinom(c(0:k[j-1]),n,p.sas.cm[j-1])-xi.j%*%pbinom(c(0:k[j]),n,p.sas.cm[j]) } eq } #Computation of appropriate starting values for multiroot-function support1<-c(0:k.with.cm[1])+k.without.cm[1] if(k.with.cm[1]>0){xi1<-dgbinom(c(0:k.with.cm[1]),K[1,-length(theta)],1-theta[-length(theta)])}else{xi1<-1} S<-as.matrix(support1[xi1>1e-05]) Xi<-as.matrix(xi1[xi1>1e-05]) for(i in c(2:r)){ S.new<-NULL Xi.new<-NULL if(k.with.cm[i]>0){xi.i<-dgbinom(c(0:k.with.cm[i]),K[i,-length(theta)],1-theta[-length(theta)])}else{xi.i<-1} support.i<-(c(0:k.with.cm[i])+k.without.cm[i])[xi.i>1e-05] xi.i<-xi.i[xi.i>1e-05] for(j in support.i){ S.new<-rbind(S.new,cbind(S,j)) Xi.new<-rbind(Xi.new,cbind(Xi,xi.i[j-support.i[1]+1])) } S<-S.new Xi<-Xi.new } xi.probs<-apply(Xi,1,prod) proportions<-(S+1)/(apply(S,1,sum)+r) M<-1-(1-p.cm)^proportions start.val<-as.numeric(apply(M*xi.probs,2,sum)) p.sas.cm<-multiroot(f.sas.cm,start.val,positive=TRUE,atol=atol,ctol=0,rtol=0) if(max(abs(p.sas.cm$f.root))>atol){ p.sas.cm<-rep(NA,r) p.follow.sas.cm<-NA n.add.sas.cm<-NA }else{ p.sas.cm<-p.sas.cm$root p.follow.sas.cm<-1-prod((1-p.sas.cm)^(A.follow/A.ref)) if(p.follow.sas.cm>p.target){ f.n<-function(n.new){ p.cm<-cm.clopper.pearson.ci(floor(n.new),apply(K,2,sum),theta,alpha,uniroot.tol=1e-12)$Upper.limit M<-1-(1-p.cm)^proportions start.val<-as.numeric(apply(M*xi.probs,2,sum)) f.sas.cm<-function(p.sas.cm){ eq<-numeric(r) eq[1]<-(1-p.cm)-prod(1-p.sas.cm) for(j in c(2:r)){ if(k[j-1]>0){xi.jminus1<-dgbinom(c(0:k[j-1]),K[j-1,],1-theta)}else{xi.jminus1<-1} if(k[j]>0){xi.j<-dgbinom(c(0:k[j]),K[j,],1-theta)}else{xi.j<-1} eq[j]<-xi.jminus1%*%pbinom(c(0:k[j-1]),floor(n.new),p.sas.cm[j-1])-xi.j%*%pbinom(c(0:k[j]),floor(n.new),p.sas.cm[j]) } eq } p.sas.cm<-multiroot(f.sas.cm,start.val,positive=TRUE,atol=atol,ctol=0,rtol=0)$root p.follow.sas.cm<-1-prod((1-p.sas.cm)^(A.follow/A.ref)) p.follow.sas.cm-p.target } n.add.sas.cm<-ceiling(uniroot(f.n,lower=n,upper=100*n,extendInt="yes")$root)-n }else{ n.add.sas.cm<-0 } } }else{ p.sas.cm<-p.cas.cm p.follow.sas.cm<-p.follow.cas.cm delta.cm<-1 n.add.sas.cm<-n.add.cas.cm } return<-list(p.cas.cm=p.cas.cm, p.sas.cm=p.sas.cm, p.follow.cas.cm=p.follow.cas.cm, p.follow.sas.cm=p.follow.sas.cm, delta.cm=delta.cm, n.add.cas.cm=n.add.cas.cm,n.add.sas.cm=n.add.sas.cm) } } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.sas.cm.R
ci.syn <- function(k,n,alpha=0.1,p.target=1,tol=1e-10){ if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){ return<-"Input error: check alpha and/or p.target!" }else{ phi<-phi.syn(k,n) if(is.character(phi)){ return<-phi }else{ if(phi$prob[1]==1){ p.hat<-qbeta(1-alpha,phi$k+1,min(n)-phi$k) }else{ f.p<-function(p){as.numeric(phi$prob%*%pbinom(phi$k,min(n),p))-alpha} p.hat<-uniroot(f.p,lower=0,upper=1,tol=tol)$root } if(p.hat>p.target){ f.n<-function(n.add){ n.new<-floor(n+n.add) phi<-phi.syn(k,n.new) if(phi$prob[1]==1){ p<-qbeta(1-alpha,phi$k+1,min(n.new)-phi$k) }else{ f.p<-function(p){phi$prob%*%pbinom(phi$k,min(n.new),p)-alpha} p<-uniroot(f.p,lower=0,upper=1,tol=tol)$root } p-p.target } n.add<-ceiling(uniroot(f.n,lower=0,upper=100*max(n),extendInt="yes")$root) }else{ n.add<-0 } return<-list(p.hat=p.hat,n.add=n.add) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.syn.R
ci.syn.cm <- function(k,n,K,theta,alpha=0.1,p.target=1,tol=1e-10){ if((alpha<=0)||(alpha>=1)||(p.target<=0)||(p.target>1)){ return<-"Input error: check alpha and/or p.target!" }else{ phi.cm<-phi.syn.cm(k,n,K,theta) if(is.character(phi.cm)){ return<-phi.cm }else{ if(phi.cm$prob[1]==1){ p.hat<-qbeta(1-alpha,phi.cm$k+1,min(n)-phi.cm$k) }else{ f.p<-function(p){as.numeric(phi.cm$prob%*%pbinom(phi.cm$k,min(n),p))-alpha} p.hat<-uniroot(f.p,lower=0,upper=1,tol=tol)$root } if(p.hat>p.target){ f.n<-function(n.add){ n.new<-floor(n+n.add) phi.cm<-phi.syn.cm(k,n.new,K,theta) if(phi.cm$prob[1]==1){ p<-qbeta(1-alpha,phi.cm$k+1,min(n.new)-phi.cm$k) }else{ f.p<-function(p){phi.cm$prob%*%pbinom(phi.cm$k,min(n.new),p)-alpha} p<-uniroot(f.p,lower=0,upper=1,tol=tol)$root } p-p.target } n.add<-ceiling(uniroot(f.n,lower=0,upper=100*max(n),extendInt="yes")$root) }else{ n.add<-0 } return<-list(p.hat.cm=p.hat,n.add.cm=n.add) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/ci.syn.cm.R
gcd.mult.ref <- function(A, prec=2){ r<-length(A) A.prec<-round(A,prec) A.prec[A.prec-A>0]<-A.prec[A.prec-A>0]-10^(-prec) A<-round(A.prec*10^prec) A<-sort(A,decreasing=TRUE) gcd<-function(a,b){ if(b==0){ return<-a }else{ return<-gcd(b,a%%b) } return } A.gcd<-A[1] if(r>1){ for(i in c(2:r)){ A.gcd<-gcd(A.gcd,A[i]) } } A.gcd/10^prec }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/gcd.mult.ref.R
phi.mult.ref <- function(k,n,A.ref,prec=2,tailcut=1e-08){ if((length(n)!=length(k))||(length(k)!=length(A.ref))){return<-"Input error: dimensions of k, n and A.ref do not match!" }else if(min(n-k)<0){return<-"Input error: k has to be <= n!" }else if(min(n)<=0){return<-"Input error: n has to be > 0!" }else if((as.character(prec)!=as.character(round(prec)))||(prec<0)){return<-"Input error: prec has to be a positive integer!" }else if(tailcut<0){return<-"Input error: tailcut has to be >= 0!" }else if(min(A.ref)<10^(-prec)){return<-"Input error: A.ref has to be >= 10^-prec!" }else{ A.prec<-round(A.ref,prec) A.prec[A.prec-A.ref>0]<-A.prec[A.prec-A.ref>0]-10^(-prec) A.ref<-A.prec prob.uj.kj.gcd<-function(uj,kj.gcd,nj.gcd,mj.gcd){ if(uj>kj.gcd){ return<-0 }else if((uj==0)&(kj.gcd>0)){ return<-0 }else{ if(uj>1){ Y<-as.matrix(c(1:(min(kj.gcd-uj+1,mj.gcd)))) if(uj>2){ for(j in c(2:(uj-1))){ Y.new<-Y if(kj.gcd>uj){ for(i in c(2:min(kj.gcd-uj+1,mj.gcd))){ Y.new<-rbind(Y.new,Y) } } Y<-cbind(sort(rep(c(1:min(kj.gcd-uj+1,mj.gcd)),dim(Y.new)[1]/min(kj.gcd-uj+1,mj.gcd))),Y.new) } } Y<-cbind(Y,kj.gcd-apply(Y,1,sum)) Y<-Y[(Y[,uj]>0)&(Y[,uj]<=mj.gcd),] }else{ Y<-kj.gcd } if(is.null(dim(Y))){ Y<-matrix(Y,1,length(Y)) } f.prob<-function(rowY){ prod(dhyper(rowY,kj.gcd-c(0,cumsum(rowY)[-uj]),nj.gcd-c(0:(uj-1))*mj.gcd-(kj.gcd-c(0,cumsum(rowY)[-uj])),mj.gcd)) } return<-choose(nj.gcd/mj.gcd,uj)*sum(apply(Y,1,f.prob)) } return } phi.j<-function(kj,nj,Aj,A.gcd){ mj.gcd<-Aj/A.gcd nj.gcd<-nj*mj.gcd Tj.gcd<-c(kj:(kj*mj.gcd)) cum.probs<-1 if(length(Tj.gcd)>1){ for(kj.gcd in Tj.gcd[-1]){ supp.uj<-c(ceiling(kj.gcd/mj.gcd):kj) uj<-matrix(supp.uj,length(supp.uj),1) cum.prob.kj.gcd<-sum(apply(uj,1,prob.uj.kj.gcd,kj.gcd,nj.gcd,mj.gcd)) if(cum.prob.kj.gcd<tailcut){break}else{cum.probs<-c(cum.probs,cum.prob.kj.gcd)} } if(length(cum.probs)>1){ phi<-cum.probs-c(cum.probs[2:length(cum.probs)],0) }else{ phi<-NULL } }else{ phi<-cum.probs } if(is.null(phi)){ return<-"Input error: tailcut too large!" }else{ return<-data.frame(kj.gcd=Tj.gcd[1:length(phi)],prob=phi) } return } r<-length(k) A.gcd<-gcd.mult.ref(A.ref,prec) phi1<-phi.j(k[1],n[1],A.ref[1],A.gcd) if(r>1){ if(is.character(phi1)){ return<-phi1 }else{ for(j in c(2:r)){ phi2<-phi.j(k[j],n[j],A.ref[j],A.gcd) if(is.character(phi2)){ phi1<-phi2 break }else{ T.gcd<-c((phi1$kj.gcd[1]+phi2$kj.gcd[1]):(max(phi1$kj.gcd)+max(phi2$kj.gcd))) prob.k.gcd<-NULL for(k.gcd in T.gcd){ k1.gcd<-c(max(phi1$kj.gcd[1],k.gcd-max(phi2$kj.gcd)):min(k.gcd-phi2$kj.gcd[1],max(phi1$kj.gcd))) k2.gcd<-k.gcd-k1.gcd prob.k.gcd<-c(prob.k.gcd,sum(phi1$prob[k1.gcd-(phi1$kj.gcd[1]-1)]*phi2$prob[k2.gcd-(phi2$kj.gcd[1]-1)])) } phi1<-data.frame(kj.gcd=T.gcd,prob=prob.k.gcd) } } } } if(is.character(phi1)){ return<-phi1 }else{ dimnames(phi1)[[2]][1]<-"k.gcd" return<-list(phi=phi1,A.gcd=A.gcd) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/phi.mult.ref.R
phi.mult.ref.cm <- function(k,n,A.ref,K,theta,prec=2,tailcut=1e-08){ r<-length(k) if((length(n)!=length(k))||(length(k)!=length(A.ref))){return<-"Input error: dimensions of k, n and A.ref do not match!" }else if(min(n-k)<0){return<-"Input error: k has to be <= n!" }else if(min(n)<=0){return<-"Input error: n has to be > 0!" }else if((as.character(prec)!=as.character(round(prec)))||(prec<0)){return<-"Input error: prec has to be a positive integer!" }else if(tailcut<0){return<-"Input error: tailcut has to be >= 0!" }else if(min(A.ref)<10^(-prec)){return<-"Input error: A.ref has to be >= 10^-prec!" }else if(!is.matrix(K)){return<-"Input error: K has to be a matrix!" }else if((r!=dim(K)[1])||(length(theta)!=dim(K)[2])){return<-"Input error: dimensions of k and K and/or theta and K do not match!" }else if((min(theta)<0)||(max(theta)>1)){return<-"Input error: theta has to be in [0,1]!" }else{ A.prec<-round(A.ref,prec) A.prec[A.prec-A.ref>0]<-A.prec[A.prec-A.ref>0]-10^(-prec) A.ref<-A.prec prob.uj.kj.gcd<-function(uj,kj.gcd,nj.gcd,mj.gcd){ if(uj>kj.gcd){ return<-0 }else if((uj==0)&(kj.gcd>0)){ return<-0 }else{ if(uj>1){ Y<-as.matrix(c(1:(min(kj.gcd-uj+1,mj.gcd)))) if(uj>2){ for(j in c(2:(uj-1))){ Y.new<-Y if(kj.gcd>uj){ for(i in c(2:min(kj.gcd-uj+1,mj.gcd))){ Y.new<-rbind(Y.new,Y) } } Y<-cbind(sort(rep(c(1:min(kj.gcd-uj+1,mj.gcd)),dim(Y.new)[1]/min(kj.gcd-uj+1,mj.gcd))),Y.new) } } Y<-cbind(Y,kj.gcd-apply(Y,1,sum)) Y<-Y[(Y[,uj]>0)&(Y[,uj]<=mj.gcd),] }else{ Y<-kj.gcd } if(is.null(dim(Y))){ Y<-matrix(Y,1,length(Y)) } f.prob<-function(rowY){ prod(dhyper(rowY,kj.gcd-c(0,cumsum(rowY)[-uj]),nj.gcd-c(0:(uj-1))*mj.gcd-(kj.gcd-c(0,cumsum(rowY)[-uj])),mj.gcd)) } return<-choose(nj.gcd/mj.gcd,uj)*sum(apply(Y,1,f.prob)) } return } phi.j<-function(kj,nj,Aj,A.gcd){ mj.gcd<-Aj/A.gcd nj.gcd<-nj*mj.gcd Tj.gcd<-c(kj:(kj*mj.gcd)) cum.probs<-1 if(length(Tj.gcd)>1){ for(kj.gcd in Tj.gcd[-1]){ supp.uj<-c(ceiling(kj.gcd/mj.gcd):kj) uj<-matrix(supp.uj,length(supp.uj),1) cum.prob.kj.gcd<-sum(apply(uj,1,prob.uj.kj.gcd,kj.gcd,nj.gcd,mj.gcd)) if(cum.prob.kj.gcd<tailcut){break}else{cum.probs<-c(cum.probs,cum.prob.kj.gcd)} } if(length(cum.probs)>1){ phi<-cum.probs-c(cum.probs[2:length(cum.probs)],0) }else{ phi<-NULL } }else{ phi<-cum.probs } if(is.null(phi)){ return<-"Input error: tailcut too large!" }else{ return<-data.frame(kj.gcd=Tj.gcd[1:length(phi)],prob=phi) } return } phi.j.cm<-function(kj,nj,jrowK,theta,Aj,A.gcd){ lj<-c(0:kj) if(kj>0){ xi.j<-dgbinom(lj,jrowK,1-theta) lj<-lj[xi.j>0];xi.j<-xi.j[xi.j>0] }else{ xi.j<-1 } mj.gcd<-Aj/A.gcd Tj.gcd.cm<-c(lj[1]:(lj[length(lj)]*mj.gcd)) phi.j.cm<-rep(0,length(Tj.gcd.cm)) return for(i in c(1:length(lj))){ phi.lj<-phi.j(lj[i],nj,Aj,A.gcd) if(is.character(phi.lj)){ phi.j.cm<-phi.lj; break }else{ phi.lj$prob<-phi.lj$prob*xi.j[i] for(s in c(1:length(phi.lj$kj.gcd))){ phi.j.cm[phi.lj$kj.gcd[s]==Tj.gcd.cm]<-phi.j.cm[phi.lj$kj.gcd[s]==Tj.gcd.cm]+phi.lj$prob[s] } } } if(is.character(phi.j.cm)){ return<-phi.j.cm }else{ return<-data.frame(kj.gcd=Tj.gcd.cm[phi.j.cm>0],prob=phi.j.cm[phi.j.cm>0]) } return } K<-cbind(K,k-apply(K,1,sum)) theta<-c(theta,0) if(min(K[,length(theta)])<0){ return<-"Input error: arguments in k and K do not match!" }else{ A.gcd<-gcd.mult.ref(A.ref,prec) phi1<-phi.j.cm(k[1],n[1],K[1,],theta,A.ref[1],A.gcd) if(r>1){ if(is.character(phi1)){ return<-phi1 }else{ for(j in c(2:r)){ phi2<-phi.j.cm(k[j],n[j],K[j,],theta,A.ref[j],A.gcd) if(is.character(phi2)){ phi1<-phi2 break }else{ T.gcd<-c((phi1$kj.gcd[1]+phi2$kj.gcd[1]):(max(phi1$kj.gcd)+max(phi2$kj.gcd))) prob.k.gcd<-NULL for(k.gcd in T.gcd){ k1.gcd<-c(max(phi1$kj.gcd[1],k.gcd-max(phi2$kj.gcd)):min(k.gcd-phi2$kj.gcd[1],max(phi1$kj.gcd))) k2.gcd<-k.gcd-k1.gcd prob.k.gcd<-c(prob.k.gcd,sum(phi1$prob[k1.gcd-(phi1$kj.gcd[1]-1)]*phi2$prob[k2.gcd-(phi2$kj.gcd[1]-1)])) } phi1<-data.frame(kj.gcd=T.gcd,prob=prob.k.gcd) } } } } if(is.character(phi1)){ return<-phi1 }else{ dimnames(phi1)[[2]][1]<-"k.gcd" return<-list(phi.cm=phi1,A.gcd=A.gcd) } } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/phi.mult.ref.cm.R
phi.syn <- function(k,n){ if(length(n)!=length(k)){return<-"Input error: dimensions of k and n do not match!" }else if(min(n-k)<0){return<-"Input error: k has to be <= n!" }else if(min(n)<=0){return<-"Input error: n has to be > 0!" }else{ r<-length(k) if(r>1){ ord<-order(n,decreasing=TRUE) n<-n[ord] k<-k[ord] n.min<-min(n) omega.r<-c(max(k-(n-n.min)):min(sum(k),n.min)) prob.k.kstar<-function(k,k.star){ if((sum(k.star)<k)||(max(k.star)>k)){ return<-0 }else{ if(r==2){ return<-choose(n.min,k.star[1])*choose(n.min-k.star[1],k-k.star[1])*choose(k.star[1],k.star[1]+k.star[2]-k)/(choose(n.min,k.star[1])*choose(n.min,k.star[2])) }else{ ord<-order(k.star,decreasing=TRUE) k.star<-k.star[ord] J.star<-as.matrix(c(0:k.star[r-1])) if(r>3){ for(i in c((r-2):2)){ J.star.new<-J.star if(k.star[i]!=0){ for(j in c(1:k.star[i])){ J.star.new<-rbind(J.star.new,J.star) } } J.star<-cbind(sort(rep(c(0:k.star[i]),dim(J.star.new)[1]/(k.star[i]+1))),J.star.new) } } J.star<-cbind(J.star,k-apply(J.star,1,sum)-k.star[1]) J.star<-J.star[(J.star[,r-1]>=0)&(J.star[,r-1]<=k.star[r-1]),] if(is.null(dim(J.star))){ J.star<-matrix(J.star,1,r-1) } f2apply<-function(rowK){ choose(n.min,k.star[1])*prod(choose(n.min-cumsum(c(k.star[1],rowK[-(r-1)])),rowK)*choose(cumsum(c(k.star[1],rowK[-(r-1)])),k.star[-1]-rowK)) } return<-sum(apply(J.star,1,f2apply))/prod(choose(n.min,k.star)) } } return } K.star<-as.matrix(c(max(0,k[r-1]-(n[r-1]-n.min)):min(k[r-1],n.min))) if(r>2){ for(i in c((r-2):1)){ T.i<-c(max(0,k[i]-(n[i]-n.min)):min(k[i],n.min)) K.star.new<-K.star if(length(T.i)>1){ for(j in c(1:(length(T.i)-1))){ K.star.new<-rbind(K.star.new,K.star) } } K.star<-cbind(sort(rep(T.i,dim(K.star.new)[1]/length(T.i))),K.star.new) } } K.star.mod<-cbind(K.star,rep(k[r],dim(K.star)[1])) phi<-NULL for(j in omega.r){ phi.j<-0 for(i in c(1:dim(K.star.mod)[1])){ phi.j<-phi.j+prob.k.kstar(j,K.star.mod[i,])*prod(dhyper(K.star.mod[i,c(1:(r-1))],k[-r],n[-r]-k[-r],n.min)) } phi<-c(phi,phi.j) } return<-data.frame(k=omega.r,prob=phi) }else{ return<-data.frame(k=k,prob=1) } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/phi.syn.R
phi.syn.cm <- function(k,n,K,theta){ r<-length(k) if(length(n)!=length(k)){return<-"Input error: dimensions of k and n do not match!" }else if(min(n-k)<0){return<-"Input error: k has to be <= n!" }else if(min(n)<=0){return<-"Input error: n has to be > 0!" }else if(!is.matrix(K)){return<-"Input error: K has to be a matrix!" }else if((r!=dim(K)[1])||(length(theta)!=dim(K)[2])){return<-"Input error: dimensions of k and K and/or theta and K do not match!" }else if((min(theta)<0)||(max(theta)>1)){return<-"Input error: theta has to be in [0,1]!" }else{ K<-cbind(K,k-apply(K,1,sum)) theta<-c(theta,0) if(min(K[,length(theta)])<0){ return<-"Input error: arguments in k and K do not match!" }else{ if(r>1){ L<-as.matrix(c(0:k[r])) for(i in c((r-1):1)){ L.new<-L if(k[i]>0){ for(j in c(1:k[i])){ L.new<-rbind(L.new,L) } } L<-cbind(sort(rep(c(0:k[i]),dim(L.new)[1]/(k[i]+1))),L.new) } phi.L<-NULL for(i in c(1:dim(L)[1])){ phi.syn.i<-phi.syn(L[i,],n) prob.i<-1 for(j in c(1:r)){ if(k[j]>0){ prob.i<-prob.i*dgbinom(L[i,j],K[j,],1-theta) } } phi.syn.i$prob<-phi.syn.i$prob*prob.i phi.L<-rbind(phi.L,phi.syn.i) } phi.cm<-NULL omega.r<-c(0:max(phi.L$k)) for(j in omega.r){ phi.cm<-c(phi.cm,sum(phi.L$prob[phi.L$k==j])) } omega.r<-omega.r[phi.cm>0] phi.cm<-phi.cm[phi.cm>0] return<-data.frame(k=omega.r,prob=phi.cm) }else{ if(k==0){ return<-data.frame(k=0,prob=1) }else{ prob<-dgbinom(c(0:k),K[1,],1-theta) return<-data.frame(k=c(0:k)[prob>0],prob=prob[prob>0]) } } } } return }
/scratch/gouwar.j/cran-all/cranData/AdvBinomApps/R/phi.syn.cm.R
# Solve anomalous diffusion using FDM # Author: Jader Lugon Junior # Date: 02/2019 # Version: 0.1.19 # # AdvDif4(parm,func) # parm = alternative to inform parameters data # func = alternative to inform functions # # Data description # k2 = 2nd order diffusion coefficient parameter # k4 = 4th order diffusion coefficient parameter # v = velocity # l = dominium # m = space discretization step number # tf = final time of simulation # n = time discretization step number # w10,w11,w12,w20,w21,w22 = left values coefficients to define boundary conditions # e10,e11,e12,e20,e21,e22 = right values coefficients to define boundary conditions # # Functions description # fbeta = beta diffusion fraction function # dbetadp = beta derivative function # fn = initial condition function # fs = source function # fw1,fw2 = left border function for boundary conditions # fe1,fe2 = right border function for boundary conditions # # # #' @export AdvDif4 <- function(parm=NA,func=NA) { # Anomalous diffusion function and variables if (any((!is.na(parm)),(!is.na(func)))) {k2 <- parm[1] k4 <- parm[2] v <- parm[3] l <- parm[4] m <- parm[5] tf <- parm[6] n <- parm[7] w10 <- parm[8] w11 <- parm[9] w12 <- parm[10] w20 <- parm[11] w21 <- parm[12] w22 <- parm[13] e10 <- parm[14] e11 <- parm[15] e12 <- parm[16] e20 <- parm[17] e21 <- parm[18] e22 <- parm[19] fbeta <- func$fbeta dbetadp <- func$dbetadp fn <- func$fn fs <- func$fs fw1 <- func$fw1 fw2 <- func$fw2 fe1 <- func$fe1 fe2 <- func$fe2} if (any((!is.function(fbeta)),(!is.function(dbetadp)),(!is.function(fn)),(!is.numeric(k2)),(!is.numeric(k4)),(!is.numeric(v)),(!is.numeric(l)),(!is.numeric(m)),(!is.numeric(tf)),(!is.numeric(n)),(!is.numeric(w10)),(!is.numeric(w11)),(!is.numeric(w12)),(!is.numeric(w20)),(!is.numeric(w21)),(!is.numeric(w22)),(!is.function(fw1)),(!is.function(fw2)),(!is.numeric(e10)),(!is.numeric(e11)),(!is.numeric(e12)),(!is.numeric(e20)),(!is.numeric(e21)),(!is.numeric(e22)),(!is.function(fe1)),(!is.function(fe2)))) {stop('Advection Bi-Flux Difusive Problem functions or variables are wrong or missing.')} dx <- l/m dt <- tf/n p1 <- seq(from=dx, to=l-dx, by=dx) bet <- p1 aw <- seq(from=dx, to=l-2*dx, by=dx) aww <- seq(from=dx, to=l-3*dx, by=dx) p <- matrix(nrow=n,ncol=m+1) ap <- p1 ae <- aw aee <- aww b <- p1 # # Initial condition definition # j <- 1 while(j<=m) {p1[j] <- fn(dx*j) j <- j+1} # # Defining some useful values # auxi6 <- 12*dx^4 # # Temporal loop # t1 <- dt i <- 1 while(i<=n) { # # Boundary conditions # if (all((w12==0),(w22==0))) # left border second derivative is unknown # {bc1 <- 1 cw <- ((w21*fw1(t1))-(w11*fw2(t1)))/((w10*w21)-(w11*w20)) dfw1 <- ((w20*fw1(t1))-(w10*fw2(t1)))/((w20*w11)-(w21*w10)) } if (all((w11==0),(w21==0))) # left border first derivative is unknown # {bc1 <- 2 cw <- ((w22*fw1(t1))-(w12*fw2(t1)))/((w10*w22)-(w12*w20)) dfw2 <- ((w20*fw1(t1))-(w10*fw2(t1)))/((w12*w20)-(w22*w10)) } if (all((w10==0),(w20==0))) # left border function value is unknown # {bc1 <- 3 dfw1 <- ((w22*fw1(t1))-(w12*fw2(t1)))/((w11*w22)-(w12*w21)) dfw2 <- ((w21*fw1(t1))-(w11*fw2(t1)))/((w12*w21)-(w11*w22)) } if (all((e12==0),(e22==0))) # right border second derivative is unknown # {bc2 <- 1 ce <- ((e21*fe1(t1))-(e11*fe2(t1)))/((e10*e21)-(e11*e20)) dfe1 <- ((e20*fe1(t1))-(e10*fe2(t1)))/((e20*e11)-(e21*e10)) } if (all((e11==0),(e21==0))) # right border first derivative is unknown # {bc2 <- 2 ce <- ((e22*fe1(t1))-(e12*fe2(t1)))/((e10*e22)-(e12*e20)) dfe2 <- ((e20*fe1(t1))-(e10*fe2(t1)))/((e12*e20)-(e22*e10)) } if (all((e10==0),(e20==0))) {bc2 <- 3 # right border function value is unknown # dfe1 <- ((e22*fe1(t1))-(e12*fe2(t1)))/((e11*e22)-(e12*e21)) dfe2 <- ((e21*fe1(t1))-(e11*fe2(t1)))/((e12*e21)-(e11*e22)) } # # Building Matrix "A" and vector "b" # j <- 1 while(j<=m-1) { bet[j] <- fbeta(p1[j]) k22 <- bet[j]*k2 k44 <- (-bet[j]*(1-bet[j])*k4) if (all((j>3),(j<m-3))) {dbedx <- dbetadp(bet[j])*(p1[j-2]-8*p1[j-1]+8*p1[j+1]-p1[j+2])/12/dx} else {dbedx <- 0} al1 <- k2*dbedx al2 <- k4*(1-2*bet[j])*dbedx auxi1 <- 12*dx^4+30*k22*dx^2*dt-6*12*k44*dt auxi2 <- (-16*k22*dx^2*dt+4*12*k44*dt+8*v*dx^3*dt-8*al1*dx^3*dt+12*al2*dx*dt) auxi3 <- (-16*k22*dx^2*dt+4*12*k44*dt-8*v*dx^3*dt+8*al1*dx^3*dt-12*al2*dx*dt) auxi4 <- k22*dx^2*dt-12*k44*dt-v*dx^3*dt+al1*dx^3*dt-6*al2*dx*dt auxi5 <- k22*dx^2*dt-12*k44*dt+v*dx^3*dt-al1*dx^3*dt+6*al2*dx*dt ap[j] <- auxi1 b[j] <- auxi6*(p1[j]+dt*fs(dx*j,i*dt)) if (j==1) {if (bc1==1) {b[j] <- b[j]+2*dx*dfw1*auxi5-auxi3*cw ap[j] <- auxi1+auxi5} if (bc1==2) {b[j] <- b[j]-2*auxi5*cw-dx^2*auxi5*dfw2-auxi3*cw ap[j] <- auxi1-auxi5} if (bc1==3) {b[j] <- b[j]+2*auxi5*dx*dfw1+auxi3*(dx*dfw1+dx^2*dfw2/2) ap[j] <- auxi1+auxi5+auxi3} } if (j==2) {if (bc1==1) {b[j] <- b[j]-auxi5*cw} if (bc1==2) {b[j] <- b[j]-auxi5*cw} if (bc1==3) {b[j] <- b[j]+auxi5*(dx*dfw1+dx^2*dfw2/2) ap[j] <- auxi1+auxi5} } if (j==m-1) {if (bc2==1) {b[j] <- b[j]-2*dx*dfe1*auxi4-auxi2*ce ap[j] <- auxi1+auxi4} if (bc2==2) {b[j] <- b[j]-2*auxi4*ce-dx^2*auxi4*dfe2-auxi2*ce ap[j] <- auxi1-auxi4} if (bc2==3) {b[j] <- b[j]-2*auxi4*dx*dfe1+auxi2*(dx^2*dfe2/2-dx*dfe1) ap[j] <- auxi1+auxi4+auxi2} } if (j==m-2) {if (bc2==1) {b[j] <- b[j]-auxi4*ce} if (bc2==2) {b[j] <- b[j]-auxi4*ce} if (bc2==3) {b[j] <- b[j]+auxi4*(dx^2*dfe2/2-dx*dfe1) ap[j] <- auxi1+auxi4} } if (j<m-2) {aee[j] <- auxi4} if (j<m-1) {ae[j] <- auxi2} if (j>1) {aw[j-1] <- auxi3} if (j>2) {aww[j-2] <- auxi5} j <- j+1} # # saving previous result # if (bc1==3) {cw <- p1[1]-dx*dfw1-dx^2*dfw2/2} p[i,1] <- cw j <- 2 while(j<=m) {p[i,j] <- p1[j-1] j <- j+1} if (bc2==3) {ce <- p1[m]+dx*dfe1-dx^2*dfe2/2} p[i,m+1] <- ce # # solving the system "Ax=b" # p1 <- pentaSolve(aww,aw,ap,ae,aee,b) # Matrix alternative to pentaSolve #a <- bandSparse(m-1,k=c(-2,-1,0,1,2),diag=list(aww,aw,ap,ae,aee)) #p1 <- solve(a,b,sparse=TRUE) t1 <- t1+dt i <- i+1} #write.table(p, file = "output.txt", append = FALSE, quote = FALSE, sep = " ", # eol = "\n", na = "NA", dec = ".", row.names = FALSE, # col.names = FALSE, qmethod = c("escape", "double"), # fileEncoding = "") return(p) }
/scratch/gouwar.j/cran-all/cranData/AdvDif4/R/AdvDif4.R
# Solve a pentadiagonal linear equation system # Author: Jader Lugon Junior # Date: 03/2017 # Version: 0.1.17 # #' @export pentaSolve <- function(a1,a2,a3,a4,a5,b) { u <- b N <- length(b) i <- 1 while(i<=N-2) { auxi <- a2[i]/a3[i] a3[i+1] <- a3[i+1]-a4[i]*auxi a4[i+1] <- a4[i+1]-a5[i]*auxi b[i+1] <- b[i+1]-b[i]*auxi auxi <- a1[i]/a3[i] a2[i+1] <- a2[i+1]-a4[i]*auxi a3[i+2] <- a3[i+2]-a5[i]*auxi b[i+2] <- b[i+2]-b[i]*auxi i <- i+1 } auxi <- a2[N-1]/a3[N-1] a3[N] <- a3[N]-a4[N-1]*auxi b[N] <- b[N]-b[N-1]*auxi # back substitution u[N] <- b[N]/a3[N] u[N-1] <- (b[N-1]-a4[N-1]*u[N])/a3[N-1] i <- N-2 while(i>=1) { u[i] <- (b[i]-a4[i]*u[i+1]-a5[i]*u[i+2])/a3[i] i <- i-1 } return(u) }
/scratch/gouwar.j/cran-all/cranData/AdvDif4/R/pentaSolve.R
#' @title Individual advanced statistics #' @description This function allows the calculation of advanced individual statistics. #' @param df1 Should be a Data Frame that represents the individual statistics or individual defensive statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the following advanced statistics calculated: #' \itemize{ #' \item Player Efficiency Rating (PER) #' \item Efficiency Field Goals percentage (eFG\%) #' \item True shooting percentage (TS\%) #' \item Three rating (3Par) #' \item Free Throw rating (FTr) #' \item Offensive rebounds percentage (ORB\%) #' \item Defensive rebounds percentage (DRB\%) #' \item Total rebounds percentage (TRB\%) #' \item Assists percentage (AST\%) #' \item Steal percentage (STL\%) #' \item Block percentage (BLK\%) #' \item Turnover percentage (TOV\%) #' \item Usage percentage (USG\%) #' } #' #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' individuals_advance_stats(df1,df2,df3) #' #' @export #' individuals_advance_stats <- function(df1,df2,df3){ df1 <- df1[-nrow(df1),] tm_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] opp_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] adv_stats <- cbind(df1[1],df1[2],df1[3],df1[4]) per <- round((df1[5] * 85.910 + df1[21] * 53.897 + df1[8] * 51.757 + df1[14] * 46.845 + df1[22] * 39.190 + df1[17] * 39.190 + df1[20] * 34.677 + df1[18] * 14.707 - df1[24] * 17.174 - (df1[9] - df1[8]) * 20.091 - (df1[6] - df1[5]) * 39.190 - df1[23] * 53.897) * (1/df1[4]),2) tpar <- round(df1[9] / df1[6],3) ftr <- round(df1[15] / df1[6],3) efg <- round((df1[5] + 0.5 * df1[8]) / df1[6],3) ts <- round(df1[25] / (2 * (df1[6] + 0.44 * df1[15])),3) orb <- round(100 * (df1[17] * (df2[1,2] / 5)) / (df1[4] * (df2[1,15] + df3[1,16])),2) drb <- round(100 * (df1[18] * (df2[1,2] / 5)) / (df1[4] * (df2[1,16] + df3[1,15])),2) trb <- round(100 * (df1[19] * (df2[1,2] / 5)) / (df1[4] * (df2[1,17] + df3[1,17])),2) ast <- round(100 * (df1[20] / (((df1[4] / (df2[1,2] / 5)) * df2[1,3]) - df1[5])),2) stl <- round(100 * (df1[21] * (df2[1,2] / 5)) / (df1[4] * opp_poss),2) blk <- round(100 * (df1[22] * (df2[1,2] / 5))/ (df1[4] * (df3[1,4] - df3[1,7])),2) tov <- round(100 * df1[23] / (df1[6] + 0.44 * df1[15] + df1[23]),2) usg <- round(100 * ((df1[6] + 0.44 * df1[15] + df1[23]) * (df2[1,2] / 5)) / (df1[4] * (df2[1,4] + 0.44 * df2[1,13] + df2[1,21])),2) adv_stats <- cbind(adv_stats,per,efg,ts,tpar,ftr,orb,drb,trb,ast,stl,blk,tov,usg) names(adv_stats) = c("Name","G","GS","MP","PER","eFG%","TS%","3PAr","FTr","ORB%","DRB%","TRB%","AST%","STL%","BLK%","TOV%","USG%") adv_stats[is.na(adv_stats)] <- 0 return(adv_stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_advance_stats.R
#' @title Individual stat adjuster #' @description The function transform the statistics entered for later use in the rest of the functions that apply to individuals statistics. #' @param df1 Should be a Data Frame that represents the individual statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @details \itemize{ #' \item The data.frame must have the same columns and these represent the same as in the example. #' \item The input data.frame must have the last row that represents the team's statistics. #' \item The function allows the transformation of the individual's statistics to which the shooting percentages and the number of total rebounds are added. #' \item The function allows the transformation of the defensive statistics to which the force missed shot and the forced turnovers. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data.frame with the transformed statistics for use in the rest of the functions. #' @return The data frame obtained for the individual's statistics will have the following format: #' \itemize{ #' \item Name of the player (Name) #' \item Games played (G) #' \item Games Started (GS) #' \item Minutes Played (MP) #' \item Field Goals Made (FG) #' \item Field Goals Attempted (FGA) #' \item Field Goals Percentage (FG\%) #' \item Three Points Made (3P) #' \item Three Points Attempted (3PA) #' \item Three Points Percentage (3P%) #' \item Two Points Made (2P) #' \item Two Points Attempted (2PA) #' \item Two Points Percentage (2P\%) #' \item Free Throw Made (FT) #' \item Free Throw Attempted (FTA) #' \item Free Throw Percentage (FT\%) #' \item Offensive Rebounds (ORB) #' \item Defensive Rebounds (DRB) #' \item Total Rebounds (TRB) #' \item Assists (AST) #' \item Steals (STL) #' \item Blocks (BLK) #' \item Turnover (TOV) #' \item Personal Fouls (PF) #' \item Points (PTS) #' \item Plus Minus (+/-) #' } #' The data frame obtained for the defensive individual's statistics will have the following format: #' \itemize{ #' \item Name of the player (Name) #' \item Minutes Played (MP) #' \item Defensive Rebounds (DRB) #' \item FGA by opposing team (FM) #' \item Blocks (BLK) #' \item (TOTAL FM) #' \item Forced turnover(FTO) #' \item Steals (STL) #' \item Total forced turnover (TOTAL FTO) #' \item FTA by opposing team (FFTA) #' \item FG made by opposing team (DFGM) #' \item FT made by opposing team (DFTM) #' } #' @examples #' df1 <- data.frame("Name" = c("James","Team"), "G" = c(67,0), "GS" = c(62,0), #' "MP" = c(2316,1), "FG" = c(643,0), "FGA" = c(1303,0),"3P " = c(148,0), #' "3PA" = c(425,0),"2P" = c(495,0), "2PA" = c(878,0), "FT" = c(264,0), #' "FTA" = c(381,0),"ORB" = c(66,0), "DRB" = c(459,0), "AST" = c(684,0), #' "STL" = c(78,0), "BLK" = c(36,0),"TOV" = c(261,0), "PF" = c(118,0), #' "PTS" = c(1698,0), "+/-" = c(0,0)) #' #' individuals_data_adjustment(df1) #' #' df2 <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200), #' "DREB" = c(1,0),"FM" = c(4,0), "BLK" = c(0,0),"FTO" = c(0,0), #' "STL" = c(1,1), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) #' #' individuals_data_adjustment(df2) #' #' @export #' individuals_data_adjustment <- function(df1){ if(ncol(df1)==21){ PFG <- sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P3P <- sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) P2P <- sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) PFT <- sample(c(round(df1[11]/df1[12],3)), size = 1, replace = TRUE) TRB <- sample(c(df1[13]+df1[14]), size = 1, replace = TRUE) df1 <- cbind(df1, PFG,P3P,P2P,PFT,TRB) data_adjustment <- subset (df1, select=c(1,2,3,4,5,6,22,7,8,23,9,10,24,11,12,25,13,14,26,15,16,17,18,19,20,21)) names(data_adjustment) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") data_adjustment[is.na(data_adjustment)] <- 0 } else if(ncol(df1)==10){ names(df1) <- c("Name","MP","DREB","FM","BLK","FTO","STL","FFTA","DFGM","DFTM") totalfm<- df1[4]+df1[5] totalfto <- df1[6]+df1[7] data_adjustment <- cbind(df1,totalfm,totalfto) data_adjustment <- subset (data_adjustment, select=c(1,2,3,4,5,11,6,7,12,8,9,10)) names(data_adjustment) <- c("Name","MP","DRB","FM","BLK","TOTAL FM","FTO","STL","TOTAL FTO","FFTA","DFGM","DFTM") data_adjustment[is.na(data_adjustment)] <- 0 } data_adjustment[is.na(data_adjustment)] <- 0 return(data_adjustment) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_data_adjustment.R
#' @title Individual's defensive actual statistics #' @description The function allows the calculation of individual defensive actual statistics on court #' @param df1 Should be a Data Frame that represents the individual defensive statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the following individual defensive actual statistics #' \itemize{ #' \item Defensive Stops (DStops) #' \item Defensive Scores Possesions (DscPoss) #' \item Defensive Possesions (DPoss) #' \item Stops percentage (STOPS\%) #' \item (TMDPossS\%) #' \item Defensive Rating (DRtg) #' } #' @examples #' #' df1 <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200), #' "DREB" = c(1,0), "FM" = c(4,0), "BLK" = c(0,0),"TOTAL FM" = c(4,0), #' "FTO" = c(0,0),"STL" = c(1,1), "TOTAL FTO " = c(1,0), "FFTA" = c(0,0), #' "DFGM" = c(1,0), "DFTM" = c(0,0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' individuals_defensive_actual_floor_stats(df1,df2,df3) #' #' @export #' individuals_defensive_actual_floor_stats <- function(df1,df2,df3){ stats <- cbind(df1[1],df1[2]) poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] ope_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] team_possessions <- (poss+ope_poss)/2 dor <- df3[1,15] / (df3[1,15] + df2[1,16]) dfg <- df3[1,3] / df3[1,4] fmwt <- (dfg * (1 - dor)) / (dfg * (1 - dor) + (1 - dfg) * dor) dstops <- df1[7] + df1[8] + df1[10]/10 + (df1[4] + df1[5]) * fmwt * (1-dor) + df1[3] * (1-fmwt) aux <- 0.45 * (df1[10] + df1[12]) * (1-(1- df1[12]/(df1[10]+df1[12])))^2 aux[is.na(aux)] <- 0 dscposs <- df1[11] + aux dposs <- dstops + dscposs stops <- dstops / (dstops + dscposs) tmdposs <- (40/df1[2])*dposs/team_possessions team_defensive_rating <- 100 * (df3[1,23] / team_possessions) d_pts_per_scposs <- df3[1,23] / (df3[1,3] + (1 - (1 - (df3[1,12] / df3[1,13]))^2) * df3[1,13]*0.4) drtg <- team_defensive_rating + tmdposs * (100 * d_pts_per_scposs * (1-stops) - team_defensive_rating) stats <- cbind(stats,round(dstops,2),round(dscposs,2),round(dposs,2),round(stops,3),round(tmdposs,3),round(drtg,2)) names(stats) = c("Name","MP","DStops","DScPoss","DPoss","Stop%","TMDPoss%","DRtg") stats[is.na(stats)] <- 0 return(stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_defensive_actual_floor_stats.R
#' @title individual's defensive estimated statistics #' @description The function allows the calculation of individual defensive estimated statistics on court #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the data_adjustment() function. #' @param df2 Should be a Data Frame. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame. The parameter has to be in the format provided by the team_stats() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the following individual defensive estimated statistics #' \itemize{ #' \item Defensive Stops (DStops) #' \item Stops percentage (STOPS\%) #' \item floor percentage (Floor\%) #' \item Defensive Rating (DRtg) #' } #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' individuals_defensive_estimated_floor_stats(df1,df2,df3) #' #' @export #' individuals_defensive_estimated_floor_stats <- function(df1,df2,df3){ df1 <- df1[-nrow(df1),] stats <- cbind(df1[1],df1[2]) team_possessions <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] dor <- df3[1,15] / (df3[1,15] + df2[1,16]) dfg <- df3[1,3] / df3[1,4] fmwt <- (dfg * (1 - dor)) / (dfg * (1 - dor) + (1 - dfg) * dor) stops1 <- df1[21] + df1[22] * fmwt * (1 - 1.07 * dor) + df1[18] * (1 - fmwt) stops2 <- (((df3[1,4] - df3[1,3] - df2[1,20]) / df2[1,2]) * fmwt * (1 - 1.07 * dor) + ((df3[1,21] - df2[1,19]) / df2[1,2])) * df1[4] + (df1[24] / df2[1,22]) * 0.4 * df3[1,13] * (1 - (df3[1,12] / df3[1,13]))^2 stops <- stops1 + stops2 stop <- (stops * df3[1,2]) / (team_possessions * df1[4]) stop[1][is.na(stop[1])] <- 0 team_defensive_rating <- 100 * (df3[1,23] / team_possessions) d_pts_per_scposs <- df3[1,23] / (df3[1,3] + (1 - (1 - (df3[1,12] / df3[1,13]))^2) * df3[1,13]*0.4) drtg <- team_defensive_rating + 0.2 * (100 * d_pts_per_scposs * (1 - stop) - team_defensive_rating) stats <- cbind(stats,round(stops/stats[2],2),round(stop,3),round(drtg,2)) names(stats) = c("Name","G","Stops","Stop%","DRtg") stats[is.na(stats)] <- 0 return(stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_defensive_estimated_floor_stats.R
#' @title individual's games adder #' @description The function allows to perform the sums of two data.frames with the same format adopted after being transformed by individuals_data_adjustment() function, #' @param df1 Should be a Data Frame that represents the first set of individual statistics or defensive individual statistics of the players. It has to be in the format provided by the individuals_data_adjustment() function #' @param df2 Should be a Data Frame that represents the second set of individual statistics or defensive individual statistics of the players. It has to be in the format provided by the individuals_data_adjustment() function #' @details The function will work correctly when the name of the players is the same, in case it is different it will take the players as different. #' @return Data frame with the sum of the statistics of the other two entered data.frame. #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"), "G" = c(67,0), #' "GS" = c(62,0), "MP" = c(2316,0), "FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0), "3P" = c(148,0), "3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0), "2P" = c(495,0), "2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0), "FT" = c(264,0), "FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0), "DRB" = c(459,0), #' "TRB" = c(525,0), "AST" = c(684,0), "STL" = c(78,0), "BLK" = c(36,0), #' "TOV" = c(261,0), "PF" = c(118,0), "PTS" = c(1698,0), "+/-" = c(0,0)) #' #' df2 <- data.frame("name" = c("LeBron James","Team"), "G" = c(67,0), #' "GS" = c(62,0), "MP" = c(2316,0), "FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0), "3P" = c(148,0), "3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0), "2P" = c(495,0), "2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0), "FT" = c(264,0), "FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0), "DRB" = c(459,0), #' "TRB" = c(525,0), "AST" = c(684,0), "STL" = c(78,0), "BLK" = c(36,0), #' "TOV" = c(261,0), "PF" = c(118,0), "PTS" = c(1698,0), "+/-" = c(0,0)) #' #' individuals_games_adder(df1,df2) #' #' @export #' #' @importFrom stats aggregate individuals_games_adder <- function(df1,df2){ if(ncol(df1) == 26 & ncol(df2) == 26){ t1 <- df1[nrow(df1),] t2 <- df2[nrow(df2),] df1<-df1[1:(nrow(df1)-1),] df2<-df2[1:(nrow(df2)-1),] adder <- rbind(df1,df2) team <- rbind(t1,t2) names(adder) <- c("Name","G","GS","MP","FG","FGA","FG%","TP","TPA","3P%","TWP","TWPA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","P","PM") names(team) <- c("Name","G","GS","MP","FG","FGA","FG%","TP","TPA","3P%","TWP","TWPA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","P","PM") adder <- aggregate(cbind(adder$G,adder$GS,adder$MP,adder$FG,adder$FGA,adder$TP,adder$TPA,adder$TWP,adder$TWPA,adder$FT,adder$FTA,adder$ORB, adder$DRB,adder$TRB,adder$AST,adder$STL,adder$BLK,adder$TOV,adder$PF,adder$P,adder$PM), by=list(Name=adder$Name), FUN=sum) team <- aggregate(cbind(team$G,team$GS,team$MP,team$FG,team$FGA,team$TP,team$TPA,team$TWP,team$TWPA,team$FT,team$FTA,team$ORB, team$DRB,team$TRB,team$AST,team$STL,team$BLK,team$TOV,team$PF,team$P,team$PM), by=list(Name=team$Name), FUN=sum) adder <- rbind(adder,team) PFG<-sample(c(round(adder[5]/adder[6],3)), size = 1, replace = TRUE) P3P<-sample(c(round(adder[7]/adder[8],3)), size = 1, replace = TRUE) P2P<-sample(c(round(adder[9]/adder[10],3)), size = 1, replace = TRUE) PFT<-sample(c(round(adder[11]/adder[12],3)), size = 1, replace = TRUE) adder <- cbind(adder, PFG,P3P,P2P,PFT) adder <- subset (adder, select=c(1,2,3,4,5,6,23,7,8,24,9,10,25,11,12,26,13,14,15,16,17,18,19,20,21,22)) adder[is.na(adder)] <- 0 names(adder) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") }else if (ncol(df1) == 12 & ncol(df2) == 12){ t1 <- df1[nrow(df1),] t2 <- df2[nrow(df2),] df1<-df1[1:(nrow(df1)-1),] df2<-df2[1:(nrow(df2)-1),] adder <- rbind(df1,df2) team <- rbind(t1,t2) names(adder) <- c("Name","MP","DREB","FM","BLK","TOTALFM","FTO","STL","TOTALFTO","FFTA","DFGM","DFTM") names(team) <- c("Name","MP","DREB","FM","BLK","TOTALFM","FTO","STL","TOTALFTO","FFTA","DFGM","DFTM") adder <- aggregate(cbind(adder$MP,adder$DREB,adder$FM,adder$BLK,adder$TOTALFM,adder$FTO,adder$STL,adder$TOTALFTO,adder$FFTA,adder$DFGM,adder$DFTM), by=list(Name=adder$Name), FUN=sum) team <- aggregate(cbind(team$MP,team$DREB,team$FM,team$BLK,team$TOTALFM,team$FTO,team$STL,team$TOTALFTO,team$FFTA,team$DFGM,team$DFTM), by=list(Name=team$Name), FUN=sum) adder <- rbind(adder,team) names(adder) <- c("Name","MP","DREB","FM","BLK","TOTALFM","FTO","STL","TOTALFTO","FFTA","DFGM","DFTM") adder[is.na(adder)] <- 0 } adder[is.na(adder)] <- 0 return(adder) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_games_adder.R
#' @title individual's offensive floor stats #' @description The function allows the calculation of individual's offensive statistics on court #' @param df1 Should be a Data Frame that represents the individual statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the following individual's offensive statistics #' \itemize{ #' \item Score possessions (Sc. Poss) #' \item Possessions attacked (Poss) #' \item floor percentage (Floor\%) #' \item Offensive Rating (ORtg) #' \item Point produced per game (Pts Prod/G) #' } #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' #' individuals_ofensive_floor_stats(df1,df2,df3) #' #' @export #' individuals_ofensive_floor_stats <- function(df1,df2,df3){ df1 <- df1[-nrow(df1),] stats <- cbind(df1[1],df1[2]) qast <- ((df1[4] / (df2[1,2] / 5)) * (1.14 * ((df2[1,18] - df1[20]) / df2[1,3]))) + ((((df2[1,18] / df2[1,2]) * df1[4] * 5 - df1[20]) / ((df2[1,3] / df2[1,2]) * df1[4] * 5 - df1[5])) * (1 - (df1[4] / (df2[1,2] / 5)))) fg_part <- df1[5] * (1 - 0.5 * ((df1[25] - df1[14]) / (2 * df1[6])) * qast) fg_part[1][is.na(fg_part[1])] <- 0 ast_part <- 0.5 * (((df2[1,23] - df2[1,12]) - (df1[25] - df1[14])) / (2 * (df2[1,4] - df1[6]))) * df1[20] ft_part <- (1-(1-(df1[14] / df1[15]))^2) * 0.4 * df1[15] ft_part[1][is.na(ft_part[1])] <- 0 team_scoring_poss <- df2[1,3] + (1 - (1 - (df2[1,12] / df2[1,13]))^2) * df2[1,13] * 0.4 team_orb <- df2[1,15] / (df2[1,15] + (df3[1,17] - df3[1,15])) team_play <- team_scoring_poss / (df2[1,4] + df2[1,13] * 0.4 + df2[1,21]) team_orb_weight <- ((1 - team_orb) * team_play) / ((1 - team_orb) * team_play + team_orb * (1 - team_play)) orb_part <- df1[17] * team_orb_weight * team_play scposs <- (fg_part + ast_part + ft_part) * (1 - (df2[1,15] / team_scoring_poss) * team_orb_weight * team_play) + orb_part fgxposs <- (df1[6] - df1[5]) * (1 - 1.07 * team_orb) ftxposs <- ((1 - (df1[14] / df1[15]))^2) * 0.4 * df1[15] ftxposs[1][is.na(ftxposs[1])] <- 0 totposs <- scposs + fgxposs + ftxposs + df1[23] pprod_fg_part <- 2 * (df1[5] + 0.5 * df1[8]) * (1 - 0.5 * ((df1[25] - df1[14]) / (2 * df1[6])) * qast) pprod_fg_part[1][is.na(pprod_fg_part[1])] <- 0 pprod_ast_part <- 2 * ((df2[1,3] - df1[5] + 0.5 * (df2[1,6] - df1[8])) / (df2[1,3] - df1[5])) * 0.5 * (((df2[1,23] - df2[1,12]) - (df1[25] - df1[14])) / (2 * (df2[1,4] - df1[6]))) * df1[20] pprod_orb_part <- df1[17] * team_orb_weight * team_play * (df2[1,23] / (df2[1,3] + (1 - (1 - (df2[1,12] / df2[1,13]))^2) * 0.4 * df2[1,13])) pprod = (pprod_fg_part + pprod_ast_part + df1[14]) * (1 - (df2[1,15] / team_scoring_poss) * team_orb_weight * team_play) + pprod_orb_part ortg <- 100 * (pprod / totposs) floor <- scposs / totposs stats <- cbind(stats,round(scposs/stats[2],2),round(totposs/stats[2],2),round(floor,3),round(ortg,2),round(pprod/stats[2],2)) names(stats) = c("Name","G","Sc. Poss","Poss","Floor%","ORtg","Pts Prod/G") stats[is.na(stats)] <- 0 return(stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_ofensive_floor_stats.R
#' @title individual's statistics per game #' @description The function allows the calculation of individual statistics per game. #' @param df1 Should be a Data Frame that represents the individual statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @details The calculation is made with the number of games played by the player. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with individual statistics per game #' @examples #' #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' individuals_stats_per_game(df1) #' #' #' @export #' individuals_stats_per_game <- function(df1){ df1 <- df1[-nrow(df1),] for(i in 4:ncol(df1)){ if(i==7 || i==10 || i==13 || i==16){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round(df1[i] / df1[2],2) } } names(df1) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_stats_per_game.R
#' @title individual statistics calculator per minutes #' @description The function allows the calculation of the statistics per game projected to M minutes. #' @param df1 Should be a Data Frame that represents the individual statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @param m Should be a number. This parameter has to be the number of minutes to which you want to project the statistics. #' @details The statistical projection is made from the relationship between the number of minutes entered and the number of minutes played by the player. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with statistics by game projected to the minutes entered. #' @examples #' #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' m <- 48 #' #' individuals_stats_per_minutes(df1,m) #' #' #' #' @export #' individuals_stats_per_minutes <- function(df1,m){ df1 <- df1[-nrow(df1),] minutes<-df1[4] df1[4] <- df1[4]/df1[2] for(i in 5:ncol(df1)){ if(i==7 || i==10 || i==13 || i==16){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i] / df1[2]) * (m/df1[4]),2) } } df1[4] <- minutes names(df1) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_stats_per_minutes.R
#' @title individual statistics calculator per possessions #' @description The function allows the calculation of the statistics per game projected to P possesions. #' @param df1 Should be a Data Frame that represents the individual statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param p Should be a number. This parameter has to be the number of possessions to which you want to project the statistics. #' @param m should be a number. This parameter has to be the duration of a single game. #' @details The statistical projection is made from the estimation of the possessions that the team plays when the player is on the court. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with statistics by game projected to the possessions entered #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), #' "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), #' "TOV" = c(261,0),"PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' #' p <- 100 #' #' m <- 48 #' #' individuals_stats_per_possesion(df1,df2,df3,p,m) #' #' @export #' individuals_stats_per_possesion <- function(df1,df2,df3,p,m){ df1 <- df1[-nrow(df1),] tm_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] opp_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] pace <- m * ((tm_poss + opp_poss) / (2 * (df2[1,2] / 5))) player_poss <- (pace/m) * df1[4] for(i in 5:ncol(df1)){ if(i==7 || i==10 || i==13 || i==16){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/player_poss) * p,2) } } names(df1) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/individuals_stats_per_possesion.R
#' @title Lineups advanced statistics #' @description This function allows the calculation of advanced player statistics. #' @param df1 Should be a Data Frame. This parameter has to be in the format provided by the lineups_advance_stats() function. #' @param m should be a number. This parameter has to be the duration of a single game. #' @details The function only works with the extended statistics of the lineups. #' @return Data frame with the following advanced statistics calculated #' \itemize{ #' \item Offensive Rating (ORtg) #' \item Defensive Rating (DRtg) #' \item Net Rating (NetRtg) #' \item Pace (Pace) #' \item Three rating (3Par) #' \item True shooting percentage (TS\%) #' \item Efficiency Field Goals percentage (eFG\%) #' \item Assists percentage (AST\%) #' \item Offensive rebounds percentage (ORB\%) #' \item Defensive rebounds percentage (DRB\%) #' \item Total rebounds percentage (TRB\%) #' \item Turnover percentage (TOV\%) #' } #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' m <- 48 #' #' lineups_advance_stats(df1,m) #' #' @export #' lineups_advance_stats <- function(df1,m){ if(ncol(df1)==41){ adv_stats <-df1[1:6] tm_poss <- df1[9] - (df1[23]/(df1[23] + df1[26])) * (df1[9] - df1[7]) * 1.07 + df1[35] + 0.4 * df1[21] opp_poss <- df1[10] - (df1[24]/(df1[24] + df1[25])) * (df1[10] - df1[8]) * 1.07 + df1[36] + 0.4 * df1[22] team <- df1[6]/cumsum(df1[6]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[6])) offrtg <- 100*((df1[39])/(tm_poss)) defrtg <- 100*((df1[40])/(opp_poss)) netrtg <- offrtg - defrtg par <- df1[13]/df1[9] ftr <- df1[21]/df1[9] ts <- df1[39] / (2 * (df1[9] + 0.44 * df1[21])) efg <- (df1[7] + 0.5 * df1[11]) / df1[9] ast <- df1[29] / df1[7] orb <- (df1[23]/(df1[23] + df1[26])) drb <- df1[25] / (df1[24] + df1[25]) trb <- df1[27] / (df1[27] + df1[28]) tov <- df1[35] / (df1[9] + 0.44 * df1[21] + df1[35]) adv_stats <- cbind(adv_stats,round(team,3),round(pace,3),round(offrtg,2),round(defrtg,2),round(netrtg,2),round(par,3), round(ftr,3),round(ts,3),round(efg,3),round(ast,3),round(orb,3),round(drb,3),round(trb,3),round(tov,3)) names(adv_stats) = c("PG","SG","SF","PF","C","MP","TEAM%","PACE","ORtg","DRtg","Net Rtg","3Par","FTr","TS%","eFG%","AST%","ORB%","DRB%","TRB%","TOV%") }else if(ncol(df1)==39){ adv_stats <-df1[1:4] tm_poss <- df1[7] - (df1[21]/(df1[21] + df1[24])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19] opp_poss <- df1[8] - (df1[22]/(df1[22] + df1[23])) * (df1[8] - df1[6]) * 1.07 + df1[34] + 0.4 * df1[20] team <- df1[4]/cumsum(df1[4]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[4])) offrtg <- 100*((df1[37])/(tm_poss)) defrtg <- 100*((df1[38])/(opp_poss)) netrtg <- offrtg - defrtg par <- df1[11]/df1[7] ftr <- df1[19]/df1[7] ts <- df1[37] / (2 * (df1[7] + 0.44 * df1[19])) efg <- (df1[5] + 0.5 * df1[9]) / df1[7] ast <- df1[27] / df1[5] orb <- (df1[21]/(df1[21] + df1[24])) drb <- df1[23] / (df1[22] + df1[23]) trb <- df1[25] / (df1[25] + df1[26]) tov <- df1[33] / (df1[7] + 0.44 * df1[19] + df1[33]) adv_stats <- cbind(adv_stats,round(team,3),round(pace,3),round(offrtg,2),round(defrtg,2),round(netrtg,2),round(par,3), round(ftr,3),round(ts,3),round(efg,3),round(ast,3),round(orb,3),round(drb,3),round(trb,3),round(tov,3)) names(adv_stats) = c("PG","SG","SF","MP","TEAM%","PACE","ORtg","DRtg","Net Rtg","3Par","FTr","TS%","eFG%","AST%","ORB%","DRB%","TRB%","TOV%") }else if(ncol(df1)==38){ adv_stats <-df1[1:3] tm_poss <- df1[6] - (df1[20]/(df1[20] + df1[23])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18] opp_poss <- df1[7] - (df1[21]/(df1[21] + df1[22])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19] team <- df1[3]/cumsum(df1[3]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[3])) offrtg <- 100*((df1[36])/(tm_poss)) defrtg <- 100*((df1[37])/(opp_poss)) netrtg <- offrtg - defrtg par <- df1[10]/df1[6] ftr <- df1[18]/df1[6] ts <- df1[36] / (2 * (df1[6] + 0.44 * df1[18])) efg <- (df1[4] + 0.5 * df1[8]) / df1[6] ast <- df1[26] / df1[4] orb <- (df1[20]/(df1[20] + df1[23])) drb <- df1[22] / (df1[21] + df1[22]) trb <- df1[24] / (df1[24] + df1[25]) tov <- df1[32] / (df1[6] + 0.44 * df1[18] + df1[32]) adv_stats <- cbind(adv_stats,round(team,3),round(pace,3),round(offrtg,2),round(defrtg,2),round(netrtg,2),round(par,3), round(ftr,3),round(ts,3),round(efg,3),round(ast,3),round(orb,3),round(drb,3),round(trb,3),round(tov,3)) names(adv_stats) = c("PF","C","MP","TEAM%","PACE","ORtg","DRtg","Net Rtg","3Par","FTr","TS%","eFG%","AST%","ORB%","DRB%","TRB%","TOV%") }else if(ncol(df1)==37){ adv_stats <-df1[1:2] tm_poss <- df1[5] - (df1[19]/(df1[19] + df1[22])) * (df1[5] - df1[3]) * 1.07 + df1[31] + 0.4 * df1[17] opp_poss <- df1[6] - (df1[20]/(df1[20] + df1[21])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18] team <- df1[2]/cumsum(df1[2]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[2])) offrtg <- 100*((df1[35])/(tm_poss)) defrtg <- 100*((df1[36])/(opp_poss)) netrtg <- offrtg - defrtg par <- df1[9]/df1[5] ftr <- df1[17]/df1[5] ts <- df1[35] / (2 * (df1[5] + 0.44 * df1[17])) efg <- (df1[3] + 0.5 * df1[7]) / df1[5] ast <- df1[25] / df1[3] orb <- (df1[19]/(df1[19] + df1[22])) drb <- df1[21] / (df1[20] + df1[21]) trb <- df1[23] / (df1[23] + df1[24]) tov <- df1[31] / (df1[5] + 0.44 * df1[17] + df1[31]) adv_stats <- cbind(adv_stats,round(team,3),round(pace,3),round(offrtg,2),round(defrtg,2),round(netrtg,2),round(par,3), round(ftr,3),round(ts,3),round(efg,3),round(ast,3),round(orb,3),round(drb,3),round(trb,3),round(tov,3)) names(adv_stats) = c("Name","MP","TEAM%","Pace","ORtg","DRtg","Net Rtg","3Par","FTr","TS%","eFG%","AST%","ORB%","DRB%","TRB%","TOV%") } adv_stats[is.na(adv_stats)] <- 0 return(adv_stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_advance_stats.R
#' @title Statistics searcher of backcourt players #' @description The function allows find the statisticts of backcourt players #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the lineups_data_adjustment() function. #' @details The function works with the basic statistics of the lineups and the extended statistics of the lineups. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the statistics of the backcourt players #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' lineups_backcourt(df1) #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' lineups_backcourt(df1) #' #' @export #' #' @importFrom stats aggregate #' lineups_backcourt <- function(df1){ if(ncol(df1)==29){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PFF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PFF,df1$P,df1$M,df1$PM), by=list(PG=df1$PG,SG=df1$SG,SF=df1$SF), FUN=sum) PFG<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[11]/df1[12],3)), size = 1, replace = TRUE) MM <- sample(c(round(df1[21]-df1[22],3)), size = 1, replace = TRUE) df1 = cbind(df1, PFG,P3P,P2P,PFT,MM) df1 = subset (df1, select=c(1,2,3,4,5,6,24,7,8,25,9,10,26,11,12,27,13,14,15,16,17,18,19,20,21,22,28)) df1[7][is.na(df1[7])] <- 0 df1[10][is.na(df1[10])] <- 0 df1[13][is.na(df1[13])] <- 0 df1[16][is.na(df1[16])] <- 0 names(df1) = c("PG","SG","SF","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if(ncol(df1)==41){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PFF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PFF,df1$oPF,df1$P,df1$M,df1$PM), by=list(PG=df1$PG,SG=df1$SG,SF=df1$SF), FUN=sum) names(df1) = c("PG","SG","SF","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") } return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_backcourt.R
#' @title Lineups statistics comparator #' @description The function allows the comparison of a lineup when it is in the court with the statistics of the rival #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the lineups_data_adjustment() function. #' @param m should be a number. This parameter has to be the duration of a single game. #' @details The function only works with the extended statistics of the lineups. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the comparison of statistics and the following values: #' \itemize{ #' \item Lineup usage percentage (Team\%) #' \item Pace (Pace) #' \item Three rating (3Par) #' \item True shooting percentage (TS\%) #' \item Efficiency Field Goals percentage (eFG\%) #' } #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' m <- 48 #' #' lineups_comparator_stats(df1,m) #' #' @export #' lineups_comparator_stats <- function(df1,m){ if(ncol(df1)==41){ adv_stats <-df1[1:6] tm_poss <- df1[9] - (df1[23]/(df1[23] + df1[26])) * (df1[9] - df1[7]) * 1.07 + df1[35] + 0.4 * df1[21] opp_poss <- df1[10] - (df1[24]/(df1[24] + df1[25])) * (df1[10] - df1[8]) * 1.07 + df1[36] + 0.4 * df1[22] team <- df1[6]/cumsum(df1[6]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[6])) fg <- df1[7] - df1[8] fga <-df1[9] - df1[10] fg1 <- (df1[7]/df1[9]) fg2 <- (df1[8]/df1[10]) fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0 fgp <- fg1 - fg2 fgp[is.na(fgp)] <- 0 tp <- df1[11] - df1[12] tpa <-df1[13] - df1[14] t1 <- (df1[11]/df1[13]) t2 <- (df1[12]/df1[14]) t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0 tgp <- t1 - t2 twp <- df1[15] - df1[16] twpa <-df1[17] - df1[18] tw1 <- (df1[15]/df1[17]) tw2 <- (df1[16]/df1[18]) tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0 twgp <- tw1 - tw2 efg <- (df1[7] + 0.5 * df1[11]) / df1[9] efg_opp <- (df1[8] + 0.5 * df1[12]) / df1[10] efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0 efgp<- efg - efg_opp ts <- df1[39] / (2 * (df1[9] + 0.44 * df1[21])) ts_opp <- df1[40] / (2 * (df1[10] + 0.44 * df1[22])) ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0 tsp <- ts - ts_opp ft <- df1[19] - df1[20] fta <-df1[21] - df1[22] f1 <-(df1[19]/df1[21]) f2 <- (df1[20]/df1[22]) f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0 ftp <- f1 - f2 pm <- df1[41] adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm) names(adv_stats) = c("PG","SG","SF","PF","C","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%", "2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-") }else if (ncol(df1)==39){ adv_stats <-df1[1:4] tm_poss <- df1[7] - (df1[21]/(df1[21] + df1[24])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19] opp_poss <- df1[8] - (df1[22]/(df1[22] + df1[23])) * (df1[8] - df1[6]) * 1.07 + df1[34] + 0.4 * df1[20] team <- df1[4]/cumsum(df1[4]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[4])) fg <- df1[5] - df1[6] fga <-df1[7] - df1[8] fg1 <- (df1[5]/df1[7]) fg2 <- (df1[6]/df1[8]) fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0 fgp <- fg1 - fg2 fgp[is.na(fgp)] <- 0 tp <- df1[9] - df1[10] tpa <-df1[11] - df1[12] t1 <- (df1[9]/df1[11]) t2 <- (df1[10]/df1[12]) t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0 tgp <- t1 - t2 twp <- df1[13] - df1[14] twpa <-df1[15] - df1[16] tw1 <- (df1[13]/df1[15]) tw2 <- (df1[14]/df1[16]) tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0 twgp <- tw1 - tw2 efg <- (df1[5] + 0.5 * df1[9]) / df1[7] efg_opp <- (df1[6] + 0.5 * df1[10]) / df1[8] efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0 efgp<- efg - efg_opp ts <- df1[37] / (2 * (df1[7] + 0.44 * df1[19])) ts_opp <- df1[38] / (2 * (df1[8] + 0.44 * df1[20])) ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0 tsp <- ts - ts_opp ft <- df1[17] - df1[18] fta <-df1[19] - df1[20] f1 <-(df1[17]/df1[19]) f2 <- (df1[18]/df1[20]) f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0 ftp <- f1 - f2 pm <- df1[39] adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm) names(adv_stats) = c("PG","SG","SF","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%", "2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-") }else if (ncol(df1)==38){ adv_stats <-df1[1:3] tm_poss <- df1[6] - (df1[20]/(df1[20] + df1[23])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18] opp_poss <- df1[7] - (df1[21]/(df1[21] + df1[22])) * (df1[7] - df1[5]) * 1.07 + df1[33] + 0.4 * df1[19] team <- df1[3]/cumsum(df1[3]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[3])) fg <- df1[4] - df1[5] fga <-df1[6] - df1[7] fg1 <- (df1[4]/df1[6]) fg2 <- (df1[5]/df1[7]) fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0 fgp <- fg1 - fg2 fgp[is.na(fgp)] <- 0 tp <- df1[8] - df1[9] tpa <-df1[10] - df1[11] t1 <- (df1[8]/df1[10]) t2 <- (df1[9]/df1[11]) t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0 tgp <- t1 - t2 twp <- df1[12] - df1[13] twpa <-df1[14] - df1[15] tw1 <- (df1[12]/df1[14]) tw2 <- (df1[13]/df1[15]) tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0 twgp <- tw1 - tw2 efg <- (df1[4] + 0.5 * df1[8]) / df1[6] efg_opp <- (df1[5] + 0.5 * df1[9]) / df1[7] efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0 efgp<- efg - efg_opp ts <- df1[36] / (2 * (df1[6] + 0.44 * df1[18])) ts_opp <- df1[37] / (2 * (df1[7] + 0.44 * df1[19])) ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0 tsp <- ts - ts_opp ft <- df1[16] - df1[17] fta <-df1[18] - df1[19] f1 <-(df1[16]/df1[18]) f2 <- (df1[17]/df1[19]) f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0 ftp <- f1 - f2 pm <- df1[38] adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm) names(adv_stats) = c("PF","C","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%", "2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-") }else if (ncol(df1)==37){ adv_stats <-df1[1:2] tm_poss <- df1[5] - (df1[19]/(df1[19] + df1[22])) * (df1[5] - df1[3]) * 1.07 + df1[31] + 0.4 * df1[17] opp_poss <- df1[6] - (df1[20]/(df1[20] + df1[21])) * (df1[6] - df1[4]) * 1.07 + df1[32] + 0.4 * df1[18] team <- df1[2]/cumsum(df1[2]) pace <- m * ((tm_poss + opp_poss) / (2 * df1[2])) fg <- df1[3] - df1[4] fga <-df1[5] - df1[6] fg1 <- (df1[3]/df1[5]) fg2 <- (df1[4]/df1[6]) fg1[is.na(fg1)] <- 0; fg2[is.na(fg2)] <- 0 fgp <- fg1 - fg2 fgp[is.na(fgp)] <- 0 tp <- df1[7] - df1[8] tpa <-df1[9] - df1[10] t1 <- (df1[7]/df1[9]) t2 <- (df1[8]/df1[10]) t1[is.na(t1)] <- 0; t2[is.na(t2)] <- 0 tgp <- t1 - t2 twp <- df1[11] - df1[12] twpa <-df1[13] - df1[14] tw1 <- (df1[11]/df1[13]) tw2 <- (df1[12]/df1[14]) tw1[is.na(tw1)] <- 0; tw2[is.na(tw2)] <- 0 twgp <- tw1 - tw2 efg <- (df1[3] + 0.5 * df1[7]) / df1[5] efg_opp <- (df1[4] + 0.5 * df1[8]) / df1[6] efg[is.na(efg)] <- 0; efg_opp[is.na(efg_opp)] <- 0 efgp<- efg - efg_opp ts <- df1[35] / (2 * (df1[5] + 0.44 * df1[17])) ts_opp <- df1[36] / (2 * (df1[6] + 0.44 * df1[18])) ts[is.na(ts)] <- 0; ts_opp[is.na(ts_opp)] <- 0 tsp <- ts - ts_opp ft <- df1[15] - df1[16] fta <-df1[17] - df1[18] f1 <-(df1[15]/df1[17]) f2 <- (df1[16]/df1[18]) f1[is.na(f1)] <- 0; f2[is.na(f2)] <- 0 ftp <- f1 - f2 pm <- df1[37] adv_stats <- cbind(adv_stats,round(team,3),round(pace,2),fg,fga,round(fgp,3),tp,tpa,round(tgp,3),twp,twpa,round(twgp,3),round(efgp,3),round(tsp,3),ft,fta,round(ftp,3),pm) names(adv_stats) = c("Name","MP","Team%","Pace","FG","FGA","FG%","3P","3PA","3P%", "2P","2PA","2P%","eFG%","TS%","FT","FTA","FT%","+/-") } adv_stats[is.na(adv_stats)] <- 0 return(adv_stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_comparator_stats.R
#' @title Lineups data adjustment #' @description The function transform the statistics entered for later use in the rest of the functions that apply to lineup statistics. #' @param df1 Should be a Data Frame #' @details \itemize{ #' \item The data.frame must have the same columns and these represent the same as in the example. #' \item The function allows the transformation of the basic statistics of the lineups to which the shooting percentages, the total rebounds and the plus minus. #' \item The function allows the transformation of the extended statistics of the lineups to which the total rebounds and the plus minus. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return The data frame obtained for the basic statistics of lineups will have the following format: #' \itemize{ #' \item Point Guard (PG) #' \item Shooting Guard (SG) #' \item Small Forward (SF) #' \item Paint Forward (PF) #' \item Center (C) #' \item Games played (G) #' \item Games Started (GS) #' \item Minutes Played (MP) #' \item Field Goals Made (FG) #' \item Field Goals Attempted (FGA) #' \item Field Goals Percentage (FG%) #' \item Three Points Made (3P) #' \item Three Points Attempted (3PA) #' \item Three Points Percentage (3P\%) #' \item Two Points Made (2P) #' \item Two Points Attempted (2PA) #' \item Free Throw Made (FT) #' \item Offensive Rebounds (ORB) #' \item Defensive Rebounds (DRB) #' \item Total Rebounds (TRB) #' \item Assists (AST) #' \item Steals (STL) #' \item Blocks (BLK) #' \item Turnover (TOV) #' \item Personal Fouls (PF) #' \item Points (PTS) #' \item Plus (+) #' \item Minus (-) #' \item Plus Minus (+/-) #' } #' For the extended statistics of the lineups it will have the same format as the basic statistics of the lineups but adding the statistics of the opponent against that lineups. #' #' #' @examples #' #' df1 <- data.frame("PG"= c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA" = c(7,0), "X3P" = c(0,0),"X3PA" = c(2,0),"X2P" = c(4,0), #' "X2PA" = c(5,0), "FT" = c(1,0), "FTA" = c(3,0),"ORB" = c(2,0), #' "DRB" = c(5,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0), #' "TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3)) #' #' lineups_data_adjustment(df1) #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG"= c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P " = c(1,0),"X3PA " = c(4,0), #' "Opp3PA ç" = c(3,0),"X2P" = c(4,0),"Opp2P" = c(5,0),"X2PA " = c(6,0), #' "Opp2PA" = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0), #' "OppFTA" = c(1,0),"OppRB" = c(2,0),"OppOppRB" = c(1,0),"DRB" = c(4,0), #' "OppDRB" = c(1,0),"AST " = c(5,0),"OppAST " = c(4,0),"STL" = c(1,0), #' "OppSTL" = c(3,0),"BLK" = c(0,0),"OppBLK" = c(1,0),"TOppV" = c(5,2), #' "OppTOppV" = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0),"PLUS" = c(15,0), #' "MINUS" = c(14,3)) #' #' #' lineups_data_adjustment(df1) #' #' @export #' #' #' @importFrom stats aggregate #' lineups_data_adjustment <- function(df1){ if(ncol(df1)==23){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","TP","TPA","TWP","TWPA","FT","FTA", "ORB","DRB","AST","STL","BLK","TOV","PPF","P","M") data_adjustment <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M), by=list(PG=df1$PG,SG=df1$SG,SF=df1$SF,PF=df1$PF,C=df1$C), FUN=sum) PFG <- sample(c(round(data_adjustment[7]/data_adjustment[8],3)), size = 1, replace = TRUE) P3P <- sample(c(round(data_adjustment[9]/data_adjustment[10],3)), size = 1, replace = TRUE) P2P <- sample(c(round(data_adjustment[11]/data_adjustment[12],3)), size = 1, replace = TRUE) PFT <- sample(c(round(data_adjustment[13]/data_adjustment[14],3)), size = 1, replace = TRUE) TOTR <- sample(c(round(data_adjustment[15]+data_adjustment[16],3)), size = 1, replace = TRUE) PM <- sample(c(round(data_adjustment[22]-data_adjustment[23],3)), size = 1, replace = TRUE) data_adjustment <- cbind(data_adjustment, PFG,P3P,P2P,PFT,TOTR,PM) data_adjustment <- subset (data_adjustment, select=c(1,2,3,4,5,6,7,8,24,9,10,25,11,12,26,13,14,27,15,16,28,17,18,19,20,21,22,23,29)) data_adjustment[is.na(data_adjustment)] <- 0 names(data_adjustment) = c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if(ncol(df1)==38){ names(df1) <- c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M") data_adjustment <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M), by=list(PG=df1$PG,SG=df1$SG,SF=df1$SF,PF=df1$PF,C=df1$C), FUN=sum) TOTR <- sample(c(round(data_adjustment[23]+data_adjustment[25],3)), size = 1, replace = TRUE) oTOTR <- sample(c(round(data_adjustment[24]+data_adjustment[26],3)), size = 1, replace = TRUE) PM <- sample(c(round(data_adjustment[37]-data_adjustment[38],3)), size = 1, replace = TRUE) data_adjustment <- cbind(data_adjustment,TOTR,oTOTR,PM) data_adjustment <- subset (data_adjustment, select=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,39,40,27,28,29,30,31,32,33,34,35,36,37,38,41)) names(data_adjustment) <- c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") } data_adjustment[is.na(data_adjustment)] <- 0 return(data_adjustment) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_data_adjustment.R
#' @title Lineups games adder #' @description The function allows to perform the sums of two data.frames with the same format adopted after being transformed by lineups_data_adjustment() function, #' @param df1 Should be a Data Frame that represents the first set of basic or extener lineups statistics. It has to be in the format provided by the lineups_data_adjustment() function. #' @param df2 Should be a Data Frame that represents the second set of basic or extener lineups statistics. It has to be in the format provided by the lineups_data_adjustment() function. #' @details \itemize{ #' \item The function will work correctly when the name of the players is the same, in case it is different it will take the lineups as different. #' \item The function sums data sets that have an identical size, #' } #' @return Data frame with the sum of the statistics of the other two entered data.frame. #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' df2 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' lineups_games_adder(df1,df2) #' #' @export #' #' #' @importFrom stats aggregate #' lineups_games_adder <- function(df1,df2){ if(ncol(df1) == 29 & ncol(df2) == 29){ adder <- rbind(df1,df2) names(adder) <- c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") adder <- aggregate(cbind(adder$MP,adder$FG,adder$FGA,adder$TP,adder$TPA,adder$TWP,adder$TWPA,adder$FT,adder$FTA,adder$ORB, adder$DRB,adder$TRB,adder$AST,adder$STL,adder$BLK,adder$TOV,adder$PPF,adder$P,adder$M,adder$PM), by=list(PG=adder$PG,SG=adder$SG,SF=adder$SF,PF=adder$PF,C=adder$C), FUN=sum) PFG <- sample(c(round(adder[7]/adder[8],3)), size = 1, replace = TRUE) P3P <- sample(c(round(adder[9]/adder[10],3)), size = 1, replace = TRUE) P2P <- sample(c(round(adder[11]/adder[12],3)), size = 1, replace = TRUE) PFT <- sample(c(round(adder[13]/adder[14],3)), size = 1, replace = TRUE) adder <- cbind(adder, PFG,P3P,P2P,PFT) adder <- subset (adder, select=c(1,2,3,4,5,6,7,8,26,9,10,27,11,12,28,13,14,29,15,16,17,18,19,20,21,22,23,24,25)) adder[is.na(adder)] <- 0 names(adder) <- c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if (ncol(df1) == 41 & ncol(df2) == 41){ adder <- rbind(df1,df2) names(adder) <- c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM") adder <- aggregate(cbind(adder$MP,adder$FG,adder$oFG,adder$FGA,adder$oFGA,adder$TP,adder$oTP,adder$TPA,adder$oTPA,adder$TWP,adder$oTWP,adder$TWPA,adder$oTWPA,adder$FT,adder$oFT,adder$FTA,adder$oFTA,adder$ORB,adder$oORB, adder$DRB,adder$oDRB,adder$TRB,adder$oTRB,adder$AST,adder$oAST,adder$STL,adder$oSTL,adder$BLK,adder$oBLK,adder$TOV,adder$oTOV,adder$PPF,adder$oPF,adder$P,adder$M,adder$PM), by=list(PG=adder$PG,SG=adder$SG,SF=adder$SF,PF=adder$PF,C=adder$C), FUN=sum) names(adder) <- c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") } adder[is.na(adder)] <- 0 return(adder) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_games_adder.R
#' @title Statistics searcher of paint players #' @description The function allows find the statisticts of paint players #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the lineups_data_adjustment() function. #' @details The function works with the basic statistics of the lineups and the extended statistics of the lineups. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the statistics of the paint players #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' lineups_paint(df1) #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' lineups_paint(df1) #' #' @export #' #' @importFrom stats aggregate #' lineups_paint <- function(df1){ if(ncol(df1)==29){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","TP","TPA","3P%","TWP","TWPA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PFF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA, df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PFF,df1$P,df1$M,df1$PM), by=list(PF=df1$PF,C=df1$C), FUN=sum) PFG<-sample(c(round(df1[4]/df1[5],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[6]/df1[7],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[8]/df1[9],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[10]/df1[11],3)), size = 1, replace = TRUE) MM <- sample(c(round(df1[20]-df1[21],3)), size = 1, replace = TRUE) df1 = cbind(df1, PFG,P3P,P2P,PFT,MM) df1 = subset (df1, select=c(1,2,3,4,5,23,6,7,24,8,9,25,10,11,26,12,13,14,15,16,17,18,19,20,21,27)) df1[6][is.na(df1[6])] <- 0 df1[9][is.na(df1[9])] <- 0 df1[12][is.na(df1[12])] <- 0 df1[15][is.na(df1[15])] <- 0 names(df1) = c("PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if(ncol(df1)==41){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PFF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PFF,df1$oPF,df1$P,df1$M,df1$PM), by=list(PF=df1$PF,C=df1$C), FUN=sum) names(df1) = c("PF","C","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") } return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_paint.R
#' @title Statistics by position #' @description The function allows you to search for statistics by position within the lineup. #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the lineups_data_adjustment() function. #' @param n Should be a number. It represents the position on which you want to perform the search. #' @details #' The function allows you to search for paint players both in basic statistics and in extended statistics. #' The supported values for n are as follows: #' \itemize{ #' \item If the value entered for n is 1, it will return the statistics of the grouped Point Guards. #' \item If the value entered for n is 2, it will return the statistics of the grouped Small Guards. #' \item If the value entered for n is 3, it will return the statistics of the grouped Small Forwards. #' \item If the value entered for n is 4, it will return the statistics of the grouped Paint Forwards. #' \item If the value entered for n is 5, it will return the statistics of the grouped Centers. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the statistics by position. #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' n <- 1 #' #' lineups_players(df1,n) #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' n <- 5 #' #' lineups_players(df1,n) #' #' @export #' #' @importFrom stats aggregate #' lineups_players <- function(df1,n){ if(ncol(df1)==29){ if(n==1){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM), by=list(PG=df1$PG), FUN=sum) PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) df1 = cbind(df1,PFG,P3P,P2P,PFT) df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) df1[5][is.na(df1[5])] <- 0 df1[8][is.na(df1[8])] <- 0 df1[11][is.na(df1[11])] <- 0 df1[14][is.na(df1[14])] <- 0 names(df1) = c("PG","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(n==2){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM), by=list(SG=df1$SG), FUN=sum) PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) df1 = cbind(df1,PFG,P3P,P2P,PFT) df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) df1[5][is.na(df1[5])] <- 0 df1[8][is.na(df1[8])] <- 0 df1[11][is.na(df1[11])] <- 0 df1[14][is.na(df1[14])] <- 0 names(df1) = c("SG","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(n==3){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM), by=list(SF=df1$SF), FUN=sum) PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) df1 = cbind(df1,PFG,P3P,P2P,PFT) df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) df1[5][is.na(df1[5])] <- 0 df1[8][is.na(df1[8])] <- 0 df1[11][is.na(df1[11])] <- 0 df1[14][is.na(df1[14])] <- 0 names(df1) = c("SF","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(n==4){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM), by=list(PF=df1$PF), FUN=sum) PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) df1 = cbind(df1,PFG,P3P,P2P,PFT) df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) df1[5][is.na(df1[5])] <- 0 df1[8][is.na(df1[8])] <- 0 df1[11][is.na(df1[11])] <- 0 df1[14][is.na(df1[14])] <- 0 names(df1) = c("PF","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(n==5){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM), by=list(C=df1$C), FUN=sum) PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE) df1 = cbind(df1,PFG,P3P,P2P,PFT) df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) df1[5][is.na(df1[5])] <- 0 df1[8][is.na(df1[8])] <- 0 df1[11][is.na(df1[11])] <- 0 df1[14][is.na(df1[14])] <- 0 names(df1) = c("C","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } } else if(ncol(df1)==41){ if(n==1){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM), by=list(PG=df1$PG), FUN=sum) names(df1) = c("PG","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") }else if(n==2){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM), by=list(SG=df1$SG), FUN=sum) names(df1) = c("SG","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") }else if(n==3){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM), by=list(SF=df1$SF), FUN=sum) names(df1) = c("SF","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") }else if(n==4){ names(df1) = c("PG","SG","SF","PPF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM), by=list(PF=df1$PF), FUN=sum) names(df1) = c("PF","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") }else if(n==5){ names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM") df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB, df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM), by=list(C=df1$C), FUN=sum) names(df1) = c("C","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA", "ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-") } } return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_players.R
#' @title Statistics searcher #' @description The function allows the statistical search of the lineups where the entered players appear. #' @param df1 Should be a Data Frame. This parameter has to be in the format provided by the lineups_advance_stats() function. #' @param n Should be a numer. It represents the number of player to be found. #' @param p1 Should be a String. Represents the name of the first player to be found. #' @param p2 Should be a String. Represents the name of the second player to be found. #' @param p3 Should be a String. Represents the name of a player to be found. #' @param p4 Should be a String. Represents the name of a player to be found. #' @details \itemize{ #' \item The function allows you to search for paint players both in basic statistics and in extended statistics. #' \item The values allowed by n are 1, 2, 3 and 4.The number entered in N must be equal to the number of players searched. #' \item The name entered in the function must be the same as the one inside the data frame. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the statistics of the lineups where the entered players appear #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' n <- 2 #' #' p1 <- "James" #' #' p2 <- "Davis" #' #' p3 <- "" #' #' p4 <- "" #' #' #' lineups_searcher(df1,n,p1,p2,p3,p4) #' #' @export #' lineups_searcher <- function(df1,n,p1,p2,p3,p4){ if(n==1){ aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,] df<-rbind(aux2,aux3,aux4,aux5,aux6) }else if(n==2){ aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,] aux1<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,];aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,] df<-rbind(aux2,aux3,aux4,aux5,aux6) }else if (n==3){ aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,]; aux1<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,]; aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,] aux<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux[aux$PG==p3,]; aux3 <- aux[aux$SG==p3,]; aux4 <- aux[aux$SF==p3,]; aux5 <- aux[aux$PF==p3,]; aux6 <- aux[aux$C==p3,] df<-rbind(aux2,aux3,aux4,aux5,aux6) }else if(n==4){ aux2 <- df1[df1$PG==p1,]; aux3 <- df1[df1$SG==p1,]; aux4 <- df1[df1$SF==p1,]; aux5 <- df1[df1$PF==p1,]; aux6 <- df1[df1$C== p1,] aux1<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux1[aux1$PG==p2,]; aux3 <- aux1[aux1$SG==p2,]; aux4 <- aux1[aux1$SF==p2,]; aux5 <- aux1[aux1$PF==p2,]; aux6 <- aux1[aux1$C==p2,] aux<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux[aux$PG==p3,]; aux3 <- aux[aux$SG==p3,]; aux4 <- aux[aux$SF==p3,]; aux5 <- aux[aux$PF==p3,]; aux6 <- aux[aux$C==p3,] aux<-rbind(aux2,aux3,aux4,aux5,aux6) aux2 <- aux[aux$PG==p4,]; aux3 <- aux[aux$SG==p4,]; aux4 <- aux[aux$SF==p4,]; aux5 <- aux[aux$PF==p4,]; aux6 <- aux[aux$C==p4,] df<-rbind(aux2,aux3,aux4,aux5,aux6) } return(df) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_searcher.R
#' @title Statistics separator #' @description The function allows to separate the extended statistics of the lineups. Therefore, you can obtain the statistics of the lineups or the rival with respect to the lineups for later analysis #' @param df1 Should be a Data Frame. The parameter has to be in the format provided by the lineups_data_adjustment() function. #' @param n Should be a number. it Represents the statistics we want to obtain. #' @details The function only works with the extended statistics of the lineups. #' The supported values for n are as follows: #' \itemize{ #' \item If n takes the value of 1, the function will return the statistics of the lineup. #' \item If n takes the value of 2, the function will return the statistics of the rival with respect to the lineup. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henare #' @return Data frame with the statistics separated in the format of the basic statistics of the lineups. #' @examples #' #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), #' "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), #' "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), #' "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , #' "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), #' "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), #' "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), #' "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), #' "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), #' "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) #' #' n <- 1 #' #' lineups_separator(df1,n) #' #' n <- 2 #' #' lineups_separator(df1,n) #' #' #' @export lineups_separator <- function(df1,n){ if(ncol(df1)==41){ separator <- df1[1:6] for(i in 7:38){ if(n==1 & (i%%2!=0)){ separator<- cbind(separator,df1[i]) } else if (n==2 & (i%%2==0)){ separator<- cbind(separator,df1[i]) } } separator<- cbind(separator,df1[39:41]) PFG<-sample(c(round(separator[7]/separator[8],3)), size = 1, replace = TRUE) P3P<-sample(c(round(separator[9]/separator[10],3)), size = 1, replace = TRUE) P2P<-sample(c(round(separator[11]/separator[12],3)), size = 1, replace = TRUE) PFT<-sample(c(round(separator[13]/separator[14],3)), size = 1, replace = TRUE) separator <- cbind(separator, PFG,P3P,P2P,PFT) separator <- subset (separator, select=c(1,2,3,4,5,6,7,8,26,9,10,27,11,12,28,13,14,29,15,16,17,18,19,20,21,22,23,24,25)) separator[9][is.na(separator[9])] <- 0 separator[12][is.na(separator[12])] <- 0 separator[15][is.na(separator[15])] <- 0 separator[18][is.na(separator[18])] <- 0 names(separator) = c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if(ncol(df1)==39){ separator <- df1[1:4] for(i in 5:36){ if(n==1 & (i%%2!=0)){ separator<- cbind(separator,df1[i]) } else if (n==2 & (i%%2==0)){ separator<- cbind(separator,df1[i]) } } separator<- cbind(separator,df1[37:39]) PFG<-sample(c(round(separator[5]/separator[6],3)), size = 1, replace = TRUE) P3P<-sample(c(round(separator[7]/separator[8],3)), size = 1, replace = TRUE) P2P<-sample(c(round(separator[9]/separator[10],3)), size = 1, replace = TRUE) PFT<-sample(c(round(separator[11]/separator[12],3)), size = 1, replace = TRUE) separator <- cbind(separator, PFG,P3P,P2P,PFT) separator <- subset (separator, select=c(1,2,3,4,5,6,24,7,8,25,9,10,26,11,12,27,13,14,15,16,17,18,19,20,21,22,23)) separator[7][is.na(separator[7])] <- 0 separator[10][is.na(separator[10])] <- 0 separator[13][is.na(separator[13])] <- 0 separator[16][is.na(separator[16])] <- 0 names(separator) = c("PG","SG","SF","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if(ncol(df1)==38){ separator <- df1[1:3] for(i in 4:35){ if(n==1 & (i%%2==0)){ separator<- cbind(separator,df1[i]) } else if (n==2 & (i%%2!=0)){ separator<- cbind(separator,df1[i]) } } separator<- cbind(separator,df1[36:38]) PFG<-sample(c(round(separator[4]/separator[5],3)), size = 1, replace = TRUE) P3P<-sample(c(round(separator[6]/separator[7],3)), size = 1, replace = TRUE) P2P<-sample(c(round(separator[8]/separator[9],3)), size = 1, replace = TRUE) PFT<-sample(c(round(separator[10]/separator[11],3)), size = 1, replace = TRUE) separator <- cbind(separator, PFG,P3P,P2P,PFT) separator <- subset (separator, select=c(1,2,3,4,5,23,6,7,24,8,9,25,10,11,26,12,13,14,15,16,17,18,19,20,21,22)) separator[6][is.na(separator[6])] <- 0 separator[9][is.na(separator[9])] <- 0 separator[12][is.na(separator[12])] <- 0 separator[15][is.na(separator[15])] <- 0 names(separator) = c("PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(ncol(df1)==37){ separator <- df1[1:2] for(i in 3:34){ if(n==1 & (i%%2!=0)){ separator<- cbind(separator,df1[i]) } else if (n==2 & (i%%2==0)){ separator<- cbind(separator,df1[i]) } } separator<- cbind(separator,df1[35:37]) PFG<-sample(c(round(separator[3]/separator[4],3)), size = 1, replace = TRUE) P3P<-sample(c(round(separator[5]/separator[6],3)), size = 1, replace = TRUE) P2P<-sample(c(round(separator[7]/separator[8],3)), size = 1, replace = TRUE) PFT<-sample(c(round(separator[9]/separator[10],3)), size = 1, replace = TRUE) separator <- cbind(separator, PFG,P3P,P2P,PFT) separator <- subset (separator, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21)) separator[5][is.na(separator[5])] <- 0 separator[8][is.na(separator[8])] <- 0 separator[11][is.na(separator[11])] <- 0 separator[14][is.na(separator[14])] <- 0 names(separator) = c("Name","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } return(separator) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_separator.R
#' @title Lineups stats per possesion #' @description The function do the calculation of statistics per p possesion for the differents lineups #' @param df1 Should be a Data Frame. This parameter has to be in the format provided by the lineups_advance_stats() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param p Should be a number. This parameter has to be the number of possessions to which you want to project the statistics. #' @param m should be a number. This parameter has to be the duration of a single game. #' @details \itemize{ #' \item The function only works with the basic statistics of the lineups. #' \item The statistical projection is made from the estimation of the possessions that the team plays when the lineups is on the court. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame whit statistics per p possesion #' @examples #' #' df1 <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), #' "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), #' "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), #' "FGA " = c(7,0),"Percentage FG" = c(0.571,0), #' "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), #' "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), #' "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), #' "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), #' "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), #' "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48),"3P" = c(782),"3PA" = c(2242), #' "Percentage 3P" = c(0.349),"2P" = c(2224), "2PA" = c(4027), #' "Percentage 2P" = c(0.552),"FT" = c(1260),"FTA FG" = c(1728), #' "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490), #' "TRB" = c(3247), "AST" = c(1803), "STL" = c(612),"BLK" = c(468), #' "TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' #' p <- 100 #' #' m <- 48 #' #' lineups_stats_per_possesion(df1,df2,df3,p,m) #' #' @export #' lineups_stats_per_possesion <- function(df1,df2,df3,p,m){ minutes <- (df2[1,2]/df2[1,1])/5 minutes <- trunc(minutes) tm_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] opp_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] pace <- m * ((tm_poss + opp_poss) / (2 * (df2[1,2] / 5))) if(ncol(df1)==29){ lyneup_poss <- (pace/m) * df1[6] for(i in 7:ncol(df1)){ if(i==9||i==12||i==15||i==18){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(ncol(df1)==27){ lyneup_poss <- (pace/m) * df1[4] for(i in 7:ncol(df1)){ if(i==7||i==10||i==13||i==16){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PG","SG","SF","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(ncol(df1)==26){ lyneup_poss <- (pace/m) * df1[3] for(i in 7:ncol(df1)){ if(i==6||i==9||i==12||i==15){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if (ncol(df1)==25){ lyneup_poss <- (pace/m) * df1[2] for(i in 7:ncol(df1)){ if(i==5||i==8||i==11||i==14){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } } df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/lineups_stats_per_possesion.R
#' @title Play advanced statistics #' @description This function allows the calculation of advanced play statistics. #' @param df1 Should be a Data Frame that represents the play's statistics. The parameter has to be in the format provided by the play_data_adjustment() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the following advanced statistics calculated: #' \itemize{ #' \item Points Per Possession (PPP) #' \item Possessions (POSS) #' \item Frequency (Freq) #' \item Efficiency Field Goals percentage (eFG\%) #' \item Free Throw Percentage (FT\%) #' \item Assists percentage (AST\%) #' \item Turnover percentage (TOV\%) #' \item And One percentage (AndOne\%) #' \item Score percentage (Score\%) #' } #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' play_advance_stats(df1) #' #' #' @export #' play_advance_stats <- function(df1){ if(ncol(df1)==18){ df1 <- df1[-nrow(df1),] adv_stats <-df1[1:2] poss <- round(df1[5] + df1[18] + 0.4 * df1[14],0) freq <- round(poss / cumsum(poss),3) ppp <- round(df1[3] / poss,2) efg <- round((df1[4] + 0.5 * df1[7]) / df1[5],3) ft_freq <- round(df1[14] / poss,3) ast_freq <- round(df1[17] / poss,3) tov_freq <- round(df1[18] / poss,3) andone_freq <- round(df1[16] / poss,3) score_freq <- round((df1[4] + 0.4 * df1[13]) / poss,3) adv_stats <- cbind(adv_stats,poss,freq,ppp,df1[3:12],efg,ft_freq,ast_freq,tov_freq,andone_freq,score_freq) names(adv_stats) = c("Name","G","Poss","Freq","PPP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","eFG%", "FT%","AST%","TOV%","And One%","Score%") adv_stats[is.na(adv_stats)] <- 0 } else if (ncol(df1)==17){ adv_stats <-df1[2] poss <- round(df1[4] + df1[17] + 0.4 * df1[13],0) freq <- round(poss / cumsum(poss),3) ppp <- round(df1[2] / poss,2) efg <- round((df1[3] + 0.5 * df1[6]) / df1[4],3) ft_freq <- round(df1[13] / poss,3) ast_freq <- round(df1[16] / poss,3) tov_freq <- round(df1[17] / poss,3) andone_freq <- round(df1[15] / poss,3) score_freq <- round((df1[3] + 0.4 * df1[12]) / poss,3) adv_stats <- cbind(adv_stats,poss,freq,ppp,df1[2:11],efg,ft_freq,ast_freq,tov_freq,andone_freq,score_freq) names(adv_stats) = c("G","Poss","Freq","PPP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","eFG%", "FT%","AST%","TOV%","And One%","Score%") } return(adv_stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_advance_stats.R
#' @title Play data adjustment #' @description The function transform the statistics entered for later use in the rest of the functions that apply to play statistics. #' @param df1 Should be a Data Frame that represents the play's statistics. The parameter has to be in the format provided by the play_data_adjustment() function. #' @details \itemize{ #' \item The data.frame must have the same columns and these represent the same as in the example. #' \item The input data.frame must have the last row that represents the team's statistics. #' \item The function allows the transformation of the play statistics to which the shooting percentages. #' } #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return The data frame obtained for the play statistics will have the following format: #' \itemize{ #' \item Name of the player (Name) #' \item Games Started (GS) #' \item Points (PTS) #' \item Field Goals Made (FG) #' \item Field Goals Attempted (FGA) #' \item Field Goals Percentage (FG\%) #' \item Three Points Made (3P) #' \item Three Points Attempted (3PA) #' \item Three Points Percentage (3P\%) #' \item Two Points Made (2P) #' \item Two Points Attempted (2PA) #' \item Two Points Percentage (2P\%) #' \item Free Throw Made (FT) #' \item Free Throw Attempted (FTA) #' \item Free Throw Percentage (FT\%) #' \item And One Times (ANDONE) #' \item Assists (AST) #' \item Turnover (TOV) #' } #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1), #' "ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) #' #' play_data_adjustment(df1) #' #' @export #' play_data_adjustment <- function(df1){ if(ncol(df1)==12){ names(df1) <- c("Name","GP","PTS","FG","FGA","3P","3PA","FT","FTA","ANDONE","AST","TOV") fgp <- round(df1[4] / df1[5],3) tp <- round(df1[6] / df1[7],3) tw <- round((df1[4] - df1[6]),3) twa <- round((df1[5] - df1[7]),3) twp <- round(tw / twa,3) ftp <- round(df1[8] / df1[9],3) data_adjustment <- cbind(df1,fgp,tp,tw,twa,twp,ftp) data_adjustment <- subset (data_adjustment, select=c(1,2,3,4,5,13,6,7,14,15,16,17,8,9,18,10,11,12)) names(data_adjustment) <- c("Name","GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","ANDONE","AST","TOV") data_adjustment[is.na(data_adjustment)] <- 0 } data_adjustment[is.na(data_adjustment)] <- 0 return(data_adjustment) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_data_adjustment.R
#' @title Play games adder #' @description The function allows to perform the sums of two data.frames with the same format adopted after being transformed by play_data_adjustment() function, #' @param df1 Should be a Data Frame that represents the first set of play's statistics. It has to be in the format provided by the play_data_adjustment() function. #' @param df2 Should be a Data Frame that represents the second set of play's statistics. It has to be in the format provided by the play_data_adjustment() function. #' @details The function will work correctly when the name of the players is the same, in case it is different it will take the players as different. #' @return Data frame with the sum of the statistics of the other two entered data frame. #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' df2 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' play_games_adder(df1,df2) #' #' #' @export #' #' #' #' @importFrom stats aggregate #' play_games_adder <- function(df1,df2){ if (ncol(df1) == 18 & ncol(df2) == 18){ t1 <- df1[nrow(df1),] t2 <- df2[nrow(df2),] df1<-df1[1:(nrow(df1)-1),] df2<-df2[1:(nrow(df2)-1),] adder <- rbind(df1,df2) team <- rbind(t1,t2) names(adder) <- c("Name","G","PTS","FG","FGA","FGP","TP","TPA","TPP","TWP","TWPA","TWPP","FT","FTA","FTP","ANDONE","AST","TOV") names(team) <- c("Name","G","PTS","FG","FGA","FGP","TP","TPA","TPP","TWP","TWPA","TWPP","FT","FTA","FTP","ANDONE","AST","TOV") adder <- aggregate(cbind(adder$G,adder$PTS,adder$FG,adder$FGA,adder$TP,adder$TPA,adder$TWP,adder$TWPA,adder$FT,adder$FTA,adder$ANDONE, adder$AST,adder$TOV), by=list(Name=adder$Name), FUN=sum) team <- aggregate(cbind(team$G,team$PTS,team$FG,team$FGA,team$TP,team$TPA,team$TWP,team$TWPA,team$FT,team$FTA,team$ANDONE, team$AST,team$TOV), by=list(Name=team$Name), FUN=sum) adder <- rbind(adder,team) fgp <- round(adder[4] / adder[5],3) tp <- round(adder[6] / adder[7],3) twp <- round(adder[8] / adder[9],3) ftp <- round(adder[10] / adder[11],3) adder <- cbind(adder,fgp,tp,twp,ftp) adder <- subset (adder, select=c(1,2,3,4,5,15,6,7,16,8,9,17,10,11,18,12,13,14)) names(adder) <- c("Name","GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","ANDONE","AST","TOV") adder[is.na(adder)] <- 0 } adder[is.na(adder)] <- 0 return(adder) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_games_adder.R
#' @title Play stats per game #' @description The function allows the calculation of play statistics per game. #' @param df1 Should be a Data Frame that represents the play's statistics. The parameter has to be in the format provided by the play_data_adjustment() function. #' @details The calculation is made with the number of games played by the player. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with play statistics per game #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' play_stats_per_game(df1) #' #' @export #' play_stats_per_game <- function(df1){ df1 <- df1[-nrow(df1),] for(i in 3:ncol(df1)){ if(i==6 || i==9 || i==12 || i==15){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round(df1[i] / df1[2],2) } } names(df1) <- c("Name","GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","And One","AST","TOV") df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_stats_per_game.R
#' @title Play stats per possesion #' @description The function allows the calculation of the statistics per game projected to P possesions. #' @param df1 Should be a Data Frame that represents the play's statistics. The parameter has to be in the format provided by the play_data_adjustment() function. #' @param df2 Should be a Data Frame that represents the team's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param df3 Should be a Data Frame that represents the rival's statistics. The parameter has to be in the format provided by the team_stats() function. #' @param p Should be a number. This parameter has to be the number of possessions to which you want to project the statistics. #' @param m should be a number. This parameter has to be the duration of a single game. #' @details The statistical projection is made from the estimation of the possessions that the team plays when the player is on the court. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with statistics by game projected to the possesions entered #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782), #' "3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), #' "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260), #' "FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), #' "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803),"STL" = c(612), #' "BLK" = c(468), "TOV" = c(1077), "PF" = c(1471), #' "PTS" = c(8054), "+/-" = c(0)) #' #' df3 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' p<- 100 #' #' m <- 48 #' #' play_stats_per_possesion(df1,df2,df3,p,m) #' #' @export #' play_stats_per_possesion <- function(df1,df2,df3,p,m){ tm_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] opp_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] pace <- m * ((tm_poss + opp_poss) / (2 * (df2[1,2] / 5))) play_poss <- (pace/m) * df1[6] for(i in 3:ncol(df1)){ if(i==6||i==9||i==12||i==15){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/play_poss) * p,2) } } names(df1) <- c("Name","GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","And One","AST","TOV") df1[is.na(df1)] <- 0 return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_stats_per_possesion.R
#' @title Team play statistics #' @description The function performs the sum of the statistical sections to obtain a data.frame with the total statistics of the team. #' @param df1 Should be a Data Frame that represents the play's statistics. This parameter has to be in the format provided by the play_data_adjustment() function. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame whit the team's plays statistics #' @examples #' #' df1 <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71), #' "PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1), #' "FGA Percentage" = c(0.552,1),"3P" = c(6,1),"3PA" = c(18,1), #' "3P Percentage" = c(0.333,1),"2P" = c(149,0),"2PA" = c(263,0), #' "2P Percentage" = c(0.567,0),"FT" = c(39,1), "FTA" = c(53,1), #' "FT Percentage" = c(0.736,1), "ANDONE" = c(12,1), "AST" = c(0,1), #' "TOV" = c(27,1)) #' #' play_team_stats(df1) #' #' @export #' play_team_stats <- function(df1){ total <- data.frame("G" = df1[nrow(df1),2]) for(i in 3:ncol(df1)){ if(i==6 || i==9 || i==12 || i==15){ div <- colSums(df1[i-2])/colSums(df1[i-1]) total <- cbind(total,round(div,3)) } else{ total <- cbind(total,round(colSums(df1[i]),3)) } } total <- data.frame(total, row.names = 1) total[is.na(total)] <- 0 names(total) <- c("GP","PTS","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%","And One","AST","TOV") return(total) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/play_team_stats.R
#' @title Team advanced statistics #' @description This function allows the calculation of advanced team's statistics. #' @param df1 Should be a Data Frame that represents the team statistics. This parameter has to be in the format provided by the team_stats() function. #' @param df2 Should be a Data Frame that represents the rival statistics. This parameter has to be in the format provided by the team_stats() function. #' @param m should be a number. This parameter has to be the duration of a single game. #' @return Data frame with the following advanced statistics calculated: #' \itemize{ #' \item Offensive Rating (ORtg) #' \item Defensive Rating (DRtg) #' \item Net Rating (NetRtg) #' \item Pace (Pace) #' \item Three rating (3Par) #' \item True shooting percentage (TS\%) #' \item Efficiency Field Goals percentage (eFG\%) #' \item Assists percentage (AST\%) #' \item Assist to Turnover Ratio (AST/TO) #' \item Assist Ratio (ASTRATIO) #' \item Offensive rebounds percentage (ORB\%) #' \item Defensive rebounds percentage (DRB\%) #' \item Total rebounds percentage (TRB\%) #' \item Turnover percentage (TOV\%) #' \item Free Throw rating (FTr) #' \item Opponent Efficiency Field Goals percentage (Opp eFG\%) #' \item Opponent Turnover percentage (Opp TOV\%) #' \item Opponent Defensive rebounds percentage (Opp DRB\%) #' \item Opponent Free Throw rating (Opp FTr) #' } #' @examples #' df1 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782), #' "3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), #' "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260), #' "FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), #' "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803),"STL" = c(612), #' "BLK" = c(468), "TOV" = c(1077), "PF" = c(1471), #' "PTS" = c(8054), "+/-" = c(0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' m <- 48 #' #' team_advanced_stats(df1,df2,m) #' #' @export #' team_advanced_stats <- function(df1,df2,m){ minutes <- (df2[1,2]/df2[1,1])/5 minutes <- trunc(minutes) tm_poss <- df1[1,4] - df1[1,15] / (df1[1,15] + df2[1,16]) * (df1[1,4] - df1[1,3]) * 1.07 + df1[1,21] + 0.4 * df1[1,13] opp_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df1[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] pace <- round(m * ((tm_poss + opp_poss) / (2 * (df1[1,2] / 5))),2) stats <- cbind(df1[1],df1[2]) offrtg <- round(100 * (df1[1,23]/tm_poss),2) defrtg <- round(100 * (df2[1,23]/opp_poss),2) netrtg <- round(offrtg - defrtg,2) TPAr <- round(df1[1,7] / df1[1,4],3) FTr <- round(df1[1,13] / df1[1,4],3) ts <- round(df1[1,23] / (2 * (df1[1,4] + 0.44 * df1[1,13])),3) efg <- round((df1[1,3] + 0.5 * df1[1,6]) / df1[1,4],3) ast <- round(df1[1,18] / df1[1,3],3) ast_to <- round(df1[1,18] / df1[1,21],2) ast_ratio <- round((df1[1,18] * 100) / tm_poss,2) orb <- round(df1[1,15] / (df1[1,15] + df2[1,16]),3) fta_rate <- round(df1[1,12] / df1[1,4],3) tov <- round(df1[1,21] / (df1[1,4] +0.44 * df1[1,13] + df1[1,21]),3) eFG_opp <- round((df2[1,3] + 0.5 * df2[1,6]) / df2[1,4],3) tov_opp <- round(df2[1,21] / (df2[1,4] +0.44 * df2[1,13] + df2[1,21]),3) offRB_opp <- round(df1[1,16] / (df1[1,16] + df2[1,15]),3) fta_rate_opp <- round(df2[1,12] / df2[1,4],3) stats <- cbind(stats,offrtg,defrtg,netrtg,pace,TPAr,FTr,ts,efg,ast,ast_to,ast_ratio,orb,tov,fta_rate,eFG_opp,tov_opp,offRB_opp,fta_rate_opp) names(stats) = c("G","MP","ORtg","DRtg",'NetRtg','Pace',"3PAr","FTr",'TS%','eFG%',"AST%","AST/TO","ASTRATIO%","ORB%","TOV%","FT/FGA","Opp eFG%","Opp TOV%","DRB%","Opp FTr") return(stats) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/team_advance_stats.R
#' @title Team statistics #' @description This function allows the team statistics from individual statistics. #' @param df1 Should be a Data Frame that represents the individual statistics or individual defensive statistics of the players. The parameter has to be in the format provided by the data_adjustment() function. #' @details The function performs the sum of the statistical sections to obtain a data.frame with the total statistics of the team. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with the sum of the team's statistics. #' @examples #' #' df1 <- data.frame("name" = c("LeBron James","Team"), "G" = c(67,0), #' "GS" = c(62,0), "MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), #' "Percentage FG" = c(0.493,0), "3P" = c(148,0), "3PA" = c(425,0), #' "Percentage 3P" = c(0.348,0), "2P" = c(495,0), "2PA" = c(878,0), #' "Percentage 2P" = c(0.564,0),"FT" = c(264,0), "FTA FG" = c(381,0), #' "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), #' "TRB" = c(525,0), "AST" = c(684,0), "STL" = c(78,0), #' "BLK" = c(36,0),"TOV" = c(261,0), "PF" = c(118,0), #' "PTS" = c(1698,0), "+/-" = c(0,0)) #' #' team_stats(df1) #' #' @export #' team_stats <- function(df1){ total <- data.frame("G" = df1[nrow(df1),2]) for(i in 4:ncol(df1)){ if(i==7 || i==10 || i==13 || i==16){ div <- colSums(df1[i-2])/colSums(df1[i-1]) total <- cbind(total,round(div,3)) } else{ total <- cbind(total,round(colSums(df1[i]),3)) } } total <- data.frame(total, row.names = 1) names(total) <- c("G","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") return(total) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/team_stats.R
#' @title Team stats per game #' @description The function allows the calculation of team's statistics per game. #' @param df1 Should be a Data Frame that represents the team statistics. This parameter has to be in the format provided by the team_stats() function. #' @details The calculation is made with the number of games played by the team. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame whit the team's statistics per game #' @examples #' #' df1 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782), #' "3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), #' "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260), #' "FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), #' "DRB" = c(2490),"TRB" = c(3247), "AST" = c(1803), "STL" = c(612), #' "BLK" = c(468), "TOV" = c(1077), "PF" = c(1471), "PTS" = c(8054), #' "+/-" = c(0)) #' #' team_stats_per_game(df1) #' #' @export #' team_stats_per_game <- function(df1){ for(i in 3:ncol(df1)){ if(i==5 || i==8 || i==11 || i==14){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round(df1[i] / df1[1],2) } } names(df1) <- c("G","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/team_stats_per_game.R
#' @title Team stats per minutes #' @description The function allows the calculation of the team statistics per game projected to M minutes. #' @param df1 Should be a Data Frame that represents the team statistics. This parameter has to be in the format provided by the team_stats() function. #' @param m Should be a number. This parameter has to be the number of minutes to which you want to project the statistics. #' @details The statistical projection is made from the relationship between the number of minutes entered and the number of minutes played by the team #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with statistics by game projected to the minutes entered. #' @examples #' #' df1 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782), #' "3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), #' "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260), #' "FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), #' "DRB" = c(2490),"TRB" = c(3247), "AST" = c(1803), "STL" = c(612), #' "BLK" = c(468), "TOV" = c(1077), "PF" = c(1471), "PTS" = c(8054), #' "+/-" = c(0)) #' #' m <- 48 #' #' team_stats_per_minutes(df1,m) #' #' @export #' team_stats_per_minutes <- function(df1,m){ minutes <- df1[2] df1[2]=df1[2]/df1[1] for(i in 3:ncol(df1)){ if(i==5 || i==8 || i==11 || i==14){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round((df1[i] / df1[1]) * ((5*m)/df1[2]),2) } } df1[2] <- minutes names(df1) <- c("G","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/team_stats_per_minutes.R
#' @title Team stats per possesion #' @description The function allows the calculation of the statistics per game projected to P possesions. #' @param df1 Should be a Data Frame that represents the team statistics. This parameter has to be in the format provided by the team_stats() function. #' @param df2 Should be a Data Frame that represents the rival statistics. This parameter has to be in the format provided by the team_stats() function. #' @param p Should be a number. This parameter has to be the number of possessions to which you want to project the statistics. #' @details The statistical projection is made from the estimation of the possessions that the team plays. #' @author Fco Javier Cantero \email{fco.cantero@@edu.uah.es} #' @author Juan José Cuadrado \email{jjcg@@uah.es} #' @author Universidad de Alcalá de Henares #' @return Data frame with statistics by game projected to the possessions entered. #' @examples #' #' df1 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), #' "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782), #' "3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), #' "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260), #' "FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), #' "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803),"STL" = c(612), #' "BLK" = c(468), "TOV" = c(1077), "PF" = c(1471), #' "PTS" = c(8054), "+/-" = c(0)) #' #' df2 <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), #' "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827), #' "3PA" = c(2373), "Percentage 3P" = c(0.349), "2P" = c(1946), #' "2PA" = c(3814), "Percentage 2P" = c(0.510), "FT" = c(1270), #' "FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), #' "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662),"STL" = c(585), #' "BLK" = c(263), "TOV" = c(1130), "PF" = c(1544), #' "PTS" = c(7643), "+/-" = c(0)) #' #' p <- 100 #' #' team_stats_per_possesion(df1,df2,p) #' #' @export #' team_stats_per_possesion <- function(df1,df2,p){ tm_poss <- df1[1,4] - df1[1,15] / (df1[1,15] + df2[1,16]) * (df1[1,4] - df1[1,3]) * 1.07 + df1[1,21] + 0.4 * df1[1,13] for(i in 3:ncol(df1)){ if(i==5 || i==8 || i==11 || i==14){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round((df1[i]/tm_poss) * p,2) } } names(df1) <- c("G","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") return(df1) }
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/R/team_stats_per_possesion.R
## ----setup, include=FALSE----------------------------------------------------- library(AdvancedBasketballStats) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ## ----------------------------------------------------------------------------- individual_stats <- data.frame("Name" = c("James","Team"), "G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,1), "FG" = c(643,0), "FGA" = c(1303,0), "3P " = c(148,0),"3PA" = c(425,0),"2P" = c(495,0), "2PA" = c(878,0), "FT" = c(264,0),"FTA" = c(381,0),"ORB" = c(66,0), "DRB" = c(459,0), "AST" = c(684,0),"STL" = c(78,0), "BLK" = c(36,0),"TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0), "+/-" = c(0,0)) individual_stats <- individuals_data_adjustment(individual_stats) individual_stats ## ----------------------------------------------------------------------------- individual <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), "TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) individual ## ----------------------------------------------------------------------------- defensive_stats <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0),"FM" = c(4,0), "BLK" = c(0,0), "FTO" = c(0,0),"STL" = c(1,1), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive_stats <- individuals_data_adjustment(defensive_stats) defensive_stats ## ----------------------------------------------------------------------------- defensive <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0), "FM" = c(4,0), "BLK" = c(0,0),"TOTAL FM" = c(4,0),"FTO" = c(0,0), "STL" = c(1,1), "TOTAL FTO " = c(1,0), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive ## ----------------------------------------------------------------------------- tm_stats <- team_stats(individual_stats) tm_stats ## ----------------------------------------------------------------------------- indi_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) indi_team_stats ## ----------------------------------------------------------------------------- indi_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) indi_rival_stats ## ----------------------------------------------------------------------------- linp_basic <- data.frame("PG"= c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA" = c(7,0), "X3P" = c(0,0),"X3PA" = c(2,0),"X2P" = c(4,0), "X2PA" = c(5,0), "FT" = c(1,0), "FTA" = c(3,0),"ORB" = c(2,0), "DRB" = c(5,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0), "TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3)) linp_basic <- lineups_data_adjustment(linp_basic) linp_basic ## ----------------------------------------------------------------------------- lineup_basic <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA " = c(7,0),"Percentage FG" = c(0.571,0), "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) lineup_basic ## ----------------------------------------------------------------------------- linp_extended <- data.frame("PG" = c("James","Rondo"),"SG"= c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P " = c(1,0),"X3PA " = c(4,0), "Opp3PA " = c(3,0),"X2P" = c(4,0),"Opp2P" = c(5,0),"X2PA " = c(6,0), "Opp2PA" = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0), "OppFTA" = c(1,0),"OppRB" = c(2,0),"OppOppRB" = c(1,0),"DRB" = c(4,0), "OppDRB" = c(1,0),"AST " = c(5,0),"OppAST " = c(4,0),"STL" = c(1,0), "OppSTL" = c(3,0),"BLK" = c(0,0),"OppBLK" = c(1,0),"TOppV" = c(5,2), "OppTOppV" = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0),"PLUS" = c(15,0), "MINUS" = c(14,3)) linp_extended <- lineups_data_adjustment(linp_extended) linp_extended ## ----------------------------------------------------------------------------- lineup_extended <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) lineup_extended ## ----------------------------------------------------------------------------- tm_stats <- team_stats(individual_stats) tm_stats ## ----------------------------------------------------------------------------- lineup_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) lineup_team_stats ## ----------------------------------------------------------------------------- lineup_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) lineup_rival_stats ## ----------------------------------------------------------------------------- play_stats <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play_stats <- play_data_adjustment(play_stats) play_stats ## ----------------------------------------------------------------------------- play <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play ## ----------------------------------------------------------------------------- tm_stats <- team_stats(individual_stats) tm_stats ## ----------------------------------------------------------------------------- play_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) play_team_stats ## ----------------------------------------------------------------------------- play_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) play_rival_stats ## ----------------------------------------------------------------------------- tm_stats <- team_stats(individual_stats) tm_stats ## ----------------------------------------------------------------------------- team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027),"Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612),"BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) team_stats ## ----------------------------------------------------------------------------- rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) rival_stats ## ----------------------------------------------------------------------------- advanced_stats <- individuals_advance_stats(individual,indi_team_stats,indi_rival_stats) advanced_stats ## ----------------------------------------------------------------------------- defensive_actual_stats <- individuals_defensive_actual_floor_stats(defensive,indi_team_stats,indi_rival_stats) defensive_actual_stats ## ----------------------------------------------------------------------------- defensive_estimated_stats <- individuals_defensive_estimated_floor_stats(individual,indi_team_stats,indi_rival_stats) defensive_estimated_stats ## ----------------------------------------------------------------------------- games_adder <- individuals_games_adder(individual,individual) games_adder ## ----------------------------------------------------------------------------- ofensive_stats <- individuals_ofensive_floor_stats(individual,indi_team_stats,indi_rival_stats) ofensive_stats ## ----------------------------------------------------------------------------- per_game_stats <- individuals_stats_per_game(individual) per_game_stats ## ----------------------------------------------------------------------------- per_minutes_stats <- individuals_stats_per_minutes(individual,36) per_minutes_stats ## ----------------------------------------------------------------------------- per_poss_stats <- individuals_stats_per_possesion(individual,indi_team_stats,indi_rival_stats,100,48) per_poss_stats ## ----------------------------------------------------------------------------- lnp_advanced_stats <- lineups_advance_stats(lineup_extended,48) lnp_advanced_stats ## ----------------------------------------------------------------------------- lnp_bs_backcourt <- lineups_backcourt(lineup_basic) lnp_bs_backcourt ## ----------------------------------------------------------------------------- lnp_ex_backcourt <- lineups_backcourt(lineup_extended) lnp_ex_backcourt ## ----------------------------------------------------------------------------- lnp_comparator <- lineups_comparator_stats(lineup_extended,48) lnp_comparator ## ----------------------------------------------------------------------------- lnp_games_adder <- lineups_games_adder(lineup_basic,lineup_basic) lnp_games_adder ## ----------------------------------------------------------------------------- lnp_bc_paint <- lineups_paint(lineup_basic) lnp_bc_paint ## ----------------------------------------------------------------------------- lnp_ex_paint <- lineups_paint(lineup_extended) lnp_ex_paint ## ----------------------------------------------------------------------------- lnp_bc_players <- lineups_players(lineup_basic,5) lnp_bc_players ## ----------------------------------------------------------------------------- lnp_ex_players <- lineups_players(lineup_extended,5) lnp_ex_players ## ----------------------------------------------------------------------------- lnp_bc_searcher <- lineups_searcher(lineup_basic,1,"James","","","") lnp_bc_searcher ## ----------------------------------------------------------------------------- lnp_ex_searcher <- lineups_searcher(lineup_extended,1,"James","","","") lnp_ex_searcher ## ----------------------------------------------------------------------------- lnp_ex_sep_one <- lineups_separator(lineup_extended,1) lnp_ex_sep_one ## ----------------------------------------------------------------------------- lnp_ex_sep_two <- lineups_separator(lineup_extended,2) lnp_ex_sep_two ## ----------------------------------------------------------------------------- lnp_per_poss_stats <- lineups_stats_per_possesion(lineup_basic,lineup_team_stats,lineup_rival_stats,100,48) lnp_per_poss_stats ## ----------------------------------------------------------------------------- play_adv_stats <- play_advance_stats(play_stats) play_adv_stats ## ----------------------------------------------------------------------------- pl_game_adder <- play_games_adder(play_stats,play_stats) pl_game_adder ## ----------------------------------------------------------------------------- play_per_game_stat <- play_stats_per_game(play_stats) play_per_game_stat ## ----------------------------------------------------------------------------- play_per_poss_stats <- play_stats_per_possesion(play_stats,play_team_stats,play_rival_stats,100,48) play_per_poss_stats ## ----------------------------------------------------------------------------- play_team_stats <- play_team_stats(play_stats) play_team_stats ## ----------------------------------------------------------------------------- team_adv_stats <- team_advanced_stats(team_stats,rival_stats,48) team_adv_stats ## ----------------------------------------------------------------------------- team_per_game_stat <- team_stats_per_game(team_stats) team_per_game_stat ## ----------------------------------------------------------------------------- team_per_minutes_stat <- team_stats_per_minutes(team_stats,36) team_per_minutes_stat ## ----------------------------------------------------------------------------- team_per_poss_stat <- team_stats_per_possesion(team_stats,rival_stats,100) team_per_poss_stat
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/inst/doc/BasketballAdvancedStats.R
--- title: "Advanced basketball statistics in R" output: rmarkdown::html_document vignette: > %\VignetteIndexEntry{Advanced basketball statistics in R} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} library(AdvancedBasketballStats) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` Advanced basketball statistics is an R package that allows you to perform different statistics calculations that are used in the world of basketball. In the package we can perform different calculations for the following types of statistics: * Calculations on a data set representing individual statistics. * Calculations on a data set representing lineup statistics. * Calculations on a data set representing play statistics. * Calculations on a data set representing team statistics. # Data set To create our data set we can do it in two different ways: After deciding how to create our data set we must know what analysis we want to perform, since depending on this we will need different types of data sets: 1. We can use the functions that allow the transformation of a simple data set, that is, without the calculations performed by the data_adjustment() functions. The functions that the transformation allows are the following: + individuals_data_adjustment. Function that allows transformation of individual stats and defensive stats. + lineups_data_adjustment. Function that allows the transformation of lineups. + play_data_adjustment. Function that allows the transformation of plays. + team_stats. Function that allows you to perform team statistics. 2. We can use Data frames with the format corresponding to the data_adjustment() functions. Once the two ways of creating the data have been commented, the examples of the data sets for subsequent use are shown: ## Individual Data Set If we want to perform the analysis of individual statistics, we must have the following data sets: * Data set that represents individual statistics. + Data set created the individuals_data_adjustment function: ```{r} individual_stats <- data.frame("Name" = c("James","Team"), "G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,1), "FG" = c(643,0), "FGA" = c(1303,0), "3P " = c(148,0),"3PA" = c(425,0),"2P" = c(495,0), "2PA" = c(878,0), "FT" = c(264,0),"FTA" = c(381,0),"ORB" = c(66,0), "DRB" = c(459,0), "AST" = c(684,0),"STL" = c(78,0), "BLK" = c(36,0),"TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0), "+/-" = c(0,0)) individual_stats <- individuals_data_adjustment(individual_stats) individual_stats ``` + Data set created with the same structure as the one generated by the individuals_data_adjustment function ```{r} individual <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), "TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) individual ``` * Data set representing individual defensive statistics. + Data set created with the individuals_data_adjustment function: ```{r} defensive_stats <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0),"FM" = c(4,0), "BLK" = c(0,0), "FTO" = c(0,0),"STL" = c(1,1), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive_stats <- individuals_data_adjustment(defensive_stats) defensive_stats ``` + Data set created with the same structure as the one generated by the individuals_data_adjustment function ```{r} defensive <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0), "FM" = c(4,0), "BLK" = c(0,0),"TOTAL FM" = c(4,0),"FTO" = c(0,0), "STL" = c(1,1), "TOTAL FTO " = c(1,0), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} indi_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) indi_team_stats ``` * Data set that represents the statistics of the rival team. + Data set created with the same structure as the one generated by the team_stats function ```{r} indi_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) indi_rival_stats ``` ## Lineup Data Set If we want to perform the analysis of lineup statistics, we must have the following data sets: * Data set that represents basic lineup statistics. + Data set created with the lineups_data_adjustment function ```{r} linp_basic <- data.frame("PG"= c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA" = c(7,0), "X3P" = c(0,0),"X3PA" = c(2,0),"X2P" = c(4,0), "X2PA" = c(5,0), "FT" = c(1,0), "FTA" = c(3,0),"ORB" = c(2,0), "DRB" = c(5,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0), "TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3)) linp_basic <- lineups_data_adjustment(linp_basic) linp_basic ``` + Data set created with the same structure as the one generated by the lineups_data_adjustment function ```{r} lineup_basic <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA " = c(7,0),"Percentage FG" = c(0.571,0), "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) lineup_basic ``` * Data set that represents extended lineup statistics. + Data set created with the lineups_data_adjustment function ```{r} linp_extended <- data.frame("PG" = c("James","Rondo"),"SG"= c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P " = c(1,0),"X3PA " = c(4,0), "Opp3PA " = c(3,0),"X2P" = c(4,0),"Opp2P" = c(5,0),"X2PA " = c(6,0), "Opp2PA" = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0), "OppFTA" = c(1,0),"OppRB" = c(2,0),"OppOppRB" = c(1,0),"DRB" = c(4,0), "OppDRB" = c(1,0),"AST " = c(5,0),"OppAST " = c(4,0),"STL" = c(1,0), "OppSTL" = c(3,0),"BLK" = c(0,0),"OppBLK" = c(1,0),"TOppV" = c(5,2), "OppTOppV" = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0),"PLUS" = c(15,0), "MINUS" = c(14,3)) linp_extended <- lineups_data_adjustment(linp_extended) linp_extended ``` + Data set created with the same structure as the one generated by the lineups_data_adjustment function ```{r} lineup_extended <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) lineup_extended ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} lineup_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) lineup_team_stats ``` * Data set that represents the statistics of the rival team. ```{r} lineup_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) lineup_rival_stats ``` ## Play Data Set If we want to perform the analysis of play statistics, we must have the following data sets: * Data set that represents play statistics. + Data set created with the play_data_adjustment function ```{r} play_stats <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play_stats <- play_data_adjustment(play_stats) play_stats ``` + Data set created with the same structure as the one generated by the play_data_adjustment function ```{r} play <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} play_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) play_team_stats ``` + Data set that represents the statistics of the rival team. ```{r} play_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) play_rival_stats ``` ## Team Data Set If we want to perform the analysis of team statistics, we must have the following data sets: * Data set that represents the statistics of the team. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027),"Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612),"BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) team_stats ``` * Data set that represents the statistics of the rival team. ```{r} rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) rival_stats ``` Once the data sets have been created, we must choose which function or functions we want to use. Below are the different functions that the package has: # Functions for individual statistics For individual statistics there are the following functions: * __individuals_advance_stats.__ Function that allows advanced statistics calculation. * __individuals_defensive_actual_floor_stats.__ Function that allows the calculation of the current defensive statistics. * __individuals_defensive_estimated_floor_stats.__ Function that allows the calculation of the estimated defensive statistics. * __individuals_games_adder.__ Function that allows the sum of two different individual statistics. * __individuals_ofensive_floor_stats.__ Function that allows the calculation of offensive statistics. * __individuals_stats_per_game.__ Function that allows the calculation of statistics per game. * __individuals_stats_per_minutes.__ Function that allows the calculation of statistics per minutes. * __individuals_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. Below is an example of how each function works and what the input parameters should be for these: ## individuals_advance_stats For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} advanced_stats <- individuals_advance_stats(individual,indi_team_stats,indi_rival_stats) advanced_stats ``` ## individuals_defensive_actual_floor_stats For this function we will have to enter defensive individual statistics, team statistics and rival team statistics: ```{r} defensive_actual_stats <- individuals_defensive_actual_floor_stats(defensive,indi_team_stats,indi_rival_stats) defensive_actual_stats ``` ## individuals_defensive_estimated_floor_stats For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} defensive_estimated_stats <- individuals_defensive_estimated_floor_stats(individual,indi_team_stats,indi_rival_stats) defensive_estimated_stats ``` ## individuals_games_adder. For this function we will have to enter the two individual statistics previously calculated which we want to add the statistics: ```{r} games_adder <- individuals_games_adder(individual,individual) games_adder ``` ## individuals_ofensive_floor_stats. For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} ofensive_stats <- individuals_ofensive_floor_stats(individual,indi_team_stats,indi_rival_stats) ofensive_stats ``` ## individuals_stats_per_game For this function we will have to enter individual statistics: ```{r} per_game_stats <- individuals_stats_per_game(individual) per_game_stats ``` ## individuals_stats_per_minutes For this function we will have to enter the individual statistics and the number of minutes to which we want to project the statistics: ```{r} per_minutes_stats <- individuals_stats_per_minutes(individual,36) per_minutes_stats ``` ## individuals_stats_per_possesion For this function we will have to enter the individual statistics, the team statistics, the rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} per_poss_stats <- individuals_stats_per_possesion(individual,indi_team_stats,indi_rival_stats,100,48) per_poss_stats ``` # Functions for lineup statistics For individual statistics there are the following functions: * __lineups_advance_stats.__ Function that allows advanced statistics calculation. * __lineups_backcourt.__ Function that allows searching for backcourt players. * __lineups_comparator_stats.__ Function that allows comparison between the statistics of the lineup and the rival lineup * __lineups_games_adder.__ Function that allows the sum of two different lineup statistics. * __lineups_paint.__ Function that allows searching for paint players. * __lineups_players.__ Function that allows searching for players by position. * __lineups_searcher.__ Function that allows searching for players within the data frame. * __lineups_separator.__ Function that allows you to obtain the statistics of the lineups or the rivals against those lineups. * __lineups_stats_per_possesion.__ Function that allows the calculation of statistics per possessions Below is an example of how each function works and what the input parameters should be for these: ## lineups_advance_stats For this function we will have to enter extended lineup statistics and the number of minutes that a single game lasts: ```{r} lnp_advanced_stats <- lineups_advance_stats(lineup_extended,48) lnp_advanced_stats ``` ## lineups_backcourt For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_bs_backcourt <- lineups_backcourt(lineup_basic) lnp_bs_backcourt ``` ```{r} lnp_ex_backcourt <- lineups_backcourt(lineup_extended) lnp_ex_backcourt ``` ## lineups_comparator_stats For this function we will have to enter extended lineup statistics: ```{r} lnp_comparator <- lineups_comparator_stats(lineup_extended,48) lnp_comparator ``` ## lineups_games_adder For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_games_adder <- lineups_games_adder(lineup_basic,lineup_basic) lnp_games_adder ``` ## lineups_paint For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_bc_paint <- lineups_paint(lineup_basic) lnp_bc_paint ``` ```{r} lnp_ex_paint <- lineups_paint(lineup_extended) lnp_ex_paint ``` ## lineups_players For this function we will have to enter basic lineup statistics or extended lineup statistics and the number of position that we want to find: ```{r} lnp_bc_players <- lineups_players(lineup_basic,5) lnp_bc_players ``` ```{r} lnp_ex_players <- lineups_players(lineup_extended,5) lnp_ex_players ``` ## lineups_searcher For this function we will have to enter basic lineup statistics or extended lineup statistics, the name of the players that we want to find and the number of players that we want to find: ```{r} lnp_bc_searcher <- lineups_searcher(lineup_basic,1,"James","","","") lnp_bc_searcher ``` ```{r} lnp_ex_searcher <- lineups_searcher(lineup_extended,1,"James","","","") lnp_ex_searcher ``` ## lineups_separator For this function we will have to enter extended lineup statistics and the indicator of what type of separation we want to make: ```{r} lnp_ex_sep_one <- lineups_separator(lineup_extended,1) lnp_ex_sep_one ``` ```{r} lnp_ex_sep_two <- lineups_separator(lineup_extended,2) lnp_ex_sep_two ``` ## lineups_stats_per_possesion For this function we will have to enter basic lineup statistics, team statistics, rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} lnp_per_poss_stats <- lineups_stats_per_possesion(lineup_basic,lineup_team_stats,lineup_rival_stats,100,48) lnp_per_poss_stats ``` # Functions for play statistics For individual statistics there are the following functions: * __play_advance_stats.__ Function that allows advanced statistics calculation. * __play_games_adder.__ Function that allows the sum of two different play statistics. * __play_stats_per_game.__ Function that allows the calculation of statistics per game. * __play_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. * __play_team_stats.__ Function that allows to carry out the statistics of the team. Below is an example of how each function works and what the input parameters should be for these: ## play_advance_stats For this function we will have to enter play statistics: ```{r} play_adv_stats <- play_advance_stats(play_stats) play_adv_stats ``` ## play_games_adder For this function we will have to enter play statistics: ```{r} pl_game_adder <- play_games_adder(play_stats,play_stats) pl_game_adder ``` ## play_stats_per_game For this function we will have to enter play statistics: ```{r} play_per_game_stat <- play_stats_per_game(play_stats) play_per_game_stat ``` ## play_stats_per_possesion For this function we will have to enter the play statistics, the team statistics, the rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} play_per_poss_stats <- play_stats_per_possesion(play_stats,play_team_stats,play_rival_stats,100,48) play_per_poss_stats ``` ## play_team_stats For this function we will have to enter play statistics: ```{r} play_team_stats <- play_team_stats(play_stats) play_team_stats ``` # Functions for team statistics For individual statistics there are the following functions: * __team_advanced_stats.__ Function that allows advanced statistics calculation. * __team_stats_per_game.__ Function that allows the calculation of statistics per game. * __team_stats_per_minutes.__ Function that allows the calculation of statistics per minutes. * __team_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. Below is an example of how each function works and what the input parameters should be for these: ## team_advanced_stats For this function we will have to enter the team statistics and the rival team statistics: ```{r} team_adv_stats <- team_advanced_stats(team_stats,rival_stats,48) team_adv_stats ``` ## team_stats_per_game For this function we will have to enter the team statistics: ```{r} team_per_game_stat <- team_stats_per_game(team_stats) team_per_game_stat ``` ## team_stats_per_minutes For this function we will have to enter the team statistics and the number of minutes to which we want to project the statistics: ```{r} team_per_minutes_stat <- team_stats_per_minutes(team_stats,36) team_per_minutes_stat ``` ## team_stats_per_possesion For this function we will have to enter the team statistics, the rival team statistics and the number of possessions to which we want to project the statistics:: ```{r} team_per_poss_stat <- team_stats_per_possesion(team_stats,rival_stats,100) team_per_poss_stat ```
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/inst/doc/BasketballAdvancedStats.Rmd
--- title: "Advanced basketball statistics in R" output: rmarkdown::html_document vignette: > %\VignetteIndexEntry{Advanced basketball statistics in R} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} library(AdvancedBasketballStats) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` Advanced basketball statistics is an R package that allows you to perform different statistics calculations that are used in the world of basketball. In the package we can perform different calculations for the following types of statistics: * Calculations on a data set representing individual statistics. * Calculations on a data set representing lineup statistics. * Calculations on a data set representing play statistics. * Calculations on a data set representing team statistics. # Data set To create our data set we can do it in two different ways: After deciding how to create our data set we must know what analysis we want to perform, since depending on this we will need different types of data sets: 1. We can use the functions that allow the transformation of a simple data set, that is, without the calculations performed by the data_adjustment() functions. The functions that the transformation allows are the following: + individuals_data_adjustment. Function that allows transformation of individual stats and defensive stats. + lineups_data_adjustment. Function that allows the transformation of lineups. + play_data_adjustment. Function that allows the transformation of plays. + team_stats. Function that allows you to perform team statistics. 2. We can use Data frames with the format corresponding to the data_adjustment() functions. Once the two ways of creating the data have been commented, the examples of the data sets for subsequent use are shown: ## Individual Data Set If we want to perform the analysis of individual statistics, we must have the following data sets: * Data set that represents individual statistics. + Data set created the individuals_data_adjustment function: ```{r} individual_stats <- data.frame("Name" = c("James","Team"), "G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,1), "FG" = c(643,0), "FGA" = c(1303,0), "3P " = c(148,0),"3PA" = c(425,0),"2P" = c(495,0), "2PA" = c(878,0), "FT" = c(264,0),"FTA" = c(381,0),"ORB" = c(66,0), "DRB" = c(459,0), "AST" = c(684,0),"STL" = c(78,0), "BLK" = c(36,0),"TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0), "+/-" = c(0,0)) individual_stats <- individuals_data_adjustment(individual_stats) individual_stats ``` + Data set created with the same structure as the one generated by the individuals_data_adjustment function ```{r} individual <- data.frame("name" = c("LeBron James","Team"),"G" = c(67,0), "GS" = c(62,0),"MP" = c(2316,0),"FG" = c(643,0), "FGA" = c(1303,0), "Percentage FG" = c(0.493,0),"3P" = c(148,0),"3PA" = c(425,0), "Percentage 3P" = c(0.348,0),"2P" = c(495,0),"2PA" = c(878,0), "Percentage 2P" = c(0.564,0),"FT" = c(264,0),"FTA FG" = c(381,0), "Percentage FT" = c(0.693,0), "ORB" = c(66,0),"DRB" = c(459,0), "TRB" = c(525,0),"AST" = c(684,0),"STL" = c(78,0),"BLK" = c(36,0), "TOV" = c(261,0), "PF" = c(118,0),"PTS" = c(1698,0),"+/-" = c(0,0)) individual ``` * Data set representing individual defensive statistics. + Data set created with the individuals_data_adjustment function: ```{r} defensive_stats <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0),"FM" = c(4,0), "BLK" = c(0,0), "FTO" = c(0,0),"STL" = c(1,1), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive_stats <- individuals_data_adjustment(defensive_stats) defensive_stats ``` + Data set created with the same structure as the one generated by the individuals_data_adjustment function ```{r} defensive <- data.frame("Name" = c("Witherspoon ","Team"), "MP" = c(14,200),"DREB" = c(1,0), "FM" = c(4,0), "BLK" = c(0,0),"TOTAL FM" = c(4,0),"FTO" = c(0,0), "STL" = c(1,1), "TOTAL FTO " = c(1,0), "FFTA" = c(0,0), "DFGM" = c(1,0), "DFTM" = c(0,0)) defensive ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} indi_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) indi_team_stats ``` * Data set that represents the statistics of the rival team. + Data set created with the same structure as the one generated by the team_stats function ```{r} indi_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) indi_rival_stats ``` ## Lineup Data Set If we want to perform the analysis of lineup statistics, we must have the following data sets: * Data set that represents basic lineup statistics. + Data set created with the lineups_data_adjustment function ```{r} linp_basic <- data.frame("PG"= c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA" = c(7,0), "X3P" = c(0,0),"X3PA" = c(2,0),"X2P" = c(4,0), "X2PA" = c(5,0), "FT" = c(1,0), "FTA" = c(3,0),"ORB" = c(2,0), "DRB" = c(5,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0), "TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3)) linp_basic <- lineups_data_adjustment(linp_basic) linp_basic ``` + Data set created with the same structure as the one generated by the lineups_data_adjustment function ```{r} lineup_basic <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(4,0), "FGA " = c(7,0),"Percentage FG" = c(0.571,0), "X3P " = c(0,0),"X3PA " = c(2,0),"Percentage 3P" = c(0,0), "X2P " = c(4,0), "X2PA " = c(5,0), "Percentage 2P" = c(0.8,0), "FT " = c(1,0), "FTA " = c(3,0), "Percentage FT" = c(0.333,0), "ORB " = c(2,0), "DRB " = c(5,0),"TRB " = c(7,0), "AST " = c(2,0), "STL " = c(1,0), "BLK " = c(0,0),"TOV " = c(7,2), "PF" = c(1,0), "PLUS" = c(9,0),"MINUS" = c(17,3),"P/M" = c(-8,-3)) lineup_basic ``` * Data set that represents extended lineup statistics. + Data set created with the lineups_data_adjustment function ```{r} linp_extended <- data.frame("PG" = c("James","Rondo"),"SG"= c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P " = c(1,0),"X3PA " = c(4,0), "Opp3PA " = c(3,0),"X2P" = c(4,0),"Opp2P" = c(5,0),"X2PA " = c(6,0), "Opp2PA" = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0), "OppFTA" = c(1,0),"OppRB" = c(2,0),"OppOppRB" = c(1,0),"DRB" = c(4,0), "OppDRB" = c(1,0),"AST " = c(5,0),"OppAST " = c(4,0),"STL" = c(1,0), "OppSTL" = c(3,0),"BLK" = c(0,0),"OppBLK" = c(1,0),"TOppV" = c(5,2), "OppTOppV" = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0),"PLUS" = c(15,0), "MINUS" = c(14,3)) linp_extended <- lineups_data_adjustment(linp_extended) linp_extended ``` + Data set created with the same structure as the one generated by the lineups_data_adjustment function ```{r} lineup_extended <- data.frame("PG" = c("James","Rondo"),"SG" = c("Green","Caruso"), "SF" = c("Caldwell","Kuzma"), "PF" = c("Davis","Davis"), "C" = c("Howard ","Howard"),"MP" = c(7,1), "FG " = c(6,0), "OppFG " = c(6,0), "FGA " = c(10,0),"OppFGA " = c(9,0), "X3P " = c(2,0),"Opp3P" = c(1,0),"X3PA" = c(4,0),"Opp3PA" = c(3,0), "X2P" = c(4,0),"Opp2P " = c(5,0), "X2PA " = c(6,0),"Opp2PA " = c(8,0) , "FT " = c(0,0),"OppFT " = c(1,0), "FTA " = c(0,0),"OppFTA " = c(1,0), "OppRB " = c(2,0),"OppOppRB " = c(1,0), "DRB" = c(4,0),"OppDRB" = c(1,0), "TRB" = c(6,0),"OppTRB" = c(2,0), "AST " = c(5,0),"OppAST " = c(4,0), "STL " = c(1,0),"OppSTL " = c(3,0), "BLK " = c(0,0), "OppBLK " = c(1,0), "TOppV " = c(5,2), "OppTOppV " = c(3,2),"PF" = c(1,0),"OppPF" = c(3,0), "PLUS" = c(15,0),"MINUS" = c(14,3),"P/M" = c(1,-3)) lineup_extended ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} lineup_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757), "DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) lineup_team_stats ``` * Data set that represents the statistics of the rival team. ```{r} lineup_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626), "Percentage FT" = c(0.781), "ORB" = c(668), "DRB" = c(2333),"TRB" = c(3001), "AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) lineup_rival_stats ``` ## Play Data Set If we want to perform the analysis of play statistics, we must have the following data sets: * Data set that represents play statistics. + Data set created with the play_data_adjustment function ```{r} play_stats <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play_stats <- play_data_adjustment(play_stats) play_stats ``` + Data set created with the same structure as the one generated by the play_data_adjustment function ```{r} play <- data.frame("Name" = c("Sabonis ","Team"), "GP" = c(62,71),"PTS" = c(387,0), "FG" = c(155,1), "FGA" = c(281,1),"3P" = c(6,1),"3PA" = c(18,1), "FT" = c(39,1), "FTA" = c(53,1),"ANDONE" = c(12,1), "AST" = c(0,1), "TOV" = c(27,1)) play ``` * Data set that represents team statistics. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} play_team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027), "Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728), "Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612), "BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) play_team_stats ``` + Data set that represents the statistics of the rival team. ```{r} play_rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) play_rival_stats ``` ## Team Data Set If we want to perform the analysis of team statistics, we must have the following data sets: * Data set that represents the statistics of the team. + Data set created with the team_stats function: ```{r} tm_stats <- team_stats(individual_stats) tm_stats ``` + Data set created with the same structure as the one generated by the team_stats function ```{r} team_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(3006), "FGA" = c(6269),"Percentage FG" = c(0.48), "3P" = c(782),"3PA" = c(2242), "Percentage 3P" = c(0.349), "2P" = c(2224), "2PA" = c(4027),"Percentage 2P" = c(0.552), "FT" = c(1260),"FTA FG" = c(1728),"Percentage FT" = c(0.729), "ORB" = c(757),"DRB" = c(2490),"TRB" = c(3247),"AST" = c(1803), "STL" = c(612),"BLK" = c(468),"TOV" = c(1077),"PF" = c(1471), "PTS" = c(8054), "+/-" = c(0)) team_stats ``` * Data set that represents the statistics of the rival team. ```{r} rival_stats <- data.frame("G" = c(71), "MP" = c(17090), "FG" = c(2773), "FGA" = c(6187),"Percentage FG" = c(0.448), "3P" = c(827),"3PA" = c(2373),"Percentage 3P" = c(0.349), "2P" = c(1946), "2PA" = c(3814),"Percentage 2P" = c(0.510), "FT" = c(1270),"FTA FG" = c(1626),"Percentage FT" = c(0.781), "ORB" = c(668),"DRB" = c(2333),"TRB" = c(3001),"AST" = c(1662), "STL" = c(585),"BLK" = c(263),"TOV" = c(1130),"PF" = c(1544), "PTS" = c(7643), "+/-" = c(0)) rival_stats ``` Once the data sets have been created, we must choose which function or functions we want to use. Below are the different functions that the package has: # Functions for individual statistics For individual statistics there are the following functions: * __individuals_advance_stats.__ Function that allows advanced statistics calculation. * __individuals_defensive_actual_floor_stats.__ Function that allows the calculation of the current defensive statistics. * __individuals_defensive_estimated_floor_stats.__ Function that allows the calculation of the estimated defensive statistics. * __individuals_games_adder.__ Function that allows the sum of two different individual statistics. * __individuals_ofensive_floor_stats.__ Function that allows the calculation of offensive statistics. * __individuals_stats_per_game.__ Function that allows the calculation of statistics per game. * __individuals_stats_per_minutes.__ Function that allows the calculation of statistics per minutes. * __individuals_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. Below is an example of how each function works and what the input parameters should be for these: ## individuals_advance_stats For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} advanced_stats <- individuals_advance_stats(individual,indi_team_stats,indi_rival_stats) advanced_stats ``` ## individuals_defensive_actual_floor_stats For this function we will have to enter defensive individual statistics, team statistics and rival team statistics: ```{r} defensive_actual_stats <- individuals_defensive_actual_floor_stats(defensive,indi_team_stats,indi_rival_stats) defensive_actual_stats ``` ## individuals_defensive_estimated_floor_stats For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} defensive_estimated_stats <- individuals_defensive_estimated_floor_stats(individual,indi_team_stats,indi_rival_stats) defensive_estimated_stats ``` ## individuals_games_adder. For this function we will have to enter the two individual statistics previously calculated which we want to add the statistics: ```{r} games_adder <- individuals_games_adder(individual,individual) games_adder ``` ## individuals_ofensive_floor_stats. For this function we will have to enter individual statistics, team statistics and rival team statistics: ```{r} ofensive_stats <- individuals_ofensive_floor_stats(individual,indi_team_stats,indi_rival_stats) ofensive_stats ``` ## individuals_stats_per_game For this function we will have to enter individual statistics: ```{r} per_game_stats <- individuals_stats_per_game(individual) per_game_stats ``` ## individuals_stats_per_minutes For this function we will have to enter the individual statistics and the number of minutes to which we want to project the statistics: ```{r} per_minutes_stats <- individuals_stats_per_minutes(individual,36) per_minutes_stats ``` ## individuals_stats_per_possesion For this function we will have to enter the individual statistics, the team statistics, the rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} per_poss_stats <- individuals_stats_per_possesion(individual,indi_team_stats,indi_rival_stats,100,48) per_poss_stats ``` # Functions for lineup statistics For individual statistics there are the following functions: * __lineups_advance_stats.__ Function that allows advanced statistics calculation. * __lineups_backcourt.__ Function that allows searching for backcourt players. * __lineups_comparator_stats.__ Function that allows comparison between the statistics of the lineup and the rival lineup * __lineups_games_adder.__ Function that allows the sum of two different lineup statistics. * __lineups_paint.__ Function that allows searching for paint players. * __lineups_players.__ Function that allows searching for players by position. * __lineups_searcher.__ Function that allows searching for players within the data frame. * __lineups_separator.__ Function that allows you to obtain the statistics of the lineups or the rivals against those lineups. * __lineups_stats_per_possesion.__ Function that allows the calculation of statistics per possessions Below is an example of how each function works and what the input parameters should be for these: ## lineups_advance_stats For this function we will have to enter extended lineup statistics and the number of minutes that a single game lasts: ```{r} lnp_advanced_stats <- lineups_advance_stats(lineup_extended,48) lnp_advanced_stats ``` ## lineups_backcourt For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_bs_backcourt <- lineups_backcourt(lineup_basic) lnp_bs_backcourt ``` ```{r} lnp_ex_backcourt <- lineups_backcourt(lineup_extended) lnp_ex_backcourt ``` ## lineups_comparator_stats For this function we will have to enter extended lineup statistics: ```{r} lnp_comparator <- lineups_comparator_stats(lineup_extended,48) lnp_comparator ``` ## lineups_games_adder For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_games_adder <- lineups_games_adder(lineup_basic,lineup_basic) lnp_games_adder ``` ## lineups_paint For this function we will have to enter basic lineup statistics or extended lineup statistics: ```{r} lnp_bc_paint <- lineups_paint(lineup_basic) lnp_bc_paint ``` ```{r} lnp_ex_paint <- lineups_paint(lineup_extended) lnp_ex_paint ``` ## lineups_players For this function we will have to enter basic lineup statistics or extended lineup statistics and the number of position that we want to find: ```{r} lnp_bc_players <- lineups_players(lineup_basic,5) lnp_bc_players ``` ```{r} lnp_ex_players <- lineups_players(lineup_extended,5) lnp_ex_players ``` ## lineups_searcher For this function we will have to enter basic lineup statistics or extended lineup statistics, the name of the players that we want to find and the number of players that we want to find: ```{r} lnp_bc_searcher <- lineups_searcher(lineup_basic,1,"James","","","") lnp_bc_searcher ``` ```{r} lnp_ex_searcher <- lineups_searcher(lineup_extended,1,"James","","","") lnp_ex_searcher ``` ## lineups_separator For this function we will have to enter extended lineup statistics and the indicator of what type of separation we want to make: ```{r} lnp_ex_sep_one <- lineups_separator(lineup_extended,1) lnp_ex_sep_one ``` ```{r} lnp_ex_sep_two <- lineups_separator(lineup_extended,2) lnp_ex_sep_two ``` ## lineups_stats_per_possesion For this function we will have to enter basic lineup statistics, team statistics, rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} lnp_per_poss_stats <- lineups_stats_per_possesion(lineup_basic,lineup_team_stats,lineup_rival_stats,100,48) lnp_per_poss_stats ``` # Functions for play statistics For individual statistics there are the following functions: * __play_advance_stats.__ Function that allows advanced statistics calculation. * __play_games_adder.__ Function that allows the sum of two different play statistics. * __play_stats_per_game.__ Function that allows the calculation of statistics per game. * __play_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. * __play_team_stats.__ Function that allows to carry out the statistics of the team. Below is an example of how each function works and what the input parameters should be for these: ## play_advance_stats For this function we will have to enter play statistics: ```{r} play_adv_stats <- play_advance_stats(play_stats) play_adv_stats ``` ## play_games_adder For this function we will have to enter play statistics: ```{r} pl_game_adder <- play_games_adder(play_stats,play_stats) pl_game_adder ``` ## play_stats_per_game For this function we will have to enter play statistics: ```{r} play_per_game_stat <- play_stats_per_game(play_stats) play_per_game_stat ``` ## play_stats_per_possesion For this function we will have to enter the play statistics, the team statistics, the rival team statistics, the number of minutes that a single game lasts and the number of possessions to which we want to project the statistics: ```{r} play_per_poss_stats <- play_stats_per_possesion(play_stats,play_team_stats,play_rival_stats,100,48) play_per_poss_stats ``` ## play_team_stats For this function we will have to enter play statistics: ```{r} play_team_stats <- play_team_stats(play_stats) play_team_stats ``` # Functions for team statistics For individual statistics there are the following functions: * __team_advanced_stats.__ Function that allows advanced statistics calculation. * __team_stats_per_game.__ Function that allows the calculation of statistics per game. * __team_stats_per_minutes.__ Function that allows the calculation of statistics per minutes. * __team_stats_per_possesion.__ Function that allows the calculation of statistics per possessions. Below is an example of how each function works and what the input parameters should be for these: ## team_advanced_stats For this function we will have to enter the team statistics and the rival team statistics: ```{r} team_adv_stats <- team_advanced_stats(team_stats,rival_stats,48) team_adv_stats ``` ## team_stats_per_game For this function we will have to enter the team statistics: ```{r} team_per_game_stat <- team_stats_per_game(team_stats) team_per_game_stat ``` ## team_stats_per_minutes For this function we will have to enter the team statistics and the number of minutes to which we want to project the statistics: ```{r} team_per_minutes_stat <- team_stats_per_minutes(team_stats,36) team_per_minutes_stat ``` ## team_stats_per_possesion For this function we will have to enter the team statistics, the rival team statistics and the number of possessions to which we want to project the statistics:: ```{r} team_per_poss_stat <- team_stats_per_possesion(team_stats,rival_stats,100) team_per_poss_stat ```
/scratch/gouwar.j/cran-all/cranData/AdvancedBasketballStats/vignettes/BasketballAdvancedStats.Rmd
#' \code{AeRobiology} package #' #' AeRobiology computational tool #' #' @docType package #' @name AeRobiology NULL ## quiets concerns of R CMD check re: the .'s that appear in pipelines if(getRversion() >= "2.15.1") utils::globalVariables(c(".", ":=", "DOY", "Max", "Mean", "Min", "Risk", "Year", "en.jd", "j.days", "jd", "opacity", "phen", "pk.jd", "pollen", "seasons", "size", "sm.ps", "st.jd", "strokeWidth", "value", "week", "wt", "x", "variable", "Hour", "location", "percent"),add=TRUE)
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/AeRobiology.R
#' 3-hourly pollen data of Munich and Viechtach (2018), obtained automatically by BAA500 #' #' A dataset containing information of 3-hourly concentrations of pollen in the atmosphere of Munich (DEBIED) and Viechtach (DEVIEC) during the year 2018. Pollen types included: \emph{"Poaceae"} and \emph{"Pinus"}. #' @format Time series of 3-hours pollen concentrations expressed as pollen grains / m3 of air. #' @details Data were obtained by the automatic pollen monitor BAA500 from Munich and Viechtach in Bavaria (Germany) \code{data("POMO_pollen")}, supplied by the public ePIN Network supported by the Bavarian Government. The ePIN Network was built by Das Bayerische Landesamt für Gesundheit und Lebensmittelsicherheit (LGL) in collaboration with Zentrum Allergie und Umwelt (ZAUM). #'@references Oteros, J., et al., ... & Buters, J. T. (2019). Building an automatic Pollen Monitoring Network (ePIN): Selection of optimal sites by clustering pollen stations. #'@references Oteros, J., Pusch, G., Weichenmeier, I., Heimann, U., Mueller, R., Roeseler, S., ... & Buters, J. T. (2015). Automatic and online pollen monitoring. #' @references Hirst, J.M., 1952. AN AUTOMATIC VOLUMETRIC SPORE TRAP. Ann. Appl. Biol. 39, 257_265. #' @references VDI 4252_4. (2016). Bioaerosole und biologische Agenzien_Ermittlung von Pollen und Sporen in der Aussenluft unterVerwendung einer volumetrischen Methode fuer einMessnetz zu allergologischen Zwecken. VDI_Richtlinie4252 Blatt 4, Entwurf. VDI/DIN_Handbuch Reinhaltungder Luft, Band 1a: Beuth, Berlin #' @source \url{https://www.lgl.bayern.de/} #' @source \url{https://www.zaum-online.de/} "POMO_pollen"
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/POMO_pollen.R
#' Calculating and Plotting Trends of Pollen Data (summary plot). #' #' Function to calculate the main seasonal indexes of the pollen season (\emph{Start Date}, \emph{Peak Date}, \emph{End Date} and \emph{Pollen Integral}). Trends analysis of the parameters over the seasons. Summary dot plot showing the distribution of the main seasonal indexes over the years. #' #' @param data A \code{data.frame} object. This \code{data.frame} should include a first column in format \code{Date} and the rest of columns in format \code{numeric} belonging to each pollen type by column. #' @param interpolation A \code{logical} value specifying if the visualization shows the gaps in the inputs data (\code{interpolation = FALSE}) or if an interpolation method is used for filling the gaps (\code{interpolation = TRUE}). By default, \code{interpolation = TRUE}. #' @param int.method A \code{character} string with the name of the interpolation method to be used. The implemented methods that may be used are: \code{"lineal"}, \code{"movingmean"}, \code{"tseries"} or \code{"spline"}. By default, \code{int.method = "lineal"}. #' @param export.plot A \code{logical} value specifying if a plot will be exported or not. If \code{FALSE} graphical results will only be displayed in the active graphics window. If \code{TRUE} graphical results will be displayed in the active graphics window and also one pdf/png file will be saved within the \emph{plot_AeRobiology} directory automatically created in the working directory. By default, \code{export.plot = TRUE}. #' @param export.format A \code{character} string specifying the format selected to save the plot. The implemented formats that may be used are: \code{"pdf"} or \code{"png"}. By default, \code{export.format = "pdf"}. #' @param export.result A \code{logical} value. If \code{export.result = TRUE}, a table is exported with the extension \emph{.xlsx}, in the directory \emph{table_AeRobiology}. This table has the information about the \code{slope} \emph{"beta coefficient of a lineal model using as predictor the year and as dependent variable one of the main pollen season indexes"}. The information is referred to the main pollen season indexes: \emph{Start Date}, \emph{Peak Date}, \emph{End Date} and \emph{Pollen Integral}. #' @param method A \code{character} string specifying the method applied to calculate the pollen season and the main seasonal parameters. The implemented methods that can be used are: \code{"percentage"}, \code{"logistic"}, \code{"moving"}, \code{"clinical"} or \code{"grains"}. By default, \code{method = "percentage"} (\code{perc = 95}\%). A more detailed information about the different methods for defining the pollen season may be consulted in the function \code{\link{calculate_ps}}. #' @param quantil A \code{numeric} value (between 0 and 1) indicating the quantile of data to be displayed in the graphical output of the function. \code{quantil = 1} would show all the values, however a lower quantile will exclude the most extreme values of the sample. To split the parameters using a different sampling units (e.g. dates and pollen concentrations) can be used low vs high values of \code{quantil} argument (e.g. 0.5 vs 1). Also can be used an extra argument: \code{split}. By default, \code{quantil = 0.75}. \code{quantil} argument can only be applyed when \code{split = FALSE}. #' @param significant A \code{numeric} value indicating the significant level to be considered in the linear trends analysis. This \emph{p} level is displayed in the graphical output of the function. By default, \code{significant = 0.05}. #' @param split A \code{logical} argument. If \code{split = TRUE}, the plot is separated in two according to the nature of the variables (i.e. dates or pollen concentrations). By default, \code{split = TRUE}. #'@param result A \code{character} object with the definition of the object to be produced by the function. If \code{result == "plot"}, the function returns a list of objects of class \pkg{ggplot2}; if \code{result == "table"}, the function returns a \pkg{data.frame}. By default, \code{result = "table"}. #' @param ... Additional arguments for the function \code{\link{calculate_ps}} are also accepted. #' @details This function allows to study time series trends of the pollen season. Even though the package was originally designed to treat aeropalynological data, it can be used to study many other atmospheric components (e.g., bacteria in the air, fungi, insects ...) \emph{(Buters et al., 2018; Oteros et al., 2019)}. The study of trends in pollen time series is a common approach to study the impact of climate change or other environmental factors on vegetation (Galan et al., 2016; Garcia_Mozo et al., 2016; Recio et al., 2018). This tool can also be useful for studying trends in other fields (Oteros et al., 2015). #' @return If \code{result == "plot"}, the function returns a list of objects of class \pkg{ggplot2}; if \code{result == "table"}, the function returns a \pkg{data.frame} with the hourly patterns. #' The plot is of the class \pkg{ggplot2} or a list of plots of the class \pkg{ggplot2} (depending on the argument \code{split}). This is a combined dot plot showing the trends (\emph{slope} and \emph{p} value) of the main seasonal features.\cr #' The object of the class \code{data.frame} has the information about the \code{slope} \emph{(beta coefficient of a lineal model using as predictor the year and as dependent variable one of the main pollen season indexes)}. The information is referred to the main pollen season indexes: \emph{Start Date}, \emph{Peak Date}, \emph{End Date} and \emph{Pollen Integral}. #' #' @references Buters, J. T. M., Antunes, C., Galveias, A., Bergmann, K. C., Thibaudon, M., Galan, C., ... & Oteros, J. (2018). Pollen and spore monitoring in the world. \emph{Clinical and translational allergy}, 8(1), 9. #' @references Galan, C., Alcazar, P., Oteros, J., Garcia_Mozo, H., Aira, M. J., Belmonte, J., ... & Perez_Badia, R. (2016). Airborne pollen trends in the Iberian Peninsula. \emph{Science of the Total Environment}, 550, 53_59. #' @references Garcia_Mozo, H., Oteros, J. A., & Galan, C. (2016). Impact of land cover changes and climate on the main airborne pollen types in Southern Spain. \emph{Science of the Total Environment}, 548, 221_228. #' @references Oteros, J., Garcia_Mozo, H., Botey, R., Mestre, A., & Galan, C. (2015). Variations in cereal crop phenology in Spain over the last twenty_six years (1986_2012). \emph{Climatic Change}, 130(4), 545_558. #' @references Oteros, J., Bartusel, E., Alessandrini, F., Nunez, A., Moreno, D. A., Behrendt, H., ... & Buters, J. (2019). Artemisia pollen is the main vector for airborne endotoxin. \emph{Journal of Allergy and Clinical Immunology}. #' @references Recio, M., Picornell, A., Trigo, M. M., Gharbi, D., Garcia_Sanchez, J., & Cabezudo, B. (2018). Intensity and temporality of airborne Quercus pollen in the southwest Mediterranean area: Correlation with meteorological and phenoclimatic variables, trends and possible adaptation to climate change. \emph{Agricultural and Forest Meteorology}, 250, 308_318. #' @seealso \code{\link{calculate_ps}}; \code{\link{plot_trend}} #' @examples data("munich_pollen") #' @examples analyse_trend(munich_pollen, interpolation = FALSE, export.result = FALSE, export.plot = FALSE) #' @importFrom graphics plot #' @importFrom utils data #' @importFrom ggplot2 aes element_blank element_text geom_point geom_vline ggplot guide_legend guides labs scale_colour_manual scale_fill_discrete scale_fill_gradientn scale_x_continuous theme theme_bw #' @importFrom grDevices dev.off pdf png rainbow #' @importFrom grid grid.layout pushViewport viewport #' @importFrom lubridate is.POSIXt #' @importFrom stats as.formula complete.cases lm pf quantile #' @importFrom writexl write_xlsx #' @importFrom tidyr %>% #' @export analyse_trend <- function (data, interpolation = TRUE, int.method = "lineal", export.plot = TRUE, export.format = "pdf",# pdf, png export.result=TRUE, method="percentage", quantil=0.75, significant=0.05, split=TRUE, result="table", ...){ # Sys.setlocale(category = "LC_ALL", locale="english") ############################################# CHECK THE ARGUMENTS ############################# if(export.plot == TRUE){ifelse(!dir.exists(file.path("plot_AeRobiology")), dir.create(file.path("plot_AeRobiology")), FALSE)} if(export.result == TRUE){ifelse(!dir.exists(file.path("table_AeRobiology")), dir.create(file.path("table_AeRobiology")), FALSE)} data<-data.frame(data) if(class(data) != "data.frame") stop ("Please include a data.frame: first column with date, and the rest with pollen types") if(class(export.plot) != "logical") stop ("Please include only logical values for export.plot argument") if(export.format != "pdf" & export.format != "png") stop ("Please export.format only accept values: 'pdf' or 'png'") if(class(data[,1])[1]!="Date" & !is.POSIXt(data[,1])) {stop("Please the first column of your data must be the date in 'Date' format")} data[,1]<-as.Date(data[,1]) if(class(interpolation) != "logical") stop ("Please include only logical values for interpolation argument") if(class(split) != "logical") stop ("Please include only logical values for split argument") if(class(quantil) != "numeric") stop ("Please include only logical values for quantil argument") if(class(significant) != "numeric") stop ("Please include only logical values for significant argument") if(method != "percentage" & method != "logistic" & method != "moving" & method != "clinical" & method != "grains") stop ("Please method only accept values: 'percentage', 'logistic', 'moving', 'clinical' or 'grains'") # if(interpolation == TRUE){data <- interpollen(data, method = int.method)} colnames(data)[1]<-"Date" ## Function for p value lmp <- function (modelobject) { if (class(modelobject) != "lm") stop("Not an object of class 'lm' ") f <- summary(modelobject)$fstatistic p <- pf(f[1],f[2],f[3],lower.tail=F) attributes(p) <- NULL return(p) } datafram<-calculate_ps(data,method=method, interpolation = interpolation, int.method=int.method,plot=FALSE,...) variables<-c("st.jd","pk.jd","en.jd","sm.ps") trendtime<-data.frame() data_summary<- for (t in 1:length(unique(datafram$type))){ type<-unique(as.character(datafram$type))[t] for (v in 1:length(variables)){ tryCatch({ variable<-variables[v] temp<-datafram[which(datafram$type==type),c(1:2,which( colnames(datafram)==variable))] lm <- lm (as.formula(paste(variable,"~ seasons")), data= temp, x = TRUE, y = TRUE) tempframe<-data.frame(type=type,variable=variable,coef=summary(lm)$coefficients[2,1],p=lmp(lm)) trendtime<-rbind(trendtime,tempframe) }, error=function(e){ print(paste(type, variable, ": Error, linear model not calculated. Probably due to insufficient amount of years")) }) } print(type) } trendtimeresult<-trendtime ### Now start the rock and roll trendtime$variable<-as.factor(trendtime$variable) trendtime2<-trendtime trendtime2<-trendtime2[complete.cases(trendtime2),] sig<-paste("Significant (p<",significant,")", sep="") trendtime2$significant<-sig #trendtime2[which(trendtime2$p<=significant),"significant"]<-sig trendtime2[which(trendtime2$p>significant),"significant"]<-"Non Significant" trendtime2[which(trendtime2$p>significant),"p"]<-0.99 trendtime2[which(trendtime2$p!=0.99),"p"]<-0.01 trendtime2$variable<-as.character(trendtime2$variable) trendtime2[which(trendtime2$variable=="st.jd"),"variable"] <- "Start Date" trendtime2[which(trendtime2$variable=="pk.jd"),"variable"] <- "Peak Date" trendtime2[which(trendtime2$variable=="en.jd"),"variable"] <- "End Date" trendtime2[which(trendtime2$variable=="sm.ps"),"variable"] <- "Total Pollen" trendtime2$variable<-as.factor(as.character(trendtime2$variable)) trend_p1 <- ggplot(trendtime2, aes(x=coef, y=type))+ theme_bw()+ geom_vline(aes(xintercept=0), colour="red", linetype = "dashed", size=1)+ geom_point(aes(fill=as.numeric(variable), colour=trendtime2$significant, stroke=2-trendtime2$p*2),size=6, alpha=0.9,shape=21)+ scale_fill_gradientn(colours = rainbow(6), labels = levels(trendtime2$variable))+ scale_colour_manual(values = c("gray80","black"))+ scale_x_continuous(limits=c(-quantile(abs(trendtime2$coef),quantil),quantile(abs(trendtime2$coef),quantil)))+ labs(x= "slope", y="")+ guides(fill=guide_legend(title=NULL))+ theme(legend.position="top", legend.title = element_blank(), axis.text.y = element_text(face="italic")) filtertrend<-trendtime2[which(trendtime2$variable!="Total Pollen"),] filtertrend$variable<-as.factor(as.character(filtertrend$variable)) filtertrend$type<-as.factor(as.character(filtertrend$type)) trend_p2 <- ggplot(filtertrend, aes(x=coef, y=type))+ theme_bw()+ geom_vline(aes(xintercept=0), colour="red", linetype = "dashed", size=1)+ geom_point(aes(fill=filtertrend$variable, colour=filtertrend$significant, stroke=2-filtertrend$p*2),size=6, alpha=0.9,shape=21)+ scale_colour_manual(values = c("gray80","black"))+ scale_x_continuous(limits=c(-max(abs(filtertrend$coef), na.rm=T),max(abs(filtertrend$coef), na.rm=T)))+ labs(x= "slope", y="")+ guides(fill=guide_legend(title=NULL))+ theme(legend.position="top", legend.title = element_blank(), axis.text.y = element_text(face="italic")) filtertrend2<-trendtime2[which(trendtime2$variable=="Total Pollen"),] filtertrend2$variable<-as.factor(as.character(filtertrend2$variable)) filtertrend2$type<-as.factor(as.character(filtertrend2$type)) trend_p3 <- ggplot(filtertrend2, aes(x=coef, y=type))+ theme_bw()+ geom_vline(aes(xintercept=0), colour="red", linetype = "dashed", size=1)+ geom_point(aes( colour=filtertrend2$significant, stroke=2-filtertrend2$p*2),size=6, alpha=0.9,shape=21,fill="lightpink")+ scale_colour_manual(values = c("gray80","black"), name = "Total Pollen: ")+ scale_x_continuous(limits=c(-max(abs(filtertrend2$coef), na.rm=T),max(abs(filtertrend2$coef), na.rm=T)))+ labs(x= "slope", y="")+ theme(legend.position="top", axis.text.y = element_text(face="italic"))+ guides(fill=guide_legend(title="")) if (split == F){ analyse_trend<-trend_p1 if(export.plot == TRUE & export.format == "png") { png(paste0("plot_AeRobiology/analyse_trend",".png"), ...) plot(analyse_trend) dev.off() } if(export.plot == TRUE & export.format == "pdf") { pdf(paste0("plot_AeRobiology/analyse_trend", ".pdf")) plot(analyse_trend) dev.off() } }else{ analyse_trend<-list() analyse_trend[[1]]<-trend_p2 analyse_trend[[2]]<-trend_p3 if(export.plot == TRUE & export.format == "png") { png("plot_AeRobiology/analyse_trend_split.png") pushViewport(viewport(layout=grid.layout(2,1))) vplayout<-function(x,y) viewport(layout.pos.row = x, layout.pos.col=y) print(trend_p2, vp = vplayout(1,1)) print(trend_p3, vp = vplayout(2,1)) dev.off() } if(export.plot == TRUE & export.format == "pdf") { pdf("plot_AeRobiology/analyse_trend_split.pdf", ...) pushViewport(viewport(layout=grid.layout(2,1))) vplayout<-function(x,y) viewport(layout.pos.row = x, layout.pos.col=y) print(trend_p2, vp = vplayout(1,1)) print(trend_p3, vp = vplayout(2,1)) dev.off() } } lista<-list() lista[["trends"]]<-trendtime lista [["Information"]] <- data.frame( Attributes = c("st.jd", "pk.jd", "en.jd", "sm.ps", "coef", "p", "", "", "Package", "Authors"), Description = c("Start-date (day of the year)","Peak-date (day of year)", "End-date (day of the year)", "Pollen integral", "Slope of the linear trend", "Significance level of the linear trend", "", "", "AeRobiology", "Jesus Rojo, Antonio Picornell & Jose Oteros")) if (export.result == TRUE) { write_xlsx(lista, "table_AeRobiology/summary_of_trends.xlsx") } if (result=="table"){ return(trendtimeresult) }else if (result=="plot"){ return(analyse_trend) } }
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/analyse_trend.R
#' Estimation of the Main Parameters of the Pollen Season #' #' Function to calculate the main parameters of the pollen season with regard to phenology and pollen intensity from a historical database of several pollen types. The function can use the most common methods in the definition of the pollen season. #' #' @param data A \code{data.frame} object including the general database where calculation of the pollen season must be applied. This \code{data.frame} must include a first column in \code{Date} format and the rest of columns in \code{numeric} format belonging to each pollen type by column. #' @param method A \code{character} string specifying the method applied to calculate the pollen season and the main parameters. The implemented methods that can be used are: \code{"percentage"}, \code{"logistic"}, \code{"moving"}, \code{"clinical"} or \code{"grains"}. A more detailed information about the different methods for defining the pollen season may be consulted in \strong{Details}. #' @param th.day A \code{numeric} value. The number of days whose pollen concentration is bigger than this threshold is calculated for each year and pollen type. This value will be obtained in the results of the function. The \code{th.day} argument will be \code{100} by default. #' @param perc A \code{numeric} value ranging \code{0_100}. This argument is valid only for \code{method = "percentage"}. This value represents the percentage of the total annual pollen included in the pollen season, removing \code{(100_perc)/2\%} of the total pollen before and after of the pollen season. The \code{perc} argument will be \code{95} by default. #' @param def.season A \code{character} string specifying the method for selecting the best annual period to calculate the pollen season. The pollen seasons may occur within the natural year between two years. The implemented options that can be used are: \code{"natural"}, \code{"interannual"} or \code{"peak"}. The \code{def.season} argument will be \code{"natural"} by default. A more detailed information about the different methods for selecting the best annual period to calculate the pollen season may be consulted in \strong{Details}. #' @param reduction A \code{logical} value. This argument is valid only for the \code{"logistic"} method. If \code{FALSE} the reduction of the pollen data is not applicable. If \code{TRUE} a reduction of the peaks above a certain level (\code{red.level} argument) will be carried out before the definition of the pollen season. The \code{reduction} argument will be \code{FALSE} by default. A more detailed information about the reduction process may be consulted in \strong{Details}. #' @param red.level A \code{numeric} value ranging \code{0_1} specifying the percentile used as level to reduce the peaks of the pollen series before the definition of the pollen season. This argument is valid only for the \code{"logistic"} method. The \code{red.level} argument will be \code{0.90} by default, specifying the percentile 90. #' @param derivative A \code{numeric} (\code{integer}) value belonging to options of \code{4}, \code{5} or \code{6} specifying the derivative that will be applied to calculate the asymptotes which determines the pollen season using the \code{"logistic"} method. This argument is valid only for the \code{"logistic"} method. The \code{derivative} argument will be \code{5} by default. More information may be consulted in \strong{Details}. #' @param man A \code{numeric} (\code{integer}) value specifying the order of the moving average applied to calculate the pollen season using the \code{"moving"} method. This argument is valid only for the \code{"moving"} method. The \code{man} argument will be \code{11} by default. #' @param th.ma A \code{numeric} value specifying the threshold used for the \code{"moving"} method for defining the beginning and the end of the pollen season. This argument is valid only for the \code{"moving"} method. The \code{th.ma} argument will be \code{5} by default. #' @param n.clinical A \code{numeric} (\code{integer}) value specifying the number of days which must exceed a given threshold (\code{th.pollen} argument) for defining the beginning and the end of the pollen season. This argument is valid only for the \code{"clinical"} method. The \code{n.clinical} argument will be \code{5} by default. #' @param window.clinical A \code{numeric} (\code{integer}) value specifying the time window during which the conditions must be evaluated for defining the beginning and the end of the pollen season using the \code{"clinical"} method. This argument is valid only for the \code{"clinical"} method. The \code{window.clinical} argument will be \code{7} by default. #' @param window.grains A \code{numeric} (\code{integer}) value specifying the time window during which the conditions must be evaluated for defining the beginning and the end of the pollen season using the \code{"grains"} method. This argument is valid only for the \code{"grains"} method. The \code{window.grains} argument will be \code{5} by default. #' @param th.pollen A \code{numeric} value specifying the threshold that must be exceeded during a given number of days (\code{n.clinical} or \code{window.grains} arguments) for defining the beginning and the end of the pollen season using the \code{"clinical"} or \code{"grains"} methods. This argument is valid only for the \code{"clinical"} or \code{"grains"} methods. The \code{th.pollen} argument will be \code{10} by default. #' @param th.sum A \code{numeric} value specifying the pollen threshold that must be exceeded by the sum of daily pollen during a given number of days (\code{n.clinical} argument) exceeding a given daily threshold (\code{th.pollen} argument) for defining the beginning and the end of the pollen season using the \code{"clinical"} method. This argument is valid only for the \code{"clinical"} method. The \code{th.sum} argument will be \code{100} by default. #' @param type A \code{character} string specifying the parameters considered according to a specific pollen type for calculating the pollen season using the \code{"clinical"} method. The implemented pollen types that may be used are: \code{"birch"}, \code{"grasses"}, \code{"cypress"}, \code{"olive"} or \code{"ragweed"}. As result for selecting any of these pollen types the parameters \code{n.clinical}, \code{window.clinical}, \code{th.pollen} and \code{th.sum} will be automatically adjusted for the \code{"clinical"} method. If no pollen types are specified (\code{type = "none"}), these parameters will be considered by the user. This argument is valid only for the \code{"clinical"} method. The \code{type} argument will be \code{"none"} by default. #' @param interpolation A \code{logical} value. If \code{FALSE} the interpolation of the pollen data is not applicable. If \code{TRUE} an interpolation of the pollen series will be applied to complete the gaps with no data before the calculation of the pollen season. The \code{interpolation} argument will be \code{TRUE} by default. A more detailed information about the interpolation method may be consulted in \strong{Details}. #' @param int.method A \code{character} string specifying the method selected to apply the interpolation method in order to complete the pollen series. The implemented methods that may be used are: \code{"lineal"}, \code{"movingmean"}, \code{"spline"} or \code{"tseries"}. The \code{int.method} argument will be \code{"lineal"} by default. #' @param maxdays A \code{numeric} (\code{integer} value) specifying the maximum number of consecutive days with missing data that the algorithm is going to interpolate. If the gap is bigger than the argument value, the gap will not be interpolated. Not valid with \code{int.method = "tseries"}. The \code{maxdays} argument will be \code{30} by default. #' @param result A \code{character} string specifying the output for the function. The implemented outputs that may be obtained are: \code{"table"} and \code{"list"}. The argument \code{result} will be \code{"table"} by default. #' @param plot A \code{logical} value specifying if a set of plots based on the definition of the pollen season will be shown in the plot history or not. If \code{FALSE} graphical results will not be shown. If \code{TRUE} a set of plots will be shown in the plot history. The \code{plot} argument will be \code{TRUE} by default. #' @param export.plot A \code{logical} value specifying if a set of plots based on the definition of the pollen season will be saved in the workspace. If \code{TRUE} a \emph{pdf} file for each pollen type showing graphically the definition of the pollen season for each studied year will be saved within the \emph{plot_AeRobiology} directory created in the working directory. The \code{plot} argument will be \code{FALSE} by default. #' @param export.result A \code{logical} value specifying if a excel file including all parameters for the definition of the pollen season saved in the working directoty will be required or not. If \code{FALSE} the results will not exported. If \code{TRUE} the results will be exported as \emph{xlsx} file including all parameters calculated from the definition of the pollen season within the \emph{table_AeRobiology} directory created in the working directory. The \code{export.result} argument will be \code{FALSE} by default. #' @details This function allows to calculate the pollen season using five different methods which are described below. After calculating the start_date, end_date and peak_date for the pollen season all rest of parameters have been calculated as detailed in \strong{Value} section. #' \itemize{ #' \item \code{"percentage"} method. This is a commonly used method for defining the pollen season based on the elimination of a certain percentage in the beginning and the end of the pollen season \emph{(Nilsson and Persson, 1981; Andersen, 1991)}. For example if the pollen season is based on the 95\% of the total annual pollen (\code{"perc" = 95}), the start_date of the pollen season is marked as the day in which 2.5\% of the total pollen is registered and the end_date of the pollen season is marked as the day in which 97.5\% of the total pollen is registered. #' \item \code{"logistic"} method. This method was developed by \emph{Ribeiro et al. (2007)} and modified by \emph{Cunha et al. (2015)}. It is based on fitting annually a non_linear logistic regression model to the daily accumulated curve for each pollen type. This logistic function and the different derivatives were considered to calculate the start_date and end_date of the pollen season, based on the asymptotes when pollen amounts are stabilized on the beginning and the end of the accumulated curve. For more information about the method to see \emph{Ribeiro et al. (2007)} and \emph{Cunha et al. (2015)}. Three different derivatives may be used (\code{derivative} argument) \code{4}, \code{5} or \code{6} that represent from higher to lower restrictive criterion for defining the pollen season. This method may be complemented with an optional method for reduction the peaks values (\code{reduction = TRUE}), thus avoiding the effect of the great influence of extreme peaks. In this sense, peaks values will be cut below a certain level that the user may select based on a percentile analysis of peaks. For example, \code{red.level = 0.90} will cut all peaks above the percentile \code{90}. #' \item \code{"moving"} method. This method is proposed the first time by the authors of this package. The definition of the pollen season is based on the application of a moving average to the pollen series in order to obtain the general seasonality of the pollen curve avoiding the great variability of the daily fluctuations. Thus, the start_date and the end_date will be established when the curve of the moving average reaches a given pollen threshold (\code{th.ma} argument). Also the order of the moving average may be customized by the user (\code{man} argument). By default, \code{man} = 11 and \code{th.ma} = 5. #' \item \code{"clinical"} method. This method was proposed by \emph{Pfaar et al. (2017)}. It is based on the expert consensus in relation to pollen exposure and the relationship with allergic symptoms derived of the literature. Different periods may be defined by this method: the pollen season, the high pollen season and the high pollen days. The start_date and end_date of the pollen season were defined as a certain number of days (\code{n.clinical} argument) within a time window period (\code{window.clinical} argument) exceeding a certain pollen threshold (\code{th.pollen} argument) which summation is above a certain pollen sum (\code{th.sum} argument). All these parameters are established for each pollen type according to \emph{Pfaar et al. (2017)} and using the \code{type} argument these parameters may be automatically adjusted for the specific pollen types (\code{"birch"}, \code{"grasses"}, \code{"cypress"}, \code{"olive"} or \code{"ragweed"}). Furthermore, the user may change all parameters to do a customized definition of the pollen season. The start_date and end_date of the high pollen season were defined as three consecutive days exceeding a certain pollen threshold (\code{th.day} argument). The number of high pollen days will also be calculated exceeding this pollen threshold (\code{th.day}). For more information about the method to see \emph{Pfaar et al. (2017)}. #' \item \code{"grains"} method. This method was proposed by \emph{Galan et al. (2001)} originally in olive pollen but after also applied in other pollen types. The start_date and end_date of the pollen season were defined as a certain number of days (\code{window.grains} argument) exceeding a certain pollen threshold (\code{th.pollen} argument). For more information about the method to see \emph{Galan et al. (2001)}. #' } #' The pollen season of the species may occur during the natural year (Calendar year: from 1. January to 31. December) or the start_date and the end_date of the pollen season may happen in two different natural years (or calendar years). This consideration has been taken into account and in this package different method for defining the period for calculating the pollen season have been implemented. In this sense, the \code{def.season} argument has been incorporated in three options: #' \itemize{ #' \item \code{"natural"}: considering the pollination year as natural year from 1st January to 31th December for defining the start_dates and end_dates of the pollen season for each pollen types. #' \item \code{"interannual"}: considering the pollination year from 1st June to 31th May for defining the start_dates and end_dates of the pollen season for each pollen types. #' \item \code{"peak"}: considering a customized pollination year for each pollen types calculated as 6 previous months and 6 later months from the average peak_date. #' } #' Pollen time series frequently have different gaps with no data and this fact could be a problem for the calculation of specific methods for defining the pollen season even providing incorrect results. In this sense by default a linear interpolation will be carried out to complete these gaps before to define the pollen season (\code{interpolation = TRUE}). Additionally, the users may select other interpolation methods using the \code{int.method} argument, as \code{"lineal"}, \code{"movingmean"}, \code{"spline"} or \code{"tseries"}. For more information to see the \code{\link{interpollen}} function. #' @return This function returns different results:\cr #' \code{data.frame} when \code{result = "table"} including the main parameters of the pollen season with regard to phenology and pollen intensity as: #' \itemize{ #' \item \strong{type}: pollen type #' \item \strong{seasons}: year of the beginning of the season #' \item \strong{st.dt}: start_date (date) #' \item \strong{st.jd}: start_date (day of the year) #' \item \strong{en.dt}: end_date (date) #' \item \strong{en.jd}: end_date (day of the year) #' \item \strong{ln.ps}: length of the season #' \item \strong{sm.tt}: total sum #' \item \strong{sm.ps}: pollen integral #' \item \strong{pk.val}: peak value #' \item \strong{pk.dt}: peak_date (date) #' \item \strong{pk.jd}: peak_date (day of year) #' \item \strong{ln.prpk}: length of the pre_peak period #' \item \strong{sm.prpk}: pollen integral of the pre_peak period #' \item \strong{ln.pspk}: length of the post_peak period #' \item \strong{sm.pspk}: pollen integral of the post_peak period #' \item \strong{daysth}: number of days with more than 100 pollen grains #' \item \strong{st.dt.hs}: start_date of the High pollen season (date, only for clinical method) #' \item \strong{st.jd.hs}: start_date of the High pollen season (day of the year, only for clinical method) #' \item \strong{en.dt.hs}: end_date of the High pollen season (date, only for clinical method) #' \item \strong{en.jd.hs}: end_date of the High pollen season (day of the year, only for clinical method) #' } #' \code{list} when \code{result = "list"} including the main parameters of the pollen season, one pollen type by element #' \code{plots} when \code{plot = TRUE} showing graphically the definition of the pollen season for each studied year in the plot history. #' If \code{export.result = TRUE} this \code{data.frame} will also be exported as \emph{xlsx} file within the \emph{table_AeRobiology} directory created in the working directory. If \code{export.result = FALSE} the results will also be showed as list object named \code{list.ps}. \cr #' If \code{export.plot = TRUE} a \emph{pdf} file for each pollen type showing graphically the definition of the pollen season for each studied year will be saved within the \emph{plot_AeRobiology} directory created in the working directory. #' @references Andersen, T.B., 1991. A model to predict the beginning of the pollen season. \emph{Grana}, 30(1), pp.269_275. #' @references Cunha, M., Ribeiro, H., Costa, P. and Abreu, I., 2015. A comparative study of vineyard phenology and pollen metrics extracted from airborne pollen time series. \emph{Aerobiologia}, 31(1), pp.45_56. #' @references Galan, C., Garcia_Mozo, H., Carinanos, P., Alcazar, P. and Dominguez_Vilches, E., 2001. The role of temperature in the onset of the \emph{Olea europaea} L. pollen season in southwestern Spain. \emph{International Journal of Biometeorology}, 45(1), pp.8_12. #' @references Nilsson, S. and Persson, S., 1981. Tree pollen spectra in the Stockholm region (Sweden), 1973_1980. \emph{Grana}, 20(3), pp.179_182. #' @references Pfaar, O., Bastl, K., Berger, U., Buters, J., Calderon, M.A., Clot, B., Darsow, U., Demoly, P., Durham, S.R., Galan, C., Gehrig, R., Gerth van Wijk, R., Jacobsen, L., Klimek, L., Sofiev, M., Thibaudon, M. and Bergmann, K.C., 2017. Defining pollen exposure times for clinical trials of allergen immunotherapy for pollen_induced rhinoconjunctivitis_an EAACI position paper. \emph{Allergy}, 72(5), pp.713_722. #' @references Ribeiro, H., Cunha, M. and Abreu, I., 2007. Definition of main pollen season using logistic model. \emph{Annals of Agricultural and Environmental Medicine}, 14(2), pp.259_264. #' @seealso \code{\link{interpollen}}, \code{\link{plot_ps}} #' @examples data("munich_pollen") #' @examples calculate_ps(munich_pollen, plot = TRUE, result = "table") #' @importFrom circular circular mean.circular #' @importFrom graphics abline lines par plot #' @importFrom grDevices dev.copy dev.off graphics.off recordPlot #' @importFrom lubridate is.POSIXt yday #' @importFrom stats aggregate coef complete.cases getInitial na.omit nls quantile SSlogis #' @importFrom utils data head globalVariables #' @importFrom writexl write_xlsx #' @importFrom tidyr %>% #' @export calculate_ps <- function(data, method = "percentage", th.day = 100, perc = 95, def.season = "natural", reduction = FALSE, red.level = 0.90, derivative = 5, man = 11, th.ma = 5, n.clinical = 5, window.clinical = 7, window.grains = 5, th.pollen = 10, th.sum = 100, type = "none", interpolation = TRUE, int.method = "lineal", maxdays = 30, result = "table", plot = TRUE, export.plot = FALSE, export.result = FALSE) { ###################################################################################################### if(class(export.plot) != "logical") stop ("Please include only logical values for export.plot argument") if(class(export.result) != "logical") stop ("Please include only logical values for export.result argument") if(export.plot == TRUE){ifelse(!dir.exists(file.path("plot_AeRobiology")), dir.create(file.path("plot_AeRobiology")), FALSE); plot = TRUE} if(export.result == TRUE){ifelse(!dir.exists(file.path("table_AeRobiology")), dir.create(file.path("table_AeRobiology")), FALSE)} data<-data.frame(data) if(class(data) != "data.frame") stop ("Please include a data.frame: first column with date, and the rest with pollen types") if(class(th.day) != "numeric" | th.day < 0) stop ("Please include only numeric values >= 0 for th.day argument") if(class(perc) != "numeric" | perc < 0 | perc > 100) stop ("Please include only numeric values between 0-100 for perc argument") if(class(reduction) != "logical") stop ("Please include only logical values for reduction argument") if(class(red.level) != "numeric" | red.level < 0 | red.level > 1) stop ("Please include only numeric values between 0-1 for red.level argument") if(derivative != 4 & derivative != 5 & derivative != 6) stop ("Please derivative only accept values: 4, 5 or 6") if(class(man) != "numeric" | man < 0) stop ("Please include only numeric values > 0 for man argument") if(class(th.ma) != "numeric" | th.ma < 0) stop ("Please include only numeric values > 0 for th.ma argument") if(result != "table" & result != "list") stop ("Please result only accept values: 'table' or 'list'") if(class(plot) != "logical") stop ("Please include only logical values for plot argument") if(class(n.clinical) != "numeric" | n.clinical < 0) stop ("Please include only numeric values >= 0 for n.clinical argument") if(class(window.clinical) != "numeric" | window.clinical < 0) stop ("Please include only numeric values >= 0 for window.clinical argument") if(class(window.grains) != "numeric" | window.grains < 0) stop ("Please include only numeric values >= 0 for window.grains argument") if(class(th.pollen) != "numeric" | th.pollen < 0) stop ("Please include only numeric values >= 0 for th.pollen argument") if(class(th.sum) != "numeric" | th.sum < 0) stop ("Please include only numeric values >= 0 for th.sum argument") if(class(interpolation) != "logical") stop ("Please include only logical values for interpolation argument") if(int.method != "lineal" & int.method != "movingmean" & int.method != "spline" & int.method != "tseries") stop ("Please int.method only accept values: 'lineal', 'movingmean', 'spline' or 'tseries'") if(def.season != "natural" & def.season != "interannual" & def.season != "peak") stop ("Please def.season only accept values: 'natural', 'interannual' or 'peak'") if(method != "percentage" & method != "logistic" & method != "moving" & method != "clinical" & method != "grains") stop ("Please method only accept values: 'percentage', 'logistic', 'moving', 'clinical' or 'grains'") if(type != "none" & type != "birch" & type != "grasses" & type != "cypress" & type != "olive" & type != "ragweed") stop ("Please def.season only accept values: 'none', 'birch', 'grasses', 'cypress', 'olive' or 'ragweed'") if(class(data[,1])[1]!="Date" & !is.POSIXt(data[,1])) {stop("Please the first column of your data must be the date in 'Date' format")} data[,1]<-as.Date(data[,1]) ###################################################################################################### SS<-c() a<-c() g<-c() b<-c() list.ps<-c() if(method == "clinical" & type == "birch") {n.clinical = 5; window.clinical = 7; th.pollen = 10; th.sum = 100; th.day = 100} if(method == "clinical" & type == "grasses") {n.clinical = 5; window.clinical = 7; th.pollen = 3; th.sum = 30; th.day = 50} if(method == "clinical" & type == "cypress") {n.clinical = 5; window.clinical = 7; th.pollen = 20; th.sum = 200; th.day = 100} if(method == "clinical" & type == "olive") {n.clinical = 5; window.clinical = 7; th.pollen = 20; th.sum = 200; th.day = 100} if(method == "clinical" & type == "ragweed") {n.clinical = 5; window.clinical = 7; th.pollen = 3; th.sum = 30; th.day = 50} th.rem = 100 - perc if(method == "clinical") {window.clinical <- window.clinical - 1} if(method == "grains") {window.grains <- window.grains - 1} if(interpolation == TRUE){data <- interpollen(data, method = int.method, maxdays = maxdays, plot = F)} type.name <- colnames(data) cols <- ncol(data) list.results <- list() for (t in 2: cols){ #################################################################################################### ################################## Definition of the season ######################################## if (def.season == "interannual"){ n.year <- rep(NA, nrow(data)) for(y in 1:length(n.year)){ if (data[y, 1] <= as.Date(paste0(strftime(data[y, 1], "%Y"),"-05-31"))) {n.year[y] <- as.numeric(strftime(data[y, 1], "%Y"))-1} else {n.year[y] <- as.numeric(strftime(data[y, 1], "%Y"))}} data$n.year <- n.year } else if (def.season == "peak") { peaks <- (aggregate(data[ ,type.name[t]] ~ strftime(data[ ,1], "%Y"), FUN = max)) %>% .[which(.[ ,2] != 0), ] date.peak <- rep(NA, nrow(peaks)) for (p in 1:nrow(peaks)){ date.peak[p] <- data[which(strftime(data[ ,1], "%Y") == peaks[p,1] & data[ , type.name[t]] == peaks[p,2]), 1][1]} date.peak <- as.Date(date.peak, origin = "1970-01-01") date.peak <- as.numeric(strftime(date.peak, "%j")) * 360 / 365 mean.cir <- round((as.numeric(mean.circular(circular(date.peak, units = "degrees")))) * 365 / 360) if(mean.cir <= 0) {mean.cir <- mean.cir + 365} date.year <- c(mean.cir - 182, mean.cir + 182); date.year <- date.year[date.year > 0 & date.year <= 365] n.year <- rep(NA, nrow(data)) for(y in 1:length(n.year)){ if (data[y, 1] <= as.Date(paste0(strftime(data[y, 1], "%Y"),substring(as.Date(strptime(date.year, "%j")), 5)))) {n.year[y] <- as.numeric(strftime(data[y, 1], "%Y")) - 1} else {n.year[y] <- as.numeric(strftime(data[y, 1], "%Y"))}} data$n.year <- n.year } else if (def.season == "natural") { n.year <- as.numeric(strftime(data[, 1], "%Y")) data$n.year <- n.year} #################################################################################################### seasons <- unique(data$n.year) st.ps <-NA; mx.ps <- NA; en.ps <- NA; st.hs <- NA; en.hs <- NA result.ps <- data.frame(seasons, st.dt = NA, st.jd = NA, en.dt = NA, en.jd = NA, ln.ps = NA, sm.tt = NA, sm.ps = NA, pk.val = NA, pk.dt = NA, pk.jd = NA, ln.prpk = NA, sm.prpk = NA, ln.pspk = NA, sm.pspk = NA, daysth = NA) if(method == "clinical") {result.ps <- data.frame(seasons, st.dt = NA, st.jd = NA, en.dt = NA, en.jd = NA, ln.ps = NA, sm.tt = NA, sm.ps = NA, pk.val = NA, pk.dt = NA, pk.jd = NA, ln.prpk = NA, sm.prpk = NA, ln.pspk = NA, sm.pspk = NA, daysth = NA, st.dt.hs = NA, st.jd.hs = NA, en.dt.hs = NA, en.jd.hs = NA)} #if(plot == TRUE){graphics.off()} #if(plot == TRUE){par(mfrow = c(ceiling(length(seasons)/4),4), mar = c(0.5,0.5,1,0.5))} par(mfrow = c(ceiling(length(seasons)/4),4), mar = c(0.5,0.5,1,0.5)) for (j in 1:length(seasons)) { tryCatch({ ye <- seasons[j] if(length(which(complete.cases(data[which(data$n.year==ye), c(1,t)]))) == 0 | sum(data[which(data$n.year==ye), type.name[t]], na.rm = T) == 0) {print(paste("Error: Year", ye, type.name[t], ". The entire aerobiological data are NA or 0")); next()} pollen.s <- na.omit(data[which(data$n.year==ye), c(1,t)]) # Pollen data without NAs #pollen.s <- data[which(data$n.year==ye), c(1,t)] pollen.s$jdays <- as.numeric(strftime(pollen.s[, 1], "%j")) pollen.s3 <- pollen.s if (method == "moving") { ### Method using the moving average limited by a threshold pollen.s1 <- data.frame(Date = seq(from = pollen.s[, 1][1], to = pollen.s[, 1][nrow(pollen.s)], by = "day"), pollen = 0, jdays = 0) colnames(pollen.s1) <- colnames(pollen.s) pollen.s1$jdays <- as.numeric(strftime(pollen.s1[, 1], "%j")) pollen.s1[which(pollen.s1[, 1] %in% pollen.s[, 1]), 2] <- pollen.s[which(pollen.s[, 1] %in% pollen.s1[, 1]), 2] pollen.s <- pollen.s1 pollen.s$ma <- ma(pollen.s[, 2], man=man) pollen.s[which(is.nan(pollen.s[, "ma"])), "ma"] <- NA Peakmod <- pollen.s[which(pollen.s[, "ma"] == max(pollen.s[, "ma"], na.rm = T)), 1][1] if (is.na(Peakmod)|max(pollen.s[, "ma"], na.rm = T)<th.ma) { mx.ps <- NA st.ps <- NA en.ps <- NA #if(is.na(mx.ps) | is.na(st.ps) | is.na(en.ps)) {print(paste("Error: Year", ye, type.name[t], ". Try to check the aerobiological data for this year")); next()} } else{ mx.ps <- pollen.s[which(pollen.s[, 2] == max(pollen.s[, 2], na.rm = T)), 1][1]%>%yday(.) #st.ps <- pollen.s[which((pollen.s[, "ma"] <= th.ma) & (yday(pollen.s[, 1]) < yday(Peakmod))), 1] %>% .[length(.)]%>%yday(.) st.ps <- pollen.s[which((pollen.s[, "ma"] < th.ma) & (pollen.s[, 1] < Peakmod)), 1] %>% .[length(.)]%>%yday(.)+1 #en.ps <- pollen.s[which((pollen.s[, "ma"] <= th.ma) & (yday(pollen.s[, 1]) > yday(Peakmod))), 1] %>% .[1]%>%yday(.) en.ps <- pollen.s[which((pollen.s[, "ma"] < th.ma) & (pollen.s[, 1] > Peakmod)), 1] %>% .[1]%>%yday(.)-1 if (is.numeric(st.ps) & length(st.ps) >=1){} else{ st.ps <- NA } if (is.numeric(mx.ps) & length(mx.ps) >=1) {} else{ mx.ps <- NA } if (is.numeric(en.ps) & length(en.ps) >=1) {} else{ en.ps <- NA } #if(is.na(mx.ps) | is.na(st.ps) | is.na(en.ps)) {print(paste("Error: Year", ye, type.name[t], ". Try to check the aerobiological data for this year")); next()} } } if (method == "percentage") { ### Method using the percentage for removing data (Andersen et al. 1991) pollen.s$ndays <- 1:nrow(pollen.s) lim <- sum(pollen.s[type.name[t]])/100*(th.rem/2) pollen.s$acum1 <- NA for (i in 1:nrow(pollen.s)) { if (i == 1) { pollen.s$acum1[i] = pollen.s[i, type.name[t]] } else { pollen.s$acum1[i] = pollen.s[i, type.name[t]] + pollen.s$acum1[i-1] } } pollen.s$acum2 <- NA for (i in nrow(pollen.s):1) { if (i == nrow(pollen.s)) { pollen.s$acum2[i] = pollen.s[i, type.name[t]] } else { pollen.s$acum2[i] = pollen.s[i, type.name[t]] + pollen.s$acum2[i+1] } } st.ps <- pollen.s$jdays[which(pollen.s$acum1 >= lim)][1] en.ps <- pollen.s$jdays[which(pollen.s$acum2 < lim)][1] - 1 mx.ps <- pollen.s$jdays[which(pollen.s[type.name[t]] == max(pollen.s[type.name[t]]))[1]] } if (method == "clinical"){ ### Method using the clinical method (Pfaar et al. 2017) #for (f in 1: (nrow(pollen.s) - window.clinical)){ # if(pollen.s[f, type.name[t]] >= th.pollen & # length(which(pollen.s[f:(f + window.clinical), type.name[t]] >= th.pollen)) >= n.clinical & # sum(head(sort(pollen.s[f:(f + window.clinical), type.name[t]][which(pollen.s[f:(f + window.clinical), type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum){ # st.ps <- pollen.s$jdays[f]; break()} #} for (f in 1: nrow(pollen.s)){ if((nrow(pollen.s) - (f + window.clinical)) <= 0){ if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:nrow(pollen.s), type.name[t]] >= th.pollen)) >= n.clinical & sum(head(sort(pollen.s[f:nrow(pollen.s), type.name[t]][which(pollen.s[f:nrow(pollen.s), type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum){ st.ps <- pollen.s$jdays[f]; break()} } else { if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f + window.clinical), type.name[t]] >= th.pollen)) >= n.clinical & sum(head(sort(pollen.s[f:(f + window.clinical), type.name[t]][which(pollen.s[f:(f + window.clinical), type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum){ st.ps <- pollen.s$jdays[f]; break()} } } #for (f in (1 + window.clinical) : nrow(pollen.s)){ # if(pollen.s[f, type.name[t]] >= th.pollen & # length(which(pollen.s[f:(f - window.clinical), type.name[t]] >= th.pollen)) >= n.clinical & # sum(head(sort(pollen.s[f:(f - window.clinical), type.name[t]][which(pollen.s[f:(f - window.clinical), type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum) { # en.ps <- pollen.s$jdays[f]} # } for (f in 1 : nrow(pollen.s)){ if((f - window.clinical) <= 0){ if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:1, type.name[t]] >= th.pollen)) >= n.clinical & sum(head(sort(pollen.s[f:1, type.name[t]][which(pollen.s[f:1, type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum) { en.ps <- pollen.s$jdays[f]} } else { if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f - window.clinical), type.name[t]] >= th.pollen)) >= n.clinical & sum(head(sort(pollen.s[f:(f - window.clinical), type.name[t]][which(pollen.s[f:(f - window.clinical), type.name[t]] >= th.pollen)], decreasing = TRUE), n.clinical)) >= th.sum) { en.ps <- pollen.s$jdays[f]} } } for (h in 1: (nrow(pollen.s) - 2)){ if(pollen.s[h, type.name[t]] >= th.day & length(which(pollen.s[h:(h + 2), type.name[t]] >= th.day)) == 3) { st.hs <- pollen.s$jdays[h]; break()} } for (h in (1 + 2) : nrow(pollen.s)){ if(pollen.s[h, type.name[t]] >= th.day & length(which(pollen.s[h:(h - 2), type.name[t]] >= th.day)) == 3) { en.hs <- pollen.s$jdays[h]} } mx.ps <- pollen.s$jdays[which(pollen.s[type.name[t]] == max(pollen.s[type.name[t]]))[1]] } if (method == "grains"){ ### Method using the grains method (Galan et al. 1991) #for (f in 1: (nrow(pollen.s) - window.grains)){ # if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f + window.grains), type.name[t]] >= th.pollen)) >= (window.grains+1)) {st.ps <- pollen.s$jdays[f]; break()} #} for (f in 1: nrow(pollen.s)){ if((nrow(pollen.s) - (f + window.grains)) <= 0){ if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:nrow(pollen.s), type.name[t]] >= th.pollen)) >= (window.grains+1)) {st.ps <- pollen.s$jdays[f]; break()} } else { if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f + window.grains), type.name[t]] >= th.pollen)) >= (window.grains+1)) {st.ps <- pollen.s$jdays[f]; break()} } } #for (f in (1 + window.grains) : nrow(pollen.s)){ # if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f - window.grains), type.name[t]] >= th.pollen)) >= (window.grains+1)) {en.ps <- pollen.s$jdays[f]} #} for (f in 1 : nrow(pollen.s)){ if((f - window.grains) <= 0){ if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:1, type.name[t]] >= th.pollen)) >= (window.grains+1)) {en.ps <- pollen.s$jdays[f]} } else { if(pollen.s[f, type.name[t]] >= th.pollen & length(which(pollen.s[f:(f - window.grains), type.name[t]] >= th.pollen)) >= (window.grains+1)) {en.ps <- pollen.s$jdays[f]} } } mx.ps <- pollen.s$jdays[which(pollen.s[type.name[t]] == max(pollen.s[type.name[t]]))[1]] } if (method == "logistic"){ ### Method using the accumulated curve (Ribeiro et al. 2004) pollen.s1 <- data.frame(Date = seq(from = pollen.s[, 1][1], to = pollen.s[, 1][nrow(pollen.s)], by = "day"), pollen = 0, jdays = 0) colnames(pollen.s1) <- colnames(pollen.s) pollen.s1$jdays <- as.numeric(strftime(pollen.s1[, 1], "%j")) pollen.s1[which(pollen.s1[, 1] %in% pollen.s[, 1]), 2] <- pollen.s[which(pollen.s[, 1] %in% pollen.s1[, 1]), 2] pollen.s <- pollen.s1 pollen.s2 <- pollen.s if(reduction == TRUE){ pollen.s[which( pollen.s[, type.name[t]] >= quantile(data[data[ ,type.name[t]] > 0, type.name[t]], red.level, na.rm = TRUE)), type.name[t]] <- quantile(data[data[ ,type.name[t]] > 0, type.name[t]], red.level, na.rm = TRUE)} #pollen.s[ , type.name[t]] <- round(ma(pollen.s[ , type.name[t]], order = 5)) pollen.s <- na.omit(pollen.s) pollen.s$ndays <- 1:nrow(pollen.s) pollen.s$acum <- NA for (i in 1:nrow(pollen.s)) { if (i==1) { pollen.s$acum[i] = pollen.s[i, type.name[t]] } else { pollen.s$acum[i] = pollen.s[i, type.name[t]] + pollen.s$acum[i-1] } } tryCatch({ tryCatch({model.acum <- nls(acum~a*(1+exp(-(b+g*ndays)))^-1, start=list(a = max(pollen.s$acum),g = 1,b = -2), data=pollen.s)}, error = function(e){}) tryCatch({ SS <- getInitial(acum ~ SSlogis(ndays,alpha,xmid,scale), data = pollen.s) a <- SS["alpha"] g <- 1/SS["scale"] b <- SS["alpha"]/(exp(SS["xmid"]/SS["scale"])+1) model.acum <- nls(acum~a*(1+exp(-(b+g*ndays)))^-1, start=list(a = a, g = g, b = b), data=pollen.s) }, error = function(e){}) }, error = function(e){print(paste("Error:", "Year:", ye, type.name[t]))}) tryCatch({ #summary(model.acum) c <- coef(model.acum) # a es c[1], g es c[2] y b es c[3] aj.acum <- function(t){c[1]*(1+exp(-(c[3]+c[2]*t)))^-1} pollen.s$model <- aj.acum(pollen.s$ndays) x2 <- -c[3]/c[2]; x2 <- round(x2) if(x2==0){ SS <- getInitial(acum ~ SSlogis(ndays,alpha,xmid,scale), data = pollen.s) a <- SS["alpha"] g <- 1/SS["scale"] b <- SS["alpha"]/(exp(SS["xmid"]/SS["scale"])+1) model.acum <- nls(acum~a*(1+exp(-(b+g*ndays)))^-1, start=list(a = a, g = g, b = b), data=pollen.s) c <- coef(model.acum) # a es c[1], g es c[2] y b es c[3] aj.acum <- function(t){c[1]*(1+exp(-(c[3]+c[2]*t)))^-1} pollen.s$model <- aj.acum(pollen.s$ndays) x2 <- -c[3]/c[2]; x2 <- round(x2) } if (derivative == 4){ # Resultados de la cuarta derivada x1 <- -(log(5+2*sqrt(6))+c[3])/c[2]; x1 <- floor(x1) x3 <- -(log(5-2*sqrt(6))+c[3])/c[2]; x3 <- ceiling(x3) } else if (derivative == 5) { # Resultados de la quinta derivada x1 <- -(c[3]+(log((sqrt(26*sqrt(105)+270)/2)+(sqrt(105)/2)+(13/2))))/c[2]; x1 <- floor(x1) x3 <- -(c[3]+(log(+(sqrt(105)/2)-(sqrt(26*sqrt(105)+270)/2)+(13/2))))/c[2]; x3 <- ceiling(x3) } else if (derivative == 6){ # Resultados de la sexta derivada x1 <- -(c[3]+log(sqrt(336*sqrt(15)+1320)/2+3*sqrt(15)+14))/c[2]; x1 <- floor(x1) x3 <- -(c[3]+log((-sqrt(336*sqrt(15)+1320)/2)+3*sqrt(15)+14))/c[2]; x3 <- ceiling(x3) } st.ps <- pollen.s$jdays[which(pollen.s$ndays == x1)] en.ps <- pollen.s$jdays[which(pollen.s$ndays == x3)] mx.ps <- pollen.s2$jdays[which(pollen.s2[type.name[t]] == max(pollen.s2[type.name[t]]))[1]] if(reduction == TRUE){pollen.s <- pollen.s2} }, error = function(e){ print(paste("Error: Year", ye, type.name[t], ". This method can not parametrize the model for this aerobiological data")) }) } # Characteristics of the pollen season (PS) result.ps[j,"st.dt"] <- as.character(pollen.s[pollen.s$jdays == st.ps, 1]) # Start-date of PS result.ps[j,"st.jd"] <- pollen.s$jdays[pollen.s$jdays == st.ps] # Start-date of PS (JD) result.ps[j,"en.dt"] <- as.character(pollen.s[pollen.s$jdays == en.ps, 1]) # End-date of PS result.ps[j,"en.jd"] <- pollen.s$jdays[pollen.s$jdays == en.ps] # End-date of PS (JD) result.ps[j,"ln.ps"] <- round(as.numeric(pollen.s[pollen.s$jdays == en.ps, 1] - pollen.s[pollen.s$jdays == st.ps, 1])) + 1 # Length of PS result.ps[j,"sm.tt"] <- sum(pollen.s[type.name[t]]) # Total sum result.ps[j,"sm.ps"] <- sum(pollen.s[which(pollen.s$jdays == st.ps) : which(pollen.s$jdays == en.ps), type.name[t]]) # Pollen Index result.ps[j,"pk.val"] <- max(pollen.s[type.name[t]]) # Peak value result.ps[j,"pk.dt"] <- as.character(pollen.s[pollen.s$jdays == mx.ps, 1]) # Peak date result.ps[j,"pk.jd"] <- pollen.s$jdays[pollen.s$jdays == mx.ps] # Peak date (JD) result.ps[j,"ln.prpk"] <- round(as.numeric(pollen.s[pollen.s$jdays == mx.ps, 1] - pollen.s[pollen.s$jdays == st.ps, 1]))+1 # Lengh of pre-peak period result.ps[j,"sm.prpk"] <- sum(pollen.s[which(pollen.s$jdays == st.ps) : which(pollen.s$jdays == mx.ps), type.name[t]]) # Pre-peak sum result.ps[j,"ln.pspk"] <- round(as.numeric(pollen.s[pollen.s$jdays == en.ps, 1] - pollen.s[pollen.s$jdays == mx.ps, 1])) # Lengh of post-peak period result.ps[j,"sm.pspk"] <- sum(pollen.s[(which(pollen.s$jdays == mx.ps)+1) : which(pollen.s$jdays == en.ps), type.name[t]]) # Post-peak sum result.ps[j,"daysth"] <- length(which(pollen.s[type.name[t]] >= th.day)) if (method == "clinical" & is.numeric(st.hs)){result.ps[j,"st.dt.hs"] <- as.character(pollen.s[pollen.s$jdays == st.hs, 1])} # Start-date of HPS if (method == "clinical" & is.numeric(st.hs)){result.ps[j,"st.jd.hs"] <- pollen.s$jdays[pollen.s$jdays == st.hs]} # Start-date of HPS (JD) if (method == "clinical" & is.numeric(en.hs)){result.ps[j,"en.dt.hs"] <- as.character(pollen.s[pollen.s$jdays == en.hs, 1])} # End-date of HPS if (method == "clinical" & is.numeric(en.hs)){result.ps[j,"en.jd.hs"] <- pollen.s$jdays[pollen.s$jdays == en.hs]} # End-date of HPS (JD) if (which(pollen.s$jdays == st.ps)-20 > 1) {pollen.s <- pollen.s[-(1:(which(pollen.s$jdays == st.ps)-20)), ]} if (which(pollen.s$jdays == en.ps)+20 < nrow(pollen.s)) {pollen.s <- pollen.s[-((which(pollen.s$jdays == en.ps)+20):nrow(pollen.s)), ]} if(plot == TRUE){ if(method == "percentage" | method == "logistic" | method == "clinical" | method == "grains"){ plot(y = pollen.s[ ,type.name[t]], x = 1:length(pollen.s$jdays), type = "l", main = paste(toupper(type.name[t]), ye), ylab = expression(paste("Granos de polen/m"^"3")), xlab = "Julian days", xaxt = "n", yaxt = "n", lwd = 1.5) #plot(y = pollen.s[ ,type.name[t]], x = pollen.s$jdays, type = "l", main = paste(toupper(type.name[t]), ye), ylab = expression(paste("Granos de polen/m"^"3")), xlab = "Julian days", xaxt = "n", yaxt = "n", lwd = 1.5) par(new=T) #plot(pollen.s$acum, x = pollen.s$ndays, type="l", col="red") #plot(pollen.s$acum, type="l", col="red") #lines(pollen.s$ndays, aj.acum(pollen.s$ndays), col="blue") ymax <- max(pollen.s[ ,type.name[t]])+100 #lines(x = c(result.ps[j,"st.jd"], result.ps[j,"st.jd"]), y = c(0,ymax), col = 2, lty = 2, lwd = 2) lines(x = c(which(pollen.s$jdays == result.ps[j,"st.jd"]), which(pollen.s$jdays == result.ps[j,"st.jd"])), y = c(0,ymax), col = 2, lty = 2, lwd = 2) #lines(x=c(mx.ps, mx.ps), y=c(0,ymax), col=2, lty=2, lwd=2) #lines(x = c(result.ps[j,"en.jd"], result.ps[j,"en.jd"]), y = c(0,ymax), col = 2, lty = 2, lwd = 2) lines(x = c(which(pollen.s$jdays == result.ps[j,"en.jd"]), which(pollen.s$jdays == result.ps[j,"en.jd"])), y = c(0,ymax), col = 2, lty = 2, lwd = 2) #lines(x = c(result.ps[j,"pk.jd"], result.ps[j,"pk.jd"]), y = c(0,ymax), col = 3, lty = 2, lwd = 2) lines(x = c(which(pollen.s$jdays == result.ps[j,"pk.jd"]), which(pollen.s$jdays == result.ps[j,"pk.jd"])), y = c(0,ymax), col = 3, lty = 2, lwd = 2) } else { #plot(y = pollen.s[ ,2], x = yday(pollen.s[ ,1]), type = "l", main = paste(toupper(type.name[t])," ", ye), xaxt = "n", yaxt = "n", lwd = 1.5) plot(y = pollen.s[ ,2], x = 1:length(yday(pollen.s[ ,1])), type = "l", main = paste(toupper(type.name[t])," ", ye), xaxt = "n", yaxt = "n", lwd = 1.5) #lines(pollen.s[ ,"ma"], x = yday(pollen.s[ ,1]), col="red") lines(pollen.s[ ,"ma"], x = 1:length(yday(pollen.s[ ,1])), col="red") #abline(v = c(st.ps,en.ps), col = 4, lty = 2, lwd = 2) abline(v = c(which(yday(pollen.s[ ,1]) == st.ps), which(yday(pollen.s[ ,1]) == en.ps)), col = 4, lty = 2, lwd = 2) abline(h = th.ma, col = 3, lty = 2, lwd = 2) } #plot.season <- recordPlot() } print(paste(ye, type.name[t])) }, error = function(e){ print(paste("Year", ye, type.name[t], ". Try to check the aerobiological data for this year")) }) result.ps[j,"sm.tt"] <- sum(pollen.s3[type.name[t]]) result.ps[j,"pk.val"] <- max(pollen.s3[type.name[t]]) result.ps[j,"pk.dt"] <- as.character(pollen.s3[which(pollen.s3[type.name[t]] == max(pollen.s3[type.name[t]]))[1], 1]) # Peak date result.ps[j,"pk.jd"] <- pollen.s3$jdays[which(pollen.s3[type.name[t]] == max(pollen.s3[type.name[t]]))[1]] # Peak date (JD) st.ps <-NA; mx.ps <- NA; en.ps <- NA; st.hs <- NA; en.hs <- NA } result.ps$st.dt <- as.Date(strptime(result.ps$st.dt, "%Y-%m-%d")) result.ps$en.dt <- as.Date(strptime(result.ps$en.dt, "%Y-%m-%d")) result.ps$pk.dt <- as.Date(strptime(result.ps$pk.dt, "%Y-%m-%d")) if(export.plot == TRUE){plot.season <- recordPlot()} list.results[[type.name[t]]] <- result.ps par(mfrow = c(1,1), mar = c(5.1, 4.1, 4.1, 2.1)) if(export.plot == TRUE){ if(method == "percentage") {dev.copy(pdf, paste0("plot_AeRobiology/plot_",type.name[t],"_",method,perc,".pdf")); plot.season; dev.off()} if(method == "logistic") {dev.copy(pdf, paste0("plot_AeRobiology/plot_",type.name[t],"_",method,derivative,".pdf")); plot.season; dev.off()} if(method == "moving") {dev.copy(pdf, paste0("plot_AeRobiology/plot_",type.name[t],"_",method,man,"_",th.ma,".pdf")); plot.season; dev.off()} if(method == "clinical") {dev.copy(pdf, paste0("plot_AeRobiology/plot_",type.name[t],"_",method,n.clinical,"_",window.clinical+1,"_",th.pollen,"_",th.sum,".pdf")); plot.season; dev.off()} if(method == "grains") {dev.copy(pdf, paste0("plot_AeRobiology/plot_",type.name[t],"_",method,window.grains+1,"_",th.pollen,".pdf")); plot.season; dev.off()} } } par(mfrow = c(1,1), mar = c(5.1, 4.1, 4.1, 2.1)) #if(plot == TRUE){graphics.off()} nam.list <- names(list.results) for(l in 1:length(nam.list)){ if(l == 1) {df.results <- data.frame(type = nam.list[l], list.results[[l]]) } else { df.results <- rbind(df.results, data.frame(type = nam.list[l], list.results[[l]])) } } list.ps <- list.results list.results [["Information"]] <- data.frame( Attributes = c("Pollen type", "seasons", "st.dt", "st.jd", "en.dt", "en.jd", "ln.ps", "sm.tt", "sm.ps", "pk.val", "pk.dt", "pk.jd", "ln.prpk", "sm.prpk", "ln.pspk", "sm.pspk", "daysth", "st.dt.hs", "st.jd.hs", "en.dt.hs", "en.jd.hs", "", "", "Method of the pollen season", "Interpolation", "Interpolation method", "Method for defining period", "", "Aditional arguments", "perc", "th.day", "reduction", "red.level", "derivative", "man", "th.ma", "n.clinical", "window.clinical", "window.grains", "th.pollen", "th.sum", "type", "", "", "Package", "Authors"), Description = c("Pollen type", "Year of the beginning of the season", "Start-date (date)", "Start-date (day of the year)", "End-date (date)", "End-date (day of the year)", "Length of the season", "Total sum", "Pollen integral", "Peak value", "Peak-date (date)", "Peak-date (day of year)", "Length of the pre-peak period", "Pollen integral of the pre-peak period", "Length of the post-peak period", "Pollen integral of the post-peak period", paste0("Number of days with more than ", th.day, " pollen grains"), "Start-date of the High pollen season (date, only for clinical method)", "Start-date of the High pollen season (day of the year, only for clinical method)", "End-date of the High pollen season (date, only for clinical method)", "End-date of the High pollen season (day of the year, only for clinical method)", "", "", method, interpolation, int.method, def.season, "", "", perc, th.day, reduction, red.level, derivative, man, th.ma, n.clinical, window.clinical, window.grains, th.pollen, th.sum, type, "", "", "AeRobiology", "Jesus Rojo, Antonio Picornell & Jose Oteros")) if (export.result == TRUE) { if(method == "percentage") {write_xlsx(list.results, paste0("table_AeRobiology/table_ps_",method,perc,".xlsx"))} if(method == "logistic") {write_xlsx(list.results, paste0("table_AeRobiology/table_ps_",method,derivative,".xlsx"))} if(method == "moving") {write_xlsx(list.results, paste0("table_AeRobiology/table_ps_",method,man,"_",th.ma,".xlsx"))} if(method == "clinical") {write_xlsx(list.results, paste0("table_AeRobiology/table_ps_",method,n.clinical,"_",window.clinical+1,"_",th.pollen,"_",th.sum,".xlsx"))} if(method == "grains") {write_xlsx(list.results, paste0("table_AeRobiology/table_ps_",method,window.grains+1,"_",th.pollen,".xlsx"))} } par(mfrow = c(1,1), mar = c(5.1, 4.1, 4.1, 2.1)) if (result == "table") {return(df.results)} if (result == "list") {return(list.ps)} }
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/calculate_ps.R
#' A view of the creators #' #' Credits #' #' @export credits <- function() { print("") print(" .vu5SdXUi ") print(" JBQgBBBBBQBQB: .ZI :7 UD. ") print(" BBBi .QQvQB57. .7SBB IQB BQB BQu ") print(" uQBBB gb BI MZdBBMP5 Bg 7BB rI. QBr ") print(" QBYQB: iER5QI iBIBLsqbBE B rZBQQr rQQ:DQg. LI: .PQBQK BQr .EQBQ5 .IBQqSdvMP uB1 ") print(" rBE 5Bd KBQBbRq rQgM iPgQ IEZL:i2Bs iBZBPBBB QBj :BdLrsQB RBi rBXvrUBB .BB71BBKiBBi BQY ") print(" dBi .gB. .BE:dXUB. :BugMEggQ :DI .:: 7B :MQ gQ7 EQ7 R7 .. .Qi DQ: Q: .: :B.:BX bB KQZ rBQ ") print(" :dP7rrKb5 rdKJUIDDM.ig1gjqBQ.s7i7.v7Yi.Q .Dd XgL 5Rr P ivrs.Sv KR: S r77v gi XdLsDE .gE:sQ7 ") print(" 1PI2XIUId .bK. :MQBQPXBiBRdB. i5.:7i.rQ :SP SEr 5b7 E:.r7:.E: KEi Z.:77..g..X1r7: UKI1Z ") print(" :qD: XKJ 2Ks:..Y.:qQDQ2:PQBQ bji::rRi iqbqi7IM 2dL rdii:iUE IZr LPii:iXK iULrr:r. .IvUu ") print(" r1J 7sU ijU5u7 :BQK BgBv 7j1Ju. :u7:Iuj L1i :uYuu7 JU: :uY1Jr .vu::jJE vrq ") print(" j7i .7K :7J ") print(" :ririrr :7Y. ") print("") print("") print("") print("The creators:") print("") print(":.:::::.:::::.:::::...............:.:...::i:iiiiiii:iiiiiiri") print(".:.:.:::.:.:.:.:....::..:iiPXKL1KMRRDg5v::.::i:i:iii:iiiiiii") print(":.:.:.:.:.:.:....isXMQRPBBBBBQBQBQBQBQBQQqr::.::iiiii:iii:ii") print("...:.:.:.:...:.ijXdQgRRQgQMQgQQQgQRQMQggRBQBqr.::i:iii:i:i:i") print(".............:rUX5PKPPqUK5qgQbbdRDRZZEQggPQBBBP:..i:i:iii:i:") print("........... .uEgbE5Sj7i7jSgRPdKK5KIjYu7JKPbQgQBB2i.::i:i:i:i") print(".......... .EMgbbIX1LrL5MgqjU77vuiirriivbZggDDQMBQj..:i:i:i:") print("......... EQgdPKPS22EMMX7i7irir:7vsJKPRgEqdKPgRgBQQi.:i:i:i") print(". . . . . iQgEdPPJu5KLr. .......::.::i:rr7712qgQgQBg.::i:i:") print(" . . . . 2QPPXRJi:. . . . ....ir12PMQMBB5.:::::") print("....... .BDD2MM: ....:..............:::r712ZMRMBs..::::") print(" . . . .RRMdZQr .i72gMBQBQgUjY7i::::J2bKgEESUL1bBgRBi :::::") print(" LBRMQg7 :YUvL777XdEXPUYi.:rLdDQMQMQMBQgSgQggB:..:.::") print(" bBDBQ7 ..:rsssdBRPEDSY: .1QMMDRDEXK5qPEqQgQBi :.:::") print(" . .ZBQBQJ ..i:rLs7sr. . .PBQMgPQBQZRdSU2gQRBPi:::::") print(" uBBPXb. ....:.. ... .sD2vriiLjXEMKKjdQQgBQv:i:i") print(" 72XivEi . ... .PKJ:::ii7vsLussSBQg5Lirir:") print(" i:.LZ7. ... .... :SdUi:::i:i::rJvqQBgv7777ri") print(" . ::u:. . . .. 7SUri:::i:irYuuDQQX7Jvv77r") print(" 7Y. . . :ii... .iJ75Lrirr77J11PBEPrvvv7L77") print(" . rvi . ... :dPY:rLDggPviii77JuU2QPPsYvYLsvLr") print(" .7j::.... :irir71KggQQBQBBBDurrrssSUEgILJYjYJYjvv") print(" :qv::.::iugQMv72II2LsbQEDDQQBbIUKPdgP7vvuJjLJvsv") print(" rDr.i:r5QBqi::i:::i:YXDbEdggQEEdPbgsssuJ1sjLsvs") print(" jgr77:Kg7 ..::vJ5Xq5dEEPDEM1Jj2jUJuJuYJL") print(" Kg2YYIZ:. ..:YXXZdZ521ISEEgEMMgUU1Uj2j1suJ1LJ") print(" .rEMEKSIv7i...r7ssEPKIUYKEMgRMbJUUSUI1UJus1JjY") print(" .i72qgQBBB::7PgMZdXPLJY7rvY1ss55U5dMgggQ5ujI1UJUu1j2JUYJ") print(".1BBBQBBBQQqsi..i7dQBMMqqXXYIKRPq2PbZEQgQgQRBgqIKPbXIj2jUJ1s") print("RBQBRgi. ....:YXMQQQRDgdMZgDZbgRQQQKZRQMQMQRBQBgqu21Uju") print("gBurL .:.. ..:iJKgQBQBQBRQRQMQgZSSPQgRgRgQgQgQQdJ2U2u") print("Dgi2 ..:.....:.rvLvIKbqEdREZPPIKKggQgMgMgQgRgQRMddXX") print("MQXj .....:.:...::iivY25qXq5K5PKEDMgRDMgRgRDQZUsuLsv") print(":7rvi. ........:...::7J55S2KSKSqSPbMSOFIA_&_ABRILgPPI2") print("") print("---- Jesus Rojo ----") print("") print("") print("") print("iiiiiriririririririririi:i:i:i:r:i:ii7r7r77v7v7L7L7L7L7L7L7Y") print("iiiiriiiiiiiriririi:i:::7sU1X5qPKsv7iii:i:ir77v7v7v7Lvv7v7L7") print("i:i:i:i:i:i:i:...rqgBQBRQdEERMRgMgQQBBBQBQBg7:rr77v7v7v7L7v7") print(":i:i:i:i:i:i..iuMBBBdEKUsUuqSbPdqdPgDRgRRBBBRLrrrv7v7v7v7vvL") print("::::i:i::::.:SBQBgSvsLYYY7suS2UJj1XKDZRZDZBBBQBJii7rv7v7v7vr") print("::::::::::. 2BBBgL:i:i:7ri:..irv7LLJuPdBgddBBBQQviirr7r77vrr") print(":::::::::..:2BBEY::.:.:.. ....ii77LvJJXDQDbPQQBBBPr:rr7r7rrr") print("::.:::.:.:2XdBRr.:.:::.......::ir7rJsuj5DgDZdBBBQBQqiiirr7r7") print(":::.:...iXBBBQj...:::.:.......::i:ii77sY25DMZgBBBBBBRr7r7r7r") print(".:.:.:.:rgBBDgi..:.:.... . ..:.::i:rr7rvLPZQMBRBQBQYirr7rr") print(":.:....7PDBEdg7.... . ......::iii:rr7JbgBQQQBBB1ri7r7r") print(".......1RRRDQB:. ....:.....::i:i:rvISEZDdPj1IPRBQBQBB1r7r7r7") print(".......:RBBMB5:rXPQBBQBgqvrirrYubQBQBBBQQQBQQPKQBQBQBs77v77r") print("....... rBQBQijE5IISXQQBQQvi:7uMQBMQQQqEqZdgZg2KBBBBgs7L7v77") print("....... iMQR irXPjSRQMQBZU..:JRBQBQPdQQggBggdPugBBQXLJvL7vr") print("........ :BU .rs5iv5SYIYrr: .LBgbI27LIX5gQMX522KBBQUUJ1Ysvv") print("......... 2Q2 . .:Lsu1Ivi:i. .7PXUsv11XPZPXjY7JudQBgKUUj1YJ7") print("......... .BR........:...::: iPU2vr:::::::irvLUEBQESXUUJjYs") print("... ..... S.... . :.:: 7XPSIi:...:::i77uIQQZXPXX12Jsv") print(" . ....... .r.... .::.: .isYIX2i:.::iir72KEMRPdPPSS1UsJ") print("........... .Lr::...::rri. .:i7dP7rri77YY5PMDMKbPEqP5Ij1L") print(" . ........ KL7rr:::i:..7i. .:YqRQP777vLI5EdgDBDbPEbdKXU2Js") print(". . ....... JgL7vriri:.iIBQPPQBBBBDPUI12SbgQgQQDPEPEqP5511Y") print(" . . . ..... DZYLvLvs7vuS5gBBBBQBgDdMMDZQPZgQQRPEPdbdKKUIsj") print(". . . . . . rBZ72XgbX2U2u7juSXgEgZRQBRBgPZBQQdZPEbEPq55uUY") print(" . . . . . . sBP7uJriJUUsujS5PSbEQMMqPZZPQQBEZEZPEPPXX2UJJ") print(". . . . . . . vQdvL...::i::iir7sIIKuUqgRBBBggEgEDbdXK22Jjv") print(" . . . . . . :gQIv:::ii7rv7J1XXZX2qQQBQQggDgEgEDPPSSuUss") print(" . . . . . . . EBbv::ruIPdDbgEDqPXMQBQQEggMDgZgEZqK2Ijuv") print(" . . . . . . :QBdui::vJZDZKKUXPQQBQQDgERDMDgDgPbXSU2sJ") print(" rQqrMBESsjvsIqU1IPPRQBQQDMbEQBggZgEZqq55u1L") print(" .7UPDBBv.iKBQMdPbZPPSgMRQBRQZggDKdBBQREDPdXXU2Jj") print(" .:rjSgMBBQEgRE..:ivSDQgBQBQQQBQQggDDZgdEPERBBBgESXIX1Us") print("rXERRBBBQBggZbKdPQP..::i:irs2qdgEgZgdEdDEgdDdDdEZBBBQgS2j1Ju") print("QgMZgdDdEPbPZPEPPgBi.:iiiirrYsX5EdDPdPZdgdDdDEZqXPBQBBBgPuY7") print("PdqZPEbbqPSZEgPdKZQD..irir71U5SPPEbdPdbZbDdEPZKXLdQQQBQBQBZX") print("bSPbDdPKbIbPgbPXbXQRP .irY2sISPXdPZPZZgdZbEPbSSLS8=DQMQgQMBQ") print("") print("---- Antonio Picornell ----") print("") print("") print("") print("777r7r7r7r77v777Y7IjU7r7BUirL5X1SPD1LiLuJ7L7v7v7Yvv7L7LvY7L7") print("r7r7r7r7r7r7r7r7v5PKPP5SEQUY21UUXDdBDgP5X2JLr77LvsvYvsvsvsvY") print("7r7r7r7r7r7rrir7SqKKDQBQBQBQBgQQBRQMQQDvIKPUjvY7LvsvsLsvsvYv") print("rrrrr7rri777YIs21EZRQQMBQBBBQBQBQBBBQBQQQgPDEgK5JvvsvYvsvYvY") print("rrrrrirrYLYuZ2PEDgBBBQBQBgMgRggRBQQBBBBQBbd1I5ZU2Y77LvL7v7v7") print("irrrrrirLYJIUPEBQBQZ2Yri....:::rrss5KZDBQBBBgDZguLrLvYvYvLvY") print("riririiiv7XI2RBBI:... . . ..:.::::rr7ruPQQBBBQg7v7LvsvY7L7") print("iiii::7QQRgBBDi. . . . . ... ........::iirijDBBBQQL7rv7L7v7v") print("i:i:::MQQQBB7 .. . ......::ii7r75BBBBQ7rr77v777") print(":i:i:rrqDBg: ... . ..::iirr77vuBQBQM7rr777r7") print("::::i:.SBQr ... . .::iirr77LLsSBQBQPrrr7r7r") print("::::.::KQE ... ..::iirr77uu2DBQBQMLririr") print(":.:.:.:SBi .. ....:iY1IjgBBBBX7:riri") print("......:BQ. ..rIZPMgMP5vi.. . ..:rJu1UXuU2UbBQBQD:iiiii") print("..... iQB. .Y2Yir7uXDQBQBEJiiir:vsdQBQBQBQBBBP5sZBBQBUi:iii:") print(".......KBi :rr:i:i:rYPqPKZXLi7L1ZQQBMgqUvJu5XDIjZBQBRJii:i:i") print(".....:LJB:..:iUPgqBQBQBQgDK...rZBBBQBQBMMgREEPXuRBBQDirii:i:") print(".... .7QQr . :iLL7YjLYjj:... :EddED2XPQgQQQdSu5QBQdv7rririi") print("..... JBi ..irv77:. .vr.::rjqPDggqYrLLBQUr7777vr7r") print(" . . Pr . .sv:. ..::::irvggvJL7rY7vrr") print(" . . ::. . :.... :72Jv:. . ..:rsLDq1Ju7s7vrri") print(" .ii.... ..r5Q: .:i.:RPv:i:iirrJUIZgU1J7r7r7ir") print(" r:.::...rUgQDr:2U. .irJ5DDggPYL7Ju22S2D2IUuvLvvrri") print(" ri.7v7ruPQE5:.iqQBqIXZQBQBBQ2EgMPKIKPdqPZ52IYjsJvv77") print(" rr:7IrudQRgIjYvvXEBBBQBQBQBMgZQQBBRbdZddDUS1Usjvv77r") print(" .Si7IrsRBBBBQBKKXPXbgZEDPZgBQBQBBQPPdDKgPX5I1UYY7v77") print(" 2U:LriJQqi.iSDu:.::irP2PgBBgKKMPrIbRZMZPSXUUJuLL77r") print(" .MKUUiLU: . ...7LJISuYr77PujPQQQMbXKIIuuLs7vr7") print(" :g51JJs. . . ....:::i7L1sYsX2K5QMQRbXP551Ussvv77r") print(" KSJuv: ::7JqqgZRKbKbUY72qddRQBgKIP55u1LYvv77rr") print(" vBZPXIv: ::vs5Ljr7r:.rUgQBQRRBbX2S22JuLY7vrri") print(" .KBBruBQPjr.. .:.:.::i:iIgMBQRPBBQgP2Uj1YsvL77rr") print(" JgZgQ .7QQBDur7r::riir7r7sXPBQBRgbQQQgBQQIS21YY77rri") print(" .EZS2ZX ...LdBBRPqrjuv7Y1EZQBBBBZZZQBBgRgBQESqIS22JYrr") print(" ..i2RqIj1ZD .::.:7PMBQQMBQBQBQBQBgZPDgQQBMRgRgQgXIIuSuI25j") print("ii.7Kd22jusDQ....::ir7v5KbbgdgEZPPXPPDgQQBMgDMgMDQX1J2j1YuJu") print(":.rXS12uUJu5B:..::ii7r77sjIIS2qSqKPPgDQQBMDEMDMZggZvjsjLL7vv") print(".7K5juJ1JUJuM2.:::.:irrvLuuX2KIS5PqDZMARCOKdEgMArCOJvY7v7v7v") print("") print("---- Jose Oteros ----") print("") print("") print(" .vu5SdXUi ") print(" JBQgBBBBBQBQB: .ZI :7 UD. ") print(" BBBi .QQvQB57. .7SBB IQB BQB BQu ") print(" uQBBB gb BI MZdBBMP5 Bg 7BB rI. QBr ") print(" QBYQB: iER5QI iBIBLsqbBE B rZBQQr rQQ:DQg. LI: .PQBQK BQr .EQBQ5 .IBQqSdvMP uB1 ") print(" rBE 5Bd KBQBbRq rQgM iPgQ IEZL:i2Bs iBZBPBBB QBj :BdLrsQB RBi rBXvrUBB .BB71BBKiBBi BQY ") print(" dBi .gB. .BE:dXUB. :BugMEggQ :DI .:: 7B :MQ gQ7 EQ7 R7 .. .Qi DQ: Q: .: :B.:BX bB KQZ rBQ ") print(" :dP7rrKb5 rdKJUIDDM.ig1gjqBQ.s7i7.v7Yi.Q .Dd XgL 5Rr P ivrs.Sv KR: S r77v gi XdLsDE .gE:sQ7 ") print(" 1PI2XIUId .bK. :MQBQPXBiBRdB. i5.:7i.rQ :SP SEr 5b7 E:.r7:.E: KEi Z.:77..g..X1r7: UKI1Z ") print(" :qD: XKJ 2Ks:..Y.:qQDQ2:PQBQ bji::rRi iqbqi7IM 2dL rdii:iUE IZr LPii:iXK iULrr:r. .IvUu ") print(" r1J 7sU ijU5u7 :BQK BgBv 7j1Ju. :u7:Iuj L1i :uYuu7 JU: :uY1Jr .vu::jJE vrq ") print(" j7i .7K :7J ") print(" :ririrr :7Y. ") print("") }
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/credits.R
#' Interpolation of Missing Data in a Pollen Database by Different Methods #' #' Function to simultaneously replace all missing data of an historical database of several pollen types by using different methods of interpolation. #' #' @param data A \code{data.frame} object including the general database where interpollation must be performed. This \code{data.frame} must include a first column in \code{Date} format and the rest of columns in \code{numeric} format. Each column must contain information of one pollen type. It is not necessary to insert missing gaps; the function will automatically detect them. #' @param method A \code{character} string specifying the method applied to calculate and generate the pollen missing data. The implemented methods that can be used are: \code{"lineal"}, \code{"movingmean"}, \code{"spline"}, \code{"tseries"} or \code{"neighbour"}. A more detailed information about the different methods may be consulted in Details. The \code{method} argument will be \code{"lineal"} by default. #' @param maxdays A \code{numeric (interger)} value specifying the maximum number of consecutive days with missing data that the algorithm is going to interpolate. If the gap is bigger than the argument value, the gap will not be interpolated. Not valid with \code{"tseries"} method. The \code{maxdays} argument will be \code{30} by default. #' @param plot A \code{logical} argument. If \code{TRUE}, graphical previews of the input database will be plot at the end of the interpolation process. All the interpolated gaps will be marked in red. The \code{plot} argument will be \code{TRUE} by default. #' @param factor A \code{numeric (interger)} value bigger than \code{1}. Only valid if the \code{"movingmean"} method is chosen. The argument specifies the factor which will multiply the gap size to stablish the range of the moving mean that will fulfill the gap. A more detailed information about the selection of the factor may be consulted in Details. The argument \code{factor} will be \code{1} by default. #' @param ndays A \code{numeric (interger)} value bigger than \code{1}. Only valid if the \code{"spline"} method is chosen. Specifies the number of days beyond each side of the gap which are used to perform the spline regression. The argument \code{ndays} will be \code{3} by default. #' @param spar A \code{numeric (double)} value ranging \code{0_1} specifying the degree of smoothness of the spline regression adjustment. As smooth as the adjustment is, more data are considered as outliers for the spline regression. Only valid if the \code{"spline"} method is chosen. The argument \code{"spar"} will be \code{0.5} by default. #' @param data2,data3,data4,data5 A \code{data.frame} object (each one) including database of a neighbour pollen station which will be used to interpolate missing data in the target station. Only valid if the "neighbour" method is chosen. This \code{data.frame} must include a first column in \code{Date} format and the rest of columns in \code{numeric} format belonging to each pollen type by column. It is not necessary to insert the missing gaps; the function will automatically detect them. The arguments will be \code{NULL} by default. #' @param mincorr A \code{numeric (double)} value ranging \code{0_1}. It specifies the minimal correlation coefficient (Spearman correlations) that neighbour stations must have with the target station to be taken into account for the interpolation. Only valid if the \code{"neighbour"} method is chosen. The argument \code{"mincorr"} will be \code{0.6} by default. #' @param result A \code{character} string specifying the format of the resulting \code{data.frame}. Only \code{"wide"} or \code{"long"}. The \code{result} argument will be \code{"wide"} by default. #' @details This function allows to interpolate missing data in a pollen database using 4 different methods which are described below. Interpolation for each pollen type will be automatically done for gaps smaller than the \code{"maxdays"} argument. \cr #' \itemize{ #' \item \code{"lineal"} method. The interpolation will be carried out by tracing a straight line between the gap extremes. #' \item \code{"movingmean"} method. It calculates the moving mean of the pollen daily concentrations with a window size of the gap size multiplicated by the \code{factor} argument and replace the missing data with the moving mean for these days. It is a dynamic function and for each gap of the database, the window size of the moving mean changes depending of each gap size. #' \item \code{"spline"} method. The interpolation will be carried out by performing a spline regression with the previous and following days to the gap. The number of days of each side of the gap that will be taken into account for calculating the spline regression are specified by \code{ndays} argument. The smoothness of the adjustment of the spline regression can be specified by the \code{spar} argument. #' \item \code{"tseries"} method. The interpolation will be carried out by analysing the time series of pollen database. It performs a seasonal_trend decomposition based on LOESS (Cleveland et al., 1990). The seasonality of the historical database is extracted and used to predict the missing data by performing a linear regression with the target year. #' \item \code{"neighbour"} method. Other near stations provided by the user are used to interpolate the missing data of the target station. First of all, a Spearman correlation is performed between the target station and the neighbour stations to discard the neighbour stations with a correlation coefficient smaller than \code{mincorr} value. For each gap, a linear regression is performed between the neighbour stations and the target stations to determine the equation which converts the pollen concentrations of the neighbour stations into the pollen concentration of the target station. Only neighbour stations without any missing data during the gap period are taken into account for each gap. #' } #' @return This function returns different results: #' \itemize{ #' \item If \code{result = "wide"}, returns a \code{data.frame} including the original data and completed with the interpolated data. #' \item If \code{result = "long"}, returns a \code{data.frame} containing your data in long format (the first column for date, the second for pollen type, the third for concentration and an additional fourth column with \code{1} if this data has been interpolated or \code{0} if not). #' \item If \code{plot = TRUE}, plots for each year and pollen type with daily values are represented in the active graphic window. Interpolated values are marked in red. If \code{method} argument is \code{"tseries"}, the seasonality is also represented in grey. #' } #' @references Cleveland RB, Cleveland WS, McRae JE, Terpenning I (1990) STL: a seasonal_trend decomposition procedure based on loess. J Off Stat 6(1):3_33. #' @seealso \code{\link{ma}} #' @examples data("munich_pollen") #' @examples interpollen(munich_pollen, method = "lineal", plot = FALSE) #' @importFrom lubridate is.POSIXt #' @importFrom graphics legend lines par plot points #' @importFrom stats aggregate cor.test lm na.omit predict predict.lm smooth.spline stl ts window #' @importFrom zoo na.approx #' @importFrom tidyr %>% gather spread #' @export interpollen <- function(data, method = "lineal" , maxdays = 30, plot = TRUE, factor = 2, ndays = 3, spar = 0.5, data2=NULL, data3=NULL, data4=NULL, data5=NULL, mincorr=0.6, result="wide") { if(class(maxdays)!="numeric"){stop("maxday: Please, insert an entire number bigger than 1")} if(class(maxdays)!="numeric"| maxdays%%1!=0| maxdays<=0){stop("maxday: Please insert an entire number bigger than 1")} if(class(method)!="character"){stop("method: Please, only type 'lineal' , 'movingmean' or 'spline'")} if (method != "lineal" & method != "movingmean" & method != "spline" & method != "neighbour" & method != "tseries"){ stop("method: Please, only type 'lineal' , 'movingmean', 'spline', 'tseries' or 'neighbour'")} if (result != "wide" & result != "long"){ stop("result: Please, only type 'wide' or 'long'")} if (plot != TRUE & plot != FALSE){ stop("plot: Please, only type 'TRUE' or 'FALSE'")} if (class(factor) != "numeric"){ stop("factor: Please, insert only a number bigger than 1")} if (factor <= 1){ stop("factor: Please, insert only a number bigger than 1")} if (class(ndays)!="numeric" | ndays %% 1 != 0){ stop("ndays:Please, insert only an entire number bigger than 1")} if (class(spar)!="numeric" | spar <= 0 | spar > 1){ stop("spar: Please, insert only a number between 0 (not included) and 1")} if (ndays <= 0){ stop("ndays: Please, insert only an entire number bigger than 1")} if (ndays >= 15){ warning("WARNING: Results of spline may not be reliable with more than 15 days")} if(mincorr<0 | mincorr>1){stop("mincorr: Please insert only a number between 0 and 1 ")} data<-data.frame(data) colnames(data)[1]<-"date" if (class(data) != "data.frame"& !is.null(data)){ stop ("Please, include a data.frame: first column with date, and the rest with pollen types")} if (class(data2) != "data.frame" & !is.null(data2)){ stop ("data2: Please, include a data.frame: first column with date, and the rest with pollen types")} if (class(data3) != "data.frame"& !is.null(data3)){ stop ("data3: Please, include a data.frame: first column with date, and the rest with pollen types")} if (class(data4) != "data.frame"& !is.null(data4)){ stop ("data4: Please, include a data.frame: first column with date, and the rest with pollen types")} if (class(data5) != "data.frame" & !is.null(data5)){ stop ("data5: Please, include a data.frame: first column with date, and the rest with pollen types")} if (method=="neighbour" & is.null(data2)){stop("You need at least another station loaded in 'data2' to use this method")} if(class(data[,1])[1]!="Date" & !is.POSIXt(data[,1])) {stop("Please the first column of your data must be the date in 'Date' format")} data[,1]<-as.Date(data[,1]) if (method == "tseries"){ warning("WARNING: 'maxdays' argument doesn't work with this method. All gaps will be interpolated.") date.st <- min(data[ ,1], na.rm = TRUE) date.en <- max(data[ ,1], na.rm = TRUE) date.seq <- seq(from = date.st, to = date.en, "days") data1 <- data.frame(matrix(data = NA, nrow = length(date.seq), ncol = length(colnames(data)))) colnames(data1) <- colnames(data) data1[ ,1] <- as.Date(date.seq) data1[data1[ ,1] %in% data[ ,1], -1] <- data[data[ ,1] %in% data1[ ,1], -1] data <- data1 data.full <- data type.name <- colnames(data) for (cols in 2: length(type.name)){ ma.data <- data.frame(date = data[ ,1], year = strftime(data[ ,1], "%Y"), ma = ma(data[ ,type.name[cols]], man = 15)) ag.data <- aggregate(ma ~ year, data = ma.data, max) ag.data$peak <- as.Date("2017-01-01") for (r in 1:nrow(ag.data)){ ag.data$peak[r] <- ma.data$date[which(ma.data$year == ag.data$year[r] & ma.data$ma == ag.data$ma[r])][1] } ag.data$st <- ag.data$peak - 182 ag.data$en <- ag.data$peak + 182 for (d in 1:nrow(ag.data)){ if (d == 1) { date.ps <- seq(from = ag.data$st[d], to = ag.data$en[d], "days") } else { date.ps <- c(date.ps, seq(from = ag.data$st[d], to = ag.data$en[d], "days")) } } ps.df <- data.frame(date = date.ps, pollen = NA) for (p in 1:nrow(ps.df)){ if (ps.df$date[p] %in% data[ ,1] == TRUE) {ps.df$pollen[p] <- data[data[ ,1] == ps.df$date[p], type.name[cols]]} } stl.df <- (stl(ts(ps.df$pollen, frequency = 365), s.window = "periodic", na.action=na.approx)$time.series[,1]) if(min(as.numeric(window(stl.df, start=c(2,1), end=c(2,365)))) < 0){ pollen.year <- floor(as.numeric(window(stl.df, start=c(2,1), end=c(2,365))) + abs(min(as.numeric(window(stl.df, start=c(2,1), end=c(2,365)))))) } else { pollen.year <- floor(as.numeric(window(stl.df, start=c(2,1), end=c(2,365)))) } par(mfrow = c(ceiling(length(unique(ag.data$year))/4),4), mar = c(0.5,0.5,1,0.5)) for (y in 1:nrow(ag.data)){ date.pred <- seq(from = ag.data$st[y], to = ag.data$en[y], "days") pollen.sel <- data.frame(date = date.pred, pollen = NA) pollen.sel$pollen[pollen.sel$date %in% data[, 1]] <- data[data[ ,1] %in% pollen.sel$date, type.name[cols]] pollen.pred <- pollen.year * summary(lm(pollen.sel$pollen ~ pollen.year + 0))$coefficients[1] data.full[which(data.full$date %in% date.pred & is.na(data.full[, type.name[cols]])), type.name[cols]] <- pollen.pred[which(date.pred %in% data.full$date[is.na(data.full[, type.name[cols]])])] pollen.full <- pollen.sel pollen.full$pollen <- NA pollen.full$pollen[pollen.full$date %in% data.full[ ,1]] <- data.full[data.full[ ,1] %in% pollen.full$date, type.name[cols]] if(plot==TRUE){ plot(pollen.year, col = "gray", lwd = 2, type = "l", xaxt = "n", yaxt = "n", main = paste(toupper(type.name[cols]), ag.data$year[y])) lines(pollen.full$pollen, col = 2) lines(pollen.sel$pollen, type = "l", col = 1, lwd = 2) legend("topleft", legend = c("original data", "interpolation", "seasonality"), col = c("black", "red", "gray"), pch = 19, cex = 0.8, bty = "n") }} } Interpolated <- gather(data.full, "type", "pollen", colnames(data.full)[-1], factor_key = TRUE) Non.interpolated <- gather (data, "type", "pollen", colnames(data.full)[-1], factor_key = TRUE) Interpolated$Interpolated <- 1 Interpolated$Interpolated[which(Interpolated$pollen == Non.interpolated$pollen)] <- 0 colnames(Interpolated) <- c("Date", "Type", "Pollen", "Interpolated") if(result=="long"){ return(Interpolated) print(paste( "Process completed: If the data has been interpolated it is marked with 1" )) }else{return(data.full)} }else{ ######CONVERSION DE DATOS WIDE-LONG ConvertData1 <- function(Dataf) { cols <- ncol(Dataf) Nombres <- colnames(Dataf) idvariables <- Nombres[1] Tipos <- Nombres[2:cols] Result <- gather(Dataf, "Type", "Pollen", Tipos, factor_key = TRUE) return(Result) } Long <- ConvertData1(data) Warning <- FALSE RawData <- na.omit(Long) Interpolated <- rep(0, nrow(RawData)) RawData <- data.frame(RawData, Interpolated) RawData[, 1] <- as.Date(RawData[, 1], origin = "1970-01-01") First <- min(RawData[, 1]) Last <- max(RawData[, 1]) PollenTypes <- unique(RawData[, 2]) nPollenTypes <- length(PollenTypes) for (a in 1:nPollenTypes) { Active_Pollen <- as.character(PollenTypes[a]) Datatemp <- RawData[RawData[, 2] == Active_Pollen, ] Days <- nrow(Datatemp) Interpolate <- data.frame() for (c in 1:(Days - 1)) { if ((Datatemp[c, 1]) != (Datatemp[c + 1, 1] - 1)) { Interpolate <- rbind(Interpolate, Datatemp[c, 1:4], Datatemp[c + 1, 1:4]) } } nInterpolate <- nrow(Interpolate) if (nInterpolate >= 2) { pares <- seq(1, nInterpolate, by = 2) npares <- length(pares) #Bucle que va cogiendo todos los pares de fechas que definen el hueco que hay. Va dando saltos de 2 en 2. for (d in 1:npares) { Active_InterpolStart <- pares[d] #Posicion en la que empieza el salto Active_InterpolEnd <- pares[d] + 1#Posicion en la que acaba el salto Datatemp2 <- Interpolate[Active_InterpolStart:Active_InterpolEnd, 1:3]#Dataframe que contiene las dos lineas del salto. colnames(Datatemp2) <- c("Date", "Type", "Pollen") ncasos <- as.numeric(Datatemp2[nrow(Datatemp2), 1] - Datatemp2[1, 1])#Numero de dias que faltan ncasos <- ncasos - 1 #Numero de datos a introducir. Date <- c() if (ncasos <= maxdays) { #No interpola si los datos que faltan son mas de 30. Type <- as.character(c()) prediccion <- data.frame() for (l in 1:ncasos) { ##Va creando los datos vacios para rellenar con el metodo Active_Date <- as.Date((as.numeric(Datatemp2[1, 1]) + l), origin = "1970-01-01") Date <- as.Date(c(Date, Active_Date), origin = "1970-01-01") Type <- as.character(c(Type, Active_Pollen)) } Pollen <- rep(NA, ncasos) prediccion <- data.frame(Date, Type, Pollen) #######METER AQUi TODOS LOS MeTODOS #LINEAL if (method == "lineal") { modelo <- lm(Pollen ~ Date, data = Datatemp2)#Modelo lineal prediccion$Pollen <- predict.lm(modelo, prediccion) } #MEDIA MoVIL if (method == "movingmean") { ma1 <- function(arr, n = 10) { if (n %% 2 == 0) { n = n + 1 try(warning (paste("WARNING! moving average is calculated for n:", n))) } temp <- arr for (i in 1:length(arr)) { if (i <= (n - 1) / 2) { init <- 1 } else{ init <- i - (n - 1) / 2 } if (i > length(arr) - (n - 1) / 2) { end <- length(arr) } else{ end <- i + (n - 1) / 2 } temp[i] = mean(arr[init:end], na.rm = T) } return(temp) } ftr <- (ncasos + 1) * factor Dt <- Datatemp[Datatemp[, 1] >= as.Date(Datatemp2[1, 1] - ftr) & Datatemp[, 1] <= as.Date(Datatemp2[2, 1] + ftr), 1:3] colnames(Dt) <- colnames(prediccion) prediccion[, 3] <- as.numeric(prediccion[, 3]) Dt <- rbind.data.frame(Dt, prediccion) Dt <- Dt[order(Dt[, 1]), ] Dt$Interpolated <- ifelse(is.na(Dt[, 3]), 1, 0) Dt[, 3] <- ma1(Dt[, 3], ftr) solution <- Dt[which(Dt[, 4] == 1), 3] prediccion$Pollen <- solution } #SPLINE if (method == "spline") { Df <- Datatemp[which(Datatemp[, 1] >= (Datatemp2[1, 1] - ndays) & Datatemp[, 1] <= (Datatemp2[2, 1] + ndays)), ] modelo <- smooth.spline(x = as.numeric(Df[, 1]), y = Df[, 3], spar = spar) prediccion$Pollen <- predict(modelo, x = as.numeric(prediccion[, 1]))$y prediccion[which(prediccion$Pollen < 0), 3] <- 0 } ########Near Station if(method=="neighbour"){ tryCatch({ mother<-data[,c(1,which(colnames(data)==Active_Pollen))] mother[,1]<-as.Date(mother[,1]) nmother<-nrow(mother) emptiness<-data.frame(as.Date(seq(mother[1,1],mother[nmother,1], by="days"))) colnames(emptiness)<-colnames(mother)[1] motherframe<-merge(emptiness, mother, by.x=c(colnames(emptiness)[1]), all.x = TRUE) data2[,1]<-as.Date(data2[,1]) colnames(data2)[1]<-colnames(data)[1] nameneigh<-colnames(data)[1] neighbours<-merge(motherframe, data2[,c(nameneigh,Active_Pollen)], by= colnames(Datatemp)[1], all.x=T) colnames(neighbours)<-c(colnames(neighbours)[1], "station1", "station2") if(!is.null(data3)){ data3[,1]<-as.Date(data3[,1]) colnames(data3)[1]<-colnames(data)[1] neighbours<-merge(neighbours, data3[,c(nameneigh, Active_Pollen)], by= colnames(Datatemp)[1], all.x=T) colnames(neighbours)<-c(colnames(neighbours)[1], "station1", "station2", "station3") } if(!is.null(data4)){ data4[,1]<-as.Date(data4[,1]) colnames(data4)[1]<-colnames(data)[1] neighbours<-merge(neighbours, data4[,c(nameneigh, Active_Pollen)], by= colnames(Datatemp)[1], all.x=T) colnames(neighbours)<-c(colnames(neighbours)[1], "station1", "station2", "station3", "station4") } if(!is.null(data5)){ data5[,1]<-as.Date(data5[,1]) colnames(data5)[1]<-colnames(data)[1] neighbours<-merge(neighbours, data5[,c(nameneigh,Active_Pollen)], by= colnames(Datatemp)[1], all.x=T) colnames(neighbours)<-c(colnames(neighbours)[1], "station1", "station2", "station3", "station4", "station5") } neighbourscomplete<-neighbours#Guardo una copia de los datos sin filtrar neighbours[neighbours<=5]<-NA#Quito todos los datos que tengan menos de 5 granos. No son fiables para hacer regresiones ncolsneig<-ncol(neighbours) for(q in 3:ncolsneig){ Correlval<-cor.test(neighbours[,2], neighbours[,q], method = "spearman")#Hago correlaciones para ver si las estaciones se relacionan lo suficiente como para aplicar el metodo if(as.numeric(Correlval$estimate)<mincorr){neighbourscomplete[,-q]}#Quito las correlaciones que no llegan al minimo } #Si no hay estaciones que tengan suficiente indice de correlacion te imprime un error if(ncol(neighbourscomplete)==2){stop(paste("ERROR: None of the neighbour stations have enough correlation with your station to use this method for a mincorr=", mincorr))} regresion<-neighbours[,-1] ###Hago las regresiones regresion<-na.omit(regresion)#Datos para entrenar que sean >5 y sin NA npred<-nrow(prediccion)#Numero de datos a predecir #Datos originales de todas las estaciones gooddata<-neighbourscomplete[which(neighbourscomplete[,1]>=prediccion[1,1] & neighbourscomplete[,1]<=prediccion[npred,1]),] columnas<-colnames(regresion) ncolumn<-length(columnas) for(x in 2:ncolumn){ Active_column<-columnas[x] if(anyNA(gooddata[,Active_column])){regresion<-regresion[,-which(colnames(regresion)==Active_column)]} } if(class(regresion)=="data.frame"){ modelo<-lm(station1~.+0, data = regresion) prediccion$Pollen<- predict.lm(modelo, gooddata[,-1]) } }, error = function(e){ print("Warning: Some of the gaps may not be interpolated due to lack of data") })} ########FIN MeTODO Interpolated <- rep(1, ncasos) prediccion <- data.frame(prediccion, Interpolated) prediccion<-na.omit(prediccion) colnames(prediccion) <- colnames(RawData) RawData <- rbind(RawData, prediccion) } else{ Warning <- TRUE } } } if (plot == TRUE) { Years <- as.numeric(unique(strftime(Datatemp[, 1], "%Y"))) nyears <- length(Years) par(mfrow = c(ceiling(nyears / 4), 4), mar = c(1, 1, 1, 0)) for (f in 1:nyears) { Active_Year <- Years[f] Dataplot <- RawData[which(as.numeric(strftime(RawData[, 1], "%Y")) == Active_Year & RawData[, 2] == Active_Pollen), ] Dataplot <- Dataplot[order(Dataplot[, 1]), ] ndataplot<-nrow(Dataplot) date<-as.Date(as.Date(Dataplot[1,1]):as.Date(Dataplot[ndataplot,1]), origin = "1970-01-01") Emptydata<-data.frame(date, Type=Active_Pollen) colnames(Emptydata)<-colnames(Dataplot)[c(1:2)] Dataplot1<-merge(Emptydata, Dataplot, by.x = c(colnames(Emptydata)[1], colnames(Emptydata)[2]), all.x = TRUE) Dataplot1<-Dataplot1[,1:3] Predicted <- Dataplot[which(Dataplot[, 4] == 1), 1:3] Prediplot <- merge( Emptydata, Predicted, by.x = c(colnames(Predicted)[1], colnames(Predicted)[2]), all.x = TRUE ) plot(y=Dataplot1[,3], x=1:nrow(Dataplot1), type = "l", col="black", lwd=1, main = paste(toupper(Active_Pollen) , Active_Year), xaxt = "n", yaxt = "n") lines( x = 1:nrow(Dataplot1), y = Prediplot[, 3], col = "red", lwd = 2, type = "l" ) points( x = 1:nrow(Dataplot1), y = Prediplot[, 3], col = "red", cex = 0.7, pch = 19 ) } } } colnames(RawData) <- c("Date", "Type", "Pollen", "Interpolated") RawData <- RawData[order(RawData$Type, RawData$Date), ] Date <- seq.Date(First, Last, by = "day") n <- length(Date) #Creo una matriz de datos vacia sobre la que meter los otros datos para que no elimine los NA interestacionales CompleteData <- data.frame() for (a in 1:nPollenTypes) { Active_Type <- as.character(PollenTypes[a]) Type <- rep(Active_Type, n) Complet <- cbind.data.frame(Date, Type) CompleteData <- rbind.data.frame(CompleteData, Complet) } colnames(CompleteData) <- colnames(RawData)[c(1, 2)] #####OUTPUT DataINTER <- merge(CompleteData, RawData, by.x = c(colnames(RawData)[1], colnames(RawData)[2]), all = TRUE) if (Warning == TRUE){ warning (paste("WARNING: Gaps with more than", maxdays, "missing data have not been interpolated"))} if(result=="long"){ return(DataINTER) print(paste( "Process completed: If the data has been interpolated it is marked with 1" )) }else{ DataINTER2<-spread(DataINTER[,1:3], "Type", "Pollen") return(DataINTER2)} }}
/scratch/gouwar.j/cran-all/cranData/AeRobiology/R/interpollen.R