eiPack/0000755000176200001440000000000014374260722011455 5ustar liggesuserseiPack/NAMESPACE0000644000176200001440000000203114374235667012702 0ustar liggesusersuseDynLib(eiPack, .registration = TRUE) export( bounds, cover.plot, densityplot, ei.MD.bayes, ei.reg.bayes, ei.reg, lambda.MD, lambda.reg, lambda.reg.bayes, mergeMD, plot.bounds, read.betas, tuneMD ) importFrom("grDevices", "rainbow") importFrom("graphics", "abline", "axis", "lines", "par", "plot", "segments", "text") importFrom("stats", "as.formula", "density", "dnorm", "lm", "median", "model.frame", "model.matrix", "model.response", "na.omit", "quantile", "rchisq", "rgamma", "rnorm", "sd") importFrom("utils", "read.table") importFrom("MASS", "mvrnorm") importFrom("coda", "is.mcmc", "as.mcmc", "mcmc", "mcpar") S3method(densityplot, lambdaMD) S3method(densityplot, lambdaReg) S3method(densityplot, lambdaRegBayes) S3method(summary, eiRegBayes) S3method(summary, eiReg) S3method(summary, eiMD) S3method(print, eiMD) S3method(print, eiReg) S3method(print, eiRegBayes) S3method(print, eiMDsum) S3method(print, eiRegBayesSum) S3method(print, bounds) S3method(plot, bounds) eiPack/demo/0000755000176200001440000000000014374235671012406 5ustar liggesuserseiPack/demo/ei.reg.bayes.R0000644000176200001440000000022614374235671015004 0ustar liggesusersdata(redistrict) out <- ei.reg.bayes(cbind(dem, rep, novote) ~ cbind(black, white, hispanic), data = redistrict) summary(out) eiPack/demo/lambda.MD.R0000644000176200001440000000062114374235671014247 0ustar liggesusers data(redistrict) data(tuneA) data(tuneB) tuneB <- array(tuneB[[1]], dim = c(3, 2, 150)) out <- ei.MD.bayes(cbind(dem, rep, novote) ~ cbind(black, white, hispanic), data = redistrict, lambda1 = 4, lambda2 = 2, tune.list = list(tuneA, tuneB), sample = 1000, thin = 200, burnin = 0, verbose = 1000) lambda <- lambda.MD(out, c("dem", "rep")) densityplot(lambda) eiPack/demo/ei.MD.bayes.R0000644000176200001440000000124214374235670014525 0ustar liggesusers data(redistrict) data(tuneA) data(tuneB) tuneB <- array(tuneB[[1]], dim = c(3, 2, 150)) out2 <- ei.MD.bayes(cbind(dem, rep, novote) ~ cbind(black, white, hispanic), data = redistrict, lambda1 = 4, lambda2 = 2, tune.list = list(tuneA, tuneB), sample = 1000, thin = 200, burnin = 0, verbose = 1000) summary(out2) data(senc) out3 <- ei.MD.bayes(cbind(dem, rep, non) ~ cbind(white, black, natam), covariate = ~ I(white/total), data = senc, sample = 1000, thin = 100, burnin = 100000, verbose = 1000, ret.beta='r') summary(out3) eiPack/demo/lambda.reg.R0000644000176200001440000000025214374235671014524 0ustar liggesusersdata(senc) out <- ei.reg(cbind(dem, rep, non) ~ cbind(black, white, natam), data = senc) lambda <- lambda.reg(out, c("dem", "rep")) densityplot(lambda) eiPack/demo/bounds.R0000644000176200001440000000047014374235670014023 0ustar liggesusers data(senc) out <- bounds(cbind(dem, rep, non) ~ cbind(black, white, natam), data = senc, rows = c("black", "white"), column = "dem", excluded = "non", threshold = 0.9) par(ask = TRUE) plot(out, row = "black", column = "dem") plot(out, row = "white", column = "dem") par(ask = FALSE) eiPack/demo/ei.reg.R0000644000176200001440000000017014374235671013700 0ustar liggesusersdata(senc) out <- ei.reg(cbind(dem, rep, non) ~ cbind(black, white, natam), data = senc) summary(out) eiPack/demo/00Index0000644000176200001440000000065214374235670013542 0ustar liggesusersbounds Demo file for bounds ei.MD.bayes Demo file for RxC Multinomial Dirichlet model with and without covariate ei.reg Demo file for Goodman's ecological regression ei.reg.bayes Demo file for a Bayesian version of Goodman's ecological regression lambda.MD Demo file for lambda.MD lambda.reg.bayes Demo file for lambda.reg.bayes lambda.reg Demo file for lambda.reg eiPack/demo/lambda.reg.bayes.R0000644000176200001440000000030714374235671015627 0ustar liggesusersdata(senc) out <- ei.reg.bayes(cbind(dem, rep, non) ~ cbind(black, white, natam), data = senc) lambda <- lambda.reg.bayes(out, c("dem", "rep"), ret.mcmc = TRUE) densityplot(lambda) eiPack/LICENSE0000644000176200001440000000174314374237763012500 0ustar liggesuserseiPack: Ecological Inference and Higher-Dimension Data Management Copyright (C) 2006-2023. Olivia Lau, Ryan Moore, and Michael Kellermann. 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 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Please contact: Michael Kellermann United States Naval Academy 105 Maryland Avenue Annapolis, MD 21401 Email: mrkellermann@gmail.com With any problems or questions. eiPack/data/0000755000176200001440000000000014374235670012372 5ustar liggesuserseiPack/data/tuneA.tab.gz0000644000176200001440000000016214374235670014554 0ustar liggesusersu @ C"DI=kSءwfݸL_eiPack/data/senc.tab.gz0000644000176200001440000001704614374235670014441 0ustar liggesusers}rGzs%HB"B HkwGXطlDYzoǗ~?埿//??_/~;g??%,^wnnvχwCJBCRC/[}IC~8߽bn!؇{bdIӐ}87II$؟8N=mݻ}zVýL5 ShCAIqe 5 `qwRjznGia:r˜i6m 1qc]Y\?>W!>q([u(y0k.&SL'վclW"؟ y覅i>MCi8E$ئm]= %zmДؚn4L6!vJ ~?޼l]4`Sv|y77eUaȶ"iJzjn{E(ym1 C6aOcy5U"{®C0mɑbhd蛯31#GG~&=Qihmf n ͧs&n)И&~%~s8Y(~h0ўUPF %6{-5Wws . tln)rۺW҃k5FeBÕPu# { fǓ9T';?DoOMlzc6#b6f/ng1[mHb锦ҕ̛vVdœbX34T"[Q`;n\1_ m7oV(' jC 3I,1cy%qŰO{-9"dcQKZ2m'K^ޮ;%>Ph4kTuJd&t9!v-r2llZ$h6K顒_[ڷvz<榡g Cfet[l&oNtWẂ+_0Q8r2)u3sJt!P8*vtҴZi=t˕iuO׾t!1sSPTL6=Mv2렧tFn1Ux– eMͭ` I ݎҵ+Q'++ثh5I&0i:];,~~p-عPB[I0zQb9^yT7P 0W+ 8*ڙ/OO7KM=qascZ3}ZޮV{`~n)"S! C=ړ[ÆgF6tHv,TS$4hLҵ?ь)D!. F4XK'ԯ}p2ƪp+ZC['>b;& i q~?lG%(,Xm+'Rf?l_޿e5LM],4kڜ}xi mNKGw@rĚzv 4Prﺢ=vyȼhy?Vy2EP`X Զ@ٔ0!sYݯ@O MMj%QY5ڔCCՄ֥PEb$l5͚) 5SV@+ &}Uݬ,&2CmUKtRD c\yˇބl+b8l iPHJ M,ovP,S 0*D4D xo (Lb;rN(hf֙ZP(8LIu&U+XO.""uFd/GS֨W!EMf8Ĩ!ۀt&ə$$zkqҥQN{aҦ?ZWz~!AJgjB](kP[b eځ,|u}mEuARrtkIK+b8UQqBA`,Eno)|s'`0岣x ۂIe:֪# rȪPg@բrb,3_ʼ]m?? Uq 3xZptǪ?%HII5;\Eh2Ap,t}w{f^(0IG\V[Ⱥ_7ϟ4 !18B<ABQ~d/mem@/BQ<͆@H ^0X0Dأx=KiKŶV!,RLOOއ& 5Rq+pnâȽO|\?T)_'UghR  ~jY&7r"1ńSim #}H&gܸ.7cc (gΧӤ!)dC2 aK;eV\L GV8LE 1}Q_1$U$* ަJb72ab@b&ϓSy>16yt>&,f7$ۉQ(  4Lj1:?`e |#Р^Gc&5@Ö:nyX$ȘDk3HO2j` @[t,Hkmx^ )x {RT54aQ.j05DC)Ϩ !u> E=ϒ@WU*\Є qu0\Z}@b+wj;<6]D+jSMXժ)K=csx=f"X|νU74k\Mʒ 8cXDk\5(ɱr.¡1%"*6n;>/7" …yɆY H۟:-ĭ֐Fm!wmy 5{ppgY})˪[MveA(-1VkɓV@DMJ3(+hB$x* l`zdܘG@@H9ZRn}j/̽⃇LUlı\Jj3fs7U DZ^J}Z?l׫w+0BI$H4&}fS@~v?GCyg4H;7&͚@y;{V]q dV Cj`uG9U$v'V-G[vM4W5J p-GW̶R; `쥈)O*9O%gX8ӓYl9mtPjW֪ ?jyW&#l!w6g4S91 /J2Bvuq8|Z= W{)1 gޠBEsԭ@HB~ 02 X*(T[c4y 1k40ژ"y3Ȅ$Nc%@WSQ鬢tҵFDzyCJ!lN^YD$]$GBh7' pcuNY 1!6b{Ct'済cҺ5HUbMuF-fJAlXC:KyX8 hC[Ai7dѪLd_ q "# MݤȚb.Ott%6!vR%dÅ;HL$>qm!NMJCigY }!x鄻ј %NNWwukuwOG}M_'2 ɕZEڡ7[7GO뇛ڻ[FKNˮYädD}A1.(B~-^@vyNWLx`GA 6OK]w෕BHPwk.aa4`W reĽrcwyf -=myhl2Q68Sx*>|5;j[rx zЦнISk,TBT4^l=ÕG;ӯ75[A γLdl奻w)$ԌIstGFz44@T A+ &\rPT#'L5⾪-E3TJŦpWAQWqn'6+p(\gv]~$(=VT~LUS1_y&|uufCB՚'Vu{3ޖ޶U}ʁ :PK;<|?މL&mMtIHo$ =ң,rC̠MHu۪U ʤ,}~ɭ}St]l]NޙU9/}rrMХNНnu Ch85=K$/*]htN/s(jgv IF4f5r:_ZX~)y@VAIPJw{6t1,qtWw9)q'NP}>WyhB,jy*8/5oda'5G i 1@C!6wwӈ.q@X^n),=3aL=գ8z[;⿦g~K 3b|]$֥1a^) lwҜE-춨o5&EN¬sh¿dK^ yWn [Eh;cpZCb]y9d.p{ǔ. J&HhEU*ҝ;_8էEK#g"k%..VێlRsKg"T,۫\i( ֥Z՝a;{uʿ8<*ZgKw}RCoե+=, >3JKg7PN]|F*{;#qZ$ 2JV?yk<+-!X]Q'^mehyhV~&AhCxiKtk ,h"e?ȃ5W`ukd,]gbig祲f3g6HL̓ikˌy4*%[j3j-nyḶXᰰ(7̬%OZk?y>QsJN1.U<18 g?'>K}kރ)J@q(N@q<7 K53 6l P\s*.c9W)Dn>g wg 7`<5v ۞I:oj=ʰ(3<''L3 lbkv |/Kɑ0eHe|?CA},C3fKEH]&JI ey}P2Zd^k9|&}Pu~ЙdȡTۢEᰪ{6^Z53E<-YKgD0ʇ_݃z ֍3&9$ޑF}Nr֕eZӓ/&Э; Hdp9K. t=Ogܟ/``p>˼.r+0P@p;kXJ"93k!%I;is\äD^.6]^H;c+燤]&}n5MCӮ.CV̛UO( һTfƢ_w(WʢSN_4HK32-\K#1M 8F֥9\<4s@y_Dzs*ubN-('-QޚLKI{;Ď!cV}(>Q$崜5DGM]AiiVYͷN[ triy8y X›>$ힾ&|봯ߑMb4kB8a7(+ᛢPtB^ٯ70;mS ,*N2/H2(+8_x臟)~م2_ P29fÉWEK \ t?hhwt: PxٵK$4W p3w>Jnpt (;Hh%g`FcE$WBw`!j} IA3TZT[1p8=@\[ 3$''#s&)A?s5e hfv#/(LiX09LN'7(7}ٍEbo\No+7MoJdr\2ܠ,mMq ǂ"XX+]ո eSԢ]& <8oUvJ+!B@%/ !`{ + 8CY3C0H> Uah7 ha` AY0 p{5;yO)hql (w(4 T{ۿB9~v0gA%?hpˎz7P #yrFNP \H<9S[p Т< (yK$Y~f|7|!iwh9htٜtn6| س)Rڦ] Ua iףrAuRϙs&9JI='hID-eukUS!3i\_b% 3$3-Y-`:ک~̴̤̄9Ԕ6iӀKn@t8BCl% P4AJKr9hZd ~pLp93f_ S3U3ԕ$3NHg]ZQ$3YR4Iiy(ڵU-kn?C. 5Ihm޼ruo&of=$3L&Cg~MkLҒ:9Lܠ(%Q`}&@@nahu>AH+9|"TjLtгZՂvw;P?M)h鬯7/jt^zR/09Z:h=q"nVQv,6u Ae]e /(}M. q{vY."Z9x~Fg9-tX |*5&PъT *V*PIYxfAo/X&-9[MNgk7+ݏABk:`uB"oj*?JaJ߮ tⶹ ZfW'F7 lv8粬nΦ50fl>T%1XnMh}krvVrv QS/g'}M]sF+7ʍ+&>J5+e|l9(svAa_dt6Uuv=*5:5:jdt6lxHo9h}D7\ˆ~Psn?cWWVeiPack/data/redistrict.tab.gz0000644000176200001440000001002114374235670015647 0ustar liggesusers=ێ7D9Zy` [Id@$3##"?߾/?׷>>ǗۏO>}?~|gתSۓ_sRg)-?xJOegri2+ól~fO)gTN=uFܵ a^b.6d-6u(9w߂Gsb@p`BX7mS2ΖlV%aJ~.;ꢞ<(- $Xkh݄kg궕lX9G=#s('UAzgJLqr(,:d?q'b,ABdܬ FXˑGr'_F0(:s^8w9&~)cyˈUp5eo0 .:ze"=(BݠDd= P{yBɋ,7⾄y<JMm%.CMa@dtِjA|l{Tzϗ|NZdFT <(gs"OΚT5 #!E7?9(g;lna@CB%gTg 6?m$6x@NQ*0eVt,ڸXэK>  *fDjH i*+!?X*3 JQ[33lDvGp5A2|)ߵi-a8J-xYi}΢p<Դ.iNPOr#:9z>W t Um2 ِS][qzM;1flGs3~:䛇[GiS7jT}F޲!G+1c2−gn^C3#2usF׍7ImM g;)p-/!++q"՝+D1@j'8mw v%P#jhF{5$:4-vgǨ'Qۚi}0 [>K0yN)2x7KF|5.9_^+ŝ'Q&26C-a"r>=;ؗ6S";<'*:CAMh. `=npч,`&z![!KF|{6q*O^T *,g-Ɨc=eENځj_w88*昒PiNFO(D\YRhZZkځ u@v5a)njЯQCdZ'LXs20VfvᘽEVY( I-ė%$֤Da1Ң" _18pq91%@M n:S!b:[fn޸**J^ ԡf(nI O3巊m;0nѕY^)L|?@:vmElqEt%cc\r+؅5I^vy/elĀ<1e鼑A@*Is-:pА}B) -詞a)AzP@b[wkD!vJ˪.Ք঒hQ5ᣃDpYb&dɏbAҥP-aeEi$èd;P>hoHOf{uRog-H:pݾB NYv\3۪8H Yu6gM593O44g*:[oWʺIixEb:ωc2exFl݇H_]-¿Nt&eVǞv"Xbs31\3N"|q :a?뱮);]-hĿ#v*k AMU 76UMʯj)4"sY?bĹ_`zBEV_v{M־.2vz=W%'!R6p#c &qw'Ӻ`Y8&\T#NkxPBE0T8ޢ}.4oI8t3F(Xb 4—G"\wb",7;at9@{(Y݉Cj4ѝ1=Q _vZ%= G]%#31ғ( &qH 3i._ibCq9/t"9pt`9B.}N{4o.ӪCk}kx6@/~:I7Q:а'(ٺ OxY„s 7N5)yF0⊀qnlk0#|feiPack/man/0000755000176200001440000000000014374235671012235 5ustar liggesuserseiPack/man/lambda.reg.bayes.Rd0000644000176200001440000000171514374235671015626 0ustar liggesusers\name{lambda.reg.bayes} \alias{lambda.reg.bayes} \title{Calculate shares using data from Bayesian regression model} \description{Calculates the population share of row members in selected columns} \usage{ lambda.reg.bayes(object, columns, ret.mcmc = TRUE) } \arguments{ \item{object}{An R object of class \code{eiRegBayes}, the output from \code{\link{ei.reg.bayes}}} \item{columns}{a character vector indicating which column marginals to be included in calculating the shares} \item{ret.mcmc}{If TRUE, posterior shares are returned as an \code{mcmc} object.} } \value{ If \code{ret.mcmc = TRUE}, draws are returned as an \code{mcmc} object with dimensions sample \eqn{\times C}{x C}. If \code{ret.mcmc = FALSE}, draws are returned as an array with dimensions \eqn{R \times C \times }{R x C x} samples array. } \seealso{\code{\link{ei.reg.bayes}}} \author{ Ryan T. Moore <\email{rtm@american.edu}> } \keyword{models} eiPack/man/read.betas.Rd0000644000176200001440000000257514374235671014545 0ustar liggesusers\name{read.betas} \alias{read.betas} \title{Function to read in eiMD parameter chains saved to disk} \description{ In \code{\link{ei.MD.bayes}}, users have the option to save parameter chains for the unit-level betas to disk rather than returning them to the workspace. This function reconstructs the parameter chains by reading them back into R and producing either an array or an \code{mcmc} object. } \usage{ read.betas(rows, columns, units, dir = NULL, ret.mcmc = TRUE) } \arguments{ \item{rows}{a character vector of the row marginals to be read back in} \item{columns}{a character vector of the column marginals to be read back in} \item{units}{a character of numeric vector with the units to be read back in} \item{dir}{an optional character string identifying the directory in which parameter chains are stored (defaults to \code{getwd})} \item{ret.mcmc}{a logical value specifying whether to return the parameters as an \code{mcmc} object (defaults to \code{TRUE})} } \value{ If \code{ret.mcmc = TRUE}, an \code{mcmc} object with row names corresponding to the parameter chains. If \code{ret.mcmc = FALSE}, an array with dimensions named according to the selected \code{rows}, \code{columns}, and \code{units}. } \author{Olivia Lau } \seealso{\code{\link{ei.MD.bayes}},\code{mcmc}} \keyword{IO} \keyword{utilities} eiPack/man/bounds.Rd0000644000176200001440000000404214374235671014016 0ustar liggesusers\name{bounds} \alias{bounds} \title{Deterministic bounds for units satisfying row thresholds} \description{Calculates the deterministic bounds on the proportion of row members within a specified column.} \usage{ bounds(formula, data, rows, column, excluded = NULL, threshold = 0.9, total = NULL) } \arguments{ \item{formula}{a formula of the form \code{cbind(col1, col2, ...) ~ cbind(row1, row2, ...)}. Column and row marginals must have the same total for each ecological unit.} \item{data}{a data frame containing the variables specified in \code{formula} and (optionally) \code{total}} \item{rows}{a character vector specifying the rows of interest} \item{column}{a character string specifying the column marginal of interest} \item{excluded}{an optional character string (or vector of character strings) specifying the columns to be excluded from the bounds calculation. For example, if the quantity of interest is Democratic share of the two-party vote, non-voters would be excluded.} \item{threshold}{the minimum proportion of the unit that row members must comprise for the bounds to be calculated for the unit. If \code{threshold = 0}, bounds will be calculated for all units.} \item{total}{if row and/or column marginals are given as proportions, \code{total} identifies the name of the variable in \code{data} containing the total number of individuals in each unit} } \value{ A list with elements \item{bounds}{a list of deterministic bounds for all units in which row proportions meet the threshold} \item{intersection}{if the intersection of the deterministic bounding intervals is non-empty, the intersection is returned. Otherwise, \code{NA} is returned.} } \seealso{\code{plot.bounds}} \references{ Otis Dudley Duncan and Beverley Davis. 1953. ``An Alternative to Ecological Correlation.'' \emph{American Sociological Review} 18: 665-666. } \author{ Ryan T. Moore <\email{rtm@american.edu}> } \keyword{models} eiPack/man/lambda.reg.Rd0000644000176200001440000000464014374235671014524 0ustar liggesusers\name{lambda.reg} \alias{lambda.reg} \title{Calculate shares using data from regression model} \description{Calculates the population share of row members in a particular column} \usage{ lambda.reg(object, columns) } \arguments{ \item{object}{An R object of class \code{eiReg}, the output from \code{\link{ei.reg}}} \item{columns}{a character vector of column names to be included in calculating the shares} } \value{ Returns a list with the following elements \item{call}{the call to \code{lambda.reg}} \item{lambda}{an \eqn{R \times k}{R x k} matrix where \eqn{k}{k} is the number of columns included in the share calculation} \item{se}{standard errors calculated using the delta method as implemented in the library \code{msm}} } \details{ Standard errors are calculated using the delta method as implemented in the library \code{msm}. The arguments passed to \code{deltamethod} in \code{msm} include \itemize{ \item{\code{g}}{a list of transformations of the form \code{~ x1 / (x1 + x2 + + ... + xk)}, \code{~ x2 / (x1 + x2 + ... + xk)}, etc.}. Each \eqn{x_c}{xc} is the estimated proportion of all row members in column \eqn{c}{c}, \eqn{\hat{\beta}_{rc}}{beta_rc} \item{\code{mean}}{the estimated proportions of the row members in the specified columns, as a proportion of the total number of row members, \eqn{(\hat{\beta}_{r1}, \hat{\beta}_{r2}, ..., \hat{\beta}_{rk})}{(beta_r1, beta_r2, ..., beta_rk)}.} \item{\code{cov}}{a diagonal matrix with the estimated variance of each \eqn{\hat{\beta}_{rc}}{beta_rc} on the diagonal. Each column marginal is assumed to be independent, such that the off-diagonal elements of this matrix are zero. Estimates come from \code{object$cov.matrices}, the estimated covariance matrix from the regression of the relevant column. Thus, } } \tabular{cccccc}{ cov \tab = \tab \eqn{Var(\hat{\beta}_{r1})}{Var(beta_r1)} \tab 0 \tab 0 \tab \eqn{\ldots}{...} \cr \tab \tab 0 \tab \eqn{Var(\hat{\beta}_{r2})}{Var(beta_r2)} \tab 0 \tab \eqn{\ldots}{...} \cr \tab \tab 0 \tab 0 \tab \eqn{Var(\hat{\beta}_{r3})}{Var(beta_{r3})} \tab \eqn{\ldots}{...} \cr \tab \tab \eqn{\vdots}{...} \tab \eqn{\vdots}{...} \tab \eqn{\vdots}{...} \tab \eqn{\ddots}{...}\cr } } \seealso{\code{\link{ei.reg}}} \author{ Ryan T. Moore <\email{rtm@american.edu}> } \keyword{models} eiPack/man/tuneA.Rd0000644000176200001440000000037314374235671013603 0ustar liggesusers\name{tuneA} \alias{tuneA} \title{Tuning parameters for alpha hyperpriors in RxC EI model} \description{ Tuning parameters for hyperpriors in RxC EI model } \usage{data(tuneA)} \format{A table containing 3 rows and 3 columns.} \keyword{datasets} eiPack/man/redistrict.Rd0000644000176200001440000000150514374235671014701 0ustar liggesusers\name{redistrict} \alias{redistrict} \title{Redistricting Monte-Carlo data} \description{ Precinct-level observations for a hypothetical jurisdiction with four proposed districts. } \usage{data(redistrict)} \format{A table containing 150 observations and 9 variables: \describe{ \item{precinct}{precinct identifier} \item{district}{proposed district number} \item{avg.age}{average age} \item{per.own}{percent homeowners} \item{black}{number of black voting age persons} \item{white}{number of white voting age persons} \item{hispanic}{number of hispanic voting age persons} \item{total}{total number of voting age persons} \item{dem}{Number of votes for the Democratic candidate} \item{rep}{Number of votes for the Republican candidate} \item{no.vote}{Number of non voters} }} \source{Daniel James Greiner} \keyword{datasets} eiPack/man/density.plot.Rd0000644000176200001440000000450514374235671015164 0ustar liggesusers\name{densityplot} \alias{densityplot} \alias{densityplot.lambdaMD} \alias{densityplot.lambdaReg} \alias{densityplot.lambdaRegBayes} \title{Density plots for population level parameters} \description{Generates a density plot for population level quantities of interest output by \code{\link{lambda.MD}}, \code{\link{lambda.reg}}, and \code{\link{lambda.reg.bayes}}. For the Bayesian methods, \code{densityplot} plots the kernel density for the draws. For the frequentist \code{\link{lambda.reg}} method, \code{densityplot} plots the canonical Normal density conditional on the mean and standard error output by \code{\link{lambda.reg}}.} \usage{ \method{densityplot}{lambdaMD}(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) \method{densityplot}{lambdaRegBayes}(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) \method{densityplot}{lambdaReg}(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) } \arguments{ \item{x}{output from \code{\link{lambda.MD}}, \code{\link{lambda.reg}}, or \code{\link{lambda.reg.bayes}}.} \item{by}{character string (defaulting to \code{"column"}) specifying whether to panel the density plot by \code{"row"} or \code{"column"} marginal.} \item{col}{an optional vector of colors, with length corresponding to the number of marginals selected in \code{by}. Defaults to \code{rainbow}.} \item{xlim,ylim}{optional limits for the x-axis and y-axis, passed to \code{plot}.} \item{main,sub}{optional title and subtitle, passed to \code{plot}.} \item{xlab,ylab}{optional labels for the x- and y-axes, passed to \code{plot}.} \item{lty,lwd}{optional arguments for line type and line width, passed to \code{lines} and \code{plot}. If either \code{lty} or \code{lwd} are vectors, it must correspond to the number of row or column marginals selected.} \item{...}{additional arguments passed to \code{par}.} } \value{ A plot with density lines for the selected margin (row or column). } \seealso{\code{plot}, \code{segments}, \code{par}} \author{ Olivia Lau <\email{olivia.lau@post.harvard.edu}> } \keyword{hplot} eiPack/man/tuneMD.Rd0000644000176200001440000000217414374235671013724 0ustar liggesusers\name{tuneMD} \alias{tuneMD} \title{Generate tuning parameters for MD model} \description{An adaptive algorithm to generate tuning parameters for the MCMC algorithm implemented in \code{\link{ei.MD.bayes}}. Since we are drawing each parameter one at a time, target acceptance rates are between 0.4 to 0.6.} \usage{ tuneMD(formula, covariate = NULL, data, ntunes = 10, totaldraws = 10000, ...) } \arguments{ \item{formula}{A formula of the form \code{cbind(col1, col2, ...) ~ cbind(row1, row2, ...)} with rows as the predictor and columns as the response} \item{covariate}{An R formula for the optional covariate in the form \code{~ x}} \item{data}{data frame containing the variables specified in \code{formula} and \code{covariate}} \item{ntunes}{number of times to iterate the tuning algorithm} \item{totaldraws}{number of iterations for each tuning run} \item{...}{additional arguments passed to \code{\link{ei.MD.bayes}}} } \value{ A list containing matrices of tuning parameters. } \seealso{\code{\link{ei.MD.bayes}}} \author{ Olivia Lau <\email{olivia.lau@post.harvard.edu}> } \keyword{iteration} \keyword{utilities} eiPack/man/mergeMD.Rd0000644000176200001440000000215414374235671014046 0ustar liggesusers\name{mergeMD} \alias{mergeMD} \title{Combine output from multiple eiMD objects} \description{Allows users to combine output from several chains output by \code{\link{ei.MD.bayes}} } \usage{ mergeMD(list, discard = 0) } \arguments{ \item{list}{A list containing the names of multiple eiMD objects generated from the same model.} \item{discard}{The number of draws to discard from the beginning of each chain. Default is to retain all draws.} } \value{ Returns an \code{eiMD} object of the same format as the input. } \references{ Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2002. \emph{Output Analysis and Diagnostics for MCMC (CODA)}. \url{ https://CRAN.R-project.org/package=coda}. Ori Rosen, Wenxin Jiang, Gary King, and Martin A. Tanner. 2001. ``Bayesian and Frequentist Inference for Ecological Inference: The \eqn{R \times C}{R x C} Case.'' \emph{Statistica Neerlandica} 55: 134-156. } \author{ Michael Kellermann <\email{mrkellermann@gmail.com}> } \seealso{\code{\link[eiPack]{ei.MD.bayes}}} \keyword{utilities} eiPack/man/ei.reg.Rd0000644000176200001440000000471214374235671013701 0ustar liggesusers\name{ei.reg} \alias{ei.reg} \title{Ecological regression} \description{ Estimate an ecological regression using least squares. } \usage{ ei.reg(formula, data, ...) } \arguments{ \item{formula}{An R formula object of the form \code{cbind(c1, c2, ...) ~ cbind(r1, r2, ...)}} \item{data}{data frame containing the variables specified in \code{formula}} \item{\dots}{Additional arguments passed to \code{\link[stats]{lm}}. } } \value{A list containing \item{call}{the call to \code{ei.reg}} \item{coefficients}{an \eqn{R \times C}{R x C} matrix of estimated population cell fractions} \item{se}{an \eqn{R \times C}{R x C} matrix of standard errors for \code{coefficients}.} \item{cov.matrices}{A list of the \eqn{C}{C} scaled variance-covariance matrices for each of the ecological regressions} } \details{ For \eqn{i \in 1,\ldots,C}{i in 1,...,C}, C regressions of the form \code{c_i ~ cbind(r1, r2, ...)} are performed. These regressions make use of the accounting identities and the constancy assumption, that \eqn{\beta_{rci} = \beta_{rc}}{beta_rci = beta_rc} for all \eqn{i}{i}. The accounting identities include \itemize{ \item{--}{defining the population cell fractions \eqn{\beta_{rc}}{beta_rc} such that \eqn{\sum_{c=1}^{C} \beta_{rc} = 1}{sum_{c=1}^{C} beta_rc = 1} for every \eqn{r}{r}} \item{--}{\eqn{\sum_{c=1}^{C} \beta_{rci} = 1}{sum_{c=1}^{C} beta_rci = 1} for \eqn{r = 1, \ldots, R}{r = 1,...,R} and \eqn{i = 1, \ldots, n}{i = 1,...,n}} \item{--}{\eqn{T_{ci} = \sum_{r=1}^R \beta_{rci}X_{ri}}{T_ci = sum_{r=1}^R beta_rci X_ri} for \eqn{c = 1,\ldots,C}{c = 1,...,C} and \eqn{i = 1\ldots,n}{i = 1,...,n}} } Then regressing \deqn{T_{ci} = \beta_{rc} X_{ri} + \epsilon_{ci}}{T_ci = beta_rc X_ri + epsilon_ci} for \eqn{c = 1,\dots,C}{c = 1,...C} recovers the population parameters \eqn{\beta_{rc}}{beta_rc} when the standard linear regression assumptions apply, including \eqn{E[\epsilon_{ci}] = 0}{E[epsilon_ci] = 0} and \eqn{Var[\epsilon_{ci}] = \sigma_c^2}{Var[epsilon_ci] = sigma_c^2} for all \eqn{i}{i}. } \references{ Leo Goodman. 1953. ``Ecological Regressions and the Behavior of Individuals.'' \emph{American Sociological Review} 18:663--664. } \author{ Olivia Lau <\email{olivia.lau@post.harvard.edu}> and Ryan T. Moore <\email{rtm@american.edu}> } \keyword{models} eiPack/man/ei.MD.bayes.Rd0000644000176200001440000003350314374235671014526 0ustar liggesusers\name{ei.MD.bayes} \alias{ei.MD.bayes} \title{Multinomial Dirichlet model for Ecological Inference in RxC tables} \description{Implements a version of the hierarchical model suggested in Rosen et al. (2001)} \usage{ ei.MD.bayes(formula, covariate = NULL, total = NULL, data, lambda1 = 4, lambda2 = 2, covariate.prior.list = NULL, tune.list = NULL, start.list = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta = 'r', ret.mcmc = TRUE, usrfun = NULL) } \arguments{ \item{formula}{A formula of the form \code{cbind(col1, col2, ...) ~ cbind(row1, row2, ...)}. Column and row marginals must have the same totals.} \item{covariate}{An optional formula of the form \code{~ covariate}. The default is \code{covariate = NULL}, which fits the model without a covariate.} \item{total}{if row and/or column marginals are given as proportions, \code{total} identifies the name of the variable in \code{data} containing the total number of individuals in each unit} \item{data}{A data frame containing the variables specified in \code{formula} and \code{total}} \item{lambda1}{The shape parameter for the gamma prior (defaults to 4)} \item{lambda2}{The rate parameter for the gamma prior (defaults to 2)} \item{covariate.prior.list}{a list containing the parameters for normal prior distributions on delta and gamma for model with covariate. See `details' for more information.} \item{tune.list}{A list containing tuning parameters for each block of parameters. See `details' for more information. Typically, this will be a list generated by \code{\link[eiPack]{tuneMD}}. The default is \code{NULL}, in which case fixed tuning parameters are used.} \item{start.list}{A list containing starting values for each block of parameters. See `details' for more information. The default is \code{start.list = NULL}, which generates appropriate random starting values.} \item{sample}{Number of draws to be saved from chain and returned as output from the function (defaults to 1000). The total length of the chain is \code{sample}*\code{thin} + \code{burnin}.} \item{thin}{an integer specifying the thinning interval for posterior draws (defaults to 1, but most problems will require a much larger thinning interval).} \item{burnin}{integer specifying the number of initial iterations to be discarded (defaults to 1000, but most problems will require a longer burnin).} \item{verbose}{an integer specifying whether the progress of the sampler is printed to the screen (defaults to 0). If \code{verbose} is greater than 0, the iteration number is printed to the screen every \code{verbose}th iteration.} \item{ret.beta}{A character indicating how the posterior draws of beta should be handled: `\code{r}'eturn as an R object, `\code{s}'ave as .txt.gz files, `\code{d}'iscard (defaults to \code{r}).} \item{ret.mcmc}{A logical value indicating how the samples from the posterior should be returned. If \code{TRUE} (default), samples are returned as coda \code{mcmc} objects. If \code{FALSE}, samples are returned as arrays.} \item{usrfun}{the name of an optional a user-defined function to obtain quantities of interest while drawing from the MCMC chain (defaults to \code{NULL}).} } \value{ A list containing \item{draws}{A list containing samples from the posterior distribution of the parameters. If a covariate is included in the model, the list contains: \itemize{ \item{\code{Dr}}{ Posterior draws for Dr parameters as an R \eqn{\times}{x}sample matrix. If \code{ret.mcmc = TRUE}, \code{Dr} is an \code{mcmc} object.} \item{\code{Beta}}{ Posterior draws for beta parameters. Only returned if \code{ret.beta = TRUE}. If \code{ret.mcmc = TRUE}, a (R * C * units) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x} C \eqn{\times}{x} units \eqn{\times}{x} sample array} \item{\code{Gamma}}{ Posterior draws for gamma parameters. If \code{ret.mcmc = TRUE}, a (R * (C - 1)) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x} (C - 1) \eqn{\times}{x} sample array} \item{\code{Delta}}{ Posterior draws for delta parameters. If \code{ret.mcmc = TRUE}, a (R * (C - 1)) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x}(C - 1) \eqn{\times}{x} sample array} \item{\code{Cell.count}}{ Posterior draws for the cell counts, summed across units. If \code{ret.mcmc = TRUE}, a (R * C) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x} C \eqn{\times}{x} sample array} } If the model is fit without a covariate, the list includes: \itemize{ \item{\code{Alpha}}{ Posterior draws for alpha parameters. If \code{ret.mcmc = TRUE}, a (R * C) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x} C \eqn{\times}{x} sample array} \item{\code{Beta}}{ Posterior draws for beta parameters. If \code{ret.mcmc = TRUE}, a (R * C * units) \eqn{\times}{x} sample matrix saved as an \code{mcmc} object. Otherwise, a R \eqn{\times}{x} C \eqn{\times}{x} units \eqn{\times}{x} sample array} \item{\code{Cell.count}}{ Posterior draws for the cell counts, summed across units. If \code{ret.mcmc = TRUE}, a (R * C) \eqn{\times}{x} sample matrix saved as an\code{mcmc} object. Otherwise, a R \eqn{\times}{x} C \eqn{\times}{x} sample array} }} \item{acc.ratios}{ A list containing acceptance ratios for the parameters. If the model includes a covariate, the list includes: \itemize{ \item{\code{dr.acc}}{ A vector of acceptance ratios for \code{Dr} draws} \item{\code{beta.acc}}{ A vector of acceptance ratios for \code{Beta} draws} \item{\code{gamma.acc}}{ A vector of acceptance ratios for \code{Gamma} and \code{Delta} draws} } If the model is fit without a covariate , the list includes: \itemize{ \item{\code{alpha.acc}}{ A vector of acceptance ratios for \code{Alpha} draws} \item{\code{beta.acc}}{ A vector of acceptance ratios for \code{Beta} draws} }} \item{usrfun}{Output from the optional \code{usrfn}} \item{call}{Call to \code{ei.MD.bayes}} } \details{ \code{ei.MD.bayes} implements a version of the hierarchical Multinomial-Dirichlet model for ecological inference in \eqn{R \times C}{R x C} tables suggested by Rosen et al. (2001). Let \eqn{r = 1, \ldots, R}{r = 1, ..., R} index rows, \eqn{C = 1, \ldots, C}{C = 1, ..., C} index columns, and \eqn{i = 1, \ldots, n}{i = 1, ..., n} index units. Let \eqn{N_{\cdot ci}}{N_.ci} be the marginal count for column \eqn{c}{c} in unit \eqn{i}{i} and \eqn{X_{ri}}{X_ri} be the marginal proportion for row \eqn{r}{r} in unit \eqn{i}{i}. Finally, let \eqn{\beta_{rci}}{beta_rci} be the proportion of row \eqn{r}{r} in column \eqn{c}{c} for unit \eqn{i}{i}. The first stage of the model assumes that the vector of column marginal counts in unit \eqn{i}{i} follows a Multinomial distribution of the form: \deqn{(N_{\cdot 1i}, \ldots, N_{\cdot Ci}) {\sim} {\rm Multinomial}(N_i,\sum_{r=1}^R \beta_{r1i}X_{ri}, \dots, \sum_{r=1}^R \beta_{rCi}X_{ri})}{(N_.1i,..., N_.Ci) ~ Multinomial(N_i,sum_{r=1}^R(beta_r1i*X_ri), ..., sum_{r=1}^R (beta_rCi*X_ri)} The second stage of the model assumes that the vector of \eqn{\beta}{beta} for row \eqn{r}{r} in unit \eqn{i}{i} follows a Dirichlet distribution with \eqn{C}{C} parameters. The model may be fit with or without a covariate. If the model is fit without a covariate, the distribution of the vector \eqn{\beta_{ri}}{beta_ri} is : \deqn{(\beta_{r1i}, \dots, \beta_{rCi}) {\sim} {\rm Dirichlet}(\alpha_{r1}, \dots, \alpha_{rC})}{(beta_r1i, ..., beta_rCi) ~ Dirichlet(alpha_r1, ..., alpha_rC)} In this case, the prior on each \eqn{\alpha_{rc}}{alpha_rc} is assumed to be: \deqn{\alpha_{rc} \sim {\rm Gamma}(\lambda_1, \lambda_2)}{alpha_rc ~ Gamma(lambda_1, lambda_2} If the model is fit with a covariate, the distribution of the vector \eqn{\beta_{ri}}{beta_ri} is : \deqn{(\beta_{r1i}, \dots, \beta_{rCi}) {\sim} {\rm Dirichlet}(d_r\exp(\gamma_{r1} + \delta_{r1}Z_i), d_r\exp(\gamma_{r(C-1)} + \delta_{r(C-1)}Z_i), d_r)}{(beta_r1i, ..., beta_rCi) ~ Dirichlet(d_r*exp(gamma_r1 + delta_r1 * Z_i), ..., d_r * exp(gamma_r(C-1) + delta_r(C-1)*Z_i), d_r)} The parameters \eqn{\gamma_{rC}}{gamma_rC} and \eqn{\delta_{rC}}{delta_rC} are constrained to be zero for identification. (In this function, the last column entered in the formula is so constrained.) Finally, the prior for \eqn{d_r}{d_r} is: \deqn{d_r \sim {\rm Gamma}(\lambda_1, \lambda_2)}{d_r ~ Gamma(lambda_1, lambda_2)} while \eqn{\gamma_{rC}}{gamma_rC} and \eqn{\delta_{rC}}{delta_rC} are given improper uniform priors if \code{covariate.prior.list = NULL} or have independent normal priors of the form: \deqn{\delta_{rC} \sim {\rm N}(\mu_{\delta_{rC}}, \sigma_{\delta_{rC}}^2)}{delta_{rC} ~ N(mu_{delta_{rC}}, sigma_{delta_{rC}}^2)} \deqn{\gamma_{rC} \sim {\rm N}(\mu_{\gamma_{rC}}, \sigma_{\gamma_{rC}}^2)}{gamma_{rC} ~ N(mu_{gamma_{rC}}, sigma_{gamma_{rC}}^2)} If the user wishes to estimate the model with proper normal priors on \eqn{\gamma_{rC}}{gamma_rC} and \eqn{\delta_{rC}}{delta_rC}, a list with four elements must be provided for \code{covariate.prior.list}: \itemize{ \item{\code{mu.delta}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of prior means for Delta} \item{\code{sigma.delta}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of prior standard deviations for Delta} \item{\code{mu.gamma}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of prior means for Gamma} \item{\code{sigma.gamma}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of prior standard deviations for Gamma}} Applying the model without a covariate is most reasonable in situations where one can think of individuals being randomly assigned to units, so that there are no aggregation or contextual effects. When this assumption is not reasonable, including an appropriate covariate may improve inferences; note, however, that there is typically little information in the data about the relationship of any given covariate to the unit parameters, which can lead to extremely slow mixing of the MCMC chains and difficulty in assessing convergence. Because the conditional distributions are non-standard, draws from the posterior are obtained by using a Metropolis-within-Gibbs algorithm. The proposal density for each parameter is a univariate normal distribution centered at the current parameter value with standard deviation equal to the tuning constant; the only exception is for draws of \eqn{\gamma_{rc}}{gamma_rc} and \eqn{\delta_{rc}}{delta_rc}, which use a bivariate normal proposal with covariance zero. The function will accept user-specified starting values as an argument. If the model includes a covariate, the starting values must be a list with the following elements, in this order: \itemize{ \item{\code{start.dr}}{ a vector of length \eqn{R}{R} of starting values for Dr. Starting values for Dr must be greater than zero.} \item{\code{start.betas}}{ an \eqn{R \times C}{R x C} by precincts array of starting values for Beta. Each row of every precinct must sum to 1.} \item{\code{start.gamma}}{ an \eqn{R \times C}{R x C} matrix of starting values for Gamma. Values in the right-most column must be zero.} \item{\code{start.delta}}{ an \eqn{R \times C}{R x C} matrix of starting values for Delta. Values in the right-most column must be zero.} } If there is no covariate, the starting values must be a list with the following elements: \itemize{ \item{\code{start.alphas}}{ an \eqn{R \times C}{R x C} matrix of starting values for Alpha. Starting values for Alpha must be greater than zero.} \item{\code{start.betas}}{ an \eqn{R \times C \times}{R x C x} units array of starting values for Beta. Each row in every unit must sum to 1.}} The function will accept user-specified tuning parameters as an argument. The tuning parameters define the standard deviation of the normal distribution used to generate candidate values for each parameter. For the model with a covariate, a bivariate normal distribution is used to generate proposals; the covariance of these normal distributions is fixed at zero. If the model includes a covariate, the tuning parameters must be a list with the following elements, in this order: \itemize{ \item{\code{tune.dr}}{ a vector of length \eqn{R}{R} of tuning parameters for Dr} \item{\code{tune.beta}}{ an \eqn{R \times (C-1)}{R x (C-1)} by precincts array of tuning parameters for Beta} \item{\code{tune.gamma}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of tuning parameters for Gamma} \item{\code{tune.delta}}{ an \eqn{R \times (C-1)}{R x (C-1)} matrix of tuning parameters for Delta}} If there is no covariate, the tuning parameters are a list with the following elements: \itemize{ \item{\code{tune.alpha}}{ an \eqn{R \times C}{R x C} matrix of tuning parameters for Alpha} \item{\code{tune.beta}}{ an \eqn{R \times (C-1)}{R x (C-1)} by precincts array of tuning parameters for Beta} } } \references{ Martyn Plummer, Nicky Best, Kate Cowles, and Karen Vines. 2002. \emph{Output Analysis and Diagnostics for MCMC (CODA)}. \url{ https://CRAN.R-project.org/package=coda}. Ori Rosen, Wenxin Jiang, Gary King, and Martin A. Tanner. 2001. ``Bayesian and Frequentist Inference for Ecological Inference: The \eqn{R \times (C-1)}{R x (C-1)} Case.'' \emph{Statistica Neerlandica} 55: 134-156. } \author{ Michael Kellermann <\email{mrkellermann@gmail.com}> and Olivia Lau <\email{olivia.lau@post.harvard.edu}> } \seealso{\code{\link[eiPack]{lambda.MD}}, \code{\link[eiPack]{cover.plot}}, \code{\link[eiPack]{density.plot}}, \code{\link[eiPack]{tuneMD}}, \code{\link[eiPack]{mergeMD}}} \keyword{models} eiPack/man/tuneB.Rd0000644000176200001440000000072014374235671013600 0ustar liggesusers\name{tuneB} \alias{tuneB} \title{Tuning parameters for the precinct level parameters in the RxC EI model} \description{ A vector containing tuning parameters for the precinct level parameters in the RxC EI model. } \usage{data(tuneB)} \format{ A vector of length 3 x 2 x 150 containing the precinct level tuning parameters for the redistricting sample data. } \examples{ data(tuneB) tuneB <- array(tuneB[[1]], dim = c(3, 2, 150)) } \keyword{datasets} eiPack/man/plot.bounds.Rd0000644000176200001440000000270314374235671014775 0ustar liggesusers\name{plot.bounds} \alias{plot} \alias{plot.bounds} \title{Plot of deterministic bounds for units satisfying row thresholds} \description{Plots the deterministic bounds on the proportion of row members within a specified column.} \usage{ \method{plot}{bounds}(x, row, column, labels = TRUE, order = NULL, intersection = TRUE, xlab, ylab, col = par("fg"), lty = par("lty"), lwd = par("lwd"), ...) } \arguments{ \item{x}{output from \code{\link{bounds}}} \item{row}{a character string specifying the row of interest} \item{column}{a character string specifying the column of interest} \item{labels}{a logical toggle specifying whether precinct labels should be printed above interval bounds} \item{order}{an optional vector of values between 0 and 1 specifying the order (left-to-right) in which interval bounds are plotted} \item{intersection}{a logical toggle specifying whether the intersection of all plotted bounds (if it exists) should be plotted} \item{xlab, ylab, ...}{additional arguments passed to \code{plot}} \item{col, lty, lwd}{additional arguments passed to \code{segments}} } \value{ A plot with vertical intervals indicating the deterministic bounds on the quantity of interest, and (optionally) a single horizontal interval indicating the intersection of these unit bounds. } \seealso{\code{bounds}} \author{ Ryan T. Moore <\email{rtm@american.edu}> } \keyword{hplot} eiPack/man/lambda.MD.Rd0000644000176200001440000000304514374235671014245 0ustar liggesusers\name{lambda.MD} \alias{lambda.MD} \title{Calculate shares using data from MD model} \description{Calculates the population share of row members in a particular column as a proportion of the total number of row members in the selected subset of columns.} \usage{ lambda.MD(object, columns, ret.mcmc = TRUE) } \arguments{ \item{object}{an R object of class \code{eiMD}, output from \code{\link{ei.MD.bayes}}} \item{columns}{a character vector of column names to be included in calculating the shares} \item{ret.mcmc}{a logical value indicating how the samples from the posterior should be returned. If \code{TRUE} (default), samples are returned as \code{mcmc} objects. If \code{FALSE}, samples are returned as arrays. } } \value{ Returns either a ((\eqn{R}{R} * included columns) \eqn{\times}{x} samples) matrix as an \code{mcmc} object or a (\eqn{R \times}{R x} included columns \eqn{\times}{x} samples) array. } \details{This function allows users to define subpopulations within the data and calculate the proportion of individuals within each of the columns that defines that subpopulation. For example, if the model includes the groups Democrat, Republican, and Unaffiliated, the argument \code{columns = c(``Democrat", ``Republican")} will calculate the two-party shares of Democrats and Republicans for each row. } \seealso{\code{\link{ei.MD.bayes}}} \author{ Michael Kellermann <\email{mrkellermann@gmail.com}> and Olivia Lau <\email{olivia.lau@post.harvard.edu}> } \keyword{models} eiPack/man/cover.plot.Rd0000644000176200001440000000363114374235671014622 0ustar liggesusers\name{cover.plot} \alias{cover.plot} \alias{coverage} \title{Unit-level coverage plots for beta parameters from MD EI model} \description{Generates a plot of central credible intervals for the unit-level beta parameters from the Multinomial-Dirichlet ecological inference model (see \code{\link{ei.MD.bayes}}).} \usage{ cover.plot(object, row, column, x = NULL, CI = 0.95, medians = TRUE, col = NULL, ylim = c(0,1), ylab, lty = par("lty"), lwd = par("lwd"), ...) } \arguments{ \item{object}{output from \code{\link{ei.MD.bayes}}} \item{row}{a character string specifying the row marginal of interest} \item{column}{a character string specifying the column marginal of interest} \item{x}{an optional covariate to index the units along the x-axis} \item{CI}{a fraction between 0 and 1 (defaults to 0.95), specifying the coverage of the central credible interval to be plotted for each unit} \item{medians}{a logical value specifying whether to plot the median (defaults to \code{TRUE}). If \code{medians = FALSE}, the medians are not plotted.} \item{col}{an optional vector of colors to be passed to \code{plot} and \code{segments}. If \code{col} is of length two, then the first color is used for \code{plot} and the second for \code{segments}.} \item{ylim}{an optional range for the y-axis (defaults to \code{c(0,1)}).} \item{ylab}{an optional label for the y-axis (defaults to \code{Proportion of row in column}).} \item{lty}{an optional line type passed to \code{segments}.} \item{lwd}{an optional line width argument passed to \code{segments}.} \item{...}{additional arguments passed to \code{plot}.} } \value{ A plot with vertical intervals indicating the central credible intervals for each ecological unit. } \seealso{\code{plot}, \code{segments}, \code{par}} \author{ Olivia Lau <\email{olivia.lau@post.harvard.edu}> } \keyword{hplot} eiPack/man/ei.reg.bayes.Rd0000644000176200001440000000365014374235671015003 0ustar liggesusers\name{ei.reg.bayes} \alias{ei.reg.bayes} \title{Ecological regression using Bayesian Normal regression} \description{ Estimate an ecological regression using Bayesian normal regression. } \usage{ ei.reg.bayes(formula, data, sample = 1000, weights = NULL, truncate=FALSE) } \arguments{ \item{formula}{An R formula object of the form \code{cbind(c1, c2, ...) ~ cbind(r1, r2, ...)}} \item{data}{data frame containing the variables specified in formula} \item{sample}{number of draws from the posterior} \item{weights}{a vector of weights} \item{truncate}{if TRUE, imposes a proper uniform prior on the unit hypercube for the coefficients; if FALSE, an improper uniform prior is assumed} } \value{ A list containing \item{call}{the call to \code{ei.reg.bayes}} \item{draws}{A, \eqn{R \times C \times}{R x C x} sample array containing posterior draws for each population cell fraction} } \details{ For \eqn{i \in 1,\ldots,C}{i in 1,...,C}, \eqn{C}{C} Bayesian regressions of the form \code{c_i ~ cbind(r1, r2, ...)} are performed. See the documentation for \code{ei.reg} for the accounting identities and constancy assumption underlying this Bayesian linear model. The sampling density is given by \deqn{y|\beta, \sigma^2, X \sim N(X\beta, \sigma^2 I)}{y| beta, sigma^2, X ~ N(X beta, sigma^2*I)} The improper prior is \eqn{p(\beta,\sigma^2|X)\propto \sigma^{-2}}{p(beta,sigma^2|X) proportional to 1/sigma^2}. The proper prior is \eqn{p(\beta, \sigma^2|x) \propto I(\beta \in [0,1])\times \sigma^{-2}}{p(beta, sigma^2|x) proportional to I(beta in [0,1])* 1/sigma^2}. } \references{ Leo Goodman. 1953. ``Ecological Regressions and the Behavior of Individuals.'' \emph{American Sociological Review} 18:663--664. } \author{ Olivia Lau <\email{olivia.lau@post.harvard.edu}> and Ryan T. Moore <\email{rtm@american.edu}> } \keyword{models} eiPack/man/senc.Rd0000644000176200001440000000300114374252000013427 0ustar liggesusers\name{senc} \alias{senc} \title{Party registration in south-east North Carolina} \description{ Registration data for White, Black, and Native American voters in eight counties of south-eastern North Carolina in 2001. } \usage{data(senc)} \format{A table containing 212 observations and 18 variables: \describe{ \item{county}{county name} \item{precinct}{precinct name} \item{total}{number of registered voters in precinct} \item{white}{number of White registered voters} \item{black}{number of Black registered voters} \item{natam}{number of Native American registered voters} \item{dem}{number of registered Democrats} \item{rep}{number of registered Republicans} \item{other}{number of registered voters without major party affiliation} \item{whdem}{number of White registered Democrats} \item{whrep}{number of White registered Republicans} \item{whoth}{number of White registered voters without major party affiliation} \item{bldem}{number of Black registered Democrats} \item{blrep}{number of Black registered Republicans} \item{bloth}{number of Black registered voters without major party affiliation} \item{natamdem}{number of Native American registered Democrats} \item{natamrep}{number of Native American registered Republicans} \item{natamoth}{number of Native American registered voters without major party affiliation} }} \source{Excerpted from North Carolina General Assembly 2001 redistricting data, https://www.ncleg.gov/Redistricting/BaseData2001 } \keyword{datasets} eiPack/DESCRIPTION0000644000176200001440000000155414374260722013170 0ustar liggesusersPackage: eiPack Type: Package Version: 0.2-2 Date: 2023-02-18 Title: Ecological Inference and Higher-Dimension Data Management Author: Olivia Lau , Ryan T. Moore , Michael Kellermann Maintainer: Michael Kellermann Depends: R (>= 2.0.0) Imports: MASS, coda, msm Suggests: lattice Description: Provides methods for analyzing R by C ecological contingency tables using the extreme case analysis, ecological regression, and Multinomial-Dirichlet ecological inference models. Also provides tools for manipulating higher-dimension data objects. License: GPL (>= 2) | file LICENSE URL: http://www.olivialau.org/software/ NeedsCompilation: yes Packaged: 2023-02-18 22:43:58 UTC; Mike Kellermann Repository: CRAN Date/Publication: 2023-02-18 23:40:02 UTC eiPack/src/0000755000176200001440000000000014374235671012251 5ustar liggesuserseiPack/src/rbycei.c0000644000176200001440000001400614374235671013673 0ustar liggesusers #include #include #include #include #include #include #include #include #include "eiutil.h" SEXP rbycei_fcn1 (SEXP alphamatrix, SEXP betaarray, SEXP TT, SEXP XX, SEXP tuneA, SEXP tuneB, SEXP NG, SEXP NP, SEXP Precincts, SEXP Lambda1, SEXP Lambda2, SEXP Sample, SEXP Thin, SEXP Burnin, SEXP Verbose, SEXP Savebeta, SEXP RR, SEXP betanames ){ int nProtected = 0, nComps = 0, counter = 0; R_len_t ii, rr, cc, tt, qq, kk; SEXP lbm,ccount, hldr; SEXP a_acc, b_acc, a_draws, b_draws, ccount_draws, output_list; R_len_t ng, np, prec, thin, samp, burn, iters, verbose; double lambda_1, lambda_2; double aprop, acurr, asumm1, lbm_rc, aprop_ll, acurr_ll; double bprop, bprop_ref, bcurr, bcurr_ref, tt_ci, tt_Ci, bprop_x, bprop_ref_x, bcurr_x, bcurr_ref_x, ulim, bcurr_ll, bprop_ll; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; lambda_1 = REAL(Lambda1)[0]; lambda_2 = REAL(Lambda2)[0]; samp = INTEGER(Sample)[0]; thin = INTEGER(Thin)[0]; burn = INTEGER(Burnin)[0]; iters = burn + samp*thin; verbose = INTEGER(Verbose)[0]; /* */ PROTECT(hldr = allocVector(NILSXP, 1)); ++nProtected; /* PROTECT(lbm = allocMatrix(REALSXP, ng , np)); ++nProtected; */ PROTECT(a_acc = allocVector(REALSXP, ng * np)); ++nProtected; ++nComps; PROTECT(b_acc = allocVector(REALSXP, ng*(np-1)*prec)); ++nProtected; ++nComps; PROTECT(ccount = allocMatrix(REALSXP, ng, np)); ++nProtected; ++nComps; for(qq = 0; qq < ng*np; ++qq){ REAL(a_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = 0; } PROTECT(ccount_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; PROTECT(a_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; if(INTEGER(Savebeta)[0] == 0){ PROTECT(b_draws = allocMatrix(REALSXP, samp, ng*np*prec)); ++nProtected; ++nComps; } GetRNGstate(); for(kk = 0; kk < iters; ++kk){ for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < (np - 1); ++cc){ bcurr = REAL(betaarray)[rr + ng*cc + ng*np*ii]; bcurr_ref = REAL(betaarray)[rr + ng*(np-1) + ng*np*ii]; ulim = bcurr + bcurr_ref; bprop = rnorm(bcurr, REAL(tuneB)[rr + ng*cc + ng*(np-1)*ii]); bprop_ref = ulim - bprop; if(bprop > 0 && bprop < ulim){ tt_ci = REAL(TT)[cc + np*ii]; tt_Ci = REAL(TT)[(np - 1) + np*ii]; bcurr_x = 0; bcurr_ref_x = 0; for(qq = 0; qq < ng; ++qq){ bcurr_x += REAL(betaarray)[qq + ng*cc + ng*np*ii]* REAL(XX)[qq + ng*ii]; bcurr_ref_x += REAL(betaarray)[qq + ng*(np-1) + ng*np*ii] * REAL(XX)[qq + ng*ii]; } bprop_x = bcurr_x - bcurr*REAL(XX)[rr + ng*ii] + bprop*REAL(XX)[rr + ng*ii]; bprop_ref_x = bcurr_ref_x - bcurr_ref*REAL(XX)[rr + ng*ii] + bprop_ref*REAL(XX)[rr + ng*ii]; bprop_ll = beta_ll(bprop, bprop_ref, REAL(alphamatrix)[rr + ng*cc], REAL(alphamatrix)[rr + ng*(np-1)],tt_ci, tt_Ci, bprop_x, bprop_ref_x); bcurr_ll = beta_ll(bcurr, bcurr_ref, REAL(alphamatrix)[rr + ng*cc], REAL(alphamatrix)[rr + ng*(np-1)], tt_ci, tt_Ci, bcurr_x, bcurr_ref_x); /* Rprintf("%f %f %f %f %f\n", bprop, bprop_ref, bprop_x, bprop_ref_x, bprop_ll - bcurr_ll); */ if(acc_tog(bprop_ll, bcurr_ll) == 1){ REAL(betaarray)[rr + ng*cc + ng*np*ii] = bprop; REAL(betaarray)[rr + ng*(np-1) + ng*np*ii] = bprop_ref; REAL(b_acc)[rr + ng*cc + ng*(np - 1)*ii] += 1; } } } } } PROTECT(lbm = logbetamat(betaarray, NG, NP, Precincts)); for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ acurr = REAL(alphamatrix)[rr + ng*cc]; aprop = rnorm(acurr, REAL(tuneA)[rr + ng*cc]); lbm_rc = REAL(lbm)[rr + ng*cc]; asumm1 = 0; for(tt = 0; tt < np; ++tt){ asumm1 += REAL(alphamatrix)[rr + ng*tt]; } asumm1 = asumm1 - acurr; if(aprop > 0){ aprop_ll = alpha_ll(aprop, asumm1, lbm_rc, lambda_1, lambda_2, prec); acurr_ll = alpha_ll(acurr, asumm1, lbm_rc, lambda_1, lambda_2, prec); /*Rprintf("%f %f \n", aprop, aprop_ll - acurr_ll); */ if(acc_tog(aprop_ll, acurr_ll) == 1){ REAL(alphamatrix)[rr + ng*cc] = aprop; REAL(a_acc)[rr + ng*cc] += 1; } } } } UNPROTECT(1); if(kk >= burn && ((kk % thin) == 0)){ ccount = cellcount(betaarray,RR, NG, NP, Precincts); for(qq = 0; qq < np*ng; ++qq){ REAL(a_draws)[counter + qq*samp] = REAL(alphamatrix)[qq]; REAL(ccount_draws)[counter + qq*samp] = REAL(ccount)[qq]; } if(INTEGER(Savebeta)[0] == 0){ for(qq = 0; qq < np*ng*prec; ++qq){ REAL(b_draws)[counter + qq*samp] = REAL(betaarray)[qq]; } } if(INTEGER(Savebeta)[0] == 2){ write_beta(betaarray, betanames); } counter += 1; } if(verbose > 0 && kk % verbose == 0){ Rprintf("\n MCMC iteration %i of %i \n", kk + 1, iters); } R_CheckUserInterrupt(); } /* * PROTECT(dim_matrix1 = allocVector(INTSXP, 2)); *++nProtected; * INTEGER(dim_matrix1)[0] = ncol; * INTEGER(dim_matrix1)[1] = nrow; * * setAttrib(matrix1, R_DimSymbol, dim_matrix1); */ for(qq = 0; qq < ng*np; ++qq){ REAL(a_acc)[qq] = REAL(a_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = REAL(b_acc)[qq]/iters; } if(INTEGER(Savebeta)[0]==0){ PROTECT(output_list = allocVector(VECSXP, 5)); ++nProtected; SET_VECTOR_ELT(output_list, 0, a_draws); SET_VECTOR_ELT(output_list, 1, b_draws); SET_VECTOR_ELT(output_list, 2, a_acc); SET_VECTOR_ELT(output_list, 3, b_acc); SET_VECTOR_ELT(output_list, 4, ccount_draws); }else{ PROTECT(output_list = allocVector(VECSXP, 4)); ++nProtected; SET_VECTOR_ELT(output_list, 0, a_draws); SET_VECTOR_ELT(output_list, 1, a_acc); SET_VECTOR_ELT(output_list, 2, b_acc); SET_VECTOR_ELT(output_list, 3, ccount_draws); } PutRNGstate(); UNPROTECT(nProtected); return(output_list); } eiPack/src/init.c0000644000176200001440000000240614374235671013362 0ustar liggesusers#include #include #include // for NULL #include /* FIXME: Check these declarations against the C/Fortran source code. */ /* .Call calls */ extern SEXP rbycei_fcn1(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP rbycei_fcn2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP rbycei_fcn3(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP rbycei_fcn4(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); static const R_CallMethodDef CallEntries[] = { {"rbycei_fcn1", (DL_FUNC) &rbycei_fcn1, 18}, {"rbycei_fcn2", (DL_FUNC) &rbycei_fcn2, 21}, {"rbycei_fcn3", (DL_FUNC) &rbycei_fcn3, 28}, {"rbycei_fcn4", (DL_FUNC) &rbycei_fcn4, 31}, {NULL, NULL, 0} }; void R_init_eiPack(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } eiPack/src/eiutil.h0000644000176200001440000000127214374235671013717 0ustar liggesusers #ifndef EIUTIL_H #define EIUTIL_H double beta_ll (double beta, double beta_ref, double alpha, double alpha_ref, double tt_ci, double tt_Ci, double beta_X, double beta_ref_X); double alpha_ll (double alpha, double sum_alphaminus, double lbmat, double lambda1, double lambda2, int prec); int acc_tog (double prop_ll, double curr_ll); SEXP cellcount (SEXP betas, SEXP RR, SEXP NG, SEXP NP, SEXP Precincts); SEXP logbetamat (SEXP aa, SEXP NG, SEXP NP, SEXP Precincts); SEXP write_beta (SEXP betaarray, SEXP filenames); SEXP usr_fun_eval(SEXP usr_fun, SEXP cur_values, SEXP usr_env, int usr_len); #endif eiPack/src/rbyceicov2.c0000644000176200001440000003025214374235671014466 0ustar liggesusers #include #include #include #include #include #include #include #include #include "eiutil.h" SEXP rbycei_fcn3 (SEXP drvector, SEXP betaarray, SEXP gammamatrix, SEXP deltamatrix, SEXP TT, SEXP XX, SEXP ZZ, SEXP tuneDr, SEXP tuneB, SEXP tuneG, SEXP tuneD, SEXP NG, SEXP NP, SEXP Precincts, SEXP Lambda1, SEXP Lambda2, SEXP Covprior, SEXP Delmean, SEXP Delsd, SEXP Gammean, SEXP Gamsd, SEXP Sample, SEXP Thin, SEXP Burnin, SEXP Verbose, SEXP Savebeta, SEXP RR, SEXP betanames ){ int nProtected = 0, nComps = 0, counter = 0; R_len_t ii, rr, cc, qq, kk; SEXP ccount, hldr; SEXP beta_dim, TT_dim, RR_dim; SEXP dr_acc, b_acc, g_acc, d_acc; SEXP dr_draws, b_draws, g_draws, d_draws, ccount_draws, output_list; R_len_t ng, np, npm1, prec, thin, samp, burn, iters, verbose; double lambda1, lambda2; SEXP explp; double bprop, bprop_ref, bcurr, bcurr_ref, tt_ci, tt_Ci, bprop_x, bprop_ref_x, bcurr_x, bcurr_ref_x, ulim, bcurr_ll, bprop_ll, alpha_ci, alpha_Ci; double drcurr, drprop, drcurr_ll, drprop_ll, tmp_currB, tmp_propB; double gcurr, gprop, gcurr_ll, gprop_ll, tmp_gcurr, tmp_gprop; double dcurr, dprop; /* ,dcurr_ll, dprop_ll, tmp_dcurr, tmp_dprop */ int covprior; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; npm1 = np - 1; lambda1 = REAL(Lambda1)[0]; lambda2 = REAL(Lambda2)[0]; samp = INTEGER(Sample)[0]; thin = INTEGER(Thin)[0]; burn = INTEGER(Burnin)[0]; iters = burn + samp*thin; verbose = INTEGER(Verbose)[0]; covprior = INTEGER(Covprior)[0]; PROTECT(beta_dim = allocVector(INTSXP, 3)); ++nProtected; INTEGER(beta_dim)[0] = ng; INTEGER(beta_dim)[1] = np; INTEGER(beta_dim)[2] = prec; setAttrib(betaarray, R_DimSymbol, beta_dim); PROTECT(TT_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(TT_dim)[0] = np; INTEGER(TT_dim)[1] = prec; setAttrib(TT, R_DimSymbol, TT_dim); PROTECT(RR_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(RR_dim)[0] = ng; INTEGER(RR_dim)[1] = prec; setAttrib(RR, R_DimSymbol, RR_dim); /* */ PROTECT(hldr = allocVector(NILSXP, 1)); ++nProtected; PROTECT(ccount = allocMatrix(REALSXP, ng, np)); ++nProtected; PROTECT(explp = allocVector(REALSXP, ng*np*prec)); ++nProtected; PROTECT(dr_acc = allocVector(REALSXP, ng)); ++nProtected; ++nComps; PROTECT(b_acc = allocVector(REALSXP, ng*(np-1)*prec)); ++nProtected; ++nComps; PROTECT(g_acc = allocVector(REALSXP, ng*(np-1))); ++nProtected; ++nComps; PROTECT(d_acc = allocVector(REALSXP, ng*(np-1))); ++nProtected; ++nComps; for(qq = 0; qq < ng; ++qq){ REAL(dr_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(g_acc)[qq] = 0; REAL(d_acc)[qq] = 0;} PROTECT(ccount_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; PROTECT(dr_draws = allocMatrix(REALSXP, samp , ng)); ++nProtected; ++nComps; PROTECT(g_draws = allocMatrix(REALSXP, samp , ng*npm1)); ++nProtected; ++nComps; PROTECT(d_draws = allocMatrix(REALSXP, samp , ng*npm1)); ++nProtected; ++nComps; if(INTEGER(Savebeta)[0] == 0){ PROTECT(b_draws = allocMatrix(REALSXP, samp, ng*np*prec)); ++nProtected; ++nComps; } GetRNGstate(); for(kk = 0; kk < iters; ++kk){ /* create exp(gamma_rc + delta_rc*Z_i)*/ for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ REAL(explp)[rr + ng*cc + ng*np*ii] = exp(REAL(gammamatrix)[rr + ng*cc] + REAL(deltamatrix)[rr + ng*cc]*REAL(ZZ)[ii]); } } } /* draw d_r */ for(rr = 0; rr < ng; ++rr){ drcurr = REAL(drvector)[rr]; drprop = rnorm(drcurr, REAL(tuneDr)[rr]); if(drprop > 0){ drcurr_ll = 0; drprop_ll = 0; for(ii = 0; ii < prec; ++ii){ for(cc = 0; cc < np; ++cc){ drcurr_ll += -1*lgammafn(drcurr * REAL(explp)[rr + ng*cc + ng*np*ii]) + drcurr*REAL(explp)[rr + ng*cc + ng*np*ii]*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); drprop_ll += -1*lgammafn(drprop * REAL(explp)[rr + ng*cc + ng*np*ii]) + drprop*REAL(explp)[rr + ng*cc + ng*np*ii]*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); } } for(ii = 0; ii < prec; ++ii){ tmp_currB = 0; tmp_propB = 0; for(cc = 0; cc < np; ++cc){ tmp_currB += drcurr * REAL(explp)[rr + ng*cc + ng*np*ii]; tmp_propB += drprop * REAL(explp)[rr + ng*cc + ng*np*ii]; } drcurr_ll += lgammafn(tmp_currB); drprop_ll += lgammafn(tmp_propB); } drcurr_ll = drcurr_ll - lambda2*drcurr + (lambda1 - 1)*log(drcurr); drprop_ll = drprop_ll - lambda2*drprop + (lambda1 - 1)*log(drprop); /* Rprintf("%f %f %f %f\n", drcurr, drprop, drprop_ll, drcurr_ll); */ if(acc_tog(drprop_ll, drcurr_ll) == 1){ REAL(drvector)[rr] = drprop; REAL(dr_acc)[rr] += 1; } } } for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < (np - 1); ++cc){ bcurr = REAL(betaarray)[rr + ng*cc + ng*np*ii]; bcurr_ref = REAL(betaarray)[rr + ng*(np-1) + ng*np*ii]; ulim = bcurr + bcurr_ref; bprop = rnorm(bcurr, REAL(tuneB)[rr + ng*cc + ng*(np-1)*ii]); bprop_ref = ulim - bprop; if(bprop > 0 && bprop < ulim){ tt_ci = REAL(TT)[cc + np*ii]; tt_Ci = REAL(TT)[(np - 1) + np*ii]; bcurr_x = 0; bcurr_ref_x = 0; for(qq = 0; qq < ng; ++qq){ bcurr_x += REAL(betaarray)[qq + ng*cc + ng*np*ii]* REAL(XX)[qq + ng*ii]; bcurr_ref_x += REAL(betaarray)[qq + ng*(np-1) + ng*np*ii] * REAL(XX)[qq + ng*ii]; } bprop_x = bcurr_x - bcurr*REAL(XX)[rr + ng*ii] + bprop*REAL(XX)[rr + ng*ii]; bprop_ref_x = bcurr_ref_x - bcurr_ref*REAL(XX)[rr + ng*ii] + bprop_ref*REAL(XX)[rr + ng*ii]; alpha_ci = REAL(drvector)[rr]*REAL(explp)[rr + ng*cc + ng*np*ii]; alpha_Ci = REAL(drvector)[rr]*REAL(explp)[rr + ng*npm1 + ng*np*ii]; bprop_ll = beta_ll(bprop, bprop_ref, alpha_ci, alpha_Ci,tt_ci, tt_Ci, bprop_x, bprop_ref_x); bcurr_ll = beta_ll(bcurr, bcurr_ref, alpha_ci, alpha_Ci, tt_ci, tt_Ci, bcurr_x, bcurr_ref_x); /* */ if(acc_tog(bprop_ll, bcurr_ll) == 1){ REAL(betaarray)[rr + ng*cc + ng*np*ii] = bprop; REAL(betaarray)[rr + ng*(np-1) + ng*np*ii] = bprop_ref; REAL(b_acc)[rr + ng*cc + ng*(np - 1)*ii] += 1; } } } } } for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < npm1; ++cc){ gcurr = REAL(gammamatrix)[rr + ng*cc]; gprop = rnorm(gcurr, REAL(tuneG)[rr + cc*ng]); dcurr = REAL(deltamatrix)[rr + ng*cc]; dprop = rnorm(dcurr, REAL(tuneD)[rr + cc*ng]); gcurr_ll = 0; gprop_ll = 0; for(ii = 0; ii < prec; ++ii){ tmp_gcurr = exp(gcurr + dcurr*REAL(ZZ)[ii]); tmp_gprop = exp(gprop + dprop*REAL(ZZ)[ii]); gcurr_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_gcurr) + REAL(drvector)[rr]*tmp_gcurr*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); gprop_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_gprop) + REAL(drvector)[rr]*tmp_gprop*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); } /* Rprintf("%f %f %f %f\n", gcurr, gprop, gprop_ll, gcurr_ll); */ for(ii = 0; ii < prec; ++ii){ tmp_currB = 0; tmp_propB = 0; for(qq = 0; qq < np; ++qq){ tmp_currB += REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]); /* Rprintf("%i %f \n", qq, exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]));*/ } tmp_propB = tmp_currB - REAL(drvector)[rr] * exp(gcurr + dcurr*REAL(ZZ)[ii]) + REAL(drvector)[rr] * exp(gprop + dprop*REAL(ZZ)[ii]); /*Rprintf("%i %f \n", cc, exp(gcurr + REAL(deltamatrix)[rr + ng*cc]*REAL(ZZ)[ii]));*/ gcurr_ll += lgammafn(tmp_currB); gprop_ll += lgammafn(tmp_propB); if(verbose > 0 && kk % verbose == 0){ /* Rprintf("%f %f %f %f %f %f \n", gcurr, gprop, gcurr_ll, gprop_ll, tmp_currB, tmp_propB); */ } } if(covprior==1){ gcurr_ll += dnorm(gcurr,REAL(Gammean)[rr + ng*cc] ,REAL(Gamsd)[rr + ng*cc] , 1) + dnorm(dcurr,REAL(Delmean)[rr + ng*cc] , REAL(Delsd)[rr + ng*cc], 1); gprop_ll += dnorm(gprop,REAL(Gammean)[rr + ng*cc] ,REAL(Gamsd)[rr + ng*cc] , 1) + dnorm(dprop,REAL(Delmean)[rr + ng*cc] ,REAL(Delsd)[rr + ng*cc] , 1); } if(acc_tog(gprop_ll, gcurr_ll) == 1){ REAL(gammamatrix)[rr + ng*cc] = gprop; REAL(deltamatrix)[rr + ng*cc] = dprop; REAL(g_acc)[rr + ng*cc] += 1; } } } /* for(rr = 0; rr < ng; ++rr){ * for(cc = 0; cc < npm1; ++cc){ * dcurr = REAL(deltamatrix)[rr + ng*cc]; * dprop = rnorm(dcurr, REAL(tuneD)[rr + cc*ng]); * * dcurr_ll = 0; * dprop_ll = 0; * for(ii = 0; ii < prec; ++ii){ * tmp_dcurr = exp(REAL(gammamatrix)[rr + ng*cc] + dcurr*REAL(ZZ)[ii]); * tmp_dprop = exp(REAL(gammamatrix)[rr + ng*cc] + dprop*REAL(ZZ)[ii]); * dcurr_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_dcurr) + REAL(drvector)[rr]*tmp_dcurr*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); * dprop_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_dprop) + REAL(drvector)[rr]*tmp_dprop*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); * } * for(ii = 0; ii < prec; ++ii){ * tmp_currB = 0; * tmp_propB = 0; * for(qq = 0; qq < np; ++qq){ * tmp_currB += REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]); * } * tmp_propB = tmp_currB - REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*cc] + dcurr*REAL(ZZ)[ii]) + REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*cc] + dprop*REAL(ZZ)[ii]); * dcurr_ll += lgammafn(tmp_currB); * dprop_ll += lgammafn(tmp_propB); * } * * * if(acc_tog(dprop_ll, dcurr_ll) == 1){ * REAL(deltamatrix)[rr + ng*cc] = dprop; * REAL(d_acc)[rr + ng*cc] += 1; * } * } *} */ if(kk >= burn && ((kk % thin) == 0)){ ccount = cellcount(betaarray, RR, NG, NP, Precincts); for(qq = 0; qq < np*ng; ++qq){ REAL(ccount_draws)[counter + qq*samp] = REAL(ccount)[qq]; } for(qq = 0; qq < ng; ++qq){ REAL(dr_draws)[counter + qq*samp] = REAL(drvector)[qq]; } for(qq = 0; qq < ng*npm1; ++qq){ REAL(g_draws)[counter + qq*samp] = REAL(gammamatrix)[qq]; REAL(d_draws)[counter + qq*samp] = REAL(deltamatrix)[qq]; } if(INTEGER(Savebeta)[0] == 0){ for(qq = 0; qq < np*ng*prec; ++qq){ REAL(b_draws)[counter + qq*samp] = REAL(betaarray)[qq]; } } if(INTEGER(Savebeta)[0] == 2){ hldr = write_beta(betaarray, betanames); } counter += 1; } if(verbose > 0 && kk % verbose == 0){ Rprintf("\n MCMC iteration %i of %i \n", kk + 1, iters); } R_CheckUserInterrupt(); } for(qq = 0; qq < ng; ++qq){ REAL(dr_acc)[qq] = REAL(dr_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = REAL(b_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(g_acc)[qq] = REAL(g_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(d_acc)[qq] = REAL(d_acc)[qq]/iters; } if(INTEGER(Savebeta)[0]==0){ PROTECT(output_list = allocVector(VECSXP, 9)); ++nProtected; SET_VECTOR_ELT(output_list, 0, dr_draws); SET_VECTOR_ELT(output_list, 1, b_draws); SET_VECTOR_ELT(output_list, 2, g_draws); SET_VECTOR_ELT(output_list, 3, d_draws); SET_VECTOR_ELT(output_list, 4, dr_acc); SET_VECTOR_ELT(output_list, 5, b_acc); SET_VECTOR_ELT(output_list, 6, g_acc); SET_VECTOR_ELT(output_list, 7, d_acc); SET_VECTOR_ELT(output_list, 8, ccount_draws); }else{ PROTECT(output_list = allocVector(VECSXP, 8)); ++nProtected; SET_VECTOR_ELT(output_list, 0, dr_draws); SET_VECTOR_ELT(output_list, 1, g_draws); SET_VECTOR_ELT(output_list, 2, d_draws); SET_VECTOR_ELT(output_list, 3, dr_acc); SET_VECTOR_ELT(output_list, 4, b_acc); SET_VECTOR_ELT(output_list, 5, g_acc); SET_VECTOR_ELT(output_list, 6, d_acc); SET_VECTOR_ELT(output_list, 7, ccount_draws); } PutRNGstate(); UNPROTECT(nProtected); return(output_list); } eiPack/src/rbycei2.c0000644000176200001440000001661414374235671013764 0ustar liggesusers #include #include #include #include #include #include #include #include #include "eiutil.h" SEXP rbycei_fcn2 (SEXP alphamatrix, SEXP betaarray, SEXP TT, SEXP XX, SEXP tuneA, SEXP tuneB, SEXP NG, SEXP NP, SEXP Precincts, SEXP Lambda1, SEXP Lambda2, SEXP Sample, SEXP Thin, SEXP Burnin, SEXP Verbose, SEXP Savebeta, SEXP RR, SEXP usr_fcn, SEXP usr_env, SEXP usr_len, SEXP betanames ){ int nProtected = 0, nComps = 0, counter = 0; R_len_t ii, rr, cc, tt, qq, kk; SEXP lbm,ccount, usr, hldr; SEXP usr_list, alpha_dim, beta_dim, TT_dim, RR_dim; SEXP a_acc, b_acc, a_draws, b_draws, ccount_draws, usr_draws, output_list; R_len_t ng, np, prec, thin, samp, burn, iters, verbose, usr_length; double lambda_1, lambda_2; double aprop, acurr, asumm1, lbm_rc, aprop_ll, acurr_ll; double bprop, bprop_ref, bcurr, bcurr_ref, tt_ci, tt_Ci, bprop_x, bprop_ref_x, bcurr_x, bcurr_ref_x, ulim, bcurr_ll, bprop_ll; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; lambda_1 = REAL(Lambda1)[0]; lambda_2 = REAL(Lambda2)[0]; usr_length = INTEGER(usr_len)[0]; samp = INTEGER(Sample)[0]; thin = INTEGER(Thin)[0]; burn = INTEGER(Burnin)[0]; iters = burn + samp*thin; verbose = INTEGER(Verbose)[0]; PROTECT(alpha_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(alpha_dim)[0] = ng; INTEGER(alpha_dim)[1] = np; setAttrib(alphamatrix, R_DimSymbol, alpha_dim); PROTECT(beta_dim = allocVector(INTSXP, 3)); ++nProtected; INTEGER(beta_dim)[0] = ng; INTEGER(beta_dim)[1] = np; INTEGER(beta_dim)[2] = prec; setAttrib(betaarray, R_DimSymbol, beta_dim); PROTECT(TT_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(TT_dim)[0] = np; INTEGER(TT_dim)[1] = prec; setAttrib(TT, R_DimSymbol, TT_dim); PROTECT(RR_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(RR_dim)[0] = ng; INTEGER(RR_dim)[1] = prec; setAttrib(RR, R_DimSymbol, RR_dim); PROTECT(usr_list = allocVector(VECSXP, 4)); ++nProtected; PROTECT(hldr = allocVector(NILSXP, 1)); ++nProtected; /* PROTECT(lbm = allocMatrix(REALSXP, ng , np)); ++nProtected; */ PROTECT(usr = allocVector(REALSXP, usr_length)); ++nProtected; /*PROTECT(ccount = allocMatrix(REALSXP, ng, np)); ++nProtected; */ PROTECT(a_acc = allocVector(REALSXP, ng * np)); ++nProtected; ++nComps; PROTECT(b_acc = allocVector(REALSXP, ng*(np-1)*prec)); ++nProtected; ++nComps; for(qq = 0; qq < ng*np; ++qq){ REAL(a_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = 0; } PROTECT(ccount_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; PROTECT(usr_draws = allocMatrix(REALSXP, samp , usr_length)); ++nProtected; ++nComps; PROTECT(a_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; if(INTEGER(Savebeta)[0] == 0){ PROTECT(b_draws = allocMatrix(REALSXP, samp, ng*np*prec)); ++nProtected; ++nComps; } GetRNGstate(); for(kk = 0; kk < iters; ++kk){ for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < (np - 1); ++cc){ bcurr = REAL(betaarray)[rr + ng*cc + ng*np*ii]; bcurr_ref = REAL(betaarray)[rr + ng*(np-1) + ng*np*ii]; ulim = bcurr + bcurr_ref; bprop = rnorm(bcurr, REAL(tuneB)[rr + ng*cc + ng*(np-1)*ii]); bprop_ref = ulim - bprop; if(bprop > 0 && bprop < ulim){ tt_ci = REAL(TT)[cc + np*ii]; tt_Ci = REAL(TT)[(np - 1) + np*ii]; bcurr_x = 0; bcurr_ref_x = 0; for(qq = 0; qq < ng; ++qq){ bcurr_x += REAL(betaarray)[qq + ng*cc + ng*np*ii]* REAL(XX)[qq + ng*ii]; bcurr_ref_x += REAL(betaarray)[qq + ng*(np-1) + ng*np*ii] * REAL(XX)[qq + ng*ii]; } bprop_x = bcurr_x - bcurr*REAL(XX)[rr + ng*ii] + bprop*REAL(XX)[rr + ng*ii]; bprop_ref_x = bcurr_ref_x - bcurr_ref*REAL(XX)[rr + ng*ii] + bprop_ref*REAL(XX)[rr + ng*ii]; bprop_ll = beta_ll(bprop, bprop_ref, REAL(alphamatrix)[rr + ng*cc], REAL(alphamatrix)[rr + ng*(np-1)],tt_ci, tt_Ci, bprop_x, bprop_ref_x); bcurr_ll = beta_ll(bcurr, bcurr_ref, REAL(alphamatrix)[rr + ng*cc], REAL(alphamatrix)[rr + ng*(np-1)], tt_ci, tt_Ci, bcurr_x, bcurr_ref_x); /* Rprintf("%f %f %f %f %f\n", bprop, bprop_ref, bprop_x, bprop_ref_x, bprop_ll - bcurr_ll); */ if(acc_tog(bprop_ll, bcurr_ll) == 1){ REAL(betaarray)[rr + ng*cc + ng*np*ii] = bprop; REAL(betaarray)[rr + ng*(np-1) + ng*np*ii] = bprop_ref; REAL(b_acc)[rr + ng*cc + ng*(np - 1)*ii] += 1; } } } } } PROTECT(lbm = logbetamat(betaarray, NG, NP, Precincts)); for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ acurr = REAL(alphamatrix)[rr + ng*cc]; aprop = rnorm(acurr, REAL(tuneA)[rr + ng*cc]); lbm_rc = REAL(lbm)[rr + ng*cc]; asumm1 = 0; for(tt = 0; tt < np; ++tt){ asumm1 += REAL(alphamatrix)[rr + ng*tt]; } asumm1 = asumm1 - acurr; if(aprop > 0){ aprop_ll = alpha_ll(aprop, asumm1, lbm_rc, lambda_1, lambda_2, prec); acurr_ll = alpha_ll(acurr, asumm1, lbm_rc, lambda_1, lambda_2, prec); /*Rprintf("%f %f \n", aprop, aprop_ll - acurr_ll); */ if(acc_tog(aprop_ll, acurr_ll) == 1){ REAL(alphamatrix)[rr + ng*cc] = aprop; REAL(a_acc)[rr + ng*cc] += 1; } } } } UNPROTECT(1); if(kk >= burn && ((kk % thin) == 0)){ SET_VECTOR_ELT(usr_list, 0, alphamatrix); SET_VECTOR_ELT(usr_list, 1, betaarray); SET_VECTOR_ELT(usr_list, 2, TT); SET_VECTOR_ELT(usr_list, 3, RR); PROTECT(ccount = cellcount(betaarray, RR, NG, NP, Precincts)); usr = usr_fun_eval(usr_fcn, usr_list, usr_env, usr_length); for(qq = 0; qq < usr_length; ++qq){ REAL(usr_draws)[counter + qq*samp] = REAL(usr)[qq]; } for(qq = 0; qq < np*ng; ++qq){ REAL(a_draws)[counter + qq*samp] = REAL(alphamatrix)[qq]; REAL(ccount_draws)[counter + qq*samp] = REAL(ccount)[qq]; } UNPROTECT(1); if(INTEGER(Savebeta)[0] == 0){ for(qq = 0; qq < np*ng*prec; ++qq){ REAL(b_draws)[counter + qq*samp] = REAL(betaarray)[qq]; } } if(INTEGER(Savebeta)[0] == 2){ hldr = write_beta(betaarray, betanames); } counter += 1; } if(verbose > 0 && kk % verbose == 0){ Rprintf("\n MCMC iteration %i of %i \n", kk + 1, iters); } R_CheckUserInterrupt(); } for(qq = 0; qq < ng*np; ++qq){ REAL(a_acc)[qq] = REAL(a_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = REAL(b_acc)[qq]/iters; } if(INTEGER(Savebeta)[0]==0){ PROTECT(output_list = allocVector(VECSXP, 6)); ++nProtected; SET_VECTOR_ELT(output_list, 0, a_draws); SET_VECTOR_ELT(output_list, 1, b_draws); SET_VECTOR_ELT(output_list, 2, a_acc); SET_VECTOR_ELT(output_list, 3, b_acc); SET_VECTOR_ELT(output_list, 4, ccount_draws); SET_VECTOR_ELT(output_list, 5, usr_draws); }else{ PROTECT(output_list = allocVector(VECSXP, 5)); ++nProtected; SET_VECTOR_ELT(output_list, 0, a_draws); SET_VECTOR_ELT(output_list, 1, a_acc); SET_VECTOR_ELT(output_list, 2, b_acc); SET_VECTOR_ELT(output_list, 3, ccount_draws); SET_VECTOR_ELT(output_list, 4, usr_draws); } PutRNGstate(); UNPROTECT(nProtected); return(output_list); } eiPack/src/rbyceicov4.c0000644000176200001440000003253014374235671014471 0ustar liggesusers #include #include #include #include #include #include #include #include #include "eiutil.h" SEXP rbycei_fcn4 (SEXP drvector, SEXP betaarray, SEXP gammamatrix, SEXP deltamatrix, SEXP TT, SEXP XX, SEXP ZZ, SEXP tuneDr, SEXP tuneB, SEXP tuneG, SEXP tuneD, SEXP NG, SEXP NP, SEXP Precincts, SEXP Lambda1, SEXP Lambda2, SEXP Covprior, SEXP Delmean, SEXP Delsd, SEXP Gammean, SEXP Gamsd, SEXP Sample, SEXP Thin, SEXP Burnin, SEXP Verbose, SEXP Savebeta, SEXP RR, SEXP usr_fcn, SEXP usr_env, SEXP usr_len, SEXP betanames ){ int nProtected = 0, nComps = 0, counter = 0; R_len_t ii, rr, cc, qq, kk; SEXP ccount, usr, hldr; SEXP usr_list, beta_dim, gamma_dim, delta_dim, TT_dim, RR_dim; SEXP dr_acc, b_acc, g_acc, d_acc; SEXP dr_draws, b_draws, g_draws, d_draws, ccount_draws, usr_draws, output_list; R_len_t ng, np, npm1, prec, thin, samp, burn, iters, verbose,usr_length; double lambda1, lambda2; SEXP explp; double bprop, bprop_ref, bcurr, bcurr_ref, tt_ci, tt_Ci, bprop_x, bprop_ref_x, bcurr_x, bcurr_ref_x, ulim, bcurr_ll, bprop_ll, alpha_ci, alpha_Ci; double drcurr, drprop, drcurr_ll, drprop_ll, tmp_currB, tmp_propB; double gcurr, gprop, gcurr_ll, gprop_ll, tmp_gcurr, tmp_gprop; double dcurr, dprop; /*,dcurr_ll, dprop_ll, tmp_dcurr, tmp_dprop*/ int covprior; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; npm1 = np - 1; lambda1 = REAL(Lambda1)[0]; lambda2 = REAL(Lambda2)[0]; covprior = INTEGER(Covprior)[0]; samp = INTEGER(Sample)[0]; thin = INTEGER(Thin)[0]; burn = INTEGER(Burnin)[0]; iters = burn + samp*thin; verbose = INTEGER(Verbose)[0]; usr_length = INTEGER(usr_len)[0]; PROTECT(beta_dim = allocVector(INTSXP, 3)); ++nProtected; INTEGER(beta_dim)[0] = ng; INTEGER(beta_dim)[1] = np; INTEGER(beta_dim)[2] = prec; setAttrib(betaarray, R_DimSymbol, beta_dim); PROTECT(gamma_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(gamma_dim)[0] = ng; INTEGER(gamma_dim)[1] = np; setAttrib(gammamatrix, R_DimSymbol, gamma_dim); PROTECT(delta_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(delta_dim)[0] = ng; INTEGER(delta_dim)[1] = np; setAttrib(deltamatrix, R_DimSymbol, delta_dim); PROTECT(TT_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(TT_dim)[0] = np; INTEGER(TT_dim)[1] = prec; setAttrib(TT, R_DimSymbol, TT_dim); PROTECT(RR_dim = allocVector(INTSXP, 2)); ++nProtected; INTEGER(RR_dim)[0] = ng; INTEGER(RR_dim)[1] = prec; setAttrib(RR, R_DimSymbol, RR_dim); /* */ PROTECT(hldr = allocVector(NILSXP, 1)); ++nProtected; /* PROTECT(ccount = allocMatrix(REALSXP, ng, np)); ++nProtected; */ PROTECT(explp = allocVector(REALSXP, ng*np*prec)); ++nProtected; PROTECT(dr_acc = allocVector(REALSXP, ng)); ++nProtected; ++nComps; PROTECT(b_acc = allocVector(REALSXP, ng*(np-1)*prec)); ++nProtected; ++nComps; PROTECT(g_acc = allocVector(REALSXP, ng*(np-1))); ++nProtected; ++nComps; PROTECT(d_acc = allocVector(REALSXP, ng*(np-1))); ++nProtected; ++nComps; for(qq = 0; qq < ng; ++qq){ REAL(dr_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = 0; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(g_acc)[qq] = 0; REAL(d_acc)[qq] = 0;} PROTECT(usr = allocVector(REALSXP, usr_length)); ++nProtected; ++nComps; PROTECT(ccount_draws = allocMatrix(REALSXP, samp , ng*np)); ++nProtected; ++nComps; PROTECT(usr_list = allocVector(VECSXP, 6)); ++nProtected; PROTECT(usr_draws = allocMatrix(REALSXP, samp , usr_length)); ++nProtected; ++nComps; PROTECT(dr_draws = allocMatrix(REALSXP, samp , ng)); ++nProtected; ++nComps; PROTECT(g_draws = allocMatrix(REALSXP, samp , ng*npm1)); ++nProtected; ++nComps; PROTECT(d_draws = allocMatrix(REALSXP, samp , ng*npm1)); ++nProtected; ++nComps; if(INTEGER(Savebeta)[0] == 0){ PROTECT(b_draws = allocMatrix(REALSXP, samp, ng*np*prec)); ++nProtected; ++nComps; } GetRNGstate(); for(kk = 0; kk < iters; ++kk){ /* create exp(gamma_rc + delta_rc*Z_i)*/ for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ REAL(explp)[rr + ng*cc + ng*np*ii] = exp(REAL(gammamatrix)[rr + ng*cc] + REAL(deltamatrix)[rr + ng*cc]*REAL(ZZ)[ii]); } } } /* draw d_r */ for(rr = 0; rr < ng; ++rr){ drcurr = REAL(drvector)[rr]; drprop = rnorm(drcurr, REAL(tuneDr)[rr]); if(drprop > 0){ drcurr_ll = 0; drprop_ll = 0; for(ii = 0; ii < prec; ++ii){ for(cc = 0; cc < np; ++cc){ drcurr_ll += -1*lgammafn(drcurr * REAL(explp)[rr + ng*cc + ng*np*ii]) + drcurr*REAL(explp)[rr + ng*cc + ng*np*ii]*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); drprop_ll += -1*lgammafn(drprop * REAL(explp)[rr + ng*cc + ng*np*ii]) + drprop*REAL(explp)[rr + ng*cc + ng*np*ii]*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); } } for(ii = 0; ii < prec; ++ii){ tmp_currB = 0; tmp_propB = 0; for(cc = 0; cc < np; ++cc){ tmp_currB += drcurr * REAL(explp)[rr + ng*cc + ng*np*ii]; tmp_propB += drprop * REAL(explp)[rr + ng*cc + ng*np*ii]; } drcurr_ll += lgammafn(tmp_currB); drprop_ll += lgammafn(tmp_propB); } drcurr_ll = drcurr_ll - lambda2*drcurr + (lambda1 - 1)*log(drcurr); drprop_ll = drprop_ll - lambda2*drprop + (lambda1 - 1)*log(drprop); /* Rprintf("%f %f %f %f\n", drcurr, drprop, drprop_ll, drcurr_ll); */ if(acc_tog(drprop_ll, drcurr_ll) == 1){ REAL(drvector)[rr] = drprop; REAL(dr_acc)[rr] += 1; } } } for(ii = 0; ii < prec; ++ii){ for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < (np - 1); ++cc){ bcurr = REAL(betaarray)[rr + ng*cc + ng*np*ii]; bcurr_ref = REAL(betaarray)[rr + ng*(np-1) + ng*np*ii]; ulim = bcurr + bcurr_ref; bprop = rnorm(bcurr, REAL(tuneB)[rr + ng*cc + ng*(np-1)*ii]); bprop_ref = ulim - bprop; if(bprop > 0 && bprop < ulim){ tt_ci = REAL(TT)[cc + np*ii]; tt_Ci = REAL(TT)[(np - 1) + np*ii]; bcurr_x = 0; bcurr_ref_x = 0; for(qq = 0; qq < ng; ++qq){ bcurr_x += REAL(betaarray)[qq + ng*cc + ng*np*ii]* REAL(XX)[qq + ng*ii]; bcurr_ref_x += REAL(betaarray)[qq + ng*(np-1) + ng*np*ii] * REAL(XX)[qq + ng*ii]; } bprop_x = bcurr_x - bcurr*REAL(XX)[rr + ng*ii] + bprop*REAL(XX)[rr + ng*ii]; bprop_ref_x = bcurr_ref_x - bcurr_ref*REAL(XX)[rr + ng*ii] + bprop_ref*REAL(XX)[rr + ng*ii]; alpha_ci = REAL(drvector)[rr]*REAL(explp)[rr + ng*cc + ng*np*ii]; alpha_Ci = REAL(drvector)[rr]*REAL(explp)[rr + ng*npm1 + ng*np*ii]; bprop_ll = beta_ll(bprop, bprop_ref, alpha_ci, alpha_Ci,tt_ci, tt_Ci, bprop_x, bprop_ref_x); bcurr_ll = beta_ll(bcurr, bcurr_ref, alpha_ci, alpha_Ci, tt_ci, tt_Ci, bcurr_x, bcurr_ref_x); /* */ if(acc_tog(bprop_ll, bcurr_ll) == 1){ REAL(betaarray)[rr + ng*cc + ng*np*ii] = bprop; REAL(betaarray)[rr + ng*(np-1) + ng*np*ii] = bprop_ref; REAL(b_acc)[rr + ng*cc + ng*(np - 1)*ii] += 1; } } } } } for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < npm1; ++cc){ gcurr = REAL(gammamatrix)[rr + ng*cc]; gprop = rnorm(gcurr, REAL(tuneG)[rr + cc*ng]); dcurr = REAL(deltamatrix)[rr + ng*cc]; dprop = rnorm(dcurr, REAL(tuneD)[rr + cc*ng]); gcurr_ll = 0; gprop_ll = 0; for(ii = 0; ii < prec; ++ii){ tmp_gcurr = exp(gcurr + dcurr*REAL(ZZ)[ii]); tmp_gprop = exp(gprop + dprop*REAL(ZZ)[ii]); gcurr_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_gcurr) + REAL(drvector)[rr]*tmp_gcurr*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); gprop_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_gprop) + REAL(drvector)[rr]*tmp_gprop*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); } /* Rprintf("%f %f %f %f\n", gcurr, gprop, gprop_ll, gcurr_ll); */ for(ii = 0; ii < prec; ++ii){ tmp_currB = 0; tmp_propB = 0; for(qq = 0; qq < np; ++qq){ tmp_currB += REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]); /* Rprintf("%i %f \n", qq, exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]));*/ } tmp_propB = tmp_currB - REAL(drvector)[rr] * exp(gcurr + dcurr*REAL(ZZ)[ii]) + REAL(drvector)[rr] * exp(gprop + dprop*REAL(ZZ)[ii]); /*Rprintf("%i %f \n", cc, exp(gcurr + REAL(deltamatrix)[rr + ng*cc]*REAL(ZZ)[ii]));*/ gcurr_ll += lgammafn(tmp_currB); gprop_ll += lgammafn(tmp_propB); if(verbose > 0 && kk % verbose == 0){ /* Rprintf("%f %f %f %f %f %f \n", gcurr, gprop, gcurr_ll, gprop_ll, tmp_currB, tmp_propB); */ } } if(covprior==1){ gcurr_ll += dnorm(gcurr,REAL(Gammean)[rr + ng*cc] ,REAL(Gamsd)[rr + ng*cc] , 1) + dnorm(dcurr,REAL(Delmean)[rr + ng*cc] , REAL(Delsd)[rr + ng*cc], 1); gprop_ll += dnorm(gprop,REAL(Gammean)[rr + ng*cc] ,REAL(Gamsd)[rr + ng*cc] , 1) + dnorm(dprop,REAL(Delmean)[rr + ng*cc] ,REAL(Delsd)[rr + ng*cc] , 1); } if(acc_tog(gprop_ll, gcurr_ll) == 1){ REAL(gammamatrix)[rr + ng*cc] = gprop; REAL(deltamatrix)[rr + ng*cc] = dprop; REAL(g_acc)[rr + ng*cc] += 1; } } } /* for(rr = 0; rr < ng; ++rr){ * for(cc = 0; cc < npm1; ++cc){ * dcurr = REAL(deltamatrix)[rr + ng*cc]; * dprop = rnorm(dcurr, REAL(tuneD)[rr + cc*ng]); * * dcurr_ll = 0; * dprop_ll = 0; * for(ii = 0; ii < prec; ++ii){ * tmp_dcurr = exp(REAL(gammamatrix)[rr + ng*cc] + dcurr*REAL(ZZ)[ii]); * tmp_dprop = exp(REAL(gammamatrix)[rr + ng*cc] + dprop*REAL(ZZ)[ii]); * dcurr_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_dcurr) + REAL(drvector)[rr]*tmp_dcurr*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); * dprop_ll += -1*lgammafn(REAL(drvector)[rr] * tmp_dprop) + REAL(drvector)[rr]*tmp_dprop*log(REAL(betaarray)[rr + ng*cc + ng*np*ii]); * } * for(ii = 0; ii < prec; ++ii){ * tmp_currB = 0; * tmp_propB = 0; * for(qq = 0; qq < np; ++qq){ * tmp_currB += REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*qq] + REAL(deltamatrix)[rr + ng*qq]*REAL(ZZ)[ii]); * } * tmp_propB = tmp_currB - REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*cc] + dcurr*REAL(ZZ)[ii]) + REAL(drvector)[rr] * exp(REAL(gammamatrix)[rr + ng*cc] + dprop*REAL(ZZ)[ii]); * dcurr_ll += lgammafn(tmp_currB); * dprop_ll += lgammafn(tmp_propB); * } * * * if(acc_tog(dprop_ll, dcurr_ll) == 1){ * REAL(deltamatrix)[rr + ng*cc] = dprop; * REAL(d_acc)[rr + ng*cc] += 1; * } * } *} */ if(kk >= burn && ((kk % thin) == 0)){ SET_VECTOR_ELT(usr_list, 0, drvector); SET_VECTOR_ELT(usr_list, 1, betaarray); SET_VECTOR_ELT(usr_list, 2, gammamatrix); SET_VECTOR_ELT(usr_list, 3, deltamatrix); SET_VECTOR_ELT(usr_list, 4, TT); SET_VECTOR_ELT(usr_list, 5, RR); PROTECT(ccount = cellcount(betaarray, RR, NG, NP, Precincts)); usr = usr_fun_eval(usr_fcn, usr_list, usr_env, usr_length); for(qq = 0; qq < usr_length; ++qq){ REAL(usr_draws)[counter + qq*samp] = REAL(usr)[qq]; } for(qq = 0; qq < np*ng; ++qq){ REAL(ccount_draws)[counter + qq*samp] = REAL(ccount)[qq]; } UNPROTECT(1); for(qq = 0; qq < ng; ++qq){ REAL(dr_draws)[counter + qq*samp] = REAL(drvector)[qq]; } for(qq = 0; qq < ng*npm1; ++qq){ REAL(g_draws)[counter + qq*samp] = REAL(gammamatrix)[qq]; REAL(d_draws)[counter + qq*samp] = REAL(deltamatrix)[qq]; } if(INTEGER(Savebeta)[0] == 0){ for(qq = 0; qq < np*ng*prec; ++qq){ REAL(b_draws)[counter + qq*samp] = REAL(betaarray)[qq]; } } if(INTEGER(Savebeta)[0] == 2){ hldr = write_beta(betaarray, betanames); } counter += 1; } if(verbose > 0 && kk % verbose == 0){ Rprintf("\n MCMC iteration %i of %i \n", kk + 1, iters); } R_CheckUserInterrupt(); } for(qq = 0; qq < ng; ++qq){ REAL(dr_acc)[qq] = REAL(dr_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1)*prec;++qq){ REAL(b_acc)[qq] = REAL(b_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(g_acc)[qq] = REAL(g_acc)[qq]/iters; } for(qq = 0; qq < ng*(np-1);++qq){ REAL(d_acc)[qq] = REAL(d_acc)[qq]/iters; } if(INTEGER(Savebeta)[0]==0){ PROTECT(output_list = allocVector(VECSXP, 10)); ++nProtected; SET_VECTOR_ELT(output_list, 0, dr_draws); SET_VECTOR_ELT(output_list, 1, b_draws); SET_VECTOR_ELT(output_list, 2, g_draws); SET_VECTOR_ELT(output_list, 3, d_draws); SET_VECTOR_ELT(output_list, 4, dr_acc); SET_VECTOR_ELT(output_list, 5, b_acc); SET_VECTOR_ELT(output_list, 6, g_acc); SET_VECTOR_ELT(output_list, 7, d_acc); SET_VECTOR_ELT(output_list, 8, ccount_draws); SET_VECTOR_ELT(output_list, 9, usr_draws); }else{ PROTECT(output_list = allocVector(VECSXP, 9)); ++nProtected; SET_VECTOR_ELT(output_list, 0, dr_draws); SET_VECTOR_ELT(output_list, 1, g_draws); SET_VECTOR_ELT(output_list, 2, d_draws); SET_VECTOR_ELT(output_list, 3, dr_acc); SET_VECTOR_ELT(output_list, 4, b_acc); SET_VECTOR_ELT(output_list, 5, g_acc); SET_VECTOR_ELT(output_list, 6, d_acc); SET_VECTOR_ELT(output_list, 7, ccount_draws); SET_VECTOR_ELT(output_list, 8, usr_draws); } PutRNGstate(); UNPROTECT(nProtected); return(output_list); } eiPack/src/eiutil.c0000644000176200001440000000566714374235671013726 0ustar liggesusers #include #include #include #include #include #include #include #include #include "eiutil.h" double beta_ll (double beta, double beta_ref, double alpha, double alpha_ref, double tt_ci, double tt_Ci, double beta_X, double beta_ref_X){ double ll; ll = tt_ci*log(beta_X) + tt_Ci*log(beta_ref_X) + (alpha-1)*log(beta) + (alpha_ref - 1)*log(beta_ref); return(ll); } double alpha_ll (double alpha, double sum_alphaminus, double lbmat, double lambda1, double lambda2, int prec){ double ll; ll = (lambda1 - 1)*log(alpha) - lambda2*alpha + prec*(lgammafn((alpha + sum_alphaminus)) - lgammafn(alpha)) + lbmat*alpha; return(ll); } int acc_tog (double prop_ll, double curr_ll){ int toggle = 0; double log_rat; log_rat = prop_ll - curr_ll; if(log(runif(0,1)) < log_rat){ toggle = 1;} return(toggle); } SEXP cellcount (SEXP betas, SEXP RR, SEXP NG, SEXP NP, SEXP Precincts){ int nProtect = 0; R_len_t rr, cc, ii; int ng, np, prec; double tmp = 0.0; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; SEXP ret_val; PROTECT(ret_val = allocMatrix(REALSXP, ng, np)); ++nProtect; for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ tmp = 0.0; for(ii = 0; ii < prec; ++ii){ tmp += REAL(betas)[rr + ng * cc + ng * np * ii]*REAL(RR)[rr + ng*ii]; } REAL(ret_val)[rr + ng * cc] = tmp; } } UNPROTECT(1); return(ret_val); } SEXP logbetamat (SEXP aa, SEXP NG, SEXP NP, SEXP Precincts){ int nProtect = 0; R_len_t rr, cc, ii; int ng, np, prec; double tmp = 0.0; ng = INTEGER(NG)[0]; np = INTEGER(NP)[0]; prec = INTEGER(Precincts)[0]; SEXP ret_val; PROTECT(ret_val = allocMatrix(REALSXP, ng, np)); ++nProtect; for(rr = 0; rr < ng; ++rr){ for(cc = 0; cc < np; ++cc){ tmp = 0.0; for(ii = 0; ii < prec; ++ii){ tmp += log(REAL(aa)[rr + ng * cc + ng * np * ii]); } REAL(ret_val)[rr + ng * cc] = tmp; } } UNPROTECT(1); return(ret_val); } SEXP write_beta (SEXP betaarray, SEXP filenames){ int ret=0; R_len_t nn, ii; nn = length(filenames); for(ii = 0; ii < nn; ++ii){ char tmp[500]; snprintf(tmp, sizeof(tmp), "echo \"%.16f\" | gzip >> %s", REAL(betaarray)[ii], CHAR(STRING_ELT(filenames,ii))); ret=system(tmp); } R_CheckUserInterrupt(); return(R_NilValue); } SEXP usr_fun_eval(SEXP usr_fun, SEXP cur_values, SEXP usr_env, int usr_len){ SEXP R_fcall, usr_fcn_output; if(!isFunction(usr_fun)) error("`usr_fun' must be a function"); if(!isEnvironment(usr_env)) error("`usr_env' must be an environment"); PROTECT(R_fcall = lang2(usr_fun, R_NilValue)); SETCADR(R_fcall, cur_values); PROTECT(usr_fcn_output = allocVector(REALSXP, usr_len)); usr_fcn_output = eval(R_fcall, usr_env); UNPROTECT(2); return(usr_fcn_output); } eiPack/COPYING0000644000176200001440000003536414374235667012535 0ustar liggesusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. eiPack/R/0000755000176200001440000000000014374252256011661 5ustar liggesuserseiPack/R/densityplot.default.R0000644000176200001440000000016314374235667016014 0ustar liggesusersdensityplot.default <- function(object, ...) { stop(paste("no method `densityplot' for class", class(object))) } eiPack/R/summary.eiMD.R0000644000176200001440000000657214374235670014331 0ustar liggesuserssummary.eiMD <- function(object, short = TRUE, ...) { "%w/o%" <- function(x,y) x[!x %in% y] get2 <- function(x) x[2] getm1 <- function(x) x[2:length(x)] if (is.mcmc(object$draws$Cell.counts)) { tnames <- strsplit(colnames(object$draws$Cell.counts), "ccount.") idx <- strsplit(sapply(tnames, get2), ".", fixed = TRUE) idx <- as.list(as.data.frame(matrix(unlist(idx), byrow = TRUE, nrow = length(idx), ncol = length(idx[[1]])))) idx <- lapply(idx, as.character) idx <- lapply(idx, unique) } else { idx <- dimnames(object$draws$Cell.counts)[1:2] } names(idx) <- c("rows", "columns") cnames <- apply(expand.grid(idx), 1, paste, collapse = ".") cells <- prod(sapply(idx, length)) for (ii in names(object$acc.ratios) %w/o% c("beta.acc")) { ll <- length(object$acc.ratios[[ii]]) if (ll == length(idx[[1]])) { names(object$acc.ratios[[ii]]) <- idx[[1]] } else if (ll < cells) { cc <- ll / length(idx[[1]]) object$acc.ratios[[ii]] <- matrix(object$acc.ratios[[ii]], nrow = length(idx[[1]]), ncol = cc, dimnames = list(idx[[1]], idx[[2]][1:cc])) } else if (ll == cells) { object$acc.ratios[[ii]] <- matrix(object$acc.ratios[[ii]], nrow = length(idx[[1]]), ncol = length(idx[[2]]), dimnames = idx[1:2]) } } if (short) { # old code created r by c array, not r by (c-1) by l array #tmp <- array(object$acc.ratios$beta.acc, # dim = sapply(idx, length), # dimnames = idx) rr <- length(idx[[1]])# cc <- length(idx[[2]]) - 1# ll <- length(object$acc.ratios$beta.acc)/(rr*cc)# tmp <- array(object$acc.ratios$beta.acc,# dim = c(rr,cc,ll))# object$acc.ratios$beta.acc <- apply(tmp, c(1,2), mean) dimnames(object$acc.ratios$beta.acc) <- list(idx[[1]], idx[[2]][1:cc])# } else { #old code filled matrix in wrong direction bacc <- object$acc.ratios$beta.acc rr <- length(idx[[1]])# cc <- length(idx[[2]]) - 1# ll <- length(object$acc.ratios$beta.acc)/(rr*cc)# object$acc.ratios$beta.acc <- matrix(bacc, nrow = ll, ncol = rr*cc, dimnames = list(as.character(1:ll),cnames[1:(rr*cc)]), byrow=TRUE)# } for (ii in names(object$draws) %w/o% c("Beta")) { aa <- object$draws[[ii]] if (!is.mcmc(aa)) { if (length(dim(aa)) > 2) { nc <- prod(dim(aa)[1:2]) aa <- matrix(c(aa), nrow = dim(aa)[3], ncol = nc, byrow = TRUE, dimnames = list(NULL, cnames[1:nc])) } else aa <- t(aa) } object$draws[[ii]] <- cbind(apply(aa, 2, mean), apply(aa, 2, sd), t(apply(aa, 2, quantile, c(0.025,0.975)))) colnames(object$draws[[ii]])[1:2] <- c("Mean", "Std. Error") if (ncol(aa) == length(idx[[1]])) rownames(object$draws[[ii]]) <- idx[[1]] else if (ncol(aa) <= cells) rownames(object$draws[[ii]]) <- cnames[1:ncol(aa)] } object$short <- short class(object) <- "eiMDsum" object } eiPack/R/BayesMDei.R0000644000176200001440000001404314374235667013617 0ustar liggesusersBayesMDei <- function(formula, data, total, lambda1 = 4, lambda2 = 2, tune.alpha = NULL, tune.beta = NULL, start.alphas = NULL, start.betas = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta ='r', ret.mcmc = TRUE, ...){ if(thin < 1){stop('thin must be positive integer')} if(sample < 1){stop('thin must be positive integer')} if(burnin < 0){stop('burnin must be non-negative integer')} DD <- model.frame(formula, data) countParty <- countGroup <- propParty <- propGroup <- FALSE checkGroups <- round(apply(DD[[2]], 1, sum), 3) checkParties <- round(apply(DD[[1]], 1, sum), 3) if(all(DD[[1]] %% 1 == 0) & all(DD[[1]] >= 0)){countParty <- TRUE} else if(all(0 <= DD[[1]] & DD[[1]] <= 1)){ if(all(checkParties == 1)){propParty <- TRUE}else{ stop("column marginals are proportions that do not sum to 1 - please respecify data")}} else stop("column marginals are neither counts nor proportions - please respecify data") if(all(DD[[2]] %% 1 == 0) & all(DD[[2]] >= 0)){countGroup <- TRUE} else if(all(0 <= DD[[2]] & DD[[2]] <= 1)){ if(all(checkGroups == 1)){propGroup <- TRUE}else{ stop("row marginals are proportions that do not sum to 1 - please respecify data")}} else stop("row marginals are neither counts nor proportions - please respecify data") if((propParty | propGroup) & is.null(total)){ stop("one or both marginals are proportions - 'total' must be provided")} if(propParty & !is.null(total)){ DD[[1]] <- DD[[1]] * total warning("column marginals are proportions - multiplying by unit size")} if(propGroup & !is.null(total)){ DD[[2]] <- DD[[2]] * total warning("row margnials are proportions - multiplying by unit size")} checkGroups <- round(apply(DD[[2]], 1, sum), 1) checkParties <- round(apply(DD[[1]], 1, sum), 1) if(identical(checkParties, checkGroups) == FALSE){ stop("row and column totals unequal in some units - please respecify data")} Groups <- DD[[2]] TT <- t(DD[[1]]) XX <- t(Groups/apply(Groups,1,sum)) group.names <- colnames(Groups) party.names <- rownames(TT) RR <- t(Groups) NG <- nrow(XX) NP <- nrow(TT) Precincts <- nrow(DD) if(is.null(start.alphas)){ start.alphas <- matrix(rgamma(NG*NP, lambda1, lambda2), NG, NP)} if(min(start.alphas) <= 0){stop('inadmissable starting values for alpha')} if(is.null(start.betas)){ start.betas <- array(NA, dim= c(NG, NP, Precincts)) for(i in 1:Precincts){ start.betas[,,i] <- rdirichlet(NG, rep(1,NP))} } if(identical(round(apply(start.betas, c(1,3), sum),10), matrix(1,NG, Precincts))!=TRUE){ stop('inadmissable starting values for beta')} if(is.null(tune.alpha)){ tune.alpha <- matrix(rep(.25,NG*NP), NG, NP)} if(is.null(tune.beta)){ tune.beta <- array(rep(.05, NG*(NP-1)*Precincts), c(NG, NP-1, Precincts))} tune.alpha <- as.matrix(tune.alpha) if(identical(dim(tune.alpha), c(NG, NP))!=TRUE) {stop("'tune.alpha' has incorrect dimensions")} if(identical(as.numeric(dim(tune.beta)), c(NG, NP-1, Precincts))!=TRUE) {stop("'tune.beta' has incorrect dimensions")} beta.names <- paste(paste(paste(group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep="."), ".txt.gz", sep="") if(ret.beta == 's'){touch.betas(beta.names) ret.beta <- 2} if(ret.beta == 'd'){ret.beta <- 1} if(ret.beta == 'r'){ret.beta <- 0} if(is.numeric(ret.beta)==FALSE){stop('incorrect option for ret.beta')} output <- .Call("rbycei_fcn1", as.numeric(start.alphas), as.numeric(start.betas), as.numeric(TT), as.numeric(XX), as.numeric(tune.alpha), as.numeric(tune.beta), as.integer(NG), as.integer(NP), as.integer(Precincts), as.numeric(lambda1), as.numeric(lambda2), as.integer(sample), as.integer(thin), as.integer(burnin), as.integer(verbose), as.integer(ret.beta), as.numeric(RR), as.character(beta.names) ) if(ret.beta==0){names(output) <- c("Alpha", "Beta", "alpha.acc", "beta.acc", "cell.count")} else{names(output) <- c("Alpha", "alpha.acc", "beta.acc","cell.count")} if(ret.mcmc){ colnames(output$Alpha) <- paste("alpha",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$Alpha <- coda::mcmc(output$Alpha, thin=thin) colnames(output$cell.count) <- paste("ccount",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$cell.count <- coda::mcmc(output$cell.count, thin=thin) if(ret.beta==0){ colnames(output$Beta) <- paste(paste("beta", group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep=".") output$Beta <- coda::mcmc(output$Beta, thin=thin) } }else{ output$Alpha <- array(t(output$Alpha), c(NG, NP, sample)) dimnames(output$Alpha) <- list(group.names, party.names, 1:sample) output$cell.count <- array(t(output$cell.count), c(NG, NP, sample)) dimnames(output$cell.count) <- list(group.names, party.names, 1:sample) if(ret.beta==0){ output$Beta <- array(t(output$Beta), c(NG, NP, Precincts, sample)) dimnames(output$Beta) <- list(group.names, party.names, 1:Precincts, 1:sample) } } return(output) } eiPack/R/print.lambdaReg.R0000644000176200001440000000067214374235670015023 0ustar liggesusersprint.lambdaReg <- function(x, digits = max(2, getOption("digits") - 4), ...) { denom <- as.character(x$call$columns)[2] for(i in 3:length(as.character(x$call$columns))){ denom <- paste(denom,as.character(x$call$columns)[i], sep=", ") } cat("\nDenominator is sum(", denom,").", "\n\n", sep="") print.default(format(x$coef, digits = digits), print.gap = 2, quote = FALSE, ...) } eiPack/R/ei.reg.bayes.R0000644000176200001440000000466714374235670014275 0ustar liggesusersei.reg.bayes <- function(formula, data, sample=1000, weights = NULL, truncate=FALSE) { D <- model.frame(formula, data = data) G <- D[[2]] T <- D[[1]] idx.r <- apply(G,1,sum) idx.c <- apply(T,1,sum) countG <- countT <- propG <- propT <- FALSE if(all(as.integer(T)==T) && all(T)>=0){ countT <- TRUE } else{ propT <- TRUE } if(all(as.integer(G)==G) & all(G)>=0){ countG <- TRUE } else{propG <- TRUE} if(countT & countG){ if(all(idx.r == idx.c)){ G <- G/idx.r T <- T/idx.c countT <- countG <- FALSE propT <- propG <- TRUE } else{ stop("row and column count totals unequal in some precincts - please respecify data") } } if(countT & propG){ if(!all(0 <= G && G <= 1)){ stop("row proportions are not within [0,1] - please respecify data") } else{ T <- T/idx.c propT <- TRUE countT <- FALSE } } if(propT & countG){ if(!all(0 <= T && T <= 1)){ stop("column proportions are not within [0,1] - please respecify data") } else{ G <- G/idx.r propG <- TRUE countG <- FALSE } } if(propT & propG){ idx.r <- apply(G,1,sum) idx.c <- apply(T,1,sum) if(!all(round(idx.r, digits=3)==1)){ stop("row marginals are proportions that do not sum to 1 - please respecify data") } if(!all(round(idx.c, digits=3)==1)){ stop("column marginals are proportions that do not sum to 1 - please respecify data") } } parties <- list() for (i in 1:(ncol(T))) { beta <- bayes.regress(T[,i] ~ G - 1, data = data, sample = sample, weights = weights, truncate=truncate) parties[[colnames(T)[i]]] <- beta colnames(parties[[colnames(T)[i]]]) <- colnames(G) } # ridx <- colnames(parties[[1]]) # tmp.no <- matrix(NA, nrow(parties[[1]]), length(ridx)) # colnames(tmp.no) <- ridx # for (i in 1:length(ridx)){ # tmp.sum <- rep(0, length(parties[[1]][,1])) # for(j in 1:length(parties)){ # tmp.sum <- tmp.sum + parties[[j]][,i] # } # tmp.no[,ridx[i]] <- 1 - tmp.sum # } # NoVote <- tmp.no draws <- array(NA, dim=c(ncol(G), ncol(T), sample)) for(i in 1:sample){ for(j in 1:length(parties)){ draws[,j,i] <- parties[[j]][i,] } # draws[,(j+1),i] <- NoVote[i,] } rownames(draws) <- colnames(G) colnames(draws) <- colnames(T) out <- list(call=match.call(), draws=draws) class(out) <- "eiRegBayes" out } eiPack/R/rdirichlet.R0000644000176200001440000000067614374235670014147 0ustar liggesusers## ## Dirichlet (Multivariate Beta) ## ## From MCMCpack 0.7-2 by Andrew Martin and Kevin Quinn # # # note: this code is taken verbatim from the R-package # "Greg's Miscellaneous Functions" maintained by # Gregory R. Warnes # # Kevin Rompala 5/6/2003 rdirichlet <- function(n, alpha) { l <- length(alpha) x <- matrix(rgamma(l*n,alpha),ncol=l,byrow=TRUE) sm <- x%*%rep(1,l) return(x/as.vector(sm)) } eiPack/R/print.eiRegBayesSum.R0000644000176200001440000000053614374235670015650 0ustar liggesusersprint.eiRegBayesSum <- function(x, digits = max(2, getOption("digits") - 4), ...) { cat("\nFormula: ", deparse(x$call$formula), "\n") cat("Total sims: ", x$sims, "\n\n") cat("Estimated internal cells: (across simulations)\n") print.default(format(x$coef, digits = digits), print.gap = 2, quote = FALSE, ...) invisible(x) } eiPack/R/lambda.MD.R0000644000176200001440000000342414374251650013523 0ustar liggesuserslambda.MD <- function(object, columns, ret.mcmc = TRUE){ get2 <- function(x) x[2] if (inherits(object, "eiMD")==FALSE) stop("'object' must be output from 'ei.MD.bayes'") if (missing(columns) | length(columns) < 2) stop("'columns' requires at least two column names") cc <- object$draws$Cell.counts if (is.mcmc(cc)) { tnames <- strsplit(colnames(cc), "ccount.") idx <- strsplit(sapply(tnames, get2), ".", fixed = TRUE) idx <- as.list(as.data.frame(matrix(unlist(idx), byrow = TRUE, nrow = length(idx), ncol = length(idx[[1]])))) idx <- lapply(idx, as.character) idx <- lapply(idx, unique) sims <- nrow(cc) mcpar.cc <- mcpar(cc) cc <- array(t(cc), c(sapply(idx, length), sims), dimnames = list(idx[[1]], idx[[2]], 1:sims)) } else { idx <- names(object$draws$Cell.counts)[1:2] sims <- dim(cc)[3] } names(idx) <- c("rows", "columns") NG <- length(idx[[1]]) NP <- length(idx[[2]]) NI <- length(columns) lambda.out <- array(NA, c(NG, NI, sims), dimnames = list(idx[[1]], columns, 1:sims)) for (ii in idx[[1]]) { lambda.out[ii,,] <- t(t(cc[ii, columns,]) / apply(cc[ii, columns,], 2, sum)) } if (ret.mcmc){ lambda.out <- t(matrix(lambda.out , NG*NI, sims)) colnames(lambda.out) <- paste("lambda", matrix(rep(idx[[1]], NI),NG,NI), matrix(rep(columns, NG),NG,NI, byrow=TRUE) ,sep=".") lambda.out <- coda::mcmc(lambda.out) attr(lambda.out, "mcpar") <- mcpar.cc } class(lambda.out) <- c("lambdaMD", class(lambda.out)) lambda.out } eiPack/R/BayesMDei4cov.R0000644000176200001440000002305714374235667014420 0ustar liggesusersBayesMDei4cov <- function(formula, covariate, total, data, lambda1 = 2, lambda2 = 4, covariateprior = NULL, tune.dr = NULL, tune.beta = NULL, tune.gamma = NULL, tune.delta = NULL, start.dr = NULL, start.betas = NULL, start.gamma = NULL, start.delta = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta = 'r', ret.mcmc = TRUE, usrfun = NULL, ...){ if(thin < 1){stop('thin must be positive integer')} if(sample < 1){stop('thin must be positive integer')} if(burnin < 0){stop('burnin must be non-negative integer')} DD <- model.frame(formula, data) countParty <- countGroup <- propParty <- propGroup <- FALSE checkGroups <- round(apply(DD[[2]], 1, sum), 3) checkParties <- round(apply(DD[[1]], 1, sum), 3) if(all(DD[[1]] %% 1 == 0) & all(DD[[1]] >= 0)){countParty <- TRUE} else if(all(0 <= DD[[1]] & DD[[1]] <= 1)){ if(all(checkParties == 1)){propParty <- TRUE}else{ stop("column marginals are proportions that do not sum to 1 - please respecify data")}} else stop("column marginals are neither counts nor proportions - please respecify data") if(all(DD[[2]] %% 1 == 0) & all(DD[[2]] >= 0)){countGroup <- TRUE} else if(all(0 <= DD[[2]] & DD[[2]] <= 1)){ if(all(checkGroups == 1)){propGroup <- TRUE}else{ stop("row marginals are proportions that do not sum to 1 - please respecify data")}} else stop("row marginals are neither counts nor proportions - please respecify data") if((propParty | propGroup) & is.null(total)){ stop("one or both marginals are proportions - 'total' must be provided")} if(propParty & !is.null(total)){ DD[[1]] <- DD[[1]] * total warning("column margnials are proportions - multiplying by unit size")} if(propGroup & !is.null(total)){ DD[[2]] <- DD[[2]] * total warning("row margnials are proportions - multiplying by unit size")} checkGroups <- round(apply(DD[[2]], 1, sum), 1) checkParties <- round(apply(DD[[1]], 1, sum), 1) if(identical(checkParties, checkGroups) == FALSE){ stop("row and column totals unequal in some units - please respecify data")} Groups <- DD[[2]] TT <- t(DD[[1]]) XX <- t(Groups/apply(Groups,1,sum)) group.names <- colnames(Groups) party.names <- rownames(TT) RR <- t(Groups) CC <- model.frame(covariate, data) ZZ <- as.matrix(CC) NG <- nrow(XX) NP <- nrow(TT) Precincts <- nrow(DD) if(is.null(start.dr)){ start.dr <- matrix(rgamma(NG, lambda1, lambda2), NG)} if(min(start.dr) <= 0){stop("inadmissable starting values for dr")} if(is.null(start.betas)){ start.betas <- array(NA, dim= c(NG, NP, Precincts)) for(i in 1:Precincts){ start.betas[,,i] <- rdirichlet(NG, rep(1,NP))} } if(identical(round(apply(start.betas, c(1,3), sum),10),matrix(1,NG, Precincts))!=TRUE){stop("inadmissable starting values for beta")} if(is.null(start.gamma)){ start.gamma <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)} if(identical(start.gamma[,NP], rep(0,NG))!=TRUE){stop("final column of 'start.gamma' must be zero")} if(is.null(start.delta)){ start.delta <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)} if(identical(start.delta[,NP], rep(0,NG))!=TRUE){stop("final column of 'start.delta' must be zero")} usrenv <- environment(fun = usrfun) usrlen <- length(as.numeric(usrfun(list(start.dr, start.betas, start.gamma, start.delta, TT, RR)))) if(is.null(tune.dr)){ tune.dr <- rep(2,NG)} if(is.null(tune.beta)){ tune.beta <- array(rep(.05, NG*(NP-1)*Precincts), c(NG, NP-1, Precincts))} if(is.null(tune.gamma)){ tune.gamma <- matrix(.25, NG, NP-1)} if(is.null(tune.delta)){ tune.delta <- matrix(.25, NG, NP-1)} if(identical(length(tune.dr), NG)!=TRUE) {stop("'tune.dr' has incorrect dimensions")} if(identical(as.numeric(dim(tune.beta)), c(NG, NP-1, Precincts))!=TRUE) {stop("'tune.beta' has incorrect dimensions")} if(identical(as.numeric(dim(tune.gamma)), c(NG, NP-1))!=TRUE) {stop("'tune.gamma' has incorrect dimensions")} if(identical(as.numeric(dim(tune.delta)), c(NG, NP-1))!=TRUE) {stop("'tune.delta' has incorrect dimensions")} if(is.null(covariateprior)){ covprior <- 0 delmean <- gammean <- rep(0, NG*(NP-1)) delsd <- gamsd <- rep(1, NG*(NP-1)) }else{ covprior <- 1 delmean <- covariateprior[[1]] delsd <- covariateprior[[2]] gammean <- covariateprior[[3]] gamsd <- covariateprior[[4]] if(identical(as.numeric(dim(delmean)), c(NG, NP-1))!=TRUE) {stop("matrix of prior means for delta has incorrect dimensions")} if(identical(as.numeric(dim(delsd)), c(NG, NP-1))!=TRUE) {stop("matrix of prior sd for delta has incorrect dimensions")} if(identical(as.numeric(dim(gammean)), c(NG, NP-1))!=TRUE) {stop("matrix of prior means for gamma has incorrect dimensions")} if(identical(as.numeric(dim(gamsd)), c(NG, NP-1))!=TRUE) {stop("matrix of prior sd for gamma has incorrect dimensions")} if(min(gamsd)<=0) {stop("prior sd for gamma must be > 0")} if(min(gamsd)<=0) {stop("prior sd for delta must be > 0")} } beta.names <- paste(paste(paste(group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep="."), ".txt.gz", sep="") if(ret.beta == 's'){touch.betas(beta.names) ret.beta <- 2} if(ret.beta == 'd'){ret.beta <- 1} if(ret.beta == 'r'){ret.beta <- 0} if(is.numeric(ret.beta)==FALSE){stop("incorrect option for ret.beta")} output <- .Call("rbycei_fcn4", as.numeric(start.dr), as.numeric(start.betas), as.numeric(start.gamma), as.numeric(start.delta), as.numeric(TT), as.numeric(XX), as.numeric(ZZ), as.numeric(tune.dr), as.numeric(tune.beta), as.numeric(tune.gamma), as.numeric(tune.delta), as.integer(NG), as.integer(NP), as.integer(Precincts), as.numeric(lambda1), as.numeric(lambda2), as.integer(covprior), as.numeric(delmean), as.numeric(delsd), as.numeric(gammean), as.numeric(gamsd), as.integer(sample), as.integer(thin), as.integer(burnin), as.integer(verbose), as.integer(ret.beta), as.numeric(RR), usrfun, usrenv, as.integer(usrlen), as.character(beta.names) ) if(ret.beta==0){names(output) <- c("Dr", "Beta","Gamma","Delta", "dr.acc","beta.acc", "gamma.acc", "delta.acc","cell.count", "usrfun")} else{names(output) <- c("Dr","Gamma","Delta", "dr.acc","beta.acc", "gamma.acc", "delta.acc","cell.count", "usrfun")} if(ret.mcmc){ colnames(output$Dr) <- paste("dr", group.names, sep=".") output$Dr <- coda::mcmc(output$Dr, thin=thin) colnames(output$cell.count) <- paste("ccount",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$cell.count <- coda::mcmc(output$cell.count, thin=thin) colnames(output$Gamma) <- paste("gamma",matrix(rep(group.names, (NP-1)),NG,NP-1) ,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1, byrow=T) ,sep=".") output$Gamma <- coda::mcmc(output$Gamma, thin=thin) colnames(output$Delta) <- paste("delta",matrix(rep(group.names, (NP-1)),NG,NP-1) ,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1, byrow=T) ,sep=".") output$Delta <- coda::mcmc(output$Delta, thin=thin) if(ret.beta==0){ colnames(output$Beta) <- paste(paste("beta", group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep=".") output$Beta <- coda::mcmc(output$Beta, thin=thin) } }else{ output$Dr <- t(output$Dr) dimnames(output$Dr) <- list(paste("dr", group.names, sep="."), 1:sample) output$cell.count <- array(t(output$cell.count), c(NG, NP, sample)) dimnames(output$cell.count) <- list(group.names, party.names, 1:sample) output$Gamma <- array(t(output$Gamma), c(NG, NP-1, sample)) dimnames(output$Gamma) <- list(group.names, party.names[1:(NP-1)], 1:sample) output$Delta <- array(t(output$Delta), c(NG, NP-1,sample)) dimnames(output$Delta) <- list(group.names, party.names[1:(NP-1)], 1:sample) if(ret.beta==0){ output$Beta <- array(t(output$Beta), c(NG, NP, Precincts, sample)) dimnames(output$Beta) <- list(group.names, party.names, 1:Precincts, 1:sample) } } return(output) } eiPack/R/delta.R0000644000176200001440000000213514374235667013105 0ustar liggesusersdelta <- function(object, cols){ se <- matrix(NA, nrow(object[["se"]]), length(cols)) rownames(se) <- rownames(object[["se"]]) colnames(se) <- cols cov.array <- array(dim=c(nrow(se), nrow(se), ncol(se))) rownames(cov.array) <- colnames(cov.array) <- rownames(se) dimnames(cov.array)[[3]] <- cols for(i in 1:length(cols)){ cov.array[,,i] <- object[["cov.matrices"]][cols[i]][[1]] } delta.nums <- paste("x",1:length(cols), sep="") delta.denom <- paste(delta.nums[1],"+", delta.nums[2], sep="") if(length(delta.nums)>2){ for(i in 3:length(delta.nums)){ delta.denom <- paste(delta.denom, "+", delta.nums[i], sep="") } } delta.formula <- list() for(i in 1:length(delta.nums)){ delta.formula[[i]] <- as.formula(paste("~ ", delta.nums[i], "/(", delta.denom,")", sep="")) } for(i in 1:nrow(se)){ se[i,] <- msm::deltamethod(delta.formula, m=object[["coefficients"]][i,cols], cov=diag(cov.array[i,i,cols])) } se } eiPack/R/print.eiRegBayes.R0000644000176200001440000000060314374235670015156 0ustar liggesusersprint.eiRegBayes <- function(x, digits = max(2, getOption("digits") - 4), ...) { cat("\nFormula: ", deparse(x$call$formula), "\n") cat("Total sims: ", dim(x$draws)[3], "\n\n") cat("Estimated internal cells: (averaged across simulations)\n") print.default(format(apply(x$draws, c(1,2), mean), digits = digits), print.gap = 2, quote = FALSE, ...) invisible(x) } eiPack/R/read.betas.R0000644000176200001440000000215114374235670014014 0ustar liggesusersread.betas <- function(rows, columns, units, dir = NULL, ret.mcmc = TRUE) { "%w/o%" <- function(x,y) x[!x %in% y] #-- x without y idx <- expand.grid(rows, columns, units) idx <- apply(idx, 1, paste, collapse = ".") files <- paste(idx, ".txt.gz", sep = "") if (is.null(dir)) { dir <- getwd() } else { current.dir <- getwd() setwd(dir) } check <- system("ls", intern = TRUE) if (!all(files %in% check)) stop(paste(paste(paste(files %w/o% check, ".txt.gz", sep = ""), collapse = " "), " files not found in ", dir, sep = "")) readin <- list() for (ii in files) readin[[ii]] <- read.table(gzfile(files[ii]), as.is = TRUE, header=TRUE)[[1]] vidx <- names(readin) if (ret.mcmc) { dat <- as.mcmc(readin) class(dat) <- c(class(dat), "eiMD.beta") } else { idx1 <- list(rows = rows, columns = columns, units = units) idx1[[4]] <- 1:length(readin[[1]]) names(idx1) <- c("rows", "columns", "units", "sims") dat <- array(t(readin), dim = sapply(idx, length), dimnames = idx) class(dat) <- c("array", "eiMD.beta") } dat } eiPack/R/BayesMDei3cov.R0000644000176200001440000002235214374235667014414 0ustar liggesusersBayesMDei3cov <- function(formula, covariate, total, data, lambda1 = 2, lambda2 = 4, covariateprior=NULL, tune.dr = NULL, tune.beta = NULL, tune.gamma = NULL, tune.delta = NULL, start.dr = NULL, start.betas = NULL, start.gamma = NULL, start.delta = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta = 'r', ret.mcmc = TRUE, ...){ if(thin < 1){stop('thin must be positive integer')} if(sample < 1){stop('thin must be positive integer')} if(burnin < 0){stop('burnin must be non-negative integer')} DD <- model.frame(formula, data) countParty <- countGroup <- propParty <- propGroup <- FALSE checkGroups <- round(apply(DD[[2]], 1, sum), 3) checkParties <- round(apply(DD[[1]], 1, sum), 3) if(all(DD[[1]] %% 1 == 0) & all(DD[[1]] >= 0)){countParty <- TRUE} else if(all(0 <= DD[[1]] & DD[[1]] <= 1)){ if(all(checkParties == 1)){propParty <- TRUE}else{ stop("column marginals are proportions that do not sum to 1 - please respecify data")}} else stop("column marginals are neither counts nor proportions - please respecify data") if(all(DD[[2]] %% 1 == 0) & all(DD[[2]] >= 0)){countGroup <- TRUE} else if(all(0 <= DD[[2]] & DD[[2]] <= 1)){ if(all(checkGroups == 1)){propGroup <- TRUE}else{ stop("row marginals are proportions that do not sum to 1 - please respecify data")}} else stop("row marginals are neither counts nor proportions - please respecify data") if((propParty | propGroup) & is.null(total)){ stop("one or both marginals are proportions - 'total' must be provided")} if(propParty & !is.null(total)){ DD[[1]] <- DD[[1]] * total warning("column margnials are proportions - multiplying by unit size")} if(propGroup & !is.null(total)){ DD[[2]] <- DD[[2]] * total warning("row margnials are proportions - multiplying by unit size")} checkGroups <- round(apply(DD[[2]], 1, sum), 1) checkParties <- round(apply(DD[[1]], 1, sum), 1) if(identical(checkParties, checkGroups) == FALSE){ stop("row and column totals unequal in some units - please respecify data")} Groups <- DD[[2]] TT <- t(DD[[1]]) XX <- t(Groups/apply(Groups,1,sum)) group.names <- colnames(Groups) party.names <- rownames(TT) RR <- t(Groups) CC <- model.frame(covariate, data) ZZ <- as.matrix(CC) NG <- nrow(XX) NP <- nrow(TT) Precincts <- nrow(DD) if(is.null(start.dr)){ start.dr <- matrix(rgamma(NG, lambda1, lambda2), NG)} if(min(start.dr) <= 0){stop("inadmissable starting values for dr")} if(is.null(start.betas)){ start.betas <- array(NA, dim= c(NG, NP, Precincts)) for(i in 1:Precincts){ start.betas[,,i] <- rdirichlet(NG, rep(1,NP))} } if(identical(round(apply(start.betas, c(1,3), sum),10),matrix(1,NG, Precincts))!=TRUE){stop("inadmissable starting values for beta")} if(is.null(start.gamma)){ start.gamma <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)} if(identical(start.gamma[,NP], rep(0,NG))!=TRUE){stop("final column of 'start.gamma' must be zero")} if(is.null(start.delta)){ start.delta <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)} if(identical(start.delta[,NP], rep(0,NG))!=TRUE){stop("final column of 'start.delta' must be zero")} if(is.null(tune.dr)){ tune.dr <- rep(2,NG)} if(is.null(tune.beta)){ tune.beta <- array(rep(.05, NG*(NP-1)*Precincts), c(NG, NP-1, Precincts))} if(is.null(tune.gamma)){ tune.gamma <- matrix(.25, NG, NP-1)} if(is.null(tune.delta)){ tune.delta <- matrix(.25, NG, NP-1)} if(identical(length(tune.dr), NG)!=TRUE) {stop("'tune.dr' has incorrect dimensions")} if(identical(as.numeric(dim(tune.beta)), c(NG, NP-1, Precincts))!=TRUE) {stop("'tune.beta' has incorrect dimensions")} if(identical(as.numeric(dim(tune.gamma)), c(NG, NP-1))!=TRUE) {stop("'tune.gamma' has incorrect dimensions")} if(identical(as.numeric(dim(tune.delta)), c(NG, NP-1))!=TRUE) {stop("'tune.delta' has incorrect dimensions")} if(is.null(covariateprior)){ covprior <- 0 delmean <- gammean <- rep(0, NG*(NP-1)) delsd <- gamsd <- rep(1, NG*(NP-1)) }else{ covprior <- 1 delmean <- covariateprior[[1]] delsd <- covariateprior[[2]] gammean <- covariateprior[[3]] gamsd <- covariateprior[[4]] if(identical(as.numeric(dim(delmean)), c(NG, NP-1))!=TRUE) {stop("matrix of prior means for delta has incorrect dimensions")} if(identical(as.numeric(dim(delsd)), c(NG, NP-1))!=TRUE) {stop("matrix of prior sd for delta has incorrect dimensions")} if(identical(as.numeric(dim(gammean)), c(NG, NP-1))!=TRUE) {stop("matrix of prior means for gamma has incorrect dimensions")} if(identical(as.numeric(dim(gamsd)), c(NG, NP-1))!=TRUE) {stop("matrix of prior sd for gamma has incorrect dimensions")} if(min(gamsd)<=0) {stop("prior sd for gamma must be > 0")} if(min(gamsd)<=0) {stop("prior sd for delta must be > 0")} } beta.names <- paste(paste(paste(group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep="."), ".txt.gz", sep="") if(ret.beta == 's'){touch.betas(beta.names) ret.beta <- 2} if(ret.beta == 'd'){ret.beta <- 1} if(ret.beta == 'r'){ret.beta <- 0} if(is.numeric(ret.beta)==FALSE){stop("incorrect option for 'ret.beta'")} output <- .Call("rbycei_fcn3", as.numeric(start.dr), as.numeric(start.betas), as.numeric(start.gamma), as.numeric(start.delta), as.numeric(TT), as.numeric(XX), as.numeric(ZZ), as.numeric(tune.dr), as.numeric(tune.beta), as.numeric(tune.gamma), as.numeric(tune.delta), as.integer(NG), as.integer(NP), as.integer(Precincts), as.numeric(lambda1), as.numeric(lambda2), as.integer(covprior), as.numeric(delmean), as.numeric(delsd), as.numeric(gammean), as.numeric(gamsd), as.integer(sample), as.integer(thin), as.integer(burnin), as.integer(verbose), as.integer(ret.beta), as.numeric(RR), as.character(beta.names) ) if(ret.beta==0){names(output) <- c("Dr", "Beta","Gamma","Delta", "dr.acc","beta.acc", "gamma.acc", "delta.acc","cell.count")} else{names(output) <- c("Dr","Gamma","Delta", "dr.acc","beta.acc", "gamma.acc", "delta.acc","cell.count")} if(ret.mcmc){ colnames(output$Dr) <- paste("dr", group.names, sep=".") output$Dr <- coda::mcmc(output$Dr, thin=thin) colnames(output$cell.count) <- paste("ccount",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$cell.count <- coda::mcmc(output$cell.count, thin=thin) colnames(output$Gamma) <- paste("gamma",matrix(rep(group.names, (NP-1)),NG,NP-1) ,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1, byrow=T) ,sep=".") output$Gamma <- coda::mcmc(output$Gamma, thin=thin) colnames(output$Delta) <- paste("delta",matrix(rep(group.names, (NP-1)),NG,NP-1) ,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1, byrow=T) ,sep=".") output$Delta <- coda::mcmc(output$Delta, thin=thin) if(ret.beta==0){ colnames(output$Beta) <- paste(paste("beta", group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep=".") output$Beta <- coda::mcmc(output$Beta, thin=thin) } }else{ output$Dr <- t(output$Dr) dimnames(output$Dr) <- list(paste("dr", group.names, sep="."), 1:sample) output$cell.count <- array(t(output$cell.count), c(NG, NP, sample)) dimnames(output$cell.count) <- list(group.names, party.names, 1:sample) output$Gamma <- array(t(output$Gamma), c(NG, NP-1, sample)) dimnames(output$Gamma) <- list(group.names, party.names[1:(NP-1)], 1:sample) output$Delta <- array(t(output$Delta), c(NG, NP-1,sample)) dimnames(output$Delta) <- list(group.names, party.names[1:(NP-1)], 1:sample) if(ret.beta==0){ output$Beta <- array(t(output$Beta), c(NG, NP, Precincts, sample)) dimnames(output$Beta) <- list(group.names, party.names, 1:Precincts, 1:sample) } } return(output) } eiPack/R/bayes.regress.R0000644000176200001440000000210414374235667014564 0ustar liggesusersbayes.regress <- function(formula, data, sample = 1000, weights = NULL, truncate=FALSE){ fml <- as.formula(formula) D <- model.frame(fml, data = data) Y <- as.matrix(model.response(D)) X <- model.matrix(formula, data = D) if (!is.null(weights)) { weights <- weights/sum(weights) w <- weights^(-1/2) X <- w * X Y <- w * Y } n <- nrow(X) nu <- n - ncol(X) s2 <- as.numeric((t(Y) %*% Y - t(Y) %*% X %*% solve(t(X) %*% X) %*% t(X) %*% Y)) / nu phi <- rchisq(sample, df = nu) sigma2 <- (nu * s2) / phi beta.hat <- solve(t(X) %*% X) %*% t(X) %*% Y tXX <- function(sigma2, X) sigma2 * solve(t(X) %*% X) Sigma <- lapply(sigma2, tXX, X) truncMVRnorm <- function(sig, mean, n){ repeat{ draw <- mvrnorm(n=n, mu=mean, Sigma=sig) if(min(draw)>=0 & max(draw)<=1){ return(draw) } } } if(truncate==TRUE){ beta <- t(sapply(Sigma, truncMVRnorm, n = 1, mean = beta.hat)) }else{ beta <- t(sapply(Sigma, mvrnorm, n = 1, mu = beta.hat)) } colnames(beta) <- colnames(X) beta } eiPack/R/turnout.R0000644000176200001440000000013514374235670013524 0ustar liggesusersturnout <- function(iterlist){ x <- 1 - iterlist[[2]][,ncol(iterlist[[1]]) ,] return(x)} eiPack/R/densityplot.lambdaReg.R0000644000176200001440000000646714374235670016255 0ustar liggesusersdensityplot.lambdaReg <- function(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) { readpars <- par(no.readonly = TRUE) idx <- dimnames(x$lambda) lidx <- sapply(idx, length) names(lidx) <- names(idx) <- c("rows", "columns") dens <- array(NA, dim = lidx, dimnames = idx) for (i in idx[[2]]) { for (j in idx[[1]]) dens[j,i] <- dnorm(x$lambda[j,i], mean = x$lambda[j,i], sd = x$se[j,i]) } if (missing(xlim)) { tmpL <- x$lambda - 3*x$se tmpH <- x$lambda + 3*x$se xlim <- c(min(tmpL), max(tmpH)) } if (by == "row") { par(mfrow = c(lidx[1], 1), ...) if (missing(ylim)) { ylim <- apply(dens, 1, max) } if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[1]])) } else if (length(xlab) != length(idx[[1]])) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[1])[1:lidx[1]] } if (missing(col)) { col <- rainbow(lidx[2]) } else { if (length(col) < lidx[2]) col <- rep(col, idx[[2]])[1:lidx[2]] if (length(col) > lidx[2]) col <- col[1:lidx[2]] } names(col) <- idx[[2]] names(xlab) <- idx[[1]] for (ii in idx[[1]]) { x1 <- seq(tmpL[ii,1], tmpH[ii,1], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[ii,1], sd = x$se[ii,1]) plot(x1, d1, type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[2]][2:lidx[2]]) { x1 <- seq(tmpL[ii,jj], tmpH[ii,jj], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[ii,jj], sd = x$se[ii,jj]) lines(x1, d1, lty = lty, lwd = lwd, col = col[jj]) } abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } if (by == "column") { par(mfrow = c(lidx[2], 1), ...) if (missing(ylim)) { ylim <- apply(dens, 2, max) } if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[2]])) } else { if (length(xlab) != lidx[1]) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[2])[1:lidx[2]] } } if (missing(col)) { col <- rainbow(lidx[1]) } else { if (length(col) < lidx[1]) col <- rep(col, idx[[1]])[1:lidx[1]] if (length(col) > lidx[1]) col <- col[1:lidx[1]] } names(col) <- idx[[1]] names(xlab) <- idx[[2]] for (ii in idx[[2]]) { x1 <- seq(tmpL[1,ii], tmpH[1,ii], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[1,ii], sd = x$se[1,ii]) plot(x1, d1, type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[1]][2:lidx[1]]) { x1 <- seq(tmpL[jj,ii], tmpH[jj,ii], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[jj,ii], sd = x$se[jj,ii]) lines(x1, d1, lty = lty, lwd = lwd, col = col[jj]) } abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } return(invisible(x)) par(readpars) } eiPack/R/ei.MD.bayes.R0000644000176200001440000001542514374250103013776 0ustar liggesusersei.MD.bayes <- function(formula, covariate = NULL, total = NULL, data, lambda1 = 4, lambda2 = 2, covariate.prior.list = NULL, tune.list = NULL, start.list = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta = 'r', ret.mcmc = TRUE, usrfun = NULL){ if(inherits(tune.list,"tuneMD")){ if(identical(tune.list$call$lambda1, lambda1)==FALSE){ stop("tuning parameters assumed different prior for lambda1")} if(identical(tune.list$call$lambda2, lambda2)==FALSE){ stop("tuning parameters assumed different prior for lambda2")} if(identical(tune.list$call$covariate.prior.list, covariate.prior.list)==FALSE){ stop("tuning parameters assumed different prior for gamma and delta")} } if(!is.null(total)){ if(!is.numeric(total)){ if(is.character(total)){ total <- data[[total]]}else{ total <- data[[deparse(substitute(total))]]}}} if(is.null(covariate)){ if(is.null(tune.list)){ tune.alpha <- NULL tune.beta <- NULL}else{ tune.alpha <- tune.list[[1]] tune.beta <- tune.list[[2]]} if(is.null(start.list)){ start.alphas <- NULL start.betas <- NULL}else{ start.alphas <- start.list[[1]] start.betas <- start.list[[2]]} if(is.null(usrfun)){ output <- BayesMDei(formula, data, total=total, lambda1 = lambda1, lambda2 = lambda2, tune.alpha = tune.alpha, tune.beta = tune.beta, start.alphas = start.alphas, start.betas = start.betas, sample = sample, thin = thin, burnin = burnin, verbose = verbose, ret.beta = ret.beta, ret.mcmc = ret.mcmc) output <- list(list(output$Alpha, output$Beta, output$cell.count), list(output$alpha.acc, output$beta.acc)) names(output) <- c("draws", "acc.ratios") names(output$draws) <- c("Alpha", "Beta", "Cell.counts") names(output$acc.ratios) <- c("alpha.acc", "beta.acc")} else{output <- BayesMDei2(formula, data, total=total, lambda1 = lambda1, lambda2 = lambda2, tune.alpha = tune.alpha, tune.beta = tune.beta, start.alphas = start.alphas, start.betas = start.betas, sample = sample, thin = thin, burnin = burnin, verbose = verbose, ret.beta = ret.beta, ret.mcmc = ret.mcmc, usrfun = usrfun) output <- list(list(output$Alpha, output$Beta, output$cell.count), list(output$alpha.acc, output$beta.acc), output$usrfun) names(output) <- c("draws", "acc.ratios","usrfun") names(output$draws) <- c("Alpha", "Beta", "Cell.counts") names(output$acc.ratios) <- c("alpha.acc", "beta.acc") } }else{ if(is.null(tune.list)){ tune.dr <- NULL tune.beta <- NULL tune.gamma <- NULL tune.delta <- NULL}else{ tune.dr <- tune.list[[1]] tune.beta <- tune.list[[2]] tune.gamma <- tune.list[[3]] tune.delta <- tune.list[[4]]} if(is.null(start.list)){ start.dr <- NULL start.betas <- NULL start.gamma <- NULL start.delta <- NULL}else{ start.dr <- start.list[[1]] start.betas <- start.list[[2]] start.gamma <- start.list[[3]] start.delta <- start.list[[4]]} if(is.null(usrfun)){output <- BayesMDei3cov(formula, covariate, total = total, data, lambda1 = lambda1, lambda2 = lambda2, covariateprior = covariate.prior.list, tune.dr = tune.dr, tune.beta = tune.beta, tune.gamma=tune.gamma, tune.delta = tune.delta, start.dr = start.dr, start.betas = start.betas, start.gamma = start.gamma, start.delta = start.delta, sample = sample, thin = thin, burnin = burnin, verbose = verbose, ret.beta = ret.beta, ret.mcmc = ret.mcmc) output <- list(list(output$Dr, output$Beta, output$Gamma, output$Delta, output$cell.count), list(output$dr.acc, output$beta.acc, output$gamma.acc)) names(output) <- c("draws", "acc.ratios") names(output$draws) <- c("Dr", "Beta", "Gamma", "Delta","Cell.counts") names(output$acc.ratios) <- c("dr.acc", "beta.acc","gamma.acc") } else{output <- BayesMDei4cov(formula, covariate, total = total, data, lambda1 = lambda1, lambda2 = lambda2, covariateprior = covariate.prior.list, tune.dr = tune.dr, tune.beta = tune.beta, tune.gamma=tune.gamma, tune.delta = tune.delta, start.dr = start.dr, start.betas = start.betas, start.gamma = start.gamma, start.delta = start.delta, sample = sample, thin = thin, burnin = burnin, verbose = verbose, ret.beta = ret.beta, ret.mcmc = ret.mcmc, usrfun = usrfun) output <- list(list(output$Dr, output$Beta, output$Gamma, output$Delta, output$cell.count), list(output$dr.acc, output$beta.acc, output$gamma.acc), output$usrfun) names(output) <- c("draws", "acc.ratios","usrfun") names(output$draws) <- c("Dr", "Beta", "Gamma", "Delta","Cell.counts") names(output$acc.ratios) <- c("dr.acc", "beta.acc","gamma.acc") } } output$call <- match.call() output$call$burnin <- burnin output$call$sample <- sample output$call$thin <- thin output$call$lambda1 <- lambda1 output$call$lambda2 <- lambda2 output$call$covariate.prior.list <- covariate.prior.list class(output) <- "eiMD" return(output) } eiPack/R/summary.lambdaReg.R0000644000176200001440000000126314374235670015361 0ustar liggesuserssummary.lambdaReg <- function(object, ...){ nidx <- apply(expand.grid(dimnames(object$lambda.out)), 1, paste, collapse = ".") object$table <- cbind(c(object$lambda.out), c(object$se), c(object$lambda.out)/c(object$se)) colnames(object$table) <- c("Estimate", "Std. Error", "t-stat") rown <- array(NA, nrow(object$table)) for(i in 1:ncol(object$lambda.out)){ rown[((i-1)*nrow(object$lambda.out)+1):(i*nrow(object$lambda.out))] <- paste("Proportion", rownames(object$lambda.out), "in", colnames(object$lambda.out)[i]) } rownames(object$table) <- rown object$lambda.out <- object$table object$table <- NULL object$lambda.out } eiPack/R/mergeMD.R0000644000176200001440000000346114374252164013326 0ustar liggesusers mergeMD <- function(list, discard = 0){ objectlist <- list eiform <- objectlist[[1]]$call$formula draws.names <- names(objectlist[[1]]$draws) for(ii in 2:length(objectlist)){ if(eiform != objectlist[[ii]]$call$formula | !identical(draws.names, names(objectlist[[ii]]$draws))){stop('eiMD objects not from same model')} } if(inherits(objectlist[[1]]$draws[[1]],"mcmc")){ samples <- nrow(objectlist[[1]]$draws[[1]]) for(jj in 1:length(objectlist[[1]]$draws)){ objectlist[[1]]$draws[[jj]] <- objectlist[[1]]$draws[[jj]][(discard + 1):samples,] for(ii in 2:length(objectlist)){ objectlist[[1]]$draws[[jj]] <- rbind(objectlist[[1]]$draws[[jj]], objectlist[[ii]]$draws[[jj]][(discard + 1):samples,]) } objectlist[[1]]$draws[[jj]] <- mcmc(objectlist[[1]]$draws[[jj]]) } }else{ samples <- dim(objectlist[[1]]$draws[[1]])[length(dim(objectlist[[1]]$draws[[1]]))] for(jj in 1:length(objectlist[[1]]$draws)){ tmp.names <- dimnames(objectlist[[1]]$draws[[jj]]) tmp.dims <- dim(objectlist[[1]]$draws[[jj]]) tmp.dims[length(tmp.dims)] <- (tmp.dims[length(tmp.dims)]- discard)*length(objectlist) nparam <- prod(tmp.dims[1:(length(tmp.dims)-1)]) tmp <- as.numeric(objectlist[[1]]$draws[[jj]])[(discard*nparam + 1):(nparam*samples)] for(ii in 2:length(objectlist)){ tmp <- c(tmp, as.numeric(objectlist[[ii]]$draws[[jj]])[(discard*nparam + 1):(nparam*samples)]) } objectlist[[1]]$draws[[jj]] <- array(tmp, c(tmp.dims)) tmp.names[[length(tmp.names)]] <- 1:tmp.dims[length(tmp.names)] dimnames(objectlist[[1]]$draws[[jj]]) <- tmp.names } } objectlist[[1]]$acc.ratios <- NULL objectlist[[1]]$sources <- match.call() return(objectlist[[1]]) } eiPack/R/summary.eiReg.R0000644000176200001440000000051514374235670014535 0ustar liggesuserssummary.eiReg <- function(object, ...){ nidx <- apply(expand.grid(dimnames(object$coef)), 1, paste, collapse = ".") object$coef <- cbind(c(object$coef), c(object$se), c(object$coef)/c(object$se)) colnames(object$coef) <- c("Estimate", "Std. Error", "t-stat") rownames(object$coef) <- nidx object } eiPack/R/lambda.reg.R0000644000176200001440000000115314374251733013777 0ustar liggesuserslambda.reg <- function(object, columns){ if (inherits(object,"eiReg")==FALSE) stop("'object' must be output from 'ei.reg'") if (missing(columns) | length(columns) < 2) stop("'columns' requires at least two column names") coefs <- matrix(NA, nrow(object$coef), length(columns)) rownames(coefs) <- rownames(object$coef) colnames(coefs) <- columns for(i in columns){ coefs[,i] <- object$coef[,i]/apply(object$coef[,columns],1,sum) } se <- delta(object, columns) lambda.out <- list(call = match.call(), lambda = coefs, se = se) class(lambda.out) <- c("lambdaReg", "list") lambda.out } eiPack/R/touch.betas.R0000644000176200001440000000067614374235670014235 0ustar liggesuserstouch.betas <- function(names) { check <- system("ls", intern = TRUE) if (any(check %in% names)) { exist <- na.omit(check[match(names, check)]) stop(paste( length(exist), " files already exist in ", getwd(), ". Either select a new working directory or remove these files and try again.", sep = "")) } for (ii in names) { cmd <- paste("echo \"", ii, "\" | gzip >> ", ii, sep = "") system(cmd) } return(invisible(0)) } eiPack/R/densityplot.lambdaRegBayes.R0000644000176200001440000000631514374235670017231 0ustar liggesusersdensityplot.lambdaRegBayes <- function(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) { readpars <- par(no.readonly = TRUE) getY <- function(x) x[[1]]$y getX <- function(x) x[[1]]$x get2 <- function(x) x[2] idx <- strsplit(dimnames(x)[2][[1]], ".", fixed = TRUE) idx <- as.list(as.data.frame(matrix(unlist(idx), byrow = TRUE, nrow = length(idx), ncol = length(idx[[1]])))) idx <- lapply(idx, as.character) idx <- lapply(idx, unique) lidx <- sapply(idx, length) names(lidx) <- names(idx) <- c("rows", "columns") if (is.mcmc(x)) { x <- array(t(x), dim = c(sapply(idx, length), nrow(x)), dimnames = list(rows = idx[[1]], columns = idx[[2]], simulations = 1:nrow(x))) } dens <- apply(x, c(1,2), density) if (missing(ylim)) { ylim <- apply(apply(dens, c(1,2), getY), c(2,3), max) } if (missing(xlim)) { XX <- apply(dens, c(1,2), getX) xlim <- c(min(XX, 0), max(XX, 1)) } if (by == "row") { par(mfrow = c(lidx[1], 1), ...) if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[1]])) } else if (length(xlab) != length(idx[[1]])) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[1])[1:lidx[1]] } if (missing(col)) { col <- rainbow(lidx[2]) } else { if (length(col) < lidx[2]) col <- rep(col, idx[[2]])[1:lidx[2]] if (length(col) > lidx[2]) col <- col[1:lidx[2]] } names(col) <- idx[[2]] names(xlab) <- idx[[1]] for (ii in idx[[1]]) { plot(dens[ii, 1][[1]], type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii,])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[2]][2:lidx[2]]) lines(dens[ii,jj][[1]], lty = lty, lwd = lwd, col = col[jj]) abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } if (by == "column") { par(mfrow = c(lidx[2], 1), ...) if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[2]])) } else { if (length(xlab) != lidx[1]) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[2])[1:lidx[2]] } } if (missing(col)) { col <- rainbow(lidx[1]) } else { if (length(col) < lidx[1]) col <- rep(col, idx[[1]])[1:lidx[1]] if (length(col) > lidx[1]) col <- col[1:lidx[1]] } names(col) <- idx[[1]] names(xlab) <- idx[[2]] for (ii in idx[[2]]) { plot(dens[1, ii][[1]], type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[,ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[1]][2:lidx[1]]) lines(dens[jj,ii][[1]], lty = lty, lwd = lwd, col = col[jj]) abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } par(readpars) return(invisible(x)) } eiPack/R/print.bounds.R0000644000176200001440000000050514374235670014432 0ustar liggesusersprint.bounds <- function(x, digits = max(2, getOption("digits") - 4), ...) { cat("\nDeterministic bounds:\n\n") for(i in 1:length(x$bounds)){ cat(names(x$bounds)[i], "\n") print.default(format(x$bounds[[i]], digits = digits), print.gap = 2, quote = FALSE, ...) cat("\n") } invisible(x) } eiPack/R/bounds.R0000644000176200001440000001216514374235667013312 0ustar liggesusersbounds <- function(formula, data, rows, column, excluded=NULL, threshold = 0.9, total=NULL){ "%wo%" <- function(x,y){x[!x %in% y]} D <- model.frame(formula, data = data) G <- D[[2]] T <- D[[1]] idx.r <- apply(G,1,sum) idx.c <- apply(T,1,sum) prop.rows <- list() countG <- countT <- propG <- propT <- FALSE if(!is.null(total)){ if(!is.numeric(total)){ if(is.character(total)){ total <- data[[total]]}else{ total <- data[[deparse(substitute(total))]]}}} if(all(as.integer(T)==T) && all(T)>=0){ countT <- TRUE } else{propT <- TRUE} if(all(as.integer(G)==G) & all(G)>=0){ countG <- TRUE } else{propG <- TRUE} if(propT && is.null(total)){ stop("columns are proportions but no unit totals are provided - please respecify data") } if(propG && is.null(total)){ stop("rows are proportions but no unit totals are provided - please respecify data") } if(propT){ idx.pc <- apply(T,1,sum) if(!all(round(idx.pc, digits=3)==1)){ stop("column marginals are proportions that do not sum to 1 - please respecify data") } } if(propG){ idx.pr <- apply(G,1,sum) if(!all(round(idx.pr, digits=3)==1)){ stop("row marginals are proportions that do not sum to 1 - please respecify data") } } if(countT & propG){ if(!all(0 <= G && G <= 1)){ stop("row proportions are not within [0,1] - please respecify data") } else{ G <- G*total propG <- FALSE countG <- TRUE } } if(propT & countG){ if(!all(0 <= T && T <= 1)){ stop("column proportions are not within [0,1] - please respecify data") } else{ T <- T*total propT <- FALSE countT <- TRUE } } if(propT & propG){ G <- G*total T <- T*total propT <- propG <- FALSE countT <- countG <- TRUE } if(countT & countG){ if(all(idx.r == idx.c)){ for(i in rows){ prop.rows[[i]] <- G[,i]/idx.r } } else{ stop("row and column count totals unequal in some precincts - please respecify data") } } idx <- list() for(i in rows){ idx[[i]] <- which(prop.rows[[i]] >= threshold) } if(all(lapply(idx, length) == 0)){ stop("no precincts satisfy homogeneity threshold - try lowering threshold") } bounds.out <- list() bound.names <- paste(rows, column, sep=".") intersection <- list() count <- 1 for(i in rows){ if(length(idx[[i]])==0){ bounds.out[[bound.names[count]]] <- NA } else{ mat <- matrix(NA, length(idx[[i]]), 4) T.tmp <- as.matrix(T[idx[[i]],]) if(ncol(T.tmp)==1){ T.tmp <- t(T.tmp) } rownames(T.tmp) <- idx[[i]] if(nrow(T.tmp)>1){ mat[,1] <- pmax(0,G[idx[[i]],i]- apply(as.matrix(T.tmp[, colnames(T) %wo% column]),1,sum)) mat[,2] <- apply(cbind(G[idx[[i]],i], apply(as.matrix(T.tmp[, colnames(T) %wo% c(column,excluded)]), 1,sum)), 1, min) mat[,3] <- apply(cbind(G[idx[[i]],i],T.tmp[,column]),1,min) mat[,4] <- pmax(0,G[idx[[i]],i]- apply(as.matrix(T.tmp[, colnames(T)[colnames(T) %in% c(column, excluded)]]),1,sum)) } else{ mat[,1] <- pmax(0,G[idx[[i]],i]- apply(t(T.tmp[, colnames(T) %wo% column]),1,sum)) mat[,2] <- apply(cbind(G[idx[[i]],i], apply(as.matrix(t(T.tmp[, colnames(T) %wo% c(column,excluded)])), 1,sum)), 1, min) mat[,3] <- apply(cbind(G[idx[[i]],i],t(T.tmp[,column])),1,min) mat[,4] <- pmax(0,G[idx[[i]],i]- apply(as.matrix(t(T.tmp[, colnames(T)[colnames(T) %in% c(column, excluded)]])),1,sum)) } bounds.out[[bound.names[count]]] <- cbind(mat[,1]/(mat[,1]+mat[,2]), mat[,3]/(mat[,3]+mat[,4])) bounds.out[[bound.names[count]]][which(mat[,3]+mat[,4]==0),]<-0 rownames(bounds.out[[bound.names[count]]]) <- idx[[i]] colnames(bounds.out[[bound.names[count]]]) <- c("lower", "upper") glb <- max(bounds.out[[bound.names[count]]][,"lower"]) lub <- min(bounds.out[[bound.names[count]]][,"upper"]) } if(glb 2) stop(paste(row, "matches more than one row marginal")) if (length(fcolumn) < 1) stop(paste(column, "not among available column marginals:", paste(idx$columns, collapse = " "))) if (length(fcolumn) > 2) stop(paste(column, "matches more than one column marginal")) usebetas <- t(Betas[frow, fcolumn, ,]) quant.fcn <- function(x){quantile(x, c(0.5 - CI/2, 0.5 + CI/2))} seglims <- apply(usebetas, 2, quant.fcn) meds <- apply(usebetas, 2, median) if (is.null(x)) x <- as.integer(names(meds)) if (missing(ylab)) ylab <- paste("Proportion of", row, "in", column) if (length(col) >= 2) { col1 <- col[1] col2 <- col[2] } else { if (is.null(col)) col1 <- col2 <- par("fg") else col1 <- col2 <- col } if (medians) type <- "p" else type <- "n" plot(x, meds, type = type, ylim = ylim, ylab = ylab, col = col1, ...) segments(x, seglims[1,], x, seglims[2,], col = col2, lty = lty, lwd = lwd) } eiPack/R/densityplot.lambdaMD.R0000644000176200001440000000606114374235670016026 0ustar liggesusersdensityplot.lambdaMD <- function(x, by = "column", col, xlim = c(0,1), ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) { readpars <- par(no.readonly = TRUE) if (all(class(x) != "lambdaMD")) stop("works only with output from `lambda.MD'") getY <- function(x) x[[1]]$y get2 <- function(x) x[2] tnames <- strsplit(colnames(x), "lambda.") idx <- strsplit(sapply(tnames, get2), ".", fixed = TRUE) idx <- as.list(as.data.frame(matrix(unlist(idx), byrow = TRUE, nrow = length(idx), ncol = length(idx[[1]])))) idx <- lapply(idx, as.character) idx <- lapply(idx, unique) lidx <- sapply(idx, length) names(lidx) <- names(idx) <- c("rows", "columns") if (is.mcmc(x)) { x <- array(t(x), dim = c(sapply(idx, length), nrow(x)), dimnames = list(rows = idx[[1]], columns = idx[[2]], simulations = 1:nrow(x))) } dens <- apply(x, c(1,2), density) if (missing(ylim)) { ylim <- apply(apply(dens, c(1,2), getY), c(2,3), max) } if (by == "row") { par(mfrow = c(lidx[1], 1), ...) if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[1]])) } else if (length(xlab) != length(idx[[1]])) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[1])[1:lidx[1]] } if (missing(col)) { col <- rainbow(lidx[2]) } else { if (length(col) < lidx[2]) col <- rep(col, idx[[2]])[1:lidx[2]] if (length(col) > lidx[2]) col <- col[1:lidx[2]] } names(col) <- idx[[2]] names(xlab) <- idx[[1]] for (ii in idx[[1]]) { plot(dens[ii, 1][[1]], type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii,])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[2]][2:lidx[2]]) lines(dens[ii,jj][[1]], lty = lty, lwd = lwd, col = col[jj]) } } if (by == "column") { par(mfrow = c(lidx[2], 1), ...) if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[2]])) } else { if (length(xlab) != lidx[1]) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[2])[1:lidx[2]] } } if (missing(col)) { col <- rainbow(lidx[1]) } else { if (length(col) < lidx[1]) col <- rep(col, idx[[1]])[1:lidx[1]] if (length(col) > lidx[1]) col <- col[1:lidx[1]] } names(col) <- idx[[1]] names(xlab) <- idx[[2]] for (ii in idx[[2]]) { plot(dens[1, ii][[1]], type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[,ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[1]][2:lidx[1]]) lines(dens[jj,ii][[1]], lty = lty, lwd = lwd, col = col[jj]) } } par(readpars) return(invisible(x)) } eiPack/R/print.eiMDsum.R0000644000176200001440000000240414374235670014503 0ustar liggesusersprint.eiMDsum <- function(x, digits = max(3, getOption("digits") - 4), ...) { cat("\nFormula: ", deparse(x$call$formula), "\n") cat("Total sims: ", (x$call$burnin) + (x$call$sample * x$call$thin), "\n") cat("Burnin discarded: ", x$call$burnin, "\n") cat("Sims saved: ", x$call$sample, "\n\n") "%w/o%" <- function(x,y) x[!x %in% y] if (x$short) cat("\nAcceptance ratios for Beta (averaged over units):\n") else cat("\nAcceptance ratios for Beta:\n") print.default(format(x$acc.ratios$beta.acc, digits = digits), print.gap = 1, quote = FALSE) for (ii in names(x$acc.ratios) %w/o% c("beta.acc")) { cat(paste("\nAcceptance ratios for ", strsplit(ii, ".acc", fixed = TRUE)[1], ":\n", sep = "")) print.default(format(x$acc.ratios[[ii]], digits = digits), print.gap = 1, quote = FALSE) } for (ii in names(x$draws) %w/o% c("Beta", "Cell.counts")) { cat(paste("\nDraws for ", ii, ":\n", sep = "")) print.default(format(x$draws[[ii]], digits = digits), print.gap = 1, quote = FALSE) } cat("\nAggregate cell counts (summed over units):\n") print.default(format(x$draws$Cell.counts, digits = digits), print.gap = 1, quote = FALSE) invisible(x) } eiPack/R/print.eiMD.R0000644000176200001440000000334614374235670013764 0ustar liggesusersprint.eiMD <- function(x, digits = min(3, getOption("digits") - 5), short = TRUE, ...) { cat("\nFormula: ", deparse(x$call$formula), "\n") cat("Total sims: ", (x$call$burnin) + (x$call$sample * x$call$thin), "\n") cat("Burnin discarded: ", x$call$burnin, "\n") cat("Sims saved: ", x$call$sample, "\n\n") "%w/o%" <- function(x,y) x[!x %in% y] if (is.mcmc(x$draws$Cell.counts)) { tnames <- strsplit(colnames(x$draws$Cell.counts), "ccount.") get2 <- function(x) x[2] idx <- strsplit(sapply(tnames, get2), ".", fixed = TRUE) idx <- as.list(as.data.frame(matrix(unlist(idx), byrow = TRUE, nrow = length(idx), ncol = length(idx[[1]])))) idx <- lapply(idx, as.character) idx <- lapply(idx, unique) } else { idx <- dimnames(x$draws$Cell.counts)[1:2] } names(idx) <- c("rows", "columns") for (ii in names(x$draws) %w/o% c("Beta")) { if (is.mcmc(x$draws[[ii]])) { nr <- length(idx[[1]]) nc <- ncol(x$draws[[ii]]) / nr cc <- array(t(x$draws[[ii]]), dim = c(nr, nc, nrow(x$draws[[ii]])), dimnames = list(idx[[1]], idx[[2]][1:nc], NULL)) } else { cc <- x$draws[[ii]] nr <- dim(x$draws[[ii]])[1] nc <- dim(x$draws[[ii]])[2] nz <- dim(x$draws[[ii]])[3] if (nr == length(idx[[1]]) & is.na(nz)) { nc <- 1 } } cat(paste("Mean ", ii, ": (averaged over simulations)\n", sep = "")) if (nc > 1) print.default(format(apply(cc, c(1,2), mean), digits = digits), print.gap = 2, quote = FALSE) else { print.default(format(apply(cc, 1, mean), digits = digits), print.gap = 2, quote = FALSE) } cat("\n") } invisible(x) } eiPack/R/tuneMD.R0000644000176200001440000000562114374235670013205 0ustar liggesuserstuneMD <- function(formula, covariate = NULL, data, ntunes = 10, totaldraws = 10000, ...) { D <- model.frame(formula, data) Groups <- D[[2]] ng <- ncol(Groups) N <- t(D[[1]]) np <- nrow(N) npm1 <- np-1 precincts <- nrow(D) sdtune <- function(xx){ if((.3 < xx) & (xx <= .4)) return(.95) if(xx <= .3) return(.84) if((.4 < xx) & (xx <= .5)) return(1) if((.5 < xx) & (xx < .7)) return(1.05) if(.7 <= xx) return(1.15) } sample <- 1 thin <- totaldraws burnin <- 0 if (is.null(covariate)) { tuneA <- matrix(0.25, nrow = ng, ncol = np) tuneB <- array(0.05, dim = c(ng, npm1, precincts)) for(jj in 1:ntunes){ tl <- list(tune.alpha = tuneA, tune.beta = tuneB) tmp <- ei.MD.bayes(formula, covariate = covariate, data = data, sample = sample, thin = thin, burnin=burnin, tune.list = tl, ...) Beta <- array(tmp$acc.ratios$beta.acc, dim = c(ng, npm1, precincts)) Alpha <- matrix(tmp$acc.ratios$alpha.acc, nrow = ng, ncol = np) for (ii in 1:precincts) { for(rr in 1:ng){ for(cc in 1:npm1){ tuneB[rr,cc,ii] <- tuneB[rr,cc,ii] * sdtune(Beta[rr,cc,ii]) } } } for(rr in 1:ng){ for(cc in 1:np){ tuneA[rr,cc] <- tuneA[rr,cc] * sdtune(Alpha[rr,cc]) } } } output <- list(tune.alpha = tuneA, tune.beta = tuneB) output$call <- tmp$call class(output) <- "tuneMD" return(output) } else { tuneDr <- array(0.20, ng) tuneB <- array(0.05, dim = c(ng, npm1, precincts)) tuneD <- tuneG <- matrix(0.25, nrow = ng, ncol = npm1) for(jj in 1:ntunes){ tl <- list(tune.dr = tuneDr, tune.beta = tuneB, tune.gamma = tuneG, tune.delta = tuneD) tmp <- ei.MD.bayes(formula, covariate = covariate, data = data, sample = sample, thin = thin, burnin=burnin, tune.list = tl, ...) Dr <- tmp$acc.ratios$dr.acc Beta <- array(tmp$acc.ratios$beta.acc, dim = c(ng, npm1, precincts)) Gamma <- matrix(tmp$acc.ratios$gamma.acc, nrow = ng, ncol = npm1) Delta <- matrix(tmp$acc.ratios$gamma.acc, nrow = ng, ncol = npm1) for (ii in 1:precincts) { for(rr in 1:ng){ for(cc in 1:npm1){ tuneB[rr,cc,ii] <- tuneB[rr,cc,ii] * sdtune(Beta[rr,cc,ii]) } } } for(rr in 1:ng){ tuneDr[rr] <- tuneDr[rr] * sdtune(Dr[rr]) for(cc in 1:npm1){ tuneG[rr,cc] <- tuneG[rr,cc]*sdtune(Gamma[rr,cc]) tuneD[rr,cc] <- tuneD[rr,cc]*sdtune(Delta[rr,cc]) } } } output <- list(tune.dr = tuneDr, tune.beta = tuneB, tune.gamma = tuneG, tune.delta = tuneD) output$call <- tmp$call class(output) <- "tuneMD" return(output) } } eiPack/R/summary.eiRegBayes.R0000644000176200001440000000115314374235670015520 0ustar liggesuserssummary.eiRegBayes <- function(object, CI = 0.95, ...){ coef <- apply(object$draws, c(1,2), mean) se <- apply(object$draws, c(1,2), sd) cc <- apply(object$draws, c(1,2), quantile, c((1-CI)/2, 1-(1-CI)/2)) quants <- matrix(cc, nrow = prod(dim(coef)[1:2]), ncol = 2, byrow = TRUE) nidx <- apply(expand.grid(dimnames(coef)), 1, paste, collapse = ".") tab <- cbind(c(coef), c(se), quants) colnames(tab) <- c("Mean", "Std. Dev.", rownames(cc)) rownames(tab) <- nidx out <- list(call = object$call, coef = tab, sims = dim(object$draws)[3]) class(out) <- "eiRegBayesSum" out } eiPack/R/plot.bounds.R0000644000176200001440000000301414374250036014243 0ustar liggesusersplot.bounds <- function(x, row, column, labels = TRUE, order = NULL, intersection = TRUE, xlab, ylab, col = par("fg"), lty = par("lty"), lwd = par("lwd"), ...){ if(inherits(x,"bounds")==FALSE){ stop("'x' must be output from 'bounds'") } bounds <- x$bounds idx <- paste(row, ".", column, sep="") if (!(idx %in% names(bounds))){ stop("selected row or column bounds not in 'x' - please choose a different row or column") } if(all(is.na(bounds[[idx]]))){ stop("selected row or column bounds not in 'x' - no precincts satisfy threshold") } "%wo%" <- function(x,y){x[!x %in% y]} threshold <- 100*x$threshold if(is.null(order)){ order <- (1:nrow(bounds[[idx]]))/(nrow(bounds[[idx]])+1) xl <- 0:1 axes <- FALSE } else { xl <- range(order) axes <- TRUE } if (missing(xlab)) { xlab <- paste("Precincts with at least", threshold, "% ", row) } if (missing(ylab)) { ylab <- paste("Proportion ", column, sep="") } plot(xl, 0:1, type = "n", xlab = xlab, ylab = ylab, axes = axes, ...) axis(side = 2, labels=TRUE) segments(order, bounds[[idx]][,"lower"], order, bounds[[idx]][,"upper"], col = col, lty = lty, lwd = lwd) if(labels){ text(order, bounds[[idx]][,"upper"]+.02, rownames(bounds[[idx]]), cex=0.4) } if(intersection){ if(!all(is.na(x$intersection[[row]]))){ abline(h=c(x$intersection[[row]][1], x$intersection[[row]][2]), col="grey80") } } } eiPack/R/ei.reg.R0000644000176200001440000000443414374235670013163 0ustar liggesusersei.reg <- function(formula, data, ...) { D <- model.frame(formula, data = data) G <- D[[2]] T <- D[[1]] idx.r <- apply(G,1,sum) idx.c <- apply(T,1,sum) countG <- countT <- propG <- propT <- FALSE if(all(as.integer(T)==T) && all(T)>=0){ countT <- TRUE } else{ propT <- TRUE } if(all(as.integer(G)==G) & all(G)>=0){ countG <- TRUE } else{propG <- TRUE} if(countT & countG){ if(all(idx.r == idx.c)){ G <- G/idx.r T <- T/idx.c countT <- countG <- FALSE propT <- propG <- TRUE } else{ stop("row and column count totals unequal in some precincts - please respecify data") } } if(countT & propG){ if(!all(0 <= G && G <= 1)){ stop("row proportions are not within [0,1] - please respecify data") } else{ T <- T/idx.c propT <- TRUE countT <- FALSE } } if(propT & countG){ if(!all(0 <= T && T <= 1)){ stop("column proportions are not within [0,1] - please respecify data") } else{ G <- G/idx.r propG <- TRUE countG <- FALSE } } if(propT & propG){ idx.r <- apply(G,1,sum) idx.c <- apply(T,1,sum) if(!all(round(idx.r, digits=3)==1)){ stop("row marginals are proportions that do not sum to 1 - please respecify data") } if(!all(round(idx.c, digits=3)==1)){ stop("column marginals are proportions that do not sum to 1 - please respecify data") } } out <- list() se <- list() cov.out <- list() for (i in 1:(ncol(T))) { lm.out <- lm(T[,i] ~ G - 1, ...) out[[colnames(T)[i]]] <- lm.out$coef se[[colnames(T)[i]]] <- summary(lm.out)$coef[,2] cov.out[[colnames(T)[i]]] <- summary(lm.out)$sigma * summary(lm.out)$cov.unscaled colnames(cov.out[[colnames(T)[i]]]) <- colnames(G) rownames(cov.out[[colnames(T)[i]]]) <- colnames(G) } tab <- cbind(out[[1]], out[[2]]) se.tab <- cbind(se[[1]], se[[2]]) if (length(out)>2){ for(i in 3:length(out)){ tab <- cbind(tab,out[[i]]) se.tab <- cbind(se.tab,se[[i]]) } } colnames(tab) <- colnames(se.tab) <- colnames(T) rownames(tab) <- rownames(se.tab) <- colnames(G) out <- list(call=match.call(), coefficients=tab, se=se.tab, cov.matrices=cov.out) class(out) <- "eiReg" out } eiPack/R/print.eiReg.R0000644000176200001440000000040414374235670014171 0ustar liggesusersprint.eiReg <- function(x, digits = max(2, getOption("digits") - 4), ...) { cat("\nCall: ", deparse(x$call), "\n\n") cat("Estimated internal cells:\n") print.default(format(x$coef, digits = digits), print.gap = 2, quote = FALSE, ...) } eiPack/R/BayesMDei2.R0000644000176200001440000001515714374235667013710 0ustar liggesusersBayesMDei2 <- function(formula, data, total, lambda1 = 4, lambda2 = 2, tune.alpha = NULL, tune.beta = NULL, start.alphas = NULL, start.betas = NULL, sample = 1000, thin = 1, burnin = 1000, verbose = 0, ret.beta = 'r', ret.mcmc = TRUE, usrfun = NULL, ...){ if(thin < 1){stop('thin must be positive integer')} if(sample < 1){stop('thin must be positive integer')} if(burnin < 0){stop('burnin must be non-negative integer')} DD <- model.frame(formula, data) countParty <- countGroup <- propParty <- propGroup <- FALSE checkGroups <- round(apply(DD[[2]], 1, sum), 3) checkParties <- round(apply(DD[[1]], 1, sum), 3) if(all(DD[[1]] %% 1 == 0) & all(DD[[1]] >= 0)){countParty <- TRUE} else if(all(0 <= DD[[1]] & DD[[1]] <= 1)){ if(all(checkParties == 1)){propParty <- TRUE}else{ stop("column marginals are proportions that do not sum to 1 - please respecify data")}} else stop("column marginals are neither counts nor proportions - please respecify data") if(all(DD[[2]] %% 1 == 0) & all(DD[[2]] >= 0)){countGroup <- TRUE} else if(all(0 <= DD[[2]] & DD[[2]] <= 1)){ if(all(checkGroups == 1)){propGroup <- TRUE}else{ stop("row marginals are proportions that do not sum to 1 - please respecify data")}} else stop("row marginals are neither counts nor proportions - please respecify data") if((propParty | propGroup) & is.null(total)){ stop("one or both marginals are proportions - 'total' must be provided")} if(propParty & !is.null(total)){ DD[[1]] <- DD[[1]] * total warning("column margnials are proportions - multiplying by unit size")} if(propGroup & !is.null(total)){ DD[[2]] <- DD[[2]] * total warning("row margnials are proportions - multiplying by unit size")} checkGroups <- round(apply(DD[[2]], 1, sum), 1) checkParties <- round(apply(DD[[1]], 1, sum), 1) if(identical(checkParties, checkGroups) == FALSE){ stop("row and column totals unequal in some units - please respecify data")} Groups <- DD[[2]] TT <- t(DD[[1]]) XX <- t(Groups/apply(Groups,1,sum)) group.names <- colnames(Groups) party.names <- rownames(TT) RR <- t(Groups) NG <- nrow(XX) NP <- nrow(TT) Precincts <- nrow(DD) usrenv <- environment(fun = usrfun) if(is.null(start.alphas)){ start.alphas <- matrix(rgamma(NG*NP, lambda1, lambda2), NG, NP)} if(min(start.alphas) <= 0){stop("inadmissable starting values for alpha")} if(is.null(start.betas)){ start.betas <- array(NA, dim= c(NG, NP, Precincts)) for(i in 1:Precincts){ start.betas[,,i] <- rdirichlet(NG, rep(1,NP))} } if(identical(round(apply(start.betas, c(1,3), sum),10),matrix(1,NG, Precincts))!=TRUE){stop("inadmissable starting values for beta")} usrlen <- length(as.numeric(usrfun(list(start.alphas, start.betas, TT, RR)))) if(is.null(tune.alpha)){ tune.alpha <- matrix(rep(.25,NG*NP), NG, NP)} if(is.null(tune.beta)){ tune.beta <- array(rep(.05, NG*(NP-1)*Precincts), c(NG, NP-1, Precincts))} tune.alpha <- as.matrix(tune.alpha) if(identical(dim(tune.alpha), c(NG, NP))!=TRUE) {stop("'tune.alpha' has incorrect dimensions")} if(identical(as.numeric(dim(tune.beta)), c(NG, NP-1, Precincts))!=TRUE) {stop("'tune.beta' has incorrect dimensions")} beta.names <- paste(paste(paste(group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep="."), ".txt.gz", sep="") if(ret.beta == 's'){touch.betas(beta.names) ret.beta <- 2} if(ret.beta == 'd'){ret.beta <- 1} if(ret.beta == 'r'){ret.beta <- 0} if(is.numeric(ret.beta)==FALSE){stop('incorrect option for ret.beta')} output <- .Call("rbycei_fcn2", as.numeric(start.alphas), as.numeric(start.betas), as.numeric(TT), as.numeric(XX), as.numeric(tune.alpha), as.numeric(tune.beta), as.integer(NG), as.integer(NP), as.integer(Precincts), as.numeric(lambda1), as.numeric(lambda2), as.integer(sample), as.integer(thin), as.integer(burnin), as.integer(verbose), as.integer(ret.beta), as.numeric(RR), usrfun, usrenv, as.integer(usrlen), as.character(beta.names) ) if(ret.beta==0){names(output) <- c("Alpha", "Beta", "alpha.acc", "beta.acc", "cell.count", "usrfun")} else{names(output) <- c("Alpha", "alpha.acc", "beta.acc","cell.count", "usrfun")} if(ret.mcmc){ colnames(output$Alpha) <- paste("alpha",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$Alpha <- coda::mcmc(output$Alpha, thin=thin) colnames(output$cell.count) <- paste("ccount",matrix(rep(group.names, NP),NG,NP) ,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep=".") output$cell.count <- coda::mcmc(output$cell.count, thin=thin) colnames(output$usrfun) <- paste("usrfun", 1:ncol(output$usrfun), sep=".") output$usrfun <- coda::mcmc(output$usrfun, thin=thin) if(ret.beta==0){ colnames(output$Beta) <- paste(paste("beta", group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep=".") output$Beta <- coda::mcmc(output$Beta, thin=thin) } }else{ output$Alpha <- array(t(output$Alpha), c(NG, NP, sample)) dimnames(output$Alpha) <- list(group.names, party.names, 1:sample) output$cell.count <- array(t(output$cell.count), c(NG, NP, sample)) dimnames(output$cell.count) <- list(group.names, party.names, 1:sample) colnames(output$usrfun) <- paste("usrfun", 1:ncol(output$usrfun), sep=".") if(ret.beta==0){ output$Beta <- array(t(output$Beta), c(NG, NP, Precincts, sample)) dimnames(output$Beta) <- list(group.names, party.names, 1:Precincts, 1:sample) } } return(output) } eiPack/R/densityplot.R0000644000176200001440000000042714374235667014374 0ustar liggesusersdensityplot <- function(x, by = "column", col, xlim = c(0,1), ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) { UseMethod("densityplot", x) } eiPack/R/lambda.reg.bayes.R0000644000176200001440000000206514374251701015077 0ustar liggesuserslambda.reg.bayes <- function(object, columns, ret.mcmc = TRUE){ if (inherits(object,"eiRegBayes")==FALSE) stop("'object' must be output from 'ei.reg.bayes'") if (missing(columns) | length(columns) < 2) stop("'columns' requires at least two column names") lambda.out <- array(NA, dim=c(length(rownames(object$draws)), length(columns), dim(object$draws)[3])) rownames(lambda.out) <- rownames(object$draws) colnames(lambda.out) <- columns for(i in columns){ lambda.out[,i,] <- object$draws[,i,]/apply(object$draws[,columns,],c(1,3),sum) } if (ret.mcmc){ lambda.out <- t(matrix(lambda.out, nrow(lambda.out)*ncol(lambda.out), dim(lambda.out)[3])) colnames(lambda.out) <- apply(expand.grid(rownames(object$draws), columns)[,1:2], 1, paste, collapse=".") lambda.out <- coda::mcmc(lambda.out) } class(lambda.out) <- c("lambdaRegBayes", class(lambda.out)) lambda.out } eiPack/R/summary.lambdaRegBayes.R0000644000176200001440000000254614374235670016352 0ustar liggesuserssummary.lambdaRegBayes <- function(object, ...){ if(!is.mcmc(object$lambda.out)){ coef <- apply(object$lambda.out, c(1,2), mean) sd <- apply(object$lambda.out, c(1,2), sd) quants <- matrix(apply(object$lambda.out, c(1,2), quantile, probs=c(.025, 0.05, 0.25, 0.5, 0.75, 0.95, 0.975)), nrow(coef)*ncol(coef), 7, byrow=T) nidx <- apply(expand.grid(dimnames(coef)), 1, paste, collapse = ".") tab <- cbind(c(coef), c(sd), quants) rownames(tab) <- nidx } if(is.mcmc(object$lambda.out)){ coef <- apply(object$lambda.out, 2, mean) sd <- apply(object$lambda.out, 2, sd) quants <- t(apply(object$lambda.out, 2, quantile, probs=c(.025, 0.05, 0.25, 0.5, 0.75, 0.95, 0.975))) tab <- cbind(c(coef), c(sd), quants) } colnames(tab) <- c("Mean", "Std. Dev.", "2.5%", "5%", "25%", "50%", "75%", "95%", "97.5%") tab } eiPack/R/write.betas.R0000644000176200001440000000023314374235670014232 0ustar liggesuserswrite.betas <- function(beta, names) { cmd <- paste("echo \"", beta, "\" | gzip >> ", names, ".txt.gz", sep = "") system(cmd) return(invisible(0)) } eiPack/MD50000644000176200001440000000772114374260722011774 0ustar liggesusers263b03fca1747f78c6f7dc74e8d028b3 *COPYING 4820ac14abc77dac440e7a66bb4118a5 *DESCRIPTION c530e5002d84866e37517ff1a2d01dff *INDEX 942e57a52faabd00b7b9698a60743688 *LICENSE 65817621f2e4e8e99d6a2555dd34063f *NAMESPACE 69e67ea7331940dcd810dbd5d46fe94a *R/BayesMDei.R 9e4d66c8ecf0fb4a61d81eee67fa9d4d *R/BayesMDei2.R 660018f74d8e9aa3db98935f618e98df *R/BayesMDei3cov.R c31f76fa43d059f0dfb3642d0c788ae5 *R/BayesMDei4cov.R 212806df9082626b8b22971da498d97c *R/bayes.regress.R e4fcda6fa62643b76a4d9b8125050382 *R/bounds.R dca7959b739f8adb77e0805916e38d4b *R/cover.plot.R 3b60adb7cceaa804a3667bfca06d54b7 *R/delta.R 4f8ae4120dcbe80d84f560560131d059 *R/densityplot.R 9fbe7a39a515e8acd3934b35f21f44d4 *R/densityplot.default.R 2ef8dddb251b2c36a73da4342722e4ef *R/densityplot.lambdaMD.R 770a4322201f0638e97432c405fa5404 *R/densityplot.lambdaReg.R 185a97b6de9e16df83d2fa97d610a226 *R/densityplot.lambdaRegBayes.R 2d315a9f13ba449fa89f44fc34a7f452 *R/ei.MD.bayes.R 99588a3d3db53be4ca215ec239457975 *R/ei.reg.R a821c5b07ea6ea192a93067f3788d8dd *R/ei.reg.bayes.R 2da0500ab5faa3062c8cc6e644dbe348 *R/lambda.MD.R 1cd86b93d4f8e87a5c34bf0efcdfd86f *R/lambda.reg.R 41e8411c91f3c1eb67b9058faa35bb10 *R/lambda.reg.bayes.R 5d71b16f71822ee04ffe232229b2aef7 *R/mergeMD.R ce04834696c77b8661567bf5a7537118 *R/plot.bounds.R ea7ae4dfc652a2ece1d137454619c631 *R/print.bounds.R 8321b3b4af551ccd2c6719ee63da5daa *R/print.eiMD.R c4a69f14c645f1825f548c7328afeafd *R/print.eiMDsum.R 7066f0c178b8e8daa2137c25529a969d *R/print.eiReg.R 2c75b367e9d71d01d3ea2384e6d1244e *R/print.eiRegBayes.R fefe226fd385b0486ad1e006421869b2 *R/print.eiRegBayesSum.R f4efb4725f8f816516f472495d3a7793 *R/print.lambdaReg.R 80c7d081d5bde611fbfd9281835597f5 *R/rdirichlet.R 8c997ca340f50ad6b6b4e422400a43cd *R/read.betas.R 514aefc84561fe9f5db5caee907ce52d *R/summary.eiMD.R 493bb004544c2fc728a65257d880abb8 *R/summary.eiReg.R 1f7689d92766f727ccbb94c3a7a2b242 *R/summary.eiRegBayes.R e54e9317908e65f818bab3cb0469dce9 *R/summary.lambdaReg.R af7f6f3a88762efb73791f52e6387394 *R/summary.lambdaRegBayes.R 4323558f1de1919f97c820b341c51660 *R/touch.betas.R 28a0be9a1c1b954c4df16c1e523d576a *R/tuneMD.R f2697acdb3cec52a8a2dbd3d7eccfe64 *R/turnout.R b46f3867bfdab7452b50b75301d9bc6c *R/write.betas.R 69bd8da63d9ab0d7323ac0a853ac23d4 *data/redistrict.tab.gz bf5d2ef3297eaecc866a23776cfa8007 *data/senc.tab.gz 272a9326b69174183fe2a97e3b904b8d *data/tuneA.tab.gz 038ea7de7f2a6a8403a63858b129bde7 *data/tuneB.tab.gz 118d2f7b30c6393e59388366b31b7374 *demo/00Index 2774ef3c1c487952450e930776579d6a *demo/bounds.R 93c18d798088bf4abf42324dd805a273 *demo/ei.MD.bayes.R d47d78e343a9cc7b242590e19fb0127f *demo/ei.reg.R 9e126f5b08b1c376632ed2347dadc99b *demo/ei.reg.bayes.R 41587f5690c62698f6ec6840fab1f053 *demo/lambda.MD.R 32d718ace5466eaae1c294676e13ee56 *demo/lambda.reg.R 2e8af52159f393b249fc4003b5a8caa4 *demo/lambda.reg.bayes.R 7f2afe84bb52267d11854f297fd5b54d *man/bounds.Rd 7d9d30406e56133c6cc2921b25a27033 *man/cover.plot.Rd 83a734adde31fd7b732a49be31845058 *man/density.plot.Rd e2e6e7a58f69c1427c457578617ddba7 *man/ei.MD.bayes.Rd 8ac130fc58e4caff56da79e76db63cd8 *man/ei.reg.Rd 563c29206cbf736a070c6b3ee1f63faf *man/ei.reg.bayes.Rd 37f8d467cbfd15858fae193199817c2b *man/lambda.MD.Rd d56f6cd1fc3de4bcff6954d9a9401d22 *man/lambda.reg.Rd 2fa69b04746a79fa8429176d7b088455 *man/lambda.reg.bayes.Rd b2c26c2facc4ef1ab9a471b3bf68f843 *man/mergeMD.Rd a13d5efca8271e354522610b9ea0b2ee *man/plot.bounds.Rd c08da2b9f088e9bd337391968d41043f *man/read.betas.Rd 9ff3815fcd93a897df42d4ddec561387 *man/redistrict.Rd 01899d002b930de873b5823bf026c05a *man/senc.Rd b7846be622595c601aa2e5ac56e8ec84 *man/tuneA.Rd 7d1ce4741d59a1dcf56f11cc8d294bba *man/tuneB.Rd d36799714819182e168e69e7da3fe7c1 *man/tuneMD.Rd 52a8c2a5789667fb68c79d79d8baa0d7 *src/eiutil.c 478471b7b4f9bf196ecd24420923f171 *src/eiutil.h b16f3f1d4e761c556a6832d88d6a4f9a *src/init.c 11187298f7035304384c2c81393867d9 *src/rbycei.c 0df90e2de6abe68e991cda8fa8d62e6d *src/rbycei2.c 70fbc42485e4f68a4950ba9c275925ff *src/rbyceicov2.c b230608fcbf1730914cb6980894cd795 *src/rbyceicov4.c eiPack/INDEX0000644000176200001440000000301214374235667012255 0ustar liggesusersbounds Deterministic bounds for units satisfying row thresholds cover.plot Unit-level coverage plots for beta parameters from MD EI model densityplot Density plots for population level parameters ei.MD.bayes Multinomial Dirichlet model for Ecological Inference in RxC tables ei.reg Ecological regression ei.reg.bayes Ecological regression using Bayesian Normal regression lambda.MD Calculate shares using data from MD model lambda.reg Calculate shares using data from regression model lambda.reg.bayes Calculate shares using data from Bayesian regression model mergeMD Combine output from multiple eiMD objects plot.bounds Plot of deterministic bounds for units satisfying row thresholds read.betas Function to read in eiMD parameter chains saved to disk redistrict Redistricting Monte-Carlo data senc Party registration in south-east North Carolina tuneA Tuning parameters for alpha hyperpriors in RxC EI model tuneB Tuning parameters for the precinct level parameters in the RxC EI model tuneMD Generate tuning parameters for MD model