├── .github └── FUNDING.yml ├── figures ├── install.png ├── linReg2Data.png ├── linReg2Histo.png ├── linRegData.png ├── linRegHisto.png ├── Install_SetDir.png └── linRegEstimate.png ├── .gitignore ├── examples ├── README.org ├── fake_data_simulation │ └── fake_data_simulation.wls ├── identifying_mixture_models │ └── identitying_mixture_models.wls └── mcmc_option_example.nb ├── tutorial.wls ├── tests └── CmdStan_test.wl ├── CmdStan.m ├── README.org └── LICENSE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: stan-dev 2 | custom: https://mc-stan.org/support/ 3 | -------------------------------------------------------------------------------- /figures/install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/install.png -------------------------------------------------------------------------------- /figures/linReg2Data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/linReg2Data.png -------------------------------------------------------------------------------- /figures/linReg2Histo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/linReg2Histo.png -------------------------------------------------------------------------------- /figures/linRegData.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/linRegData.png -------------------------------------------------------------------------------- /figures/linRegHisto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/linRegHisto.png -------------------------------------------------------------------------------- /figures/Install_SetDir.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/Install_SetDir.png -------------------------------------------------------------------------------- /figures/linRegEstimate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stan-dev/MathematicaStan/HEAD/figures/linRegEstimate.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /README.html 2 | 3 | *.d 4 | *.csv 5 | *.hpp 6 | 7 | /examples/basic_distributions/triangle 8 | /examples/basic_distributions/wishart2 9 | 10 | /examples/time-series/AR/AR1* 11 | *.html 12 | -------------------------------------------------------------------------------- /examples/README.org: -------------------------------------------------------------------------------- 1 | #+OPTIONS: toc:nil todo:nil pri:nil tags:nil ^:nil tex:t 2 | #+TITLE: Examples 3 | 4 | # +TOC: headlines 3 5 | 6 | * Table of contents :TOC_3:noexport: 7 | - [[#tutorials][Tutorials]] 8 | - [[#option-management][Option management]] 9 | - [[#misc][Misc]] 10 | - [[#replication-of-an-easy-way-to-simulate-fake-data-from-your-stan-model][Replication of "An easy way to simulate fake data from your Stan model"]] 11 | - [[#replication-of-identifying-bayesian-mixture-models][Replication of "Identifying Bayesian Mixture Models"]] 12 | 13 | * Tutorials 14 | 15 | ** Option management 16 | 17 | The [[file:mcmc_option_example.nb][mcmc_option_example.nb]] notebook reuses the Tutorial part 1 and 18 | shows how to modify MCMC sample option values. 19 | 20 | * Misc 21 | 22 | ** Replication of "An easy way to simulate fake data from your Stan model" 23 | 24 | The file [[file:fake_data_simulation/fake_data_simulation.wls][fake_data_simulation/fake_data_simulation.wls]] contains 25 | replication of [[http://modernstatisticalworkflow.blogspot.com/2017/04/an-easy-way-to-simulate-fake-data-from.html][this blog post]]. 26 | 27 | ** Replication of "Identifying Bayesian Mixture Models" 28 | 29 | The file [[file:identifying_mixture_models/identitying_mixture_models.wls][identifying_mixture_models/identitying_mixture_models.wls]] 30 | contains replication of [[https://mc-stan.org/users/documentation/case-studies/identifying_mixture_models.html][this blog post]]. 31 | 32 | -------------------------------------------------------------------------------- /examples/fake_data_simulation/fake_data_simulation.wls: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env wolframscript 2 | (* ::Package:: *) 3 | 4 | (* ::Chapter:: *) 5 | (*Replication of*) 6 | (*http://modernstatisticalworkflow.blogspot.com/2017/04/an-easy-way-to-simulate-fake-data-from.html*) 7 | 8 | 9 | (* ::Subsubsection:: *) 10 | (*(all possible errors/misinterpretations in *this* Mathematica notebook are mine)*) 11 | 12 | 13 | (* ::Subchapter:: *) 14 | (*Stan init*) 15 | 16 | 17 | <".stan"}] 60 | 61 | 62 | (* ::Text:: *) 63 | (*note:*) 64 | (*I modified *) 65 | (* vector[N] y_sim*) 66 | (* to *) 67 | (* vector[N+10] y_sim*) 68 | (* *) 69 | (* to make clear the difference between the N theta draws and the N+10 category draws (given a fixed theta)*) 70 | (* *) 71 | 72 | 73 | (* ::Subchapter:: *) 74 | (*Write code file*) 75 | 76 | 77 | code=ExportStanCode[codeFile,code] 78 | 79 | 80 | (* ::Subchapter:: *) 81 | (*Compile it!*) 82 | 83 | 84 | CompileStanCode[code] 85 | 86 | 87 | (* ::Subchapter:: *) 88 | (*Input data: create and save*) 89 | 90 | 91 | data=<| 92 | "N"->1000, 93 | "P"->5, 94 | "y"->ConstantArray[0,1000], (* fake data *) 95 | "run_estimation"->0, 96 | "prior_sd"->100|> 97 | ExportStanData[codeFile,data] 98 | 99 | 100 | (* ::Subchapter:: *) 101 | (*Run stan and load result*) 102 | 103 | 104 | resultFile = RunStan[codeFile,SampleDefaultOptions] 105 | result = ImportStanResult[resultFile] 106 | 107 | 108 | (* ::Subchapter:: *) 109 | (*Theta*) 110 | 111 | 112 | GraphicsRow@GetStanResult[ListPlot[#,PlotRange->All]&,result,"theta"][[2;;-1]] 113 | 114 | 115 | (* ::Subchapter:: *) 116 | (*Simulated y_sym*) 117 | 118 | 119 | ysim=GetStanResult[result,"y_sim"]; 120 | Dimensions[ysim] 121 | 122 | 123 | (* ::Text:: *) 124 | (*From Dimension[] we can check that each column is N+10 draws for a given theta vector*) 125 | 126 | 127 | (* ::Text:: *) 128 | (*The problem with the current vague prior with \[Sigma]=100 leads, after the softmax, to one category embedding all the probability mass*) 129 | (*Here the first 5 columns (= 5 first realizations of theta with their associated 1010 realization of y_sim) counts:*) 130 | 131 | 132 | Table[Counts[ysim[[All,i]]],{i,5}] 133 | 134 | 135 | (* ::Subchapter:: *) 136 | (*The fix*) 137 | 138 | 139 | (* ::Text:: *) 140 | (*The prior must have a smaller range, here \[Sigma] = 1, in order to have more uniform category probabilities*) 141 | 142 | 143 | data=<| 144 | "N"->1000, 145 | "P"->5, 146 | "y"->ConstantArray[0,1000], (* fake data *) 147 | "run_estimation"->0, 148 | "prior_sd"->1|>; (* <- here new \[Sigma]=1 *) 149 | ExportStanData[codeFile,data]; 150 | 151 | 152 | resultFile = RunStan[codeFile,SampleDefaultOptions] 153 | result = ImportStanResult[resultFile] 154 | 155 | 156 | (* ::Subchapter:: *) 157 | (*Theta*) 158 | 159 | 160 | GraphicsRow@GetStanResult[ListPlot[#,PlotRange->All]&,result,"theta"][[2;;-1]] 161 | 162 | 163 | (* ::Subchapter:: *) 164 | (*The "new" simulated y_sym*) 165 | 166 | 167 | ysim=GetStanResult[result,"y_sim"]; 168 | Dimensions[ysim] 169 | 170 | 171 | (* ::Text:: *) 172 | (*We see that there is no more a "dominant" category*) 173 | 174 | 175 | Table[Counts[ysim[[All,i]]],{i,5}] 176 | 177 | 178 | (* ::Subchapter:: *) 179 | (*Test theta inference*) 180 | 181 | 182 | (* ::Text:: *) 183 | (*Ground truth for column #1*) 184 | 185 | 186 | thetaGroundTruth=GetStanResult[result,"theta"][[All,1]] 187 | 188 | 189 | data=<| 190 | "N"->1000, 191 | "P"->5, 192 | "y"->ysim[[1;;1000,1]], (* column #1 data, take 1:N sample (and not our previous 1:N+10) *) 193 | "run_estimation"->1, (* switch, now do inference *) 194 | "prior_sd"->1|>; (* <- here new \[Sigma]=1 *) 195 | ExportStanData[codeFile,data]; 196 | 197 | 198 | resultFile = RunStan[codeFile,SampleDefaultOptions] 199 | result = ImportStanResult[resultFile] 200 | 201 | 202 | GraphicsRow@GetStanResult[Histogram,result,"theta"][[2;;-1]] 203 | thetaGroundTruth[[2;;-1]] 204 | 205 | 206 | 207 | -------------------------------------------------------------------------------- /tutorial.wls: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env wolframscript 2 | (* ::Package:: *) 3 | 4 | (* ::Title:: *) 5 | (*Tutorial notebook*) 6 | 7 | 8 | (* ::Subchapter:: *) 9 | (*CmdStan package*) 10 | 11 | 12 | << CmdStan` 13 | 14 | 15 | ?CmdStan`* 16 | 17 | 18 | (* ::Chapter:: *) 19 | (*Linear regression*) 20 | 21 | 22 | (* ::Text:: *) 23 | (*exportFig=True (* if uncommented saves some figures into ./figures, used by README.org *)*) 24 | 25 | 26 | (* ::Subchapter:: *) 27 | (*Stan code*) 28 | 29 | 30 | SetDirectory[$TemporaryDirectory] 31 | 32 | 33 | stanCode="data 34 | { 35 | int N; 36 | vector[N] x; 37 | vector[N] y; 38 | } 39 | parameters 40 | { 41 | real alpha; 42 | real beta; 43 | real sigma; 44 | } 45 | model { 46 | y ~normal(alpha + beta * x, sigma); 47 | }"; 48 | 49 | 50 | 51 | stanCodeFile=ExportStanCode["linear_regression.stan",stanCode] 52 | 53 | 54 | (* ::Subchapter:: *) 55 | (*Stan exe*) 56 | 57 | 58 | stanExeFile = CompileStanCode[stanCodeFile,StanVerbose->False] 59 | 60 | 61 | (* ::Subchapter:: *) 62 | (*Linear regression data*) 63 | 64 | 65 | \[Sigma]=3;\[Alpha]=1;\[Beta]=2; 66 | n=20; 67 | X=Range[n]; 68 | Y=\[Alpha]+\[Beta]*X+RandomVariate[NormalDistribution[0,\[Sigma]],n]; 69 | p=Show[Plot[\[Alpha]+\[Beta]*x,{x,Min[X],Max[X]}],ListPlot[Transpose@{X,Y},PlotStyle->Red]] 70 | 71 | 72 | If[ValueQ[exportFig],Export["~/GitHub/MathematicaStan/figures/linRegData.png",p]] 73 | 74 | 75 | (* ::Subchapter:: *) 76 | (*Stan data.R file*) 77 | 78 | 79 | stanData=<|"N"->n,"x"->X,"y"->Y|>; 80 | stanDataFile=ExportStanData[stanExeFile,stanData] 81 | 82 | 83 | (* ::Subchapter:: *) 84 | (*Run Stan: "method=Optimize"*) 85 | 86 | 87 | stanResultFile=RunStan[stanExeFile,OptimizeDefaultOptions] 88 | 89 | 90 | RunStan[stanExeFile,OptimizeDefaultOptions,StanVerbose->False] 91 | 92 | 93 | OptimizeDefaultOptions 94 | 95 | 96 | (* ::Subchapter:: *) 97 | (*Load result*) 98 | 99 | 100 | stanResult=ImportStanResult[stanResultFile] 101 | 102 | 103 | GetStanResultMeta[stanResult,"lp__"] 104 | \[Alpha]e=GetStanResult[stanResult,"alpha"] 105 | \[Beta]e=GetStanResult[stanResult,"beta"] 106 | \[Sigma]e=GetStanResult[stanResult,"sigma"] 107 | 108 | 109 | p=Show[Plot[{\[Alpha]e+\[Beta]e*x,\[Alpha]+\[Beta]*x},{x,Min[X],Max[X]},PlotLegends->"Expressions"],ListPlot[Transpose@{X,Y},PlotStyle->Red]] 110 | 111 | 112 | If[ValueQ[exportFig],Export["~/GitHub/MathematicaStan/figures/linRegEstimate.png",p]] 113 | 114 | 115 | (* ::Subchapter:: *) 116 | (*Run Stan: "method=Variational"*) 117 | 118 | 119 | myOpt=VariationalDefaultOptions 120 | 121 | 122 | myOpt=SetStanOption[myOpt,"output.file",FileNameJoin[{Directory[],"myOutputFile.csv"}]] 123 | 124 | 125 | myOpt=SetStanOption[myOpt,"method.adapt.iter",123] 126 | 127 | 128 | GetStanOption[myOpt,"method.adapt.iter"] 129 | 130 | 131 | myOpt=RemoveStanOption[myOpt,"method.adapt.iter"] 132 | 133 | 134 | myOutputFile=RunStan[stanExeFile,myOpt,StanVerbose->False] 135 | 136 | 137 | myResult=ImportStanResult[myOutputFile] 138 | 139 | 140 | GetStanResult[Mean,myResult,"alpha"] 141 | GetStanResult[Variance,myResult,"alpha"] 142 | GetStanResult[Histogram,myResult,"alpha"] 143 | 144 | 145 | (* ::Chapter:: *) 146 | (**) 147 | 148 | 149 | (* ::Chapter:: *) 150 | (*Linear regression, more than one predictor*) 151 | 152 | 153 | (* ::Subchapter:: *) 154 | (*Stan code*) 155 | 156 | 157 | stanCode="data { 158 | int N; // number of data items 159 | int K; // number of predictors 160 | matrix[N, K] x; // predictor matrix 161 | vector[N] y; // outcome vector 162 | } 163 | parameters { 164 | real alpha; // intercept 165 | vector[K] beta; // coefficients for predictors 166 | real sigma; // error scale 167 | } 168 | model { 169 | y ~ normal(x * beta + alpha, sigma); // likelihood 170 | }"; 171 | 172 | 173 | stanCodeFile=ExportStanCode["linear_regression_vect.stan",stanCode]; 174 | stanExeFile = CompileStanCode[stanCodeFile,StanVerbose->False]; 175 | 176 | 177 | (* ::Subchapter:: *) 178 | (*Generate data*) 179 | 180 | 181 | \[Sigma]=3;\[Alpha]=1;\[Beta]1=2;\[Beta]2=0.1;\[Beta]3=0.01; 182 | n=20; 183 | X=Range[n]; 184 | Y=\[Alpha]+\[Beta]1*X+\[Beta]2*X^2+\[Beta]3*X^3+RandomVariate[NormalDistribution[0,\[Sigma]],n]; 185 | p=Show[Plot[\[Alpha]+\[Beta]1*x+\[Beta]2*x^2+\[Beta]3*x^3,{x,Min[X],Max[X]}],ListPlot[Transpose@{X,Y},PlotStyle->Red]] 186 | 187 | 188 | If[ValueQ[exportFig],Export["~/GitHub/MathematicaStan/figures/linReg2Data.png",p]] 189 | 190 | 191 | (* ::Subchapter:: *) 192 | (*Export data*) 193 | 194 | 195 | stanData=<|"N"->n,"K"->3,"x"->Transpose[{X,X^2,X^3}],"y"->Y|>; 196 | stanDataFile=ExportStanData[stanExeFile,stanData] 197 | 198 | 199 | (* ::Subchapter:: *) 200 | (*Run Stan: "method=Sample"*) 201 | 202 | 203 | stanResultFile=RunStan[stanExeFile,SampleDefaultOptions] 204 | 205 | 206 | (* ::Subchapter:: *) 207 | (*Load the CSV file*) 208 | 209 | 210 | stanResult=ImportStanResult[stanResultFile] 211 | 212 | 213 | p=GraphicsRow[GetStanResult[Histogram[#,ImageSize->200]&,stanResult,"beta"]] 214 | 215 | 216 | If[ValueQ[exportFig],Export["~/GitHub/MathematicaStan/figures/linReg2Histo.png",p]] 217 | 218 | 219 | StanResultKeys[stanResult] 220 | StanResultMetaKeys[stanResult] 221 | 222 | 223 | StanResultReducedKeys[stanResult] 224 | StanResultReducedMetaKeys[stanResult] 225 | 226 | 227 | GetStanResult[Mean,stanResult,"beta.2"] 228 | GetStanResult[Mean,stanResult,"beta"] 229 | 230 | 231 | Map[#->GetStanResult[stanResult,#]&,StanResultKeys[stanResult]]; 232 | Map[ListLinePlot[Values[#],ImageSize->200,PlotLabel->Keys[#]]&,%]; 233 | GraphicsGrid[Partition[%,3,3,{1,1},Null]] 234 | -------------------------------------------------------------------------------- /tests/CmdStan_test.wl: -------------------------------------------------------------------------------- 1 | (* ::Package:: *) 2 | 3 | SetDirectory["/tmp"] 4 | 5 | 6 | allTests={}; 7 | 8 | doTest[f_,output_]:=Block[{testResult}, 9 | testResult=VerificationTest[f,output]; 10 | AppendTo[allTests,testResult]; 11 | 12 | If[testResult["Outcome"]=="Success", 13 | 14 | Print["OK: ",f], 15 | 16 | Print[Style["FAILURE",40,Bold,Red]]; 17 | Print["Result : ",f]; 18 | Print["Expected: ",output]; 19 | ]; 20 | 21 | AppendTo[allTests,testResult]; 22 | Return[f]; 23 | ]; 24 | 25 | 26 | (* ::Chapter:: *) 27 | (*Tests*) 28 | 29 | 30 | On[Assert] 31 | <{"optimize",<||>},"data"->{Null,<|"file"->{"/tmp/bernoulli.data.R",<||>}|>}|>]]; 54 | doTest[GetStanOption[opt,"data.file"],"/tmp/bernoulli.data.R"]; 55 | doTest[opt=CmdStan`Private`completeStanOptionWithOutputFileName["/tmp/bernoulli.stan",OptimizeDefaultOptions,0],StanOptions[ <|"method"->{"optimize",<||>},"output"->{Null,<|"file"->{"/tmp/bernoulli.csv",<||>}|>}|>]]; 56 | doTest[GetStanOption[opt,"output.file"],"/tmp/bernoulli.csv"]; 57 | doTest[opt=CmdStan`Private`completeStanOptionWithOutputFileName["/tmp/bernoulli.stan",OptimizeDefaultOptions,3],StanOptions[ <|"method"->{"optimize",<||>},"output"->{Null,<|"file"->{"/tmp/bernoulli_3.csv",<||>}|>}|>]]; 58 | doTest[GetStanOption[opt,"output.file"],"/tmp/bernoulli_3.csv"]; 59 | 60 | 61 | (* ::Subchapter:: *) 62 | (*Create stan code*) 63 | 64 | 65 | stanCode="data { 66 | int N; 67 | array[N] int y; 68 | } 69 | parameters { 70 | real theta; 71 | } 72 | model { 73 | theta ~ beta(1,1); 74 | for (n in 1:N) 75 | y[n] ~ bernoulli(theta); 76 | }"; 77 | 78 | doTest[ExportStanCode["bernoulli.st an",stanCode],$Failed]; 79 | doTest[stanCodeFileName=ExportStanCode["bernoulli.stan",stanCode], "/tmp/bernoulli.stan"]; 80 | 81 | 82 | (* ::Subchapter:: *) 83 | (*Compile Stan code*) 84 | 85 | 86 | <False],"/tmp/bernoulli"]; 96 | doTest[CompileStanCode[stanCodeFileName,StanVerbose->True],"/tmp/bernoulli"]; 97 | 98 | 99 | (* ::Subchapter:: *) 100 | (*StanOptions*) 101 | 102 | 103 | (* ::Text:: *) 104 | (*A Revoir: GetStanOptionVariational et StanOptionVariational redondant + utiliser une Association TODO*) 105 | 106 | 107 | <{"variational",<|"optimize"->{Null,<|"iter"->{2016,<||>}|>}|>}|>]]; 114 | doTest[RemoveStanOption[opt,"method.optimize.iter"],StanOptions[<|"method"->{"variational",<||>}|>]]; 115 | 116 | 117 | (* ::Subchapter:: *) 118 | (*Export data for Bernoulli*) 119 | 120 | 121 | n=1000; 122 | data=Table[Random[BernoulliDistribution[0.2019]],n]; 123 | doTest[ExportStanData[stanCodeFileName,<|"N"->n,"y"->data|>],"/tmp/bernoulli.data.R"]; 124 | 125 | 126 | (* ::Subchapter:: *) 127 | (*RunStan*) 128 | 129 | 130 | <False],"/tmp/bernoulli.csv"]; 137 | 138 | 139 | doTest[RunStan[stanCodeFileName,VariationalDefaultOptions,StanVerbose->False],"/tmp/bernoulli.csv"]; 140 | 141 | 142 | doTest[outputOptimize=RunStan[stanCodeFileName,OptimizeDefaultOptions],"/tmp/bernoulli.csv"]; 143 | 144 | 145 | (* ::Subchapter:: *) 146 | (*Test import result*) 147 | 148 | 149 | <False] 197 | 198 | 199 | (* ::Section:: *) 200 | (*Create some fake data*) 201 | 202 | 203 | y=Partition[{0.201299862948504, -0.201547030912402, -0.307722736221928, 204 | -0.113909121429762, -0.317385076246514, 0.486887253813445, 0.216396070510692, 205 | -0.522504962507574, 0.0999884487329546, -0.374560249344118, 1.25230228963982, 206 | 1.32117236839097, -1.78912278548354, -1.12320907618655, 0.298757334386702, 207 | -0.643018973086524, -0.970193822958063, 1.8359248505943, -1.08397171023892, 208 | -0.681463669080701, 1.37841166199148, 0.250145455841524, 1.55188888550783, 209 | -0.94837059139759, -0.0785677710615314, 0.630262017843849, 0.0177509756762819, 210 | 0.0587175513653272, 1.5253088832499, 2.02971210407677, 1.48153547159389, 211 | 1.32561539997964, 1.61868319591135, 2.57511950976033, 1.90533033463626, 212 | -0.0392859071131051, 0.982223977047954, 0.224932037330876, 3.96756623395838, 213 | 0.56961898141743, 1.19038971367083, 1.46030520624806, -0.988041068794612, 214 | -0.13710499660733, -0.516173823435649, 1.73514001999303, 1.42450213310636, 215 | 2.42588178197086, 1.36078286104211, 2.00757973002483, 2.38142457257356, 216 | 1.9219710523873, 2.08190781987337, 0.385829858429519, 1.26125524130875, 217 | -0.133405525984022, 1.38778980737774, 1.08058596458552, 0.574498349889681, 218 | 3.32234174024842, 0.0497299209801201, 2.9224726963958, 1.77478377276629, 219 | 1.86667338790026, 0.926994133015224, 2.88792811797693, 0.77455586366817, 220 | -0.113502944729109, 3.03022684464381, 2.41360211089075, -0.286314710512999, 221 | 0.33626664500527, -0.949983239516864, 0.601482350292746, 0.731212313372704, 222 | -0.203496038340392, -0.11075627749627, 0.449160875122631, -2.01370769271222, 223 | -1.87291161344744, -1.17886113657795, -1.4965120578889, -0.161628522682308, 224 | -0.274340276559541, -0.865522537953758, -0.415682006424134, 1.74089559055984, 225 | -1.73086729463254, 0.959102863168718, -1.82543152975414, -1.73311360385246 },8]; 226 | Dimensions[y] 227 | toExport=<|"N"->Length[y],"D"->Last[Dimensions[y]],"K"->5,"y"->y|>; 228 | 229 | 230 | ExportStanData[stanExeFileName,toExport] 231 | 232 | 233 | (* ::Subsection:: *) 234 | (*Test optimize*) 235 | 236 | 237 | <False],"/tmp/soft-k-means.csv"]; 241 | 242 | 243 | result=ImportStanResult[stanOutputFilename] 244 | doTest[Dimensions[GetStanResult[result,"mu"]],{toExport["K"],Last[Dimensions[y]],1}] 245 | 246 | 247 | doTest[StanResultKeys[result],{"mu.1.1","mu.2.1","mu.3.1","mu.4.1","mu.5.1","mu.1.2","mu.2.2","mu.3.2","mu.4.2","mu.5.2","mu.1.3","mu.2.3","mu.3.3","mu.4.3","mu.5.3","mu.1.4","mu.2.4","mu.3.4","mu.4.4","mu.5.4","mu.1.5","mu.2.5","mu.3.5","mu.4.5","mu.5.5","mu.1.6","mu.2.6","mu.3.6","mu.4.6","mu.5.6","mu.1.7","mu.2.7","mu.3.7","mu.4.7","mu.5.7","mu.1.8","mu.2.8","mu.3.8","mu.4.8","mu.5.8","soft_z.1.1","soft_z.2.1","soft_z.3.1","soft_z.4.1","soft_z.5.1","soft_z.6.1","soft_z.7.1","soft_z.8.1","soft_z.9.1","soft_z.10.1","soft_z.11.1","soft_z.1.2","soft_z.2.2","soft_z.3.2","soft_z.4.2","soft_z.5.2","soft_z.6.2","soft_z.7.2","soft_z.8.2","soft_z.9.2","soft_z.10.2","soft_z.11.2","soft_z.1.3","soft_z.2.3","soft_z.3.3","soft_z.4.3","soft_z.5.3","soft_z.6.3","soft_z.7.3","soft_z.8.3","soft_z.9.3","soft_z.10.3","soft_z.11.3","soft_z.1.4","soft_z.2.4","soft_z.3.4","soft_z.4.4","soft_z.5.4","soft_z.6.4","soft_z.7.4","soft_z.8.4","soft_z.9.4","soft_z.10.4","soft_z.11.4","soft_z.1.5","soft_z.2.5","soft_z.3.5","soft_z.4.5","soft_z.5.5","soft_z.6.5","soft_z.7.5","soft_z.8.5","soft_z.9.5","soft_z.10.5","soft_z.11.5"}]; 248 | doTest[StanResultReducedKeys[result],{"mu","soft_z"}] 249 | 250 | 251 | doTest[StanResultMetaKeys[result],{"lp__"}]; 252 | doTest[StanResultReducedMetaKeys[result],{"lp__"}] 253 | 254 | 255 | (* ::Subsection:: *) 256 | (*Test variational*) 257 | 258 | 259 | doTest[stanOutputFilename=RunStan[stanCodeFileName,VariationalDefaultOptions,StanVerbose->False],"/tmp/soft-k-means.csv"]; 260 | 261 | 262 | result=ImportStanResult[stanOutputFilename] 263 | doTest[Dimensions[GetStanResult[result,"mu"]],{toExport["K"],Last[Dimensions[y]],1001}] 264 | 265 | 266 | (* ::Chapter:: *) 267 | (*Results*) 268 | 269 | 270 | TestReport[allTests] 271 | -------------------------------------------------------------------------------- /examples/identifying_mixture_models/identitying_mixture_models.wls: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env wolframscript 2 | (* ::Package:: *) 3 | 4 | (* ::Chapter:: *) 5 | (*Replication/Inspired by*) 6 | (*https://mc-stan.org/users/documentation/case-studies/identifying_mixture_models.html*) 7 | 8 | 9 | (* ::Subsubsection:: *) 10 | (*(all possible errors in *this* Mathematica notebook are mine)*) 11 | 12 | 13 | (* ::Subsection:: *) 14 | (*TODO: check if log_mix is a (1-\[Theta]), \[Theta] mixture or the reverse... I was expecting a \[Theta] , (1-\[Theta])... but for \[Lambda]=0.4, I get \[Lambda]=0.6 estimation.*) 15 | 16 | 17 | (* ::Chapter:: *) 18 | (*Stan init*) 19 | 20 | 21 | (* ::Subsection:: *) 22 | (*load Stan package*) 23 | 24 | 25 | <Directive[Bold],ImageSize->400,Frame->True,PlotRange->{Automatic,{-5,5}}]; 52 | SetOptions[ListPlot,LabelStyle->Directive[Bold],ImageSize->400,Frame->True,PlotRange->{Automatic,{-5,5}}]; 53 | 54 | 55 | (* ::Chapter:: *) 56 | (*GaussMix: degenerate implementation*) 57 | 58 | 59 | GaussMixFile=FileNameJoin[{Directory[],"Gauss_mix.stan"}] 60 | 61 | 62 | (* ::Subchapter:: *) 63 | (*Data generation*) 64 | 65 | 66 | \[Mu]={-2.75,2.75}; 67 | \[Sigma]={1,1}; 68 | \[Lambda]=0.4; 69 | 70 | 71 | n=10; (* <- and not 1000 as in the original post *) 72 | z=RandomVariate[BernoulliDistribution[\[Lambda]],n]+1; 73 | y=RandomVariate[NormalDistribution[\[Mu][[#]],\[Sigma][[#]]]]& /@ z; 74 | 75 | GaussMixData=<|"N"->n,"y"->y|>; 76 | ExportStanData[GaussMixFile,GaussMixData] 77 | 78 | 79 | (* ::Subchapter:: *) 80 | (*Stan code*) 81 | 82 | 83 | (* ::Text:: *) 84 | (*Everything is symmetric, priors etc... priors ares exchangeable*) 85 | (**) 86 | (*Subscript[\[Sigma], i] ~ \[ScriptCapitalN](0,2)*) 87 | (*Subscript[\[Mu], i] ~ \[ScriptCapitalN](0,2)*) 88 | (*\[Theta] ~ \[ScriptCapitalB](5,5) <- 2-mixture \[Theta], 1-\[Theta]*) 89 | 90 | 91 | GaussMixCode=" 92 | data { 93 | int N; 94 | vector[N] y; 95 | } 96 | 97 | parameters { 98 | vector[2] mu; 99 | array[2] real sigma; 100 | real theta; 101 | } 102 | 103 | model { 104 | sigma ~ normal(0, 2); 105 | mu ~ normal(0, 2); 106 | theta ~ beta(5, 5); 107 | for (n in 1:N) 108 | target += log_mix(theta, 109 | normal_lpdf(y[n] | mu[1], sigma[1]), 110 | normal_lpdf(y[n] | mu[2], sigma[2])); 111 | } 112 | "; 113 | ExportStanCode[GaussMixFile,GaussMixCode] 114 | CompileStanCode[GaussMixFile] 115 | 116 | 117 | (* ::Subchapter:: *) 118 | (*Run*) 119 | 120 | 121 | GaussMixResultFile = RunStan[GaussMixFile, mySampleOptions] 122 | stanResult = ImportStanResult[GaussMixResultFile] 123 | GraphicsRow[{ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 124 | 125 | 126 | (* ::Section:: *) 127 | (*and Variational?*) 128 | 129 | 130 | (* ::Text:: *) 131 | (*Even more vicious as mode switching is not clearly visible...*) 132 | 133 | 134 | GaussMixResultFile = RunStan[GaussMixFile, myVariationalOptions] 135 | stanResult = ImportStanResult[GaussMixResultFile] 136 | GraphicsRow[{ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 137 | 138 | 139 | (* ::Chapter:: *) 140 | (*GaussMix: breaking symmetries*) 141 | 142 | 143 | GaussMixNonExchangeableFile=FileNameJoin[{Directory[],"Gauss_mix_nonexchangeable.stan"}] 144 | 145 | 146 | (* ::Subchapter:: *) 147 | (*Data generation: same data as before*) 148 | 149 | 150 | GaussMixNonExchangeableData=GaussMixData; 151 | ExportStanData[GaussMixNonExchangeableFile,GaussMixData] 152 | 153 | 154 | (* ::Subchapter:: *) 155 | (*Stan code*) 156 | 157 | 158 | (* ::Text:: *) 159 | (*Priors ares non-exchangeable:*) 160 | 161 | 162 | (* ::Text:: *) 163 | (*Everything is symmetric, priors etc... priors ares exchangeable*) 164 | (**) 165 | (*Subscript[\[Sigma], i] ~ \[ScriptCapitalN](0,2)*) 166 | (*Subscript[\[Mu], 1] ~ \[ScriptCapitalN](+4,0.5), Subscript[\[Mu], 2] ~ \[ScriptCapitalN](-4,0.5)*) 167 | (*\[Theta] ~ \[ScriptCapitalB](5,5) <- 2-mixture \[Theta], 1-\[Theta]*) 168 | 169 | 170 | GaussMixNonExchangeableCode=" 171 | data { 172 | int N; 173 | vector[N] y; 174 | } 175 | 176 | parameters { 177 | vector[2] mu; 178 | array[2] real sigma; 179 | real theta; 180 | } 181 | 182 | model { 183 | sigma ~ normal(0, 2); 184 | mu[1] ~ normal(4, 0.5); // <- here (CAVEAT: for ordered(mu), we impose mu1"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 200 | 201 | 202 | (* ::Section:: *) 203 | (*and Variational?*) 204 | 205 | 206 | (* ::Text:: *) 207 | (*Ok...*) 208 | 209 | 210 | GaussMixNonExchangeableResultFile = RunStan[GaussMixNonExchangeableFile, myVariationalOptions] 211 | stanResult = ImportStanResult[GaussMixNonExchangeableResultFile] 212 | GraphicsRow[{ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 213 | 214 | 215 | (* ::Input:: *) 216 | (*\[DoubleDot]*) 217 | 218 | 219 | (* ::Chapter:: *) 220 | (*GaussMix: forcing an ordering*) 221 | 222 | 223 | GaussMixOrderedFile=FileNameJoin[{Directory[],"Gauss_mix_ordered.stan"}] 224 | 225 | 226 | (* ::Subchapter:: *) 227 | (*Data generation: same data as before*) 228 | 229 | 230 | GaussMixOrderedData=GaussMixData; 231 | ExportStanData[GaussMixOrderedFile,GaussMixData] 232 | 233 | 234 | (* ::Subchapter:: *) 235 | (*Stan code*) 236 | 237 | 238 | (* ::Text:: *) 239 | (*Priors ares non-exchangeable:*) 240 | 241 | 242 | (* ::Text:: *) 243 | (*Everything is symmetric, priors etc... priors ares exchangeable*) 244 | (**) 245 | (*Subscript[\[Sigma], i] ~ \[ScriptCapitalN](0,2)*) 246 | (*Subscript[\[Mu], i] ~ \[ScriptCapitalN](0,2) and Subscript[\[Mu], 1]"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 279 | 280 | 281 | (* ::Section:: *) 282 | (*and Variational?*) 283 | 284 | 285 | GaussMixOrderedResultFile = RunStan[GaussMixOrderedFile, myVariationalOptions] 286 | stanResult = ImportStanResult[GaussMixOrderedResultFile] 287 | GraphicsRow[{ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 288 | 289 | 290 | (* ::Chapter:: *) 291 | (*GaussMix: degenerate + overlaping*) 292 | 293 | 294 | GaussMixOverlapFile=FileNameJoin[{Directory[],"Gauss_mix_overlap.stan"}] 295 | 296 | 297 | (* ::Subchapter:: *) 298 | (*Data generation*) 299 | 300 | 301 | \[Mu]={-0.75,0.75}; (* <-- here *) 302 | \[Sigma]={1,1}; 303 | \[Lambda]=0.4; 304 | 305 | 306 | n=1000; (* <- and not 1000 as in the original post *) 307 | z=RandomVariate[BernoulliDistribution[\[Lambda]],n]+1; 308 | y=RandomVariate[NormalDistribution[\[Mu][[#]],\[Sigma][[#]]]]& /@ z; 309 | 310 | GaussMixOverlapData=<|"N"->n,"y"->y|>; 311 | ExportStanData[GaussMixOverlapFile,GaussMixOverlapData] 312 | 313 | 314 | (* ::Subchapter:: *) 315 | (*Stan code*) 316 | 317 | 318 | (* ::Text:: *) 319 | (*Everything is symmetric, priors etc... priors ares exchangeable*) 320 | (**) 321 | (*Subscript[\[Sigma], i] ~ \[ScriptCapitalN](0,2)*) 322 | (*Subscript[\[Mu], i] ~ \[ScriptCapitalN](0,2)*) 323 | (*\[Theta] ~ \[ScriptCapitalB](5,5) <- 2-mixture \[Theta], 1-\[Theta]*) 324 | 325 | 326 | GaussMixOverlapCode=" 327 | data { 328 | int N; 329 | vector[N] y; 330 | } 331 | 332 | parameters { 333 | vector[2] mu; 334 | array[2] real sigma; 335 | real theta; 336 | } 337 | 338 | model { 339 | sigma ~ normal(0, 2); 340 | mu ~ normal(0, 2); 341 | theta ~ beta(5, 5); 342 | for (n in 1:N) 343 | target += log_mix(theta, 344 | normal_lpdf(y[n] | mu[1], sigma[1]), 345 | normal_lpdf(y[n] | mu[2], sigma[2])); 346 | } 347 | "; 348 | ExportStanCode[GaussMixOverlapFile,GaussMixOverlapCode] 349 | CompileStanCode[GaussMixOverlapFile] 350 | 351 | 352 | (* ::Subchapter:: *) 353 | (*Run*) 354 | 355 | 356 | GaussMixOverlapResultFile = RunStan[GaussMixOverlapFile, mySampleOptions] 357 | stanResult = ImportStanResult[GaussMixOverlapResultFile] 358 | GraphicsRow[{ 359 | ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"], 360 | Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"], 361 | ListPlot[Transpose@{GetStanResult[stanResult,"mu.1"],GetStanResult[stanResult,"mu.2"]}]}] 362 | 363 | 364 | (* ::Section:: *) 365 | (*and Variational?*) 366 | 367 | 368 | GaussMixOverlapResultFile = RunStan[GaussMixOverlapFile, myVariationalOptions] 369 | stanResult = ImportStanResult[GaussMixOverlapResultFile] 370 | GraphicsRow[{ListLinePlot[GetStanResult[stanResult,"mu.1"],PlotLabel->"\[Mu]1"],ListLinePlot[GetStanResult[stanResult,"mu.2"],PlotLabel->"\[Mu]2"],Histogram[GetStanResult[stanResult,"theta"],PlotLabel->"\[Theta]"]}] 371 | 372 | 373 | 374 | -------------------------------------------------------------------------------- /examples/mcmc_option_example.nb: -------------------------------------------------------------------------------- 1 | (* Content-type: application/vnd.wolfram.mathematica *) 2 | 3 | (*** Wolfram Notebook File ***) 4 | (* http://www.wolfram.com/nb *) 5 | 6 | (* CreatedBy='Mathematica 11.2' *) 7 | 8 | (*CacheID: 234*) 9 | (* Internal cache information: 10 | NotebookFileLineBreakTest 11 | NotebookFileLineBreakTest 12 | NotebookDataPosition[ 158, 7] 13 | NotebookDataLength[ 21611, 585] 14 | NotebookOptionsPosition[ 17231, 496] 15 | NotebookOutlinePosition[ 17568, 511] 16 | CellTagsIndexPosition[ 17525, 508] 17 | WindowFrame->Normal*) 18 | 19 | (* Beginning of Notebook Content *) 20 | Notebook[{ 21 | 22 | Cell[CellGroupData[{ 23 | Cell["Sample Option Example", "Title", 24 | CellChangeTimes->{{3.831785820560658*^9, 25 | 3.8317858279042873`*^9}},ExpressionUUID->"6c9df950-effd-4a75-98b9-\ 26 | 594765b3cb9a"], 27 | 28 | Cell["\<\ 29 | This example reuses Tutorial part 1. At the end we show how to modify the \ 30 | \[OpenCurlyDoubleQuote]Sample\[CloseCurlyDoubleQuote] method options\ 31 | \>", "Text", 32 | CellChangeTimes->{{3.83179129350803*^9, 3.831791315164875*^9}, { 33 | 3.831791360166697*^9, 34 | 3.831791365222356*^9}},ExpressionUUID->"063e36e8-b776-4eb3-9a48-\ 35 | 3064ac7f329d"], 36 | 37 | Cell[CellGroupData[{ 38 | 39 | Cell["Unmodified beginning of the Tutorial 1", "Chapter", 40 | CellChangeTimes->{{3.831785842073092*^9, 3.831785848857202*^9}, { 41 | 3.831791331045677*^9, 42 | 3.8317913510298853`*^9}},ExpressionUUID->"6f510c45-11cb-4e2f-be32-\ 43 | dcaf37cc5878"], 44 | 45 | Cell[BoxData[ 46 | RowBox[{"<<", " ", "CmdStan`"}]], "Input",ExpressionUUID->"ce3eec43-69af-4ed0-92b8-45fd278972bc"], 47 | 48 | Cell[CellGroupData[{ 49 | 50 | Cell[BoxData[ 51 | RowBox[{"SetDirectory", "[", "$TemporaryDirectory", "]"}]], "Input",Expressio\ 52 | nUUID->"51cf99c6-20ba-4b00-92d3-c480b1206b66"], 53 | 54 | Cell[BoxData["\<\"/tmp\"\>"], "Output", 55 | CellChangeTimes->{3.831785872297336*^9, 56 | 3.932538376621771*^9},ExpressionUUID->"eb98c0f8-747b-44e6-a95e-\ 57 | 7ca5d12c5a06"] 58 | }, Open ]], 59 | 60 | Cell[BoxData[ 61 | RowBox[{ 62 | RowBox[{ 63 | RowBox[{ 64 | "stanCode", "=", 65 | "\"\ N;\n vector[N] x;\n vector[N] y;\n}\n\ 66 | parameters\n{\n real alpha;\n real beta;\n real sigma;\n}\n\ 67 | model {\n y ~normal(alpha + beta * x, sigma);\n}\>\""}], ";"}], 68 | "\n"}]], "Input",ExpressionUUID->"42fde992-f78f-4ae6-926b-edbc102ae5fa"], 69 | 70 | Cell[CellGroupData[{ 71 | 72 | Cell[BoxData[ 73 | RowBox[{"stanExeFile", " ", "=", " ", 74 | RowBox[{"CompileStanCode", "[", 75 | RowBox[{"stanCodeFile", ",", 76 | RowBox[{"StanVerbose", "->", "False"}]}], "]"}]}]], "Input",ExpressionUUID\ 77 | ->"0904a970-98bb-4c54-a784-5d25c80699d1"], 78 | 79 | Cell[BoxData[ 80 | RowBox[{"CompileStanCode", "[", 81 | RowBox[{"stanCodeFile", ",", 82 | RowBox[{"StanVerbose", "\[Rule]", "False"}]}], "]"}]], "Output", 83 | CellChangeTimes->{3.8317858834817133`*^9, 84 | 3.932538376636354*^9},ExpressionUUID->"61f4d2e2-3356-41d7-a9e4-\ 85 | 6895a3b75e1f"] 86 | }, Open ]], 87 | 88 | Cell[CellGroupData[{ 89 | 90 | Cell[BoxData[{ 91 | RowBox[{ 92 | RowBox[{"\[Sigma]", "=", "3"}], ";", 93 | RowBox[{"\[Alpha]", "=", "1"}], ";", 94 | RowBox[{"\[Beta]", "=", "2"}], ";"}], "\n", 95 | RowBox[{ 96 | RowBox[{"n", "=", "20"}], ";"}], "\n", 97 | RowBox[{ 98 | RowBox[{"X", "=", 99 | RowBox[{"Range", "[", "n", "]"}]}], ";"}], "\n", 100 | RowBox[{ 101 | RowBox[{"Y", "=", 102 | RowBox[{"\[Alpha]", "+", 103 | RowBox[{"\[Beta]", "*", "X"}], "+", 104 | RowBox[{"RandomVariate", "[", 105 | RowBox[{ 106 | RowBox[{"NormalDistribution", "[", 107 | RowBox[{"0", ",", "\[Sigma]"}], "]"}], ",", "n"}], "]"}]}]}], 108 | ";"}], "\n", 109 | RowBox[{"p", "=", 110 | RowBox[{"Show", "[", 111 | RowBox[{ 112 | RowBox[{"Plot", "[", 113 | RowBox[{ 114 | RowBox[{"\[Alpha]", "+", 115 | RowBox[{"\[Beta]", "*", "x"}]}], ",", 116 | RowBox[{"{", 117 | RowBox[{"x", ",", 118 | RowBox[{"Min", "[", "X", "]"}], ",", 119 | RowBox[{"Max", "[", "X", "]"}]}], "}"}]}], "]"}], ",", 120 | RowBox[{"ListPlot", "[", 121 | RowBox[{ 122 | RowBox[{"Transpose", "@", 123 | RowBox[{"{", 124 | RowBox[{"X", ",", "Y"}], "}"}]}], ",", 125 | RowBox[{"PlotStyle", "->", "Red"}]}], "]"}]}], "]"}]}]}], "Input",Expres\ 126 | sionUUID->"a2142860-3bba-4ca2-9652-742ebe54be57"], 127 | 128 | Cell[BoxData[ 129 | GraphicsBox[{{{{}, {}, 130 | TagBox[ 131 | {RGBColor[0.368417, 0.506779, 0.709798], AbsoluteThickness[1.6], 132 | Opacity[1.], LineBox[CompressedData[" 133 | 1:eJwtzX9M1GUAx/FD3Thv3OAyCLviDvAORLkfPMidd8j3AzxlkJx0cZNZFITH 134 | TstocJr8jkBkusEtERVkNjccLkNDkrlmTlgSTHMkGZUxrcBDbV6XeKcHEu15 135 | /vjs9c9ne0e/V2q1LxGJRDmL+9+pNyMcIpFHYIqhU9guTL7gEZhiVN47KLmo 136 | 9QhMMcLqZV9WvOsRmGKYekO83m89AlOMFvHS6qmafwTmcqRcfNg6GvAKTAma 137 | 1CMDbb5ZgSlFyLWN7pOlc0LTdKzzhuE5DBzerZ1PDeKGQ/NJjnUuaRk3Eu3W 138 | /XbT9mCuHH9/+qv8qEPCjYKhyzWY0iPFMctrRfJxJYo/trvzPgjjxiB6c8jl 139 | qBkZNxYT8mmZuGkFV4V9h7P664PDuXGY0JRKSuojuPGI+WZ4Yrs8kpuAbY9P 140 | +eePruSuwXH1JddXRjk3EdVl7beuX3+Jq0HuTl9F7etR6DkfSL2k0iGq4EDr 141 | prsKtPZ+t/Hkvzp4a/Kqfjqn5Orx4/Dcjucbo7lJaFA09TfnxnAJzljG1a+E 142 | xnKTke8322STsdxk1FQ4TquOr+KuQ7l4d0Hp2ypuCqZkXaPfr1ZzDbjhbS7c 143 | MaPmGpBmaemTX4jjGlE54Hxnyd547nro/Qqiz1zNNcF+7q+hUlkC14zwVz+s 144 | eTyWwDWjfXrC1deyhpuKtqCCwtq31nI3QPqoO/+zFxO5aVhaJJaen0nkpsHZ 145 | rb0X/YWGK2DAZ4gecmhxK9DpKkoGzH+slZjkOmYnkJ+sPJJSpWMGgP5M5TLz 146 | nzpmcTr8v4S9vDVLzxxJx9PfirO7evTM+AyYOods7tAkZmsGjFf27tryURLT 147 | kwHFHmPGnR+SmJZM0Lu+B2XrCPPrTMQNrjwdf4gwwyn22zYvH28nzAiKB+7G 148 | krojhBlJcTbUo7zZSZhyClPBlUMNJwgzhsLiL6ubPEOYWgqn5qq1bZQwsylu 149 | Xg46K1wlzE0U620G6f1rhJlD8azqxHD6GGG+QdE8sif14c+EuYWic5tKnT1F 150 | mPbFv29rw+w0YZZQFB5w3f7cTZgOilV9gQ7ffcJ8n6J3YSy020uYZRRhB4N3 151 | 5j4iTCdFuXrDaGCWMHdRGHN6Gq1PCLOCouP273fmnxJmJcV8+Qrh1BxhVi/2 152 | g7OO5T0jzFqKwY7aJwsLhFlH8R86ohrn 153 | "]]}, 154 | Annotation[#, "Charting`Private`Tag$34850#1"]& ]}, {}, {}}, {{}, {{}, 155 | {RGBColor[1, 0, 0], PointSize[0.012833333333333334`], AbsoluteThickness[ 156 | 1.6], PointBox[CompressedData[" 157 | 1:eJxTTMoPSmViYGAQAWIQDQEf7Bv0S2Y1bLy3Hyrg4LBc4L2aNbcDhMvhMOfQ 158 | 31YjD3koX8BhodOlq7MeSUH5Ig5u/EYTK1jUoHwJh38Pvm2xMdaB8mUc6ldV 159 | 32BlVofyFRyap65NmLvKEMpXcrj0/JjqtU/aUL6KgxlPyaQKXQsoX81hWvR6 160 | K05mcyhfwyHVIm+V23tTKF/LQSNGNobRxRrK13FgbPPX2ShmC+XrOUTV6H8N 161 | 6HKA8g0c5oc9rzDZYA/lGzqs8r145ZSCE5Rv5FCVbJfa4eQK5Rs7JBou+XD9 162 | qiOUb+Iwifee+3E1VwcAcb1NBA== 163 | "]]}, {}}, {}, {}, {}, {}}}, 164 | AspectRatio->NCache[GoldenRatio^(-1), 0.6180339887498948], 165 | Axes->{True, True}, 166 | AxesLabel->{None, None}, 167 | AxesOrigin->{1, 0}, 168 | DisplayFunction->Identity, 169 | Frame->{{False, False}, {False, False}}, 170 | FrameLabel->{{None, None}, {None, None}}, 171 | FrameTicks->{{Automatic, 172 | Charting`ScaledFrameTicks[{Identity, Identity}]}, {Automatic, 173 | Charting`ScaledFrameTicks[{Identity, Identity}]}}, 174 | GridLines->{None, None}, 175 | GridLinesStyle->Directive[ 176 | GrayLevel[0.5, 0.4]], 177 | ImagePadding->All, 178 | Method->{ 179 | "DefaultBoundaryStyle" -> Automatic, "DefaultMeshStyle" -> 180 | AbsolutePointSize[6], "ScalingFunctions" -> None, 181 | "CoordinatesToolOptions" -> {"DisplayFunction" -> ({ 182 | (Identity[#]& )[ 183 | Part[#, 1]], 184 | (Identity[#]& )[ 185 | Part[#, 2]]}& ), "CopiedValueFunction" -> ({ 186 | (Identity[#]& )[ 187 | Part[#, 1]], 188 | (Identity[#]& )[ 189 | Part[#, 2]]}& )}}, 190 | PlotRange->{{1, 20}, {0., 40.9999992244898}}, 191 | PlotRangeClipping->True, 192 | PlotRangePadding->{{ 193 | Scaled[0.02], 194 | Scaled[0.02]}, { 195 | Scaled[0.05], 196 | Scaled[0.05]}}, 197 | Ticks->{Automatic, Automatic}]], "Output", 198 | CellChangeTimes->{3.831785895936925*^9, 199 | 3.93253837667533*^9},ExpressionUUID->"33c76108-b5c9-45ed-9390-8f82675e1bb0"] 200 | }, Open ]], 201 | 202 | Cell[CellGroupData[{ 203 | 204 | Cell[BoxData[{ 205 | RowBox[{ 206 | RowBox[{"stanData", "=", 207 | RowBox[{"<|", 208 | RowBox[{ 209 | RowBox[{"\"\\"", "->", "n"}], ",", 210 | RowBox[{"\"\\"", "->", "X"}], ",", 211 | RowBox[{"\"\\"", "->", "Y"}]}], "|>"}]}], ";"}], "\n", 212 | RowBox[{"stanDataFile", "=", 213 | RowBox[{"ExportStanData", "[", 214 | RowBox[{"stanExeFile", ",", "stanData"}], "]"}]}]}], "Input",ExpressionUUID\ 215 | ->"27cd088e-faf8-444b-907b-9e9e08bb0198"], 216 | 217 | Cell[BoxData[ 218 | RowBox[{"ExportStanData", "[", 219 | RowBox[{ 220 | RowBox[{"CompileStanCode", "[", 221 | RowBox[{"stanCodeFile", ",", 222 | RowBox[{"StanVerbose", "\[Rule]", "False"}]}], "]"}], ",", 223 | RowBox[{"\[LeftAssociation]", 224 | RowBox[{ 225 | RowBox[{"\<\"N\"\>", "\[Rule]", "20"}], ",", 226 | RowBox[{"\<\"x\"\>", "\[Rule]", 227 | RowBox[{"{", 228 | RowBox[{ 229 | "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", 230 | "8", ",", "9", ",", "10", ",", "11", ",", "12", ",", "13", ",", "14", 231 | ",", "15", ",", "16", ",", "17", ",", "18", ",", "19", ",", "20"}], 232 | "}"}]}], ",", 233 | RowBox[{"\<\"y\"\>", "\[Rule]", 234 | RowBox[{"{", 235 | RowBox[{ 236 | RowBox[{"-", "0.47958388408073205`"}], ",", "3.403882854171485`", ",", 237 | "7.820505231488507`", ",", "6.721293774564999`", ",", 238 | "11.008732354508208`", ",", "14.100072531830389`", ",", 239 | "11.50590397367091`", ",", "17.666463892344392`", ",", 240 | "13.97429006627127`", ",", "24.177621033985098`", ",", 241 | "23.01185957699962`", ",", "21.934672023686648`", ",", 242 | "27.265645749252286`", ",", "29.08864094678393`", ",", 243 | "33.080595634638215`", ",", "31.688300663451283`", ",", 244 | "36.256189920615114`", ",", "42.51978745981519`", ",", 245 | "35.67065246598464`", ",", "42.30295656530792`"}], "}"}]}]}], 246 | "\[RightAssociation]"}]}], "]"}]], "Output", 247 | CellChangeTimes->{3.831785930642892*^9, 248 | 3.932538376680751*^9},ExpressionUUID->"279359f0-8ed6-4f2c-85f7-\ 249 | 1ea4bd10fced"] 250 | }, Open ]] 251 | }, Open ]], 252 | 253 | Cell[CellGroupData[{ 254 | 255 | Cell["Option modification example", "Chapter", 256 | CellChangeTimes->{{3.8317859541009912`*^9, 3.831785956420439*^9}, { 257 | 3.831791386567368*^9, 258 | 3.831791389447465*^9}},ExpressionUUID->"38906749-4dd4-4dbf-a5f1-\ 259 | 04434d86abbb"], 260 | 261 | Cell[CellGroupData[{ 262 | 263 | Cell["A run with sample default options", "Subchapter", 264 | CellChangeTimes->{{3.831785965125164*^9, 265 | 3.831785979485395*^9}},ExpressionUUID->"a8c5e0e9-43e0-468e-90f2-\ 266 | 0be61ab05be1"], 267 | 268 | Cell[CellGroupData[{ 269 | 270 | Cell[BoxData[ 271 | RowBox[{"stanResultFile", "=", 272 | RowBox[{"RunStan", "[", 273 | RowBox[{"stanExeFile", ",", "SampleDefaultOptions"}], "]"}]}]], "Input", 274 | CellChangeTimes->{{3.831786010778351*^9, 275 | 3.831786012374572*^9}},ExpressionUUID->"598fa5f8-79c7-4551-bc78-\ 276 | a95fa6250481"], 277 | 278 | Cell[BoxData[ 279 | RowBox[{"RunStan", "[", 280 | RowBox[{ 281 | RowBox[{"CompileStanCode", "[", 282 | RowBox[{"stanCodeFile", ",", 283 | RowBox[{"StanVerbose", "\[Rule]", "False"}]}], "]"}], 284 | ",", "\<\"method=sample \"\>"}], "]"}]], "Output", 285 | CellChangeTimes->{3.831786013171788*^9, 286 | 3.932538376698625*^9},ExpressionUUID->"629421c9-2819-4990-8b26-\ 287 | 2904bf233517"] 288 | }, Open ]] 289 | }, Open ]], 290 | 291 | Cell[CellGroupData[{ 292 | 293 | Cell["Now with customized option values", "Subchapter", 294 | CellChangeTimes->{{3.83178602843119*^9, 295 | 3.831786042247155*^9}},ExpressionUUID->"b4c0447e-acc5-4313-ac3a-\ 296 | a6126e79b74e"], 297 | 298 | Cell["\<\ 299 | Note: 300 | 301 | you can see available options looking at previous command output or by \ 302 | reading CmdStan manual 303 | https://mc-stan.org/docs/2_24/cmdstan-guide-2_24.pdf 304 | 305 | by example we will modify MCMC options: 306 | num_samples = 1000 (Default) 307 | num_warmup = 1000 (Default) 308 | 309 | and 310 | 311 | algorithm = hmc (Default) 312 | hmc 313 | engine = nuts (Default) 314 | nuts 315 | max_depth = 10 (Default)\ 316 | \>", "Text", 317 | CellChangeTimes->{{3.831786060520108*^9, 3.831786204732481*^9}, { 318 | 3.8317863861232147`*^9, 3.8317864097150927`*^9}, {3.83178644486896*^9, 319 | 3.831786450397414*^9}, {3.831791205108165*^9, 3.831791209426579*^9}, 320 | 3.831791415448629*^9},ExpressionUUID->"e9ff3f7f-5805-4b32-8588-\ 321 | 89c650e83760"], 322 | 323 | Cell[CellGroupData[{ 324 | 325 | Cell["Copy default Sample option", "Subsubsection", 326 | CellChangeTimes->{{3.831791456026843*^9, 327 | 3.831791472577626*^9}},ExpressionUUID->"c2c4825f-6f39-4a5c-84ba-\ 328 | f599e98400b8"], 329 | 330 | Cell[CellGroupData[{ 331 | 332 | Cell[BoxData[ 333 | RowBox[{"myOpt", "=", "SampleDefaultOptions"}]], "Input", 334 | CellChangeTimes->{ 335 | 3.8317861805170317`*^9, {3.8317862112224083`*^9, 3.831786229805153*^9}, 336 | 3.831791245882015*^9, {3.831791482402768*^9, 337 | 3.831791482818211*^9}},ExpressionUUID->"0bd09745-72ef-41cf-846b-\ 338 | fffe33e1b4ea"], 339 | 340 | Cell[BoxData["\<\"method=sample \"\>"], "Output", 341 | CellChangeTimes->{3.8317862310754538`*^9, 3.831787077828847*^9, 342 | 3.8317912808757753`*^9, 3.831791485125471*^9, 3.831791986732547*^9, 343 | 3.932538376703693*^9},ExpressionUUID->"241cd214-5fbb-4994-986e-\ 344 | a6513f3ba303"] 345 | }, Open ]] 346 | }, Open ]], 347 | 348 | Cell[CellGroupData[{ 349 | 350 | Cell["Modify some values", "Subsubsection", 351 | CellChangeTimes->{{3.831791491026187*^9, 352 | 3.831791497370562*^9}},ExpressionUUID->"65397619-55fe-4db8-9fd7-\ 353 | 55613f200b45"], 354 | 355 | Cell[CellGroupData[{ 356 | 357 | Cell[BoxData[{ 358 | RowBox[{"myOpt", "=", 359 | RowBox[{"SetStanOption", "[", 360 | RowBox[{"myOpt", ",", "\"\\"", ",", "2000"}], 361 | "]"}]}], "\[IndentingNewLine]", 362 | RowBox[{"myOpt", "=", 363 | RowBox[{"SetStanOption", "[", 364 | RowBox[{"myOpt", ",", "\"\\"", ",", "1500"}], 365 | "]"}]}], "\[IndentingNewLine]", 366 | RowBox[{"myOpt", "=", 367 | RowBox[{"SetStanOption", "[", 368 | RowBox[{ 369 | "myOpt", ",", "\"\\"", ",", "5"}], 370 | "]"}]}], "\[IndentingNewLine]"}], "Input", 371 | CellChangeTimes->{{3.831786232870936*^9, 3.831786262286579*^9}, { 372 | 3.8317864593513823`*^9, 3.83178652925736*^9}, {3.8317870734885883`*^9, 373 | 3.8317870751529627`*^9}, {3.8317912474827623`*^9, 3.831791250825214*^9}, { 374 | 3.8317914874347563`*^9, 375 | 3.831791488050886*^9}},ExpressionUUID->"06358e83-262a-412c-834d-\ 376 | 8257aa1bc1ab"], 377 | 378 | Cell[BoxData["\<\"method=sample adapt num_samples=2000 \"\>"], "Output", 379 | CellChangeTimes->{3.831786263790722*^9, 3.83178650542877*^9, 380 | 3.831787078635294*^9, 3.831791508694509*^9, 3.831791989081615*^9, 381 | 3.83179207552927*^9, 382 | 3.932538376715664*^9},ExpressionUUID->"c037b988-8798-40c8-a277-\ 383 | 7a988385f446"], 384 | 385 | Cell[BoxData["\<\"method=sample adapt num_samples=2000 num_warmup=1500 \ 386 | \"\>"], "Output", 387 | CellChangeTimes->{3.831786263790722*^9, 3.83178650542877*^9, 388 | 3.831787078635294*^9, 3.831791508694509*^9, 3.831791989081615*^9, 389 | 3.83179207552927*^9, 390 | 3.932538376716756*^9},ExpressionUUID->"8de4c49d-d618-4d7a-aef6-\ 391 | 99b227b97916"], 392 | 393 | Cell[BoxData["\<\"method=sample adapt num_samples=2000 num_warmup=1500 \ 394 | algorithm=hmc engine=nuts max_depth=5 \"\>"], "Output", 395 | CellChangeTimes->{3.831786263790722*^9, 3.83178650542877*^9, 396 | 3.831787078635294*^9, 3.831791508694509*^9, 3.831791989081615*^9, 397 | 3.83179207552927*^9, 398 | 3.9325383767176323`*^9},ExpressionUUID->"333d5405-3d60-484a-9896-\ 399 | da03d1c5accf"] 400 | }, Open ]] 401 | }, Open ]], 402 | 403 | Cell[CellGroupData[{ 404 | 405 | Cell["Perform a new run with these options", "Subsubsection", 406 | CellChangeTimes->{{3.831791515923255*^9, 407 | 3.83179152464325*^9}},ExpressionUUID->"26f2eb13-50bd-457d-95ff-\ 408 | 40104ba9b45f"], 409 | 410 | Cell[CellGroupData[{ 411 | 412 | Cell[BoxData[ 413 | RowBox[{"stanResultFile", "=", 414 | RowBox[{"RunStan", "[", 415 | RowBox[{"stanExeFile", ",", "myOpt"}], "]"}]}]], "Input", 416 | CellChangeTimes->{{3.831786268912915*^9, 3.8317863116099586`*^9}, 417 | 3.831791255225955*^9, {3.8317915283241587`*^9, 418 | 3.8317915287400827`*^9}},ExpressionUUID->"ba89db0f-22f3-46b8-9f90-\ 419 | 3b20a0bd4f99"], 420 | 421 | Cell[BoxData[ 422 | RowBox[{"RunStan", "[", 423 | RowBox[{ 424 | RowBox[{"CompileStanCode", "[", 425 | RowBox[{"stanCodeFile", ",", 426 | RowBox[{"StanVerbose", "\[Rule]", "False"}]}], "]"}], 427 | ",", "\<\"method=sample adapt num_samples=2000 num_warmup=1500 \ 428 | algorithm=hmc engine=nuts max_depth=5 \"\>"}], "]"}]], "Output", 429 | CellChangeTimes->{3.8317863125587397`*^9, 3.831786508589686*^9, 430 | 3.831787150928133*^9, 3.831792077850565*^9, 431 | 3.9325383767278843`*^9},ExpressionUUID->"694d359a-bcae-443e-bbfb-\ 432 | 6eb550d8f609"] 433 | }, Open ]] 434 | }, Open ]], 435 | 436 | Cell[CellGroupData[{ 437 | 438 | Cell["Read back option values", "Subsection", 439 | CellChangeTimes->{{3.831792317772191*^9, 440 | 3.831792322020649*^9}},ExpressionUUID->"ea9e4e8a-492c-4f01-bf89-\ 441 | 582887fc0890"], 442 | 443 | Cell[CellGroupData[{ 444 | 445 | Cell[BoxData[{ 446 | RowBox[{"GetStanOption", "[", 447 | RowBox[{"myOpt", ",", "\"\\""}], 448 | "]"}], "\[IndentingNewLine]", 449 | RowBox[{"GetStanOption", "[", 450 | RowBox[{"myOpt", ",", "\"\\""}], 451 | "]"}], "\[IndentingNewLine]"}], "Input", 452 | CellChangeTimes->{{3.8317923275172243`*^9, 453 | 3.8317923446215982`*^9}},ExpressionUUID->"ed1b181b-9329-4f10-9304-\ 454 | f09ef7c9ef84"], 455 | 456 | Cell[BoxData["1500"], "Output", 457 | CellChangeTimes->{3.831792345979162*^9, 458 | 3.93253837673274*^9},ExpressionUUID->"5c1d69c2-dfb1-4d8a-8310-b625252c25ce"], 459 | 460 | Cell[BoxData["5"], "Output", 461 | CellChangeTimes->{3.831792345979162*^9, 462 | 3.932538376733409*^9},ExpressionUUID->"aefca5ae-cce7-48fd-9409-\ 463 | d48ecacfa19c"] 464 | }, Open ]] 465 | }, Open ]], 466 | 467 | Cell[CellGroupData[{ 468 | 469 | Cell["Remove the preivously customized \[OpenCurlyDoubleQuote]max_depth\ 470 | \[CloseCurlyDoubleQuote] value", "Subsection", 471 | CellChangeTimes->{{3.8317915409880877`*^9, 472 | 3.831791566181119*^9}},ExpressionUUID->"b63b677e-17a9-4d05-a9e2-\ 473 | 57201c1cc6de"], 474 | 475 | Cell[CellGroupData[{ 476 | 477 | Cell[BoxData[ 478 | RowBox[{"myOpt", "=", 479 | RowBox[{"RemoveStanOption", "[", 480 | RowBox[{"myOpt", ",", "\"\\""}], 481 | "]"}]}]], "Input", 482 | CellChangeTimes->{{3.831787153812202*^9, 3.831787175875298*^9}, { 483 | 3.8317912564178877`*^9, 3.8317912572810163`*^9}, {3.831791568157092*^9, 484 | 3.831791569253112*^9}},ExpressionUUID->"03111ad7-653a-48aa-8aee-\ 485 | 37bde2ec297b"], 486 | 487 | Cell[BoxData["\<\"method=sample adapt num_samples=2000 num_warmup=1500 \ 488 | \"\>"], "Output", 489 | CellChangeTimes->{3.831787176566696*^9, 3.831791570647738*^9, 490 | 3.93253837674551*^9},ExpressionUUID->"e74a3f50-bc8f-48e9-9345-0ea6032309d2"] 491 | }, Open ]] 492 | }, Open ]] 493 | }, Open ]] 494 | }, Open ]] 495 | }, Open ]] 496 | }, 497 | WindowSize->{950, 973}, 498 | WindowMargins->{{Automatic, 5}, {0, Automatic}}, 499 | FrontEndVersion->"11.2 for Linux x86 (64-bit) (September 10, 2017)", 500 | StyleDefinitions->"Default.nb" 501 | ] 502 | (* End of Notebook Content *) 503 | 504 | (* Internal cache information *) 505 | (*CellTagsOutline 506 | CellTagsIndex->{} 507 | *) 508 | (*CellTagsIndex 509 | CellTagsIndex->{} 510 | *) 511 | (*NotebookFileOutline 512 | Notebook[{ 513 | Cell[CellGroupData[{ 514 | Cell[580, 22, 166, 3, 99, "Title",ExpressionUUID->"6c9df950-effd-4a75-98b9-594765b3cb9a"], 515 | Cell[749, 27, 342, 7, 36, "Text",ExpressionUUID->"063e36e8-b776-4eb3-9a48-3064ac7f329d"], 516 | Cell[CellGroupData[{ 517 | Cell[1116, 38, 234, 4, 70, "Chapter",ExpressionUUID->"6f510c45-11cb-4e2f-be32-dcaf37cc5878"], 518 | Cell[1353, 44, 112, 1, 31, "Input",ExpressionUUID->"ce3eec43-69af-4ed0-92b8-45fd278972bc"], 519 | Cell[CellGroupData[{ 520 | Cell[1490, 49, 140, 2, 31, "Input",ExpressionUUID->"51cf99c6-20ba-4b00-92d3-c480b1206b66"], 521 | Cell[1633, 53, 163, 3, 35, "Output",ExpressionUUID->"eb98c0f8-747b-44e6-a95e-7ca5d12c5a06"] 522 | }, Open ]], 523 | Cell[1811, 59, 359, 8, 377, "Input",ExpressionUUID->"42fde992-f78f-4ae6-926b-edbc102ae5fa"], 524 | Cell[CellGroupData[{ 525 | Cell[2195, 71, 243, 5, 31, "Input",ExpressionUUID->"0904a970-98bb-4c54-a784-5d25c80699d1"], 526 | Cell[2441, 78, 273, 6, 35, "Output",ExpressionUUID->"61f4d2e2-3356-41d7-a9e4-6895a3b75e1f"] 527 | }, Open ]], 528 | Cell[CellGroupData[{ 529 | Cell[2751, 89, 1171, 36, 124, "Input",ExpressionUUID->"a2142860-3bba-4ca2-9652-742ebe54be57"], 530 | Cell[3925, 127, 3206, 71, 240, "Output",ExpressionUUID->"33c76108-b5c9-45ed-9390-8f82675e1bb0"] 531 | }, Open ]], 532 | Cell[CellGroupData[{ 533 | Cell[7168, 203, 425, 11, 55, "Input",ExpressionUUID->"27cd088e-faf8-444b-907b-9e9e08bb0198"], 534 | Cell[7596, 216, 1531, 32, 105, "Output",ExpressionUUID->"279359f0-8ed6-4f2c-85f7-1ea4bd10fced"] 535 | }, Open ]] 536 | }, Open ]], 537 | Cell[CellGroupData[{ 538 | Cell[9176, 254, 223, 4, 70, "Chapter",ExpressionUUID->"38906749-4dd4-4dbf-a5f1-04434d86abbb"], 539 | Cell[CellGroupData[{ 540 | Cell[9424, 262, 181, 3, 65, "Subchapter",ExpressionUUID->"a8c5e0e9-43e0-468e-90f2-0be61ab05be1"], 541 | Cell[CellGroupData[{ 542 | Cell[9630, 269, 275, 6, 31, "Input",ExpressionUUID->"598fa5f8-79c7-4551-bc78-a95fa6250481"], 543 | Cell[9908, 277, 358, 9, 35, "Output",ExpressionUUID->"629421c9-2819-4990-8b26-2904bf233517"] 544 | }, Open ]] 545 | }, Open ]], 546 | Cell[CellGroupData[{ 547 | Cell[10315, 292, 180, 3, 65, "Subchapter",ExpressionUUID->"b4c0447e-acc5-4313-ac3a-a6126e79b74e"], 548 | Cell[10498, 297, 722, 23, 396, "Text",ExpressionUUID->"e9ff3f7f-5805-4b32-8588-89c650e83760"], 549 | Cell[CellGroupData[{ 550 | Cell[11245, 324, 177, 3, 46, "Subsubsection",ExpressionUUID->"c2c4825f-6f39-4a5c-84ba-f599e98400b8"], 551 | Cell[CellGroupData[{ 552 | Cell[11447, 331, 300, 6, 31, "Input",ExpressionUUID->"0bd09745-72ef-41cf-846b-fffe33e1b4ea"], 553 | Cell[11750, 339, 268, 4, 35, "Output",ExpressionUUID->"241cd214-5fbb-4994-986e-a6513f3ba303"] 554 | }, Open ]] 555 | }, Open ]], 556 | Cell[CellGroupData[{ 557 | Cell[12067, 349, 169, 3, 46, "Subsubsection",ExpressionUUID->"65397619-55fe-4db8-9fd7-55613f200b45"], 558 | Cell[CellGroupData[{ 559 | Cell[12261, 356, 859, 19, 101, "Input",ExpressionUUID->"06358e83-262a-412c-834d-8257aa1bc1ab"], 560 | Cell[13123, 377, 310, 5, 35, "Output",ExpressionUUID->"c037b988-8798-40c8-a277-7a988385f446"], 561 | Cell[13436, 384, 328, 6, 35, "Output",ExpressionUUID->"8de4c49d-d618-4d7a-aef6-99b227b97916"], 562 | Cell[13767, 392, 368, 6, 35, "Output",ExpressionUUID->"333d5405-3d60-484a-9896-da03d1c5accf"] 563 | }, Open ]] 564 | }, Open ]], 565 | Cell[CellGroupData[{ 566 | Cell[14184, 404, 186, 3, 46, "Subsubsection",ExpressionUUID->"26f2eb13-50bd-457d-95ff-40104ba9b45f"], 567 | Cell[CellGroupData[{ 568 | Cell[14395, 411, 339, 7, 31, "Input",ExpressionUUID->"ba89db0f-22f3-46b8-9f90-3b20a0bd4f99"], 569 | Cell[14737, 420, 510, 11, 59, "Output",ExpressionUUID->"694d359a-bcae-443e-bbfb-6eb550d8f609"] 570 | }, Open ]] 571 | }, Open ]], 572 | Cell[CellGroupData[{ 573 | Cell[15296, 437, 171, 3, 55, "Subsection",ExpressionUUID->"ea9e4e8a-492c-4f01-bf89-582887fc0890"], 574 | Cell[CellGroupData[{ 575 | Cell[15492, 444, 413, 9, 78, "Input",ExpressionUUID->"ed1b181b-9329-4f10-9304-f09ef7c9ef84"], 576 | Cell[15908, 455, 152, 2, 35, "Output",ExpressionUUID->"5c1d69c2-dfb1-4d8a-8310-b625252c25ce"], 577 | Cell[16063, 459, 152, 3, 35, "Output",ExpressionUUID->"aefca5ae-cce7-48fd-9409-d48ecacfa19c"] 578 | }, Open ]] 579 | }, Open ]], 580 | Cell[CellGroupData[{ 581 | Cell[16264, 468, 247, 4, 55, "Subsection",ExpressionUUID->"b63b677e-17a9-4d05-a9e2-57201c1cc6de"], 582 | Cell[CellGroupData[{ 583 | Cell[16536, 476, 395, 8, 31, "Input",ExpressionUUID->"03111ad7-653a-48aa-8aee-37bde2ec297b"], 584 | Cell[16934, 486, 233, 3, 35, "Output",ExpressionUUID->"e74a3f50-bc8f-48e9-9345-0ea6032309d2"] 585 | }, Open ]] 586 | }, Open ]] 587 | }, Open ]] 588 | }, Open ]] 589 | }, Open ]] 590 | } 591 | ] 592 | *) 593 | 594 | -------------------------------------------------------------------------------- /CmdStan.m: -------------------------------------------------------------------------------- 1 | (* ::Package:: *) 2 | 3 | (* :Title: MathematicaStan, a MMA interface to CmdStan *) 4 | (* :Context: CmdStan` *) 5 | (* :Author: Vincent Picaud *) 6 | (* :Date: 2020 *) 7 | (* :Package Version: 2.1 *) 8 | (* :Mathematica Version: 11+ *) 9 | (* :Keywords: Stan, CmdStan, Bayesian *) 10 | 11 | 12 | BeginPackage["CmdStan`"]; 13 | 14 | Unprotect @@ Names["CmdStan`*"]; 15 | ClearAll @@ Names["CmdStan`*"]; 16 | 17 | 18 | (* ::Chapter:: *) 19 | (*Public declarations*) 20 | 21 | 22 | (* ::Subchapter:: *) 23 | (*Messages*) 24 | 25 | 26 | CmdStan::cmdStanDirectoryNotDefined="CmdStan directory does not exist, use SetCmdStanDirectory[dir] to define it. This is something like SetCmdStanDirectory[\"~/GitHub/cmdstan/\"]"; 27 | CmdStan::usage="Reserved symbol for error messages"; 28 | CmdStan::incorrectFileExtension="Expected \".`1`\", got \".`2`\""; 29 | CmdStan::stanExeNotFound="Stan executable \"`1`\" not found."; 30 | CmdStan::stanOutputFileNotFound="Stan output file \"`1`\" not found."; 31 | CmdStan::stanDataFileNotFound="Stan data file \"`1`\" not found."; 32 | CmdStan::OSsupport="MathematicaStan does not support this OS=`1`"; 33 | CmdStan::optionSupport="The option \"`1`\" is not supported in this context"; 34 | 35 | 36 | (* ::Subchapter:: *) 37 | (*Options*) 38 | 39 | 40 | StanVerbose::usage="A boolean option to define verbosity."; 41 | 42 | 43 | (* ::Subchapter:: *) 44 | (*Functions*) 45 | 46 | 47 | $CmdStanConfigurationFile; 48 | GetCmdStanDirectory; 49 | SetCmdStanDirectory; 50 | 51 | 52 | ExportStanCode; 53 | CompileStanCode; 54 | 55 | 56 | StanOptions; 57 | 58 | OptimizeDefaultOptions; 59 | SampleDefaultOptions; 60 | VariationalDefaultOptions; 61 | 62 | StanOptionExistsQ; 63 | GetStanOption; 64 | SetStanOption; 65 | RemoveStanOption; 66 | 67 | 68 | ExportStanData; 69 | 70 | 71 | RunStan; 72 | 73 | 74 | StanResult; 75 | ImportStanResult; 76 | 77 | 78 | GetStanResult; 79 | GetStanResultMeta; 80 | 81 | 82 | StanResultKeys; 83 | StanResultMetaKeys; 84 | StanResultReducedKeys; 85 | StanResultReducedMetaKeys; 86 | 87 | 88 | (* ::Chapter:: *) 89 | (*Private*) 90 | 91 | 92 | Begin["`Private`"]; 93 | 94 | 95 | (* ::Subchapter:: *) 96 | (*Stan options*) 97 | 98 | 99 | StanOptions::usage="A structure that holds options"; 100 | 101 | OptimizeDefaultOptions::usage="Default options for likelihood optimization"; 102 | SampleDefaultOptions::usage="Default options for HMC sampling"; 103 | VariationalDefaultOptions::usage="Default options for Variational Bayes"; 104 | 105 | OptimizeDefaultOptions=StanOptions[<|"method"->{"optimize",<||>}|>]; 106 | SampleDefaultOptions=StanOptions[<|"method"->{"sample",<||>}|>]; 107 | VariationalDefaultOptions=StanOptions[<|"method"->{"variational",<||>}|>]; 108 | 109 | 110 | (* ::Subchapter:: *) 111 | (*Files & Directories*) 112 | 113 | 114 | $CmdStanConfigurationFile::usage="User configuration file name. Mainly used to store CmdStan directory."; 115 | $CmdStanConfigurationFile=FileNameJoin[{$UserBaseDirectory,"ApplicationData","CmdStanConfigurationFile.txt"}]; 116 | 117 | 118 | GetCmdStanDirectoryQ[]:=FileExistsQ[$CmdStanConfigurationFile]&&DirectoryQ[Import[$CmdStanConfigurationFile]] 119 | 120 | 121 | GetCmdStanDirectory::usage="GetCmdStanDirectory[] returns CmdStan directory"; 122 | GetCmdStanDirectory[]=If[!GetCmdStanDirectoryQ[],Message[CmdStan::cmdStanDirectoryNotDefined];$Failed,Import[$CmdStanConfigurationFile]]; 123 | 124 | 125 | SetCmdStanDirectory::usage="SetCmdStanDirectory[directory_String] modifies CmdStanDirectory"; 126 | SetCmdStanDirectory[directory_String]:=(Export[$CmdStanConfigurationFile,directory];directory) 127 | 128 | 129 | (* ::Subchapter:: *) 130 | (*File extensions helper*) 131 | 132 | 133 | FileMultipleExtension[fileName_String]:= 134 | Module[{res}, 135 | res=StringSplit[FileNameTake@fileName,"."]; 136 | If[Length[res]==1, 137 | res="", 138 | res=StringTake[Fold[#1<>"."<>#2&,"",res[[2;;-1]]],2;;-1] 139 | ]; 140 | res 141 | ]; 142 | 143 | 144 | CheckFileNameExtensionQ[fileName_String, expectedExt_String] := 145 | Module[{ext,ok}, 146 | ext = FileMultipleExtension[fileName]; 147 | ok = ext == expectedExt; 148 | If[Not@ok,Message[CmdStan::incorrectFileExtension, expectedExt, ext]]; 149 | ok 150 | ]; 151 | 152 | 153 | (* Returns DirectoryName[stanFileName] or Directory[] if DirectoryName[stanFileName]=="" 154 | * One must avoid to have Path="" as FileNameJoin[{"","filename"}] returns /filename which is not we want 155 | *) 156 | getDirectory[filename_String] := If[DirectoryName[filename]!="",DirectoryName[filename],Assert[Directory[]!=""]; Directory[]]; 157 | 158 | (* Get directory/filename.ext *) 159 | getDirectoryFileName[filename_String] :=FileNameJoin[{getDirectory[filename], FileNameTake[filename]}]; 160 | 161 | (* Support multiple ext, by example /tmp/filename.data.R returns /tmp/filename *) 162 | getDirectoryFileNameWithoutExt[filename_String] :=FileNameJoin[{getDirectory[filename], FixedPoint[FileBaseName,filename]}]; 163 | 164 | (* modify \\ \[Rule] / in case of Windows OS (because of cygwin that needs / despite running under Windows) *) 165 | jeffPatterson[filename_String] := If[$OperatingSystem == "Windows", StringReplace[filename,"\\"->"/"],filename]; 166 | 167 | 168 | generateStanExecFileName[stanFileName_String] := 169 | Module[{stanExecFileName}, 170 | stanExecFileName = getDirectoryFileNameWithoutExt[stanFileName]; 171 | stanExecFileName = jeffPatterson[stanExecFileName]; 172 | If[$OperatingSystem == "Windows",stanExecFileName = stanExecFileName <> ".exe"]; 173 | stanExecFileName 174 | ]; 175 | 176 | generateStanDataFileName[stanFileName_String] := 177 | Module[{stanDataFileName}, 178 | (* caveat: use FixedPoint beacause of .data.R *) 179 | stanDataFileName = getDirectoryFileNameWithoutExt[stanFileName]; 180 | stanDataFileName = jeffPatterson[stanDataFileName]; (* not sure: to check *) 181 | stanDataFileName = stanDataFileName <> ".data.R"; 182 | stanDataFileName 183 | ]; 184 | 185 | generateStanOutputFileName[stanFileName_String,processId_Integer?NonNegative] := 186 | Module[{stanOutputFileName}, 187 | stanOutputFileName = getDirectoryFileNameWithoutExt[stanFileName]; 188 | If[processId>0, 189 | stanOutputFileName = stanOutputFileName <> "_" <> ToString[processId] 190 | ]; 191 | stanOutputFileName = jeffPatterson[stanOutputFileName]; (* not sure: to check *) 192 | stanOutputFileName = stanOutputFileName <> ".csv"; 193 | 194 | stanOutputFileName 195 | ]; 196 | 197 | 198 | (* ::Text:: *) 199 | (*A helper that escape space*) 200 | (*A priori mandatory to support spaces in path/filename when completing shell command*) 201 | (*However this is certainly useless as AFAIK Make does not support space anyway: https://stackoverflow.com/a/9838604/2001017*) 202 | 203 | 204 | escapeSpace[s_String]:=StringReplace[s,{"\\ "->"\\ "," "->"\\ "}]; 205 | 206 | 207 | (* ::Subchapter:: *) 208 | (*Stan code*) 209 | 210 | 211 | ExportStanCode::usage="ExportStanCode[stanCodeFileName_String, stanCode_String] exports Stan code, return filename WITH path (MMA export generally only returns the file name)"; 212 | 213 | ExportStanCode[stanCodeFileName_String, stanCode_String]:= 214 | Module[{dirStanCodeFileName, oldCode}, 215 | (* Check extension *) 216 | If[!CheckFileNameExtensionQ[stanCodeFileName,"stan"],Return[$Failed]]; 217 | 218 | (* add explicit dir *) 219 | dirStanCodeFileName=getDirectoryFileName[stanCodeFileName]; 220 | 221 | (* Check if code has changed, if not, do not overwrite file (=do nothing) *) 222 | If[FileExistsQ[dirStanCodeFileName],oldCode=Import[dirStanCodeFileName,"String"],oldCode=""]; 223 | 224 | If[oldCode!=stanCode, 225 | PrintTemporary["Stan code changed..."]; 226 | Export[dirStanCodeFileName,stanCode,"Text"], 227 | PrintTemporary["Identical Stan code."]; 228 | ]; 229 | 230 | dirStanCodeFileName 231 | ]; 232 | 233 | 234 | (* ::Subchapter:: *) 235 | (*Stan code compilation*) 236 | 237 | 238 | CompileStanCode::usage = "CompileStanCode[stanCodeFileName_String,opts] generates Stan executable (takes some time). Default options {StanVerbose -> True}"; 239 | 240 | Options[CompileStanCode] = {StanVerbose -> True}; 241 | 242 | CompileStanCode[stanCodeFileName_String, opts : OptionsPattern[]] := 243 | Module[{command, stanExecFileName, tmpFile, verbose, runprocessResult}, 244 | 245 | If[Not@CheckFileNameExtensionQ[stanCodeFileName, "stan"], Return[$Failed]]; 246 | 247 | stanExecFileName = generateStanExecFileName[stanCodeFileName]; 248 | (* Maybe useful for Windows https://mathematica.stackexchange.com/q/140700/42847 *) 249 | command = {"make","-C",escapeSpace[GetCmdStanDirectory[]],escapeSpace[stanExecFileName]}; 250 | 251 | verbose = OptionValue[StanVerbose]; 252 | If[verbose,Print["Running: ",StringRiffle[command," "]]]; 253 | runprocessResult = RunProcess[command]; 254 | If[verbose,Print[runprocessResult["StandardOutput"]]]; 255 | 256 | If[runprocessResult["ExitCode"]==0, stanExecFileName, Print[runprocessResult["StandardError"]]; $Failed] 257 | ]; 258 | 259 | 260 | (* ::Section:: *) 261 | (*Convert data to RData, dispatched according to input type*) 262 | 263 | 264 | (* ::Subsection:: *) 265 | (*Helper that forces scientific notation (use CForm for that)*) 266 | 267 | 268 | RDumpToStringHelper[V_?VectorQ]:="c("<>StringTake[ToString[Map[CForm,V]],{2,-2}]<>")"; 269 | 270 | 271 | (* ::Subsection:: *) 272 | (*Matrix*) 273 | 274 | 275 | (* CAVEAT: needs to transpose the matrix to get the right ordering: column major *) 276 | RDumpToString[MatName_String,M_?MatrixQ]:= 277 | MatName<>" <- structure("<>RDumpToStringHelper[Flatten[Transpose[M]]] <> 278 | ", .Dim = "<>RDumpToStringHelper[Dimensions[M]]<>")\n"; 279 | 280 | 281 | (* ::Subsection:: *) 282 | (*Vector*) 283 | 284 | 285 | RDumpToString[VectName_String,V_?VectorQ]:=VectName<>" <- "<>RDumpToStringHelper[V]<>"\n"; 286 | 287 | 288 | (* ::Subsection:: *) 289 | (*Scalar*) 290 | 291 | 292 | RDumpToString[VarName_String,Var_?NumberQ]:=VarName<>" <- " <>ToString[Var]<>"\n"; 293 | 294 | 295 | ExportStanData::usage = 296 | "ExportStanData[fileNameDataR_?StringQ,Rdata_Association] creates a .data.R file from an association <|\"variable_name\"->value...|>. value can be a scalar, a vector or a matrix"; 297 | 298 | ExportStanData[stanFileName_String,Rdata_Association]:= 299 | Module[{str,stanOutputFileName}, 300 | (* Add .data.R extension if required *) 301 | stanOutputFileName=generateStanDataFileName[stanFileName]; 302 | (* Open file and save data *) 303 | str=OpenWrite[stanOutputFileName]; 304 | If[str===$Failed,Return[$Failed]]; 305 | WriteString[str,StringJoin[KeyValueMap[RDumpToString[#,#2]&,Rdata]]]; 306 | Close[str]; 307 | stanOutputFileName 308 | ]; 309 | 310 | 311 | (* ::Subchapter:: *) 312 | (*Stan option management (Refactoring: simplify and use StanOption[Association]*) 313 | 314 | 315 | (* ::Section:: *) 316 | (*Command line string*) 317 | 318 | 319 | stanOptionToCommandLineString[opt_]:= 320 | Module[{optList,f,stack={}}, 321 | f[key_String->{value_,recurse_}]:=key<>"="<>ToString[value]<>" "<>stanOptionToCommandLineString[recurse]; 322 | f[key_String->{Null,recurse_}]:=key<>" "<>stanOptionToCommandLineString[recurse]; 323 | f[other_List]:=stanOptionToCommandLineString[other]; 324 | 325 | optList=Normal[opt]; 326 | Scan[AppendTo[stack,f[#]]&,optList]; 327 | StringJoin[stack] 328 | ]; 329 | 330 | 331 | Format[StanOptions[opt_Association]] := stanOptionToCommandLineString[opt]; 332 | 333 | 334 | (* ::Section:: *) 335 | (*Split option string*) 336 | 337 | 338 | splitOptionString[keys_String]:=StringSplit[keys,"."]; 339 | 340 | 341 | (* ::Section:: *) 342 | (*Check option (it it exists)*) 343 | 344 | 345 | (* ::Text:: *) 346 | (*Needs FoldWhile (see https://mathematica.stackexchange.com/questions/19102/foldwhile-and-foldwhilelist )*) 347 | 348 | 349 | foldWhile[f_,test_,start_,secargs_List]:= 350 | Module[{last=start},Fold[If[test[##],last=f[##],Return[last,Fold]]&,start,secargs]]; 351 | 352 | 353 | stanOptionExistsQ[StanOptions[opt_Association],{keys__String}]:= 354 | Module[{status},foldWhile[Last[#1][#2]&,(status=KeyExistsQ[Last[#1],#2])&,{"",opt},{keys}];status] 355 | 356 | 357 | StanOptionExistsQ::usage="StanOptionExistsQ[opt_StanOptions,optionString_String] check if the option exists"; 358 | stanOptionExistsQ[opt_StanOptions,optionString_String]:=stanOptionExistsQ[opt,splitOptionString[optionString]]; 359 | 360 | 361 | (* ::Section:: *) 362 | (*Get option*) 363 | 364 | 365 | getStanOption[StanOptions[opt_Association],{keys__String}]:= 366 | Module[{status,extracted}, 367 | extracted=foldWhile[Last[#1][#2]&,(status=KeyExistsQ[Last[#1],#2])&,{"",opt},{keys}]; 368 | If[status,extracted,$Failed] 369 | ]; 370 | getStanOptionValue[opt_StanOptions,{keys__String}]:=With[{result=getStanOption[opt,{keys}]},If[result===$Failed,result,First[result]]]; 371 | 372 | 373 | GetStanOption::usage="GetStanOption[opt_StanOptions, optionString_String] return Stan option value, $Failed if the option is not defined"; 374 | 375 | GetStanOption[opt_StanOptions, optionString_String]:=getStanOptionValue[opt,splitOptionString[optionString]]; 376 | 377 | 378 | (* ::Section:: *) 379 | (*Set option*) 380 | 381 | 382 | (* ::Text:: *) 383 | (*Compared to the SO answer the Merge associated function nestedMerge[] merge the assoc[[All, 2]] association, value is set to the last not Null element (this is the role of nestedMergeHelper[])*) 384 | 385 | 386 | nestedMerge[assoc : {__Association}] := Merge[assoc, nestedMerge]; 387 | nestedMergeHelper[arg_List] := With[{cleaned = Select[arg, Not[# === Null] &]}, If[cleaned == {}, Null, Last[cleaned]]]; 388 | nestedMerge[assoc : {{_, __Association} ..}] := {nestedMergeHelper[assoc[[All, 1]]], Merge[assoc[[All, 2]], nestedMerge]}; 389 | 390 | 391 | setStanOption[StanOptions[org_Association], {keys__String}, value_] := Module[{tmp}, 392 | tmp = {org, Fold[ <|#2 -> If[AssociationQ[#], {Null, #}, #]|> &, {value, <||>}, Reverse@{keys}]}; 393 | StanOptions[nestedMerge[tmp]] 394 | ]; 395 | 396 | 397 | SetStanOption::usage="SetStanOption[opt_StanOptions, optionString_String, value_] add or overwrite the given Stan option."; 398 | SetStanOption[opt_StanOptions, optionString_String, value_] := setStanOption[opt,splitOptionString[optionString],value]; 399 | 400 | 401 | (* ::Section:: *) 402 | (*Delete option*) 403 | 404 | 405 | removeStanOption[StanOptions[org_Association], {oneKey_}]:=StanOptions[KeyDrop[org,oneKey]]; 406 | 407 | removeStanOption[StanOptions[org_Association], {keys__,last_}]:= 408 | Module[{extracted,buffer,indices}, 409 | If[StanOptionExistsQ[StanOptions[org], {keys,last}]===False,Return[StanOptions[org]]]; (* nothing to do the key path does not exist *) 410 | buffer=org; 411 | indices=Riffle[{keys},ConstantArray[2,Length[{keys}]]]; 412 | KeyDropFrom[buffer[[Apply[Sequence,indices]]],last]; 413 | buffer=FixedPoint[DeleteCases[# ,{Null,<||>},-1]&,buffer]; 414 | StanOptions[buffer] 415 | ]; 416 | 417 | 418 | RemoveStanOption::usage="RemoveStanOption[opt_StanOptions, optionString_String] remove the given option."; 419 | 420 | RemoveStanOption[opt_StanOptions, optionString_String]:=removeStanOption[opt,splitOptionString[optionString]]; 421 | 422 | 423 | (* ::Section:: *) 424 | (*Some helpers*) 425 | 426 | 427 | completeStanOptionWithDataFileName[stanFileName_String, stanOption_StanOptions] := 428 | Module[{stanDataFileName}, 429 | (* 430 | * Check if there is a data file name in option, 431 | * if not, try to create one from scratch 432 | *) 433 | stanDataFileName = GetStanOption[stanOption,"data.file"]; 434 | If[stanDataFileName === $Failed, 435 | stanDataFileName = generateStanDataFileName[stanFileName]; 436 | ]; 437 | Assert[CheckFileNameExtensionQ[stanDataFileName, "data.R"]]; 438 | 439 | SetStanOption[stanOption,"data.file", escapeSpace[stanDataFileName]] 440 | ]; 441 | 442 | completeStanOptionWithOutputFileName[stanFileName_String, stanOption_StanOptions, processId_?IntegerQ] := 443 | Module[{stanOutputFileName}, 444 | 445 | (* 446 | * Check if there is a output file name in option, 447 | * if not, try to create one from scratch 448 | *) 449 | stanOutputFileName = GetStanOption[stanOption,"output.file"]; 450 | 451 | If[stanOutputFileName === $Failed, 452 | stanOutputFileName = generateStanOutputFileName[stanFileName,processId]; 453 | ]; 454 | Assert[CheckFileNameExtensionQ[stanOutputFileName, "csv"]]; 455 | 456 | SetStanOption[stanOption,"output.file", escapeSpace[stanOutputFileName]] 457 | ]; 458 | 459 | 460 | (* ::Subchapter:: *) 461 | (*Stan Run*) 462 | 463 | 464 | RunStan::usage="RunStan[stanFileName_String, stanOption_StanOptions, opts : OptionsPattern[]] runs Stan."; 465 | 466 | Options[RunStan] = {StanVerbose -> True}; 467 | 468 | RunStan[stanFileName_String, stanOption_StanOptions, opts : OptionsPattern[]] := 469 | Module[{pathExecFileName, mutableOption, command, output, verbose, runprocessResult }, 470 | (* Generate Executable file name (absolute path) 471 | *) 472 | pathExecFileName = generateStanExecFileName[stanFileName]; 473 | If[pathExecFileName === $Failed, Return[$Failed]]; 474 | 475 | (* Generate Data file name (absolute path) and add it to stanOption list *) 476 | mutableOption = completeStanOptionWithDataFileName[pathExecFileName, stanOption]; 477 | If[mutableOption === $Failed, Return[$Failed]]; 478 | 479 | (* Generat Output file name *) 480 | mutableOption = completeStanOptionWithOutputFileName[stanFileName, mutableOption, 0]; (* 0 means -> only ONE output (sequential) *) 481 | 482 | (* Extract stanOptions and compute! *) 483 | command = {pathExecFileName}; 484 | command = Join[command,StringSplit[stanOptionToCommandLineString[mutableOption]," "]]; 485 | 486 | verbose = OptionValue[StanVerbose]; 487 | If[verbose, Print["Running: ", StringRiffle[command, " "]]]; 488 | runprocessResult = RunProcess[command]; 489 | If[verbose, Print[runprocessResult["StandardOutput"]]]; 490 | 491 | If[runprocessResult["ExitCode"] == 0, GetStanOption[mutableOption,"output.file"], Print[runprocessResult["StandardError"]]; $Failed] 492 | ]; 493 | 494 | 495 | (* ::Subchapter:: *) 496 | (*TODO add Stan Parallel HMC*) 497 | 498 | 499 | (* TODO: pour l'instant rien fait.... s'inspirer de RunStanOptimize etc...*) 500 | RunStanSample[stanFileName_String,NJobs_/; NumberQ[NJobs] && (NJobs > 0)]:= 501 | Module[{id,i,pathExecFileName,mutableOption,bufferMutableOption,shellScript="",finalOutputFileName,finalOutputFileNameID,output}, 502 | 503 | (* Initialize with user stanOption *) 504 | mutableOption=Join[immutableStanOptionSample,StanOptionSample[]]; 505 | 506 | If[GetStanOptionPosition["id",mutableOption]!={}, 507 | Message[RunStanSample::optionNotSupported,"id"]; 508 | Return[$Failed]; 509 | ]; 510 | 511 | (* Generate Executable file name (absolute path) 512 | *) 513 | pathExecFileName=generateStanExecFileName[stanFileName]; 514 | If[pathExecFileName===$Failed,Return[$Failed]]; 515 | 516 | (* Generate Data filen ame (absolute path) and add it to stanOption list 517 | *) 518 | mutableOption=completeStanOptionWithDataFileName[pathExecFileName,mutableOption]; 519 | If[mutableOption===$Failed,Return[$Failed]]; 520 | 521 | (* Generate script header 522 | *) 523 | If[$OperatingSystem=="Windows", 524 | 525 | (* OS = Windows 526 | *) 527 | Message[CmdStan::OSsupport,$OperatingSystem]; 528 | Return[$Failed], 529 | 530 | (* OS = Others (Linux) 531 | *) 532 | shellScript=shellScript<>"\n#!/bin/bash"; 533 | ]; 534 | 535 | (* Generate the list of commands: one command per id 536 | * - process id : "id" stanOption 537 | * - output filename : "output file" stanOption 538 | *) 539 | For[id=1,id<=NJobs,id++, 540 | (* Create output_ID.csv filename *) 541 | bufferMutableOption=completeStanOptionWithOutputFileName[stanFileName,mutableOption,id]; 542 | 543 | (* Create the ID=id stanOption *) 544 | bufferMutableOption=SetStanOption[{{"id",id}}, bufferMutableOption]; 545 | 546 | (* Form a complete shell comand including the executable *) 547 | If[$OperatingSystem=="Windows", 548 | 549 | (* OS = Windows 550 | *) 551 | Message[CmdStan::OSsupport,$OperatingSystem]; 552 | Return[$Failed], 553 | 554 | (* OS = Others (Linux) 555 | *) 556 | shellScript=shellScript<>"\n{ ("<>quoted[pathExecFileName]<>" "<>stanOptionToCommandLineString[bufferMutableOption]<>") } &"; 557 | ]; 558 | ]; (* For id *) 559 | 560 | (* Wait for jobs 561 | *) 562 | If[$OperatingSystem=="Windows", 563 | 564 | (* OS = Windows 565 | *) 566 | Message[CmdStan::OSsupport,$OperatingSystem]; 567 | Return[$Failed], 568 | 569 | (* OS = Others (Linux) 570 | *) 571 | shellScript=shellScript<>"\nwait"; 572 | ]; 573 | 574 | (* Recreate the correct output file name (id=0 and id=1) 575 | * id=0 generate the final output file name + bash script filename 576 | * id=1 generate ths csv header 577 | *) 578 | finalOutputFileName=GetStanOption["output.file",completeStanOptionWithOutputFileName[stanFileName,mutableOption,0]]; 579 | 580 | If[$OperatingSystem=="Windows", 581 | 582 | (* OS = Windows 583 | *) 584 | Message[CmdStan::OSsupport,$OperatingSystem]; 585 | Return[$Failed], 586 | 587 | (* OS = Others (Linux) 588 | *) 589 | For[id=1,id<=NJobs,id++, 590 | finalOutputFileNameID=GetStanOption["output.file",completeStanOptionWithOutputFileName[stanFileName,mutableOption,id]]; 591 | If[id==1, 592 | (* Create a unique output file *) 593 | shellScript=shellScript<>"\ngrep lp__ " <> finalOutputFileNameID <> " > " <> finalOutputFileName; 594 | ]; 595 | shellScript=shellScript<>"\nsed '/^[#l]/d' " <> finalOutputFileNameID <> " >> " <> finalOutputFileName; 596 | ]; 597 | (* Export the final script, TODO: escape space *) 598 | finalOutputFileNameID=StanRemoveFileNameExt[finalOutputFileName]<>".sh"; (* erase with script file name *) 599 | Export[finalOutputFileNameID,shellScript,"Text"]; 600 | (* Execute it! *) 601 | output=Import["!sh "<>finalOutputFileNameID<>" 2>&1","Text"]; 602 | ]; 603 | 604 | Return[output]; 605 | ]; 606 | 607 | 608 | (* ::Chapter:: *) 609 | (*Import CSV file*) 610 | 611 | 612 | (* ::Subchapter:: *) 613 | (*Structure*) 614 | 615 | 616 | StanResult::usage="A structure to store Stan Result"; 617 | 618 | 619 | (* ::Section:: *) 620 | (*Helper for pretty prints of variables*) 621 | 622 | 623 | makePairNameIndex[varName_String]:=StringSplit[varName,"."] /. {name_String,idx___}:> {name,ToExpression /@ {idx}}; 624 | 625 | 626 | varNameAsString[data_Association]:= 627 | Module[{tmp}, 628 | tmp=GroupBy[makePairNameIndex /@ Keys[data],First->Last]; 629 | tmp=Map[Max,Map[Transpose,tmp],{2}]; 630 | tmp=Map[First[#]<>" "<>StringRiffle[Last[#],"x"]&,Normal[tmp]]; 631 | tmp=StringRiffle[tmp,", "]; 632 | tmp 633 | ]; 634 | 635 | (*varNameAsString[result_StanResult]:=varNameAsString[First[result]["parameter"]];*) 636 | 637 | 638 | (* ::Subchapter:: *) 639 | (*Import routine*) 640 | 641 | 642 | ImportStanResult::usage="ImportStanResult[outputCSV_?StringQ] import csv stan output file and return a StanResult structure."; 643 | 644 | ImportStanResult[outputCSV_?StringQ]:= 645 | Module[{data,headerParameter,headerMeta,stringParameter,numericParameter,output}, 646 | If[!CheckFileNameExtensionQ[outputCSV,"csv"],Return[$Failed]]; 647 | If[!FileExistsQ[outputCSV],Message[CmdStan::stanOutputFileNotFound,outputCSV];Return[$Failed];]; 648 | 649 | data=Import[outputCSV]; 650 | data=GroupBy[data,Head[First[#]]&]; (* split string vs numeric *) 651 | stringParameter=data[String]; 652 | data=KeyDrop[data,String]; 653 | numericParameter=Transpose[First[data[]]]; 654 | data=GroupBy[stringParameter,StringTake[First[#],{1}]&]; (* split # vs other (header) *) 655 | Assert[Length[Keys[data]]==2]; (* # and other *) 656 | stringParameter=data["#"]; (* get all strings beginning by # *) 657 | data=First[KeyDrop[data,"#"]];(* get other string = one line which is header *) 658 | headerMeta=Select[First[data],(StringTake[#,{-1}]=="_")&]; 659 | headerParameter=Select[First[data],(StringTake[#,{-1}]!="_")&]; 660 | output=<||>; 661 | output["filename"]=outputCSV; 662 | output["meta"]=Association[Thread[headerMeta->numericParameter[[1;;Length[headerMeta]]]]]; 663 | output["parameter"]=Association[Thread[headerParameter->numericParameter[[Length[headerMeta]+1;;-1]]]]; 664 | output["internal"]=<|"pretty_print_parameter"->varNameAsString[output["parameter"]], 665 | "pretty_print_meta"->varNameAsString[output["meta"]], 666 | "comments"->StringJoin[Riffle[Map[ToString,stringParameter,{2}],"\n"]]|>; 667 | 668 | StanResult[output] 669 | ]; 670 | 671 | 672 | Format[StanResult[opt_Association]]:=" file: "<>opt["filename"]<>"\n meta: "<>opt["internal"]["pretty_print_meta"]<>"\nparameter: "<>opt["internal"]["pretty_print_parameter"]; 673 | 674 | 675 | (* ::Subchapter:: *) 676 | (*Get Result*) 677 | 678 | 679 | (* ::Section:: *) 680 | (*Helper*) 681 | 682 | 683 | (* ::Text:: *) 684 | (*Given an association try to find the value from the key*) 685 | (*If the key does not exist try to find an array (in the form of key.X.X...)*) 686 | (*If does not exit $Failed*) 687 | 688 | 689 | createArray[data_Association,varName_String]:= 690 | Module[{extracted,index,values,dim,array}, 691 | extracted=KeySelect[data,First[StringSplit[#,"."]]==varName&]; 692 | If[extracted==<||>,Print["missing key"];Return[$Failed]]; 693 | If[Keys[extracted]=={varName},Print["is a scalar and not an array"];Return[$Failed]]; 694 | index=GroupBy[makePairNameIndex /@ Keys[extracted],First->Last]; 695 | index=index[varName]; 696 | values=Values[extracted]; 697 | dim=Map[Max,Transpose[index]]; 698 | array=ConstantArray["NA",dim]; 699 | Scan[(array[[Apply[Sequence,Keys[#]]]]=Values[#])&,Thread[index->values]]; 700 | array 701 | ]; 702 | 703 | 704 | getStanResult[data_Association,varName_String]:=If[KeyExistsQ[data,varName],data[varName],createArray[data,varName]]; 705 | 706 | 707 | (* ::Section:: *) 708 | (*Public*) 709 | 710 | 711 | GetStanResult::usage= 712 | "GetStanResult[result_StanResult,parameterName_String] returns the parameter from its name"<> 713 | "\nGetStanResult[(f_Function|f_Symbol),result_StanResult,parameterName_String] returns f[parameter] from its name."; 714 | GetStanResult[result_StanResult,parameterName_String] := getStanResult[First[result]["parameter"],parameterName]; 715 | GetStanResult[(f_Function|f_Symbol),result_StanResult,parameterName_String] := Map[f,GetStanResult[result,parameterName],{-2}]; 716 | 717 | 718 | GetStanResultMeta::usage= 719 | "GetStanResultMeta[res_StanResult,metaName_String] return meta data form its name."<> 720 | "\nGetStanResultMeta[(f_Function|f_Symbol),result_StanResult,metaName_String] returns the f[meta] form its name."; 721 | GetStanResultMeta[result_StanResult,metaName_String] := getStanResult[First[result]["meta"],metaName]; 722 | GetStanResultMeta[(f_Function|f_Symbol),result_StanResult,metaName_String] := Map[f,GetStanResultMeta[result,metaName],{-2}]; 723 | 724 | 725 | (* ::Subsection:: *) 726 | (*Get keys: for arrays only return the "main" key without indices*) 727 | 728 | 729 | (* ::Subsubsection:: *) 730 | (*Helper*) 731 | 732 | 733 | stanResultKeys[result_StanResult,key_String]:=Keys[First[result][key]] 734 | 735 | 736 | stanResultReducedKeys[result_StanResult,key_String]:=DeleteDuplicates[Map[First[StringSplit[#,"."]]&,stanResultKeys[result,key]]]; 737 | 738 | 739 | (* ::Subsubsection:: *) 740 | (*public*) 741 | 742 | 743 | StanResultKeys::usage="StanResultKeys[result_StanResult] returns the list of parameter names."; 744 | StanResultKeys[result_StanResult]:=stanResultKeys[result,"parameter"]; 745 | 746 | 747 | StanResultMetaKeys::usage="StanResultMetaKeys[result_StanResult] returns the list of meta parameter names."; 748 | StanResultMetaKeys[result_StanResult]:=stanResultKeys[result,"meta"]; 749 | 750 | 751 | StanResultReducedKeys::usage="StanResultReducedKeys[result_StanResult] returns the list of parameter names. Attention for arrays param.X or param.X.X returns only the prefix \"param\""; 752 | StanResultReducedKeys[result_StanResult]:=stanResultReducedKeys[result,"parameter"]; 753 | 754 | 755 | StanResultReducedMetaKeys::usage="StanResultReducedMetaKeys[result_StanResult] returns the list of meta parameter names. Attention for arrays param.X or param.X.X returns only the prefix \"param\""; 756 | StanResultReducedMetaKeys[result_StanResult]:=stanResultReducedKeys[result,"meta"]; 757 | 758 | 759 | (* ::Subsection:: *) 760 | (*With extra function*) 761 | 762 | 763 | End[]; (* Private *) 764 | 765 | 766 | Protect @@ Names["CmdStan`*"]; 767 | 768 | EndPackage[]; 769 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+OPTIONS: toc:nil todo:nil pri:nil tags:nil ^:nil tex:t 2 | #+TITLE: MathematicaStan v2.2 3 | #+SUBTITLE: A Mathematica (v11+) package to interact with CmdStan 4 | #+AUTHOR: Picaud Vincent 5 | 6 | [[https://zenodo.org/doi/10.5281/zenodo.10810144][file:https://zenodo.org/badge/66637604.svg]] 7 | 8 | * Table of contents :TOC_3:noexport: 9 | - [[#introduction][Introduction]] 10 | - [[#news][News]] 11 | - [[#2024-08-13][2024-08-13]] 12 | - [[#2020-12-21][2020-12-21]] 13 | - [[#2019-06-28][2019-06-28]] 14 | - [[#installation][Installation]] 15 | - [[#the-stan-cmdstan-shell-interface][The Stan CmdStan shell interface]] 16 | - [[#the-mathematica-cmdstan-package][The Mathematica CmdStan package]] 17 | - [[#first-run][First run]] 18 | - [[#tutorial-1-linear-regression][Tutorial 1, linear regression]] 19 | - [[#introduction-1][Introduction]] 20 | - [[#stan-code][Stan code]] 21 | - [[#code-compilation][Code compilation]] 22 | - [[#simulated-data][Simulated data]] 23 | - [[#create-the-datar-data-file][Create the =data.R= data file]] 24 | - [[#run-stan-likelihood-maximization][Run Stan, likelihood maximization]] 25 | - [[#load-the-csv-result-file][Load the CSV result file]] 26 | - [[#run-stan-variational-bayes][Run Stan, Variational Bayes]] 27 | - [[#more-about-option-management][More about Option management]] 28 | - [[#overwriting-default-values][Overwriting default values]] 29 | - [[#reading-customized-values][Reading customized values]] 30 | - [[#erasing-customized-option-values][Erasing customized option values]] 31 | - [[#tutorial-2-linear-regression-with-more-than-one-predictor][Tutorial 2, linear regression with more than one predictor]] 32 | - [[#parameter-arrays][Parameter arrays]] 33 | - [[#simulated-data-1][Simulated data]] 34 | - [[#exporting-data][Exporting data]] 35 | - [[#run-stan-hmc-sampling][Run Stan, HMC sampling]] 36 | - [[#load-the-csv-result-file-1][Load the CSV result file]] 37 | - [[#unit-tests][Unit tests]] 38 | 39 | * Introduction 40 | 41 | *MathematicaStan* is a package to interact with [[http://mc-stan.org/interfaces/cmdstan][CmdStan]] from 42 | Mathematica. 43 | 44 | It is developed under *Linux* and is compatible with *Mathematica v11+* 45 | 46 | It should work under *MacOS* and also under *Windows*. 47 | 48 | *Author & contact:* picaud.vincent at gmail.com 49 | 50 | ** News 51 | 52 | *** 2024-08-13 53 | 54 | *New MathematicaStan version 2.2!* 55 | 56 | *Package test with last CmdStan v2.35.0, Mathematica 11.2, Linux* 57 | 58 | - Add some screenshots to the install procedure section 59 | 60 | - CmdStan syntax changes have been included : 61 | |----------------------------+-----------------------------------| 62 | | old | current | 63 | |----------------------------+-----------------------------------| 64 | | <- | = | 65 | | increment_log_prob(...) | target += ... | 66 | | int y[N]; | array[N] int y; | 67 | |----------------------------+-----------------------------------| 68 | 69 | - Check that unit tests and examples work. 70 | 71 | *** 2020-12-21 72 | 73 | *New MathematicaStan version 2.1!* 74 | 75 | This version has been fixed and should now run under Windows. 76 | 77 | I would like to thank *Ali Ghaderi* who had the patience to help me to 78 | debug the Windows version (I do not have access to this OS). Nothing 79 | would have been possible without him. All possibly remaining bugs are 80 | mine. 81 | 82 | As a remainder also note that one should not use path/filename with 83 | spaces (=Make= really does not like that). This consign is also true 84 | under Linux or MacOS. See [[https://stackoverflow.com/questions/9838384/can-gnu-make-handle-filenames-with-spaces][SO:can-gnu-make-handle-filenames-with-spaces]] 85 | by example. 86 | 87 | *** 2019-06-28 88 | 89 | *New MathematicaStan version 2.0!* 90 | 91 | This version uses Mathematica v11 and has been completely refactored 92 | 93 | *Caveat:* breaking changes! 94 | 95 | *Note*: the "old" MathematicaStan version based on Mathematica v8.0 is now archived in 96 | the [[https://github.com/stan-dev/MathematicaStan/tree/v1][v1 git branch]]. 97 | 98 | * Installation 99 | 100 | ** The Stan CmdStan shell interface 101 | 102 | First you must install [[http://mc-stan.org/interfaces/cmdstan][CmdStan]]. Once this is done you get a directory containing stuff like: 103 | 104 | #+BEGIN_EXAMPLE 105 | bin doc examples Jenkinsfile LICENSE make makefile README.md runCmdStanTests.py src stan test-all.sh 106 | #+END_EXAMPLE 107 | 108 | With my configuration *CmdStan* is installed in: 109 | #+BEGIN_EXAMPLE 110 | ~/ExternalSoftware/cmdstan-2.35.0 111 | #+END_EXAMPLE 112 | 113 | For Windows users it is possibly something like: 114 | #+BEGIN_EXAMPLE 115 | C:\\Users\\USER_NAME\\Documents\\R\\cmdstan-?.??.? 116 | #+END_EXAMPLE 117 | 118 | ** The Mathematica CmdStan package 119 | 120 | To install the Mathematica CmdStan package: 121 | - open the =CmdStan.m= file with Mathematica. 122 | - install it using the Mathematica Notebook *File->Install* menu. 123 | 124 | Fill in the pop-up windows as follows: 125 | [[file:figures/install.png]] 126 | 127 | ** First run 128 | 129 | The first time the package is imported 130 | #+BEGIN_SRC mathematica :eval never 131 | < False] 248 | #+END_SRC 249 | 250 | ** Simulated data 251 | 252 | Let's simulate some data: 253 | #+BEGIN_SRC mathematica :eval never 254 | σ = 3; α = 1; β = 2; 255 | n = 20; 256 | X = Range[n]; 257 | Y = α + β*X + RandomVariate[NormalDistribution[0, σ], n]; 258 | Show[Plot[α + β*x, {x, Min[X], Max[X]}], 259 | ListPlot[Transpose@{X, Y}, PlotStyle -> Red]] 260 | #+END_SRC 261 | 262 | [[file:figures/linRegData.png][file:./figures/linRegData.png]] 263 | 264 | ** Create the =data.R= data file 265 | 266 | The data are stored in a =Association= and then exported thanks to the 267 | =ExportStanData= function. 268 | 269 | #+BEGIN_SRC mathematica :eval never 270 | stanData = <|"N" -> n, "x" -> X, "y" -> Y|>; 271 | stanDataFile = ExportStanData[stanExeFile, stanData] 272 | #+END_SRC 273 | 274 | #+BEGIN_EXAMPLE 275 | /tmp/linear_regression.data.R 276 | #+END_EXAMPLE 277 | 278 | *Note:* this function returns the created file 279 | name =/tmp/linear_regression.data.R=. Its first argument, =stanExeFile= 280 | is simply the Stan executable file name with its path. The 281 | =ExportStanData[]= function modifies the file name extension and 282 | replace it with ".data.R", but you can use it with 283 | any file name: 284 | #+BEGIN_SRC mathematica :eval never 285 | ExportStanData["my_custom_path/my_custom_filename.data.R",stanData] 286 | #+END_SRC 287 | 288 | ** Run Stan, likelihood maximization 289 | 290 | We are now able to run the =stanExeFile= executable. 291 | 292 | Let's start by maximizing the likelihood 293 | #+BEGIN_SRC mathematica :eval never 294 | stanResultFile = RunStan[stanExeFile, OptimizeDefaultOptions] 295 | #+END_SRC 296 | 297 | #+BEGIN_EXAMPLE 298 | Running: /tmp/linear_regression method=optimize data file=/tmp/linear_regression.data.R output file=/tmp/linear_regression.csv 299 | 300 | method = optimize 301 | optimize 302 | algorithm = lbfgs (Default) 303 | lbfgs 304 | init_alpha = 0.001 (Default) 305 | tol_obj = 9.9999999999999998e-13 (Default) 306 | tol_rel_obj = 10000 (Default) 307 | tol_grad = 1e-08 (Default) 308 | tol_rel_grad = 10000000 (Default) 309 | tol_param = 1e-08 (Default) 310 | history_size = 5 (Default) 311 | iter = 2000 (Default) 312 | save_iterations = 0 (Default) 313 | id = 0 (Default) 314 | data 315 | file = /tmp/linear_regression.data.R 316 | init = 2 (Default) 317 | random 318 | seed = 2775739062 319 | output 320 | file = /tmp/linear_regression.csv 321 | diagnostic_file = (Default) 322 | refresh = 100 (Default) 323 | 324 | Initial log joint probability = -8459.75 325 | Iter log prob ||dx|| ||grad|| alpha alpha0 # evals Notes 326 | 19 -32.5116 0.00318011 0.00121546 0.9563 0.9563 52 327 | Optimization terminated normally: 328 | Convergence detected: relative gradient magnitude is below tolerance 329 | #+END_EXAMPLE 330 | 331 | The =stanResultFile= variable contains now the csv result file: 332 | #+BEGIN_EXAMPLE 333 | /tmp/linear_regression.csv 334 | #+END_EXAMPLE 335 | 336 | *Note:* again, if you do not want to have printed output, use the =StanVerbose->False= option. 337 | 338 | #+BEGIN_SRC mathematica :eval never 339 | stanResultFile = RunStan[stanExeFile, OptimizeDefaultOptions,StanVerbose->False] 340 | #+END_SRC 341 | 342 | *Note:* the method we use is defined by the second argument 343 | =OptimizeDefaultOptions.= If you want to use Variational Bayes or HMC 344 | sampling you must use 345 | 346 | #+BEGIN_SRC mathematica :eval never 347 | RunStan[stanExeFile, VariationalDefaultOptions] 348 | #+END_SRC 349 | or 350 | #+BEGIN_SRC mathematica :eval never 351 | RunStan[stanExeFile, SampleDefaultOptions] 352 | #+END_SRC 353 | 354 | *Note*: option management will be detailed later in this tutorial. 355 | 356 | ** Load the CSV result file 357 | 358 | To load CSV result file, do 359 | 360 | #+BEGIN_SRC mathematica :eval never 361 | stanResult = ImportStanResult[stanResultFile] 362 | #+END_SRC 363 | 364 | which prints 365 | #+BEGIN_EXAMPLE 366 | file: /tmp/linear_regression.csv 367 | meta: lp__ 368 | parameter: alpha , beta , sigma 369 | #+END_EXAMPLE 370 | 371 | To access estimated variable α, β and σ, simply do: 372 | #+BEGIN_SRC mathematica :eval never 373 | 374 | GetStanResultMeta[stanResult, "lp__"] 375 | αe=GetStanResult[stanResult, "alpha"] 376 | βe=GetStanResult[stanResult, "beta"] 377 | σe=GetStanResult[stanResult, "sigma"] 378 | #+END_SRC 379 | 380 | which prints: 381 | 382 | #+BEGIN_EXAMPLE 383 | {-32.5116} 384 | {2.51749} 385 | {1.83654} 386 | {3.08191} 387 | #+END_EXAMPLE 388 | 389 | *Note*: as with likelihood maximization we only have a point estimation, 390 | the returned values are lists of *one* number. 391 | 392 | You can plot the estimated line: 393 | 394 | #+BEGIN_SRC mathematica :eval never 395 | Show[Plot[{αe + βe*x, α + β*x}, {x, Min[X],Max[X]}, PlotLegends -> "Expressions"], 396 | ListPlot[Transpose@{X, Y}, PlotStyle -> Red]] 397 | #+END_SRC 398 | 399 | [[file:./figures/linRegEstimate.png]] 400 | 401 | ** Run Stan, Variational Bayes 402 | 403 | We want to solve the same problem but using variational inference. 404 | 405 | As explained before we must use 406 | #+BEGIN_SRC mathematica :eval never 407 | stanResultFile = RunStan[stanExeFile, VariationalDefaultOptions] 408 | #+END_SRC 409 | instead of 410 | #+BEGIN_SRC mathematica :eval never 411 | stanResultFile = RunStan[stanExeFile, OptimizeDefaultOptions] 412 | #+END_SRC 413 | 414 | However, please note that running this command will erase 415 | =stanResultFile= which is the file where result are exported. To avoid 416 | this we can modify the output file name by modifying option values. 417 | 418 | The default option values are stored in the write-protected 419 | =VariationalDefaultOptions= variable. 420 | 421 | To modify them we must first copy this protected symbol: 422 | 423 | #+BEGIN_SRC mathematica :eval never 424 | myOpt=VariationalDefaultOptions 425 | #+END_SRC 426 | which prints 427 | #+BEGIN_EXAMPLE 428 | method=variational 429 | #+END_EXAMPLE 430 | 431 | The option values are printed when you run the =RunStan= command: 432 | 433 | #+BEGIN_EXAMPLE 434 | method = variational 435 | variational 436 | algorithm = meanfield (Default) 437 | meanfield 438 | iter = 10000 (Default) 439 | grad_samples = 1 (Default) 440 | elbo_samples = 100 (Default) 441 | eta = 1 (Default) 442 | adapt 443 | engaged = 1 (Default) 444 | iter = 50 (Default) 445 | tol_rel_obj = 0.01 (Default) 446 | eval_elbo = 100 (Default) 447 | output_samples = 1000 (Default) 448 | id = 0 (Default) 449 | data 450 | file = (Default) 451 | init = 2 (Default) 452 | random 453 | seed = 2784129612 454 | output 455 | file = output.csv (Default) 456 | diagnostic_file = (Default) 457 | refresh = 100 (Default) 458 | #+END_EXAMPLE 459 | 460 | We have to modify the =output file= option value. This can be done by: 461 | #+BEGIN_SRC mathematica :eval never 462 | myOpt = SetStanOption[myOpt, "output.file", FileNameJoin[{Directory[], "myOutputFile.csv"}]] 463 | #+END_SRC 464 | which prints: 465 | #+BEGIN_EXAMPLE 466 | method=variational output file=/tmp/myOutputFile.csv 467 | #+END_EXAMPLE 468 | 469 | Now we can run Stan: 470 | 471 | #+BEGIN_SRC mathematica :eval never 472 | myOutputFile=RunStan[stanExeFile, myOpt, StanVerbose -> False] 473 | #+END_SRC 474 | which must print: 475 | #+BEGIN_EXAMPLE 476 | /tmp/myOutputFile.csv 477 | #+END_EXAMPLE 478 | 479 | Now import this CSV file: 480 | #+BEGIN_SRC mathematica :eval never 481 | myResult = ImportStanResult[myOutputFile] 482 | #+END_SRC 483 | which prints: 484 | #+BEGIN_EXAMPLE 485 | file: /tmp/myOutputFile.csv 486 | meta: lp__ , log_p__ , log_g__ 487 | parameter: alpha , beta , sigma 488 | #+END_EXAMPLE 489 | 490 | As before you can use: 491 | #+BEGIN_SRC mathematica :eval never 492 | GetStanResult[myResult,"alpha"] 493 | #+END_SRC 494 | 495 | to get =alpha= parameter value, but now you will get a list of 1000 sample: 496 | #+BEGIN_EXAMPLE 497 | {2.03816, 0.90637, ..., ..., 1.22068, 1.66392} 498 | #+END_EXAMPLE 499 | 500 | Instead of the full sample list we are often interested by sample 501 | mean, variance... You can get these quantities as follows: 502 | 503 | #+BEGIN_SRC mathematica :eval never 504 | GetStanResult[Mean, myResult, "alpha"] 505 | GetStanResult[Variance, myResult, "alpha"] 506 | #+END_SRC 507 | 508 | which prints: 509 | 510 | #+BEGIN_EXAMPLE 511 | 2.0353 512 | 0.317084 513 | #+END_EXAMPLE 514 | 515 | You can also get the sample hstogram as simply as: 516 | 517 | #+BEGIN_SRC mathematica :eval never 518 | GetStanResult[Histogram, myResult, "alpha"] 519 | #+END_SRC 520 | 521 | [[file:figures/linRegHisto.png][file:./figures/linRegHisto.png]] 522 | 523 | ** More about Option management 524 | 525 | *** Overwriting default values 526 | 527 | We provide further details concerning option related functions. 528 | 529 | To recap the first step is to perform a copy of the write-protected 530 | default option values. By example to modify default MCMC option values 531 | the first step is: 532 | 533 | #+BEGIN_SRC mathematica :eval never 534 | myOpt = SampleDefaultOptions 535 | #+END_SRC 536 | 537 | The available option are: 538 | #+begin_example 539 | method = sample (Default) 540 | sample 541 | num_samples = 1000 (Default) 542 | num_warmup = 1000 (Default) 543 | save_warmup = 0 (Default) 544 | thin = 1 (Default) 545 | adapt 546 | engaged = 1 (Default) 547 | gamma = 0.050000000000000003 (Default) 548 | delta = 0.80000000000000004 (Default) 549 | kappa = 0.75 (Default) 550 | t0 = 10 (Default) 551 | init_buffer = 75 (Default) 552 | term_buffer = 50 (Default) 553 | window = 25 (Default) 554 | algorithm = hmc (Default) 555 | hmc 556 | engine = nuts (Default) 557 | nuts 558 | max_depth = 10 (Default) 559 | metric = diag_e (Default) 560 | metric_file = (Default) 561 | stepsize = 1 (Default) 562 | stepsize_jitter = 0 (Default) 563 | id = 0 (Default) 564 | data 565 | file = /tmp/linear_regression.data.R 566 | init = 2 (Default) 567 | random 568 | seed = 3714706817 (Default) 569 | output 570 | file = /tmp/linear_regression.csv 571 | diagnostic_file = (Default) 572 | refresh = 100 (Default) 573 | sig_figs = -1 (Default) 574 | #+end_example 575 | 576 | If we want to modify: 577 | #+begin_example 578 | method = sample (Default) 579 | sample 580 | num_samples = 1000 (Default) 581 | num_warmup = 1000 (Default) 582 | #+end_example 583 | and 584 | #+begin_example 585 | method = sample (Default) 586 | sample 587 | algorithm = hmc (Default) 588 | hmc 589 | engine = nuts (Default) 590 | nuts 591 | max_depth = 10 (Default) 592 | #+end_example 593 | you must proceed as follows. For each hierarchy level use a "." as 594 | separator and do not forget to rewrite "=" with the associated 595 | value. With our example this gives: 596 | 597 | #+BEGIN_SRC mathematica :eval never 598 | myOpt = SetStanOption[myOpt, "adapt.num_samples", 2000] 599 | myOpt = SetStanOption[myOpt, "adapt.num_warmup", 1500] 600 | myOpt = SetStanOption[myOpt, "algorithm=hmc.engine=nuts.max_depth", 5] 601 | #+END_SRC 602 | 603 | Now you can run the sampler with these new option values: 604 | #+BEGIN_SRC mathematica :eval never 605 | stanResultFile = RunStan[stanExeFile, myOpt] 606 | #+END_SRC 607 | which should print: 608 | #+begin_example 609 | method = sample (Default) 610 | sample 611 | num_samples = 2000 612 | num_warmup = 1500 613 | save_warmup = 0 (Default) 614 | thin = 1 (Default) 615 | adapt 616 | engaged = 1 (Default) 617 | gamma = 0.050000000000000003 (Default) 618 | delta = 0.80000000000000004 (Default) 619 | kappa = 0.75 (Default) 620 | t0 = 10 (Default) 621 | init_buffer = 75 (Default) 622 | term_buffer = 50 (Default) 623 | window = 25 (Default) 624 | algorithm = hmc (Default) 625 | hmc 626 | engine = nuts (Default) 627 | nuts 628 | max_depth = 5 629 | metric = diag_e (Default) 630 | metric_file = (Default) 631 | stepsize = 1 (Default) 632 | stepsize_jitter = 0 (Default) 633 | id = 0 (Default) 634 | data 635 | file = /tmp/linear_regression.data.R 636 | init = 2 (Default) 637 | random 638 | seed = 3720771451 (Default) 639 | output 640 | file = /tmp/linear_regression.csv 641 | diagnostic_file = (Default) 642 | refresh = 100 (Default) 643 | sig_figs = -1 (Default) 644 | stanc_version = stanc3 b25c0b64 645 | stancflags = 646 | 647 | 648 | Gradient evaluation took 1.3e-05 seconds 649 | 1000 transitions using 10 leapfrog steps per transition would take 0.13 seconds. 650 | Adjust your expectations accordingly! 651 | 652 | 653 | Iteration: 1 / 3500 [ 0%] (Warmup) 654 | Iteration: 100 / 3500 [ 2%] (Warmup) 655 | Iteration: 200 / 3500 [ 5%] (Warmup) 656 | Iteration: 300 / 3500 [ 8%] (Warmup) 657 | Iteration: 400 / 3500 [ 11%] (Warmup) 658 | Iteration: 500 / 3500 [ 14%] (Warmup) 659 | Iteration: 600 / 3500 [ 17%] (Warmup) 660 | Iteration: 700 / 3500 [ 20%] (Warmup) 661 | Iteration: 800 / 3500 [ 22%] (Warmup) 662 | Iteration: 900 / 3500 [ 25%] (Warmup) 663 | Iteration: 1000 / 3500 [ 28%] (Warmup) 664 | Iteration: 1100 / 3500 [ 31%] (Warmup) 665 | Iteration: 1200 / 3500 [ 34%] (Warmup) 666 | Iteration: 1300 / 3500 [ 37%] (Warmup) 667 | Iteration: 1400 / 3500 [ 40%] (Warmup) 668 | Iteration: 1500 / 3500 [ 42%] (Warmup) 669 | Iteration: 1501 / 3500 [ 42%] (Sampling) 670 | Iteration: 1600 / 3500 [ 45%] (Sampling) 671 | Iteration: 1700 / 3500 [ 48%] (Sampling) 672 | Iteration: 1800 / 3500 [ 51%] (Sampling) 673 | Iteration: 1900 / 3500 [ 54%] (Sampling) 674 | Iteration: 2000 / 3500 [ 57%] (Sampling) 675 | Iteration: 2100 / 3500 [ 60%] (Sampling) 676 | Iteration: 2200 / 3500 [ 62%] (Sampling) 677 | Iteration: 2300 / 3500 [ 65%] (Sampling) 678 | Iteration: 2400 / 3500 [ 68%] (Sampling) 679 | Iteration: 2500 / 3500 [ 71%] (Sampling) 680 | Iteration: 2600 / 3500 [ 74%] (Sampling) 681 | Iteration: 2700 / 3500 [ 77%] (Sampling) 682 | Iteration: 2800 / 3500 [ 80%] (Sampling) 683 | Iteration: 2900 / 3500 [ 82%] (Sampling) 684 | Iteration: 3000 / 3500 [ 85%] (Sampling) 685 | Iteration: 3100 / 3500 [ 88%] (Sampling) 686 | Iteration: 3200 / 3500 [ 91%] (Sampling) 687 | Iteration: 3300 / 3500 [ 94%] (Sampling) 688 | Iteration: 3400 / 3500 [ 97%] (Sampling) 689 | Iteration: 3500 / 3500 [100%] (Sampling) 690 | 691 | Elapsed Time: 0.053 seconds (Warm-up) 692 | 0.094 seconds (Sampling) 693 | 0.147 seconds (Total) 694 | #+end_example 695 | 696 | You can check than the new option values have been taken into account: 697 | #+begin_example 698 | num_samples = 2000 699 | num_warmup = 1500 700 | 701 | algorithm = hmc (Default) 702 | hmc 703 | engine = nuts (Default) 704 | nuts 705 | max_depth = 5 706 | #+end_example 707 | 708 | *** Reading customized values 709 | 710 | You can get back the modified values as follows: 711 | 712 | #+BEGIN_SRC mathematica :eval never 713 | GetStanOption[myOpt, "adapt.num_warmup"] 714 | GetStanOption[myOpt, "algorithm=hmc.engine=nuts.max_depth"] 715 | #+END_SRC 716 | which prints 717 | #+BEGIN_EXAMPLE 718 | 1500 719 | 5 720 | #+END_EXAMPLE 721 | *Caveat*: if the option was not defined (by =SetStanOption=) the function 722 | returns =$Failed=. 723 | 724 | *** Erasing customized option values 725 | 726 | To erase an option value (and use its default value) use: 727 | #+BEGIN_SRC mathematica :eval never 728 | myOpt = RemoveStanOption[myOpt, "algorithm=hmc.engine=nuts.max_depth"] 729 | #+END_SRC 730 | which prints 731 | #+BEGIN_EXAMPLE 732 | method=sample adapt num_samples=2000 num_warmup=1500 733 | #+END_EXAMPLE 734 | 735 | * Tutorial 2, linear regression with more than one predictor 736 | 737 | ** Parameter arrays 738 | 739 | By now the parameters alpha, beta, sigma, were *scalars*. We will see 740 | how to handle parameters that are vectors or matrices. 741 | 742 | We use second section of the [[https://mc-stan.org/docs/2_19/stan-users-guide/linear-regression.html][linear regression]] example, entitled 743 | "Matrix notation and Vectorization". 744 | 745 | The β parameter is now a vector of size K. 746 | 747 | #+BEGIN_SRC mathematica :eval never 748 | stanCode = "data { 749 | int N; // number of data items 750 | int K; // number of predictors 751 | matrix[N, K] x; // predictor matrix 752 | vector[N] y; // outcome vector 753 | } 754 | parameters { 755 | real alpha; // intercept 756 | vector[K] beta; // coefficients for predictors 757 | real sigma; // error scale 758 | } 759 | model { 760 | y ~ normal(x * beta + alpha, sigma); // likelihood 761 | }"; 762 | 763 | stanCodeFile = ExportStanCode["linear_regression_vect.stan", stanCode]; 764 | stanExeFile = CompileStanCode[stanCodeFile]; 765 | #+END_SRC 766 | 767 | ** Simulated data 768 | 769 | Here we use {x,x²,x³} as predictors, with their coefficients 770 | β = {2,0.1,0.01} so that the model is 771 | 772 | y = α + β1 x + β2 x² + β3 x³ + ε 773 | 774 | where ε follows a normal distribution. 775 | 776 | #+BEGIN_SRC mathematica :eval never 777 | σ = 3; α = 1; β1 = 2; β2 = 0.1; β3 = 0.01; 778 | n = 20; 779 | X = Range[n]; 780 | Y = α + β1*X + β2*X^2 + β3*X^3 + RandomVariate[NormalDistribution[0, σ], n]; 781 | Show[Plot[α + β1*x + β2*x^2 + β3*x^3, {x, Min[X], Max[X]}], 782 | ListPlot[Transpose@{X, Y}, PlotStyle -> Red]] 783 | #+END_SRC 784 | 785 | [[file:figures/linReg2Data.png][file:./figures/linReg2Data.png]] 786 | 787 | ** Exporting data 788 | 789 | The expression 790 | 791 | y = α + β1 x + β2 x² + β3 x³ + ε 792 | 793 | is convenient for random variable manipulations. However in practical 794 | computations where we have to evaluate: 795 | 796 | y[i] = α + β1 x[i] + β2 (x[i])² + β3 (x[i])³ + ε[i], for i = 1..N 797 | 798 | it is more convenient to rewrite this in a "vectorized form": 799 | 800 | *y* = *α* + *X.β* + *ε* 801 | 802 | where *X* is a KxN matrix of columns X[:,j] = j th-predictor = (x[:])^j 803 | and *α* a vector of size N with constant components = α. 804 | 805 | Thus data is exported as follows: 806 | 807 | #+BEGIN_SRC mathematica :eval never 808 | stanData = <|"N" -> n, "K" -> 3, "x" -> Transpose[{X,X^2,X^3}], "y" -> Y|>; 809 | stanDataFile = ExportStanData[stanExeFile, stanData] 810 | #+END_SRC 811 | 812 | *Note:* as Mathematica stores its matrices rows by rows (the C 813 | language convention) we have to transpose ={X,X^2,X^3}= to get the 814 | right matrix X. 815 | 816 | ** Run Stan, HMC sampling 817 | 818 | We can now run Stan using the Hamiltonian Monte Carlo (HMC) method: 819 | 820 | #+BEGIN_SRC mathematica :eval never 821 | stanResultFile = RunStan[stanExeFile, SampleDefaultOptions] 822 | #+END_SRC 823 | 824 | which prints: 825 | 826 | #+BEGIN_EXAMPLE 827 | Running: /tmp/linear_regression_vect method=sample data file=/tmp/linear_regression_vect.data.R output file=/tmp/linear_regression_vect.csv 828 | 829 | method = sample (Default) 830 | sample 831 | num_samples = 1000 (Default) 832 | num_warmup = 1000 (Default) 833 | save_warmup = 0 (Default) 834 | thin = 1 (Default) 835 | adapt 836 | engaged = 1 (Default) 837 | gamma = 0.050000000000000003 (Default) 838 | delta = 0.80000000000000004 (Default) 839 | kappa = 0.75 (Default) 840 | t0 = 10 (Default) 841 | init_buffer = 75 (Default) 842 | term_buffer = 50 (Default) 843 | window = 25 (Default) 844 | algorithm = hmc (Default) 845 | hmc 846 | engine = nuts (Default) 847 | nuts 848 | max_depth = 10 (Default) 849 | metric = diag_e (Default) 850 | metric_file = (Default) 851 | stepsize = 1 (Default) 852 | stepsize_jitter = 0 (Default) 853 | id = 0 (Default) 854 | data 855 | file = /tmp/linear_regression_vect.data.R 856 | init = 2 (Default) 857 | random 858 | seed = 3043713420 859 | output 860 | file = /tmp/linear_regression_vect.csv 861 | diagnostic_file = (Default) 862 | refresh = 100 (Default) 863 | 864 | 865 | Gradient evaluation took 4e-05 seconds 866 | 1000 transitions using 10 leapfrog steps per transition would take 0.4 seconds. 867 | Adjust your expectations accordingly! 868 | 869 | 870 | Iteration: 1 / 2000 [ 0%] (Warmup) 871 | Iteration: 100 / 2000 [ 5%] (Warmup) 872 | Iteration: 200 / 2000 [ 10%] (Warmup) 873 | Iteration: 300 / 2000 [ 15%] (Warmup) 874 | Iteration: 400 / 2000 [ 20%] (Warmup) 875 | Iteration: 500 / 2000 [ 25%] (Warmup) 876 | Iteration: 600 / 2000 [ 30%] (Warmup) 877 | Iteration: 700 / 2000 [ 35%] (Warmup) 878 | Iteration: 800 / 2000 [ 40%] (Warmup) 879 | Iteration: 900 / 2000 [ 45%] (Warmup) 880 | Iteration: 1000 / 2000 [ 50%] (Warmup) 881 | Iteration: 1001 / 2000 [ 50%] (Sampling) 882 | Iteration: 1100 / 2000 [ 55%] (Sampling) 883 | Iteration: 1200 / 2000 [ 60%] (Sampling) 884 | Iteration: 1300 / 2000 [ 65%] (Sampling) 885 | Iteration: 1400 / 2000 [ 70%] (Sampling) 886 | Iteration: 1500 / 2000 [ 75%] (Sampling) 887 | Iteration: 1600 / 2000 [ 80%] (Sampling) 888 | Iteration: 1700 / 2000 [ 85%] (Sampling) 889 | Iteration: 1800 / 2000 [ 90%] (Sampling) 890 | Iteration: 1900 / 2000 [ 95%] (Sampling) 891 | Iteration: 2000 / 2000 [100%] (Sampling) 892 | 893 | Elapsed Time: 0.740037 seconds (Warm-up) 894 | 0.60785 seconds (Sampling) 895 | 1.34789 seconds (Total) 896 | #+END_EXAMPLE 897 | ** Load the CSV result file 898 | 899 | As before, 900 | 901 | #+BEGIN_SRC mathematica :eval never 902 | stanResult = ImportStanResult[stanResultFile] 903 | #+END_SRC 904 | 905 | load the generated CSV file and prints: 906 | 907 | #+BEGIN_EXAMPLE 908 | file: /tmp/linear_regression_vect.csv 909 | meta: lp__ , accept_stat__ , stepsize__ , treedepth__ , n_leapfrog__ , divergent__ , energy__ 910 | parameter: alpha , beta 3, sigma 911 | #+END_EXAMPLE 912 | 913 | Compared to the scalar case, the important thing to notice is the =beta 3=. That means that β is not a scalar anymore but a vector of size 3 914 | 915 | *Note*: here β is a vector, but if it had been a 3x5 matrix we would 916 | have had =β 3x5= printed instead. 917 | 918 | A call to 919 | #+BEGIN_SRC mathematica :eval never 920 | GetStanResult[stanResult, "beta"] 921 | #+END_SRC 922 | returns a vector of size 3 but where each component is a list of 1000 923 | sample (for β1, β2 and β3). 924 | 925 | As before it generally useful to summarize this sample with function like mean or histogram: 926 | 927 | #+BEGIN_SRC mathematica :eval never 928 | GetStanResult[Mean, stanResult, "beta"] 929 | GetStanResult[Histogram, stanResult, "beta"] 930 | #+END_SRC 931 | 932 | prints: 933 | #+BEGIN_EXAMPLE 934 | {3.30321, -0.010088, 0.0126913} 935 | #+END_EXAMPLE 936 | and plots: 937 | 938 | [[file:figures/linReg2Histo.png][file:./figures/linReg2Histo.png]] 939 | 940 | 941 | This is the moment to digress about Keys. If you try: 942 | #+BEGIN_SRC mathematica :eval never 943 | StanResultKeys[stanResult] 944 | StanResultMetaKeys[stanResult] 945 | #+END_SRC 946 | 947 | this will print: 948 | #+BEGIN_EXAMPLE 949 | {"alpha", "beta.1", "beta.2", "beta.3", "sigma"} 950 | {"lp__", "accept_stat__", "stepsize__", "treedepth__", "n_leapfrog__", "divergent__", "energy__"} 951 | #+END_EXAMPLE 952 | 953 | These functions are useful to get the complete list of keys. Note 954 | that, as β is an 1D-array of size 1 we have =beta.1, beta.2, beta.3=. If 955 | β was a NxM matrix, the list of keys would have been: =beta.1.1, 956 | beta.1.2,... beta.N.M=. 957 | 958 | There is also *reduced keys* functions: 959 | 960 | #+BEGIN_SRC mathematica :eval never 961 | StanResultReducedKeys[stanResult] 962 | StanResultReducedMetaKeys[stanResult] 963 | #+END_SRC 964 | 965 | which print 966 | 967 | #+BEGIN_EXAMPLE 968 | {"alpha", "beta", "sigma"} 969 | {"lp__", "accept_stat__", "stepsize__", "treedepth__", "n_leapfrog__", "divergent__", "energy__"} 970 | #+END_EXAMPLE 971 | 972 | As you can see the *reduced keys* functions collect and discard indices 973 | to keys associated to arrays. 974 | 975 | When accessing a parameter you can work at the component level or globally: 976 | #+BEGIN_SRC mathematica :eval never 977 | GetStanResult[Mean, stanResult, "beta.2"] 978 | GetStanResult[Mean, stanResult, "beta"] 979 | #+END_SRC 980 | 981 | which prints 982 | 983 | #+BEGIN_EXAMPLE 984 | -0.010088 985 | {3.30321, -0.010088, 0.0126913} 986 | #+END_EXAMPLE 987 | * Unit tests 988 | You can run [[file:tests/CmdStan_test.wl]] to check that everything works 989 | as expected. 990 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------