├── .github
└── workflows
│ └── run-tests.yaml
├── .gitignore
├── .project
├── .settings
├── ca.ubc.stat.blang.BlangDsl.prefs
├── org.eclipse.emf.ecore.xcore.Xcore.prefs
├── org.eclipse.jdt.core.prefs
├── org.eclipse.xtend.core.Xtend.prefs
└── org.eclipse.xtext.java.Java.prefs
├── .travis.yml
├── LICENSE.txt
├── README.md
├── build.gradle
├── doc
├── blang.js
├── build.sh
├── deploy.sh
├── download-deps.sh
├── eclipse-release-assembly
│ ├── assemble.sh
│ └── plain-eclipse
│ │ └── download-eclipse-xtext.sh
├── www
│ ├── GitHub-logo.png
│ ├── ide.jpg
│ ├── jumbotron-narrow.css
│ └── jupiter.jpg
└── xtend.js
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── settings.gradle
├── setup-cli.sh
├── setup-eclipse.sh
└── src
├── main
└── java
│ └── blang
│ ├── distributions
│ ├── Bernoulli.bl
│ ├── Beta.bl
│ ├── BetaBinomial.bl
│ ├── BetaNegativeBinomial.bl
│ ├── Binomial.bl
│ ├── Categorical.bl
│ ├── ChiSquared.bl
│ ├── ContinuousUniform.bl
│ ├── Dirichlet.bl
│ ├── DiscreteUniform.bl
│ ├── Exponential.bl
│ ├── F.bl
│ ├── Gamma.bl
│ ├── GammaMeanParam.bl
│ ├── Generators.java
│ ├── Geometric.bl
│ ├── Gompertz.bl
│ ├── Gumbel.bl
│ ├── HalfStudentT.bl
│ ├── HyperGeometric.bl
│ ├── Laplace.bl
│ ├── LnUniform.bl
│ ├── LogLogistic.bl
│ ├── LogPotential.bl
│ ├── LogUniform.bl
│ ├── Logistic.bl
│ ├── MultivariateNormal.bl
│ ├── NegativeBinomial.bl
│ ├── NegativeBinomialMeanParam.bl
│ ├── Normal.bl
│ ├── NormalField.bl
│ ├── Poisson.bl
│ ├── SimplexUniform.bl
│ ├── StudentT.bl
│ ├── SymmetricDirichlet.bl
│ ├── Weibull.bl
│ ├── YuleSimon.bl
│ └── internals
│ │ └── Helpers.java
│ ├── engines
│ ├── AdaptiveJarzynski.java
│ ├── ParallelTempering.java
│ └── internals
│ │ ├── CovarAccumulator.java
│ │ ├── EngineStaticUtils.java
│ │ ├── LogSumAccumulator.java
│ │ ├── PosteriorInferenceEngine.java
│ │ ├── Spline.java
│ │ ├── SplineDerivatives.xtend
│ │ ├── factories
│ │ ├── AIS.java
│ │ ├── Exact.java
│ │ ├── Forward.java
│ │ ├── IAIS.xtend
│ │ ├── ISCM.xtend
│ │ ├── MCMC.java
│ │ ├── None.java
│ │ ├── PT.java
│ │ ├── Pigeons.java
│ │ └── SCM.java
│ │ ├── ladders
│ │ ├── EquallySpaced.java
│ │ ├── FromAnotherExec.java
│ │ ├── Geometric.java
│ │ ├── Polynomial.java
│ │ ├── TemperatureLadder.java
│ │ └── UserSpecified.java
│ │ ├── ptanalysis
│ │ ├── PathViz.xtend
│ │ └── Paths.xtend
│ │ └── schedules
│ │ ├── AdaptiveTemperatureSchedule.java
│ │ ├── FixedTemperatureSchedule.java
│ │ ├── TemperatureSchedule.java
│ │ └── UserSpecified.java
│ ├── io
│ ├── BlangTidySerializer.xtend
│ ├── DataSource.xtend
│ ├── GlobalDataSource.xtend
│ ├── NA.xtend
│ ├── Parsers.xtend
│ └── internals
│ │ ├── CSV.xtend
│ │ ├── DataSourceReader.xtend
│ │ └── GlobalDataSourceStore.xtend
│ ├── mcmc
│ ├── CategoricalSampler.xtend
│ ├── ConnectedFactor.java
│ ├── EllipticalSliceSampler.xtend
│ ├── IntSliceSampler.java
│ ├── MHSampler.java
│ ├── RealSliceSampler.java
│ ├── SampledVariable.java
│ ├── Sampler.java
│ ├── Samplers.java
│ ├── SimplexSampler.xtend
│ ├── UniformSampler.xtend
│ └── internals
│ │ ├── BuiltSamplers.java
│ │ ├── Callback.java
│ │ ├── ExponentiatedFactor.java
│ │ ├── SamplerBuilder.java
│ │ ├── SamplerBuilderContext.java
│ │ ├── SamplerBuilderOptions.java
│ │ ├── SamplerMatch.java
│ │ ├── SamplerMatchingUtils.java
│ │ ├── SamplerSet.java
│ │ ├── SimplexWritableVariable.xtend
│ │ └── bps
│ │ ├── Likelihood2EnergyAdaptor.java
│ │ └── RealVar2MutableDouble.java
│ ├── runtime
│ ├── Observations.xtend
│ ├── PostProcessor.xtend
│ ├── Runner.xtend
│ ├── SampledModel.java
│ └── internals
│ │ ├── ComputeESS.java
│ │ ├── CreateBlangGradleProject.java
│ │ ├── DefaultPostProcessor.xtend
│ │ ├── Main.xtend
│ │ ├── RecursiveAnnotationProducer.java
│ │ ├── StandaloneCompiler.java
│ │ ├── doc
│ │ ├── Categories.java
│ │ ├── MakeHTMLDoc.xtend
│ │ └── contents
│ │ │ ├── BlangCLI.xtend
│ │ │ ├── BlangIDE.xtend
│ │ │ ├── BlangWeb.xtend
│ │ │ ├── BuiltInDistributions.xtend
│ │ │ ├── BuiltInFunctions.xtend
│ │ │ ├── BuiltInRandomVariables.xtend
│ │ │ ├── CreatingTypes.xtend
│ │ │ ├── Empty.xtend
│ │ │ ├── Examples.xtend
│ │ │ ├── GettingStarted.xtend
│ │ │ ├── Home.xtend
│ │ │ ├── InferenceAndRuntime.xtend
│ │ │ ├── InputOutput.xtend
│ │ │ ├── Javadoc.xtend
│ │ │ ├── Syntax.xtend
│ │ │ └── Testing.xtend
│ │ └── objectgraph
│ │ ├── AccessibilityGraph.java
│ │ ├── AnnealingStructure.java
│ │ ├── ArrayConstituentNode.java
│ │ ├── ArrayView.java
│ │ ├── ConstituentNode.java
│ │ ├── DeepCloner.java
│ │ ├── DoubleArrayView.java
│ │ ├── ExplorationRule.java
│ │ ├── ExplorationRules.java
│ │ ├── FieldConstituentNode.java
│ │ ├── GraphAnalysis.java
│ │ ├── IntArrayView.java
│ │ ├── MapConstituentNode.java
│ │ ├── MatrixConstituentNode.java
│ │ ├── Node.java
│ │ ├── ObjectArrayView.java
│ │ ├── ObjectNode.java
│ │ ├── SkipDependency.java
│ │ ├── SkippedFieldConstituentNode.java
│ │ ├── StaticUtils.java
│ │ ├── VariableUtils.java
│ │ └── ViewedArray.java
│ ├── types
│ ├── AnnealingParameter.xtend
│ ├── DenseSimplex.xtend
│ ├── DenseTransitionMatrix.xtend
│ ├── ExtensionUtils.xtend
│ ├── Index.xtend
│ ├── Plate.xtend
│ ├── Plated.xtend
│ ├── PlatedMatrix.xtend
│ ├── Precision.java
│ ├── Simplex.java
│ ├── SpikedRealVar.xtend
│ ├── StaticUtils.xtend
│ ├── TransitionMatrix.java
│ └── internals
│ │ ├── ColumnName.xtend
│ │ ├── Delegator.java
│ │ ├── HashPlate.xtend
│ │ ├── HashPlated.xtend
│ │ ├── IndexedDataSource.xtend
│ │ ├── IntScalar.xtend
│ │ ├── InvalidParameter.java
│ │ ├── LatentFactoryAsParser.xtend
│ │ ├── Parser.xtend
│ │ ├── PlatedSlice.xtend
│ │ ├── Query.xtend
│ │ ├── RealScalar.xtend
│ │ ├── SimpleParser.xtend
│ │ └── SimplePlate.xtend
│ └── validation
│ ├── DeterminismTest.java
│ ├── DiscreteMCTest.java
│ ├── ExactInvarianceTest.java
│ ├── Instance.xtend
│ ├── NormalizationTest.java
│ ├── UnbiasnessTest.xtend
│ └── internals
│ ├── Helpers.xtend
│ └── fixtures
│ ├── AutoBoxDeboxTests.bl
│ ├── BadNormal.bl
│ ├── BadPlate.bl
│ ├── BadRealSliceSampler.java
│ ├── CustomAnnealRef.bl
│ ├── CustomAnnealTest.bl
│ ├── Cyclic.bl
│ ├── Diffusion.bl
│ ├── Doomsday.bl
│ ├── DynamicNormalMixture.bl
│ ├── Empty.bl
│ ├── ExactHMMCalculations.java
│ ├── Examples.xtend
│ ├── FixedMatrix.bl
│ ├── Functions.xtend
│ ├── GenerateTwice.bl
│ ├── Growth.bl
│ ├── HierarchicalModel.bl
│ ├── IfElse.bl
│ ├── IntNaiveMHSampler.java
│ ├── IntRealizationSquared.java
│ ├── Ising.bl
│ ├── LinRegression.bl
│ ├── ListHash.java
│ ├── MarkovChain.bl
│ ├── MixtureModel.bl
│ ├── Multimodal.bl
│ ├── NoGen.bl
│ ├── NormalFieldExamples.bl
│ ├── NotNormalForm.bl
│ ├── Operations.bl
│ ├── PCR.bl
│ ├── PlatedMatrixTests.bl
│ ├── PoissonAllInOne.bl
│ ├── PoissonNormalField.bl
│ ├── RealNaiveMHSampler.java
│ ├── RealRealizationSquared.java
│ ├── Scalability.bl
│ ├── Simple.bl
│ ├── SimpleHierarchicalModel.bl
│ ├── SmallHMM.bl
│ ├── SometimesNaN.bl
│ ├── SpikeAndSlab.bl
│ ├── SpikedGLM.bl
│ ├── Unid.bl
│ ├── UnspecifiedParam.bl
│ └── VectorHash.java
└── test
├── java
└── blang
│ ├── TestCloning.xtend
│ ├── TestDiscreteModels.xtend
│ ├── TestDocumentation.xtend
│ ├── TestESS.xtend
│ ├── TestEndToEnd.xtend
│ ├── TestExactTest.xtend
│ ├── TestFixedMatrix.xtend
│ ├── TestLadders.java
│ ├── TestMoments.java
│ ├── TestRunner.java
│ ├── TestSDKDistributions.xtend
│ ├── TestSDKNormalizations.java
│ ├── TestSMCUnbiasness.xtend
│ ├── TestSparseDirichletAndBetaWarnings.xtend
│ ├── TestStandaloneCompiler.xtend
│ ├── TestSyntax.java
│ └── runtime
│ └── TestSampledModel.java
└── resource
└── data.csv
/.github/workflows/run-tests.yaml:
--------------------------------------------------------------------------------
1 | name: Java CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - uses: actions/checkout@v3
11 | - name: Set up JDK 11
12 | uses: actions/setup-java@v3
13 | with:
14 | java-version: '11'
15 | distribution: 'adopt'
16 | - name: Validate Gradle wrapper
17 | uses: gradle/wrapper-validation-action@v1
18 | - name: Assemble
19 | uses: gradle/gradle-build-action@v2
20 | with:
21 | arguments: installDist
22 | - name: Build with Gradle
23 | uses: gradle/gradle-build-action@v2
24 | with:
25 | arguments: test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | .classpath
3 | bin/
4 | .DS_Store
5 | build
6 | results
7 | java.hprof.txt
8 | src/main/xtend-gen/blang/examples/.gitignore
9 | src/main/xtend-gen/blang/mcmc/.gitignore
10 | src/main/xtend-gen/blang/runtime/.gitignore
11 | src/main/xtend-gen/blang/types/.gitignore
12 | src/main/xtend-gen/blang/utils/.gitignore
13 | samples
14 | failed-test-info-*
15 | doc/www/ace
16 | doc/ace-master
17 | doc/bootstrap
18 | doc/www/dist
19 | Home.html
20 | Quick_Start.html
21 | data.csv
22 | Reference.html
23 | doc/eclipse-release-assembly/plain-eclipse/Eclipse.app
24 | doc/eclipse-release-assembly/blang
25 | doc/www/downloads
26 | Getting_started.html
27 | doc/www/Blang_IDE.html
28 | doc/www/Blang_in_browser.html
29 | doc/www/Blang_via_web.html
30 | logNormEstimate.txt
31 | runningTimeSummary.tsv
32 | index.html
33 | Useful_types.html
34 | Built-in_random_variables.html
35 | Random_variables.html
36 | Reading_from_command_line.html
37 | Syntax_reference.html
38 | doc/www/Inference_and_runtime.html
39 | doc/www/Template.html
40 | Creating_random_types.html
41 | Input_and_output.html
42 | Testing_Blang_models.html
43 | Distributions.html
44 | Functions.html
45 | Examples.html
46 | CLI.html
47 | doc/www/javadoc-dsl
48 | doc/www/javadoc-inits
49 | doc/www/javadoc-sdk
50 | doc/www/javadoc-xlinear
51 | Javadoc.html
52 | data/
53 | *.swp
54 | lin-reg-data.csv
55 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | blang
4 |
5 |
6 |
7 | org.eclipse.jdt.core.javanature
8 | org.eclipse.xtext.ui.shared.xtextNature
9 |
10 |
11 |
12 | org.eclipse.jdt.core.javabuilder
13 |
14 |
15 |
16 | org.eclipse.xtext.ui.shared.xtextBuilder
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.settings/ca.ubc.stat.blang.BlangDsl.prefs:
--------------------------------------------------------------------------------
1 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=build/blang/main
2 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/resources.directory=build/blang/main
3 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=build/blang/test
4 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/resources.directory=build/blang/test
5 | BuilderConfiguration.is_project_specific=true
6 | ValidatorConfiguration.is_project_specific=true
7 | eclipse.preferences.version=1
8 | generateGeneratedAnnotation=false
9 | generateSuppressWarnings=true
10 | includeDateInGenerated=false
11 | outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true
12 | outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false
13 | outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=true
14 | targetJavaVersion=Java8
15 | useJavaCompilerCompliance=true
16 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.emf.ecore.xcore.Xcore.prefs:
--------------------------------------------------------------------------------
1 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/blang/main.directory=
2 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/blang/main.ignore=
3 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/main.directory=
4 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/main.ignore=
5 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=
6 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.ignore=
7 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/xtend-gen.directory=
8 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/xtend-gen.ignore=
9 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=
10 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.ignore=
11 | BuilderConfiguration.is_project_specific=true
12 | autobuilding=true
13 | eclipse.preferences.version=1
14 | generateGeneratedAnnotation=false
15 | generateSuppressWarnings=true
16 | generatedAnnotationComment=
17 | includeDateInGenerated=false
18 | outlet.DEFAULT_OUTPUT.cleanDirectory=false
19 | outlet.DEFAULT_OUTPUT.cleanupDerived=true
20 | outlet.DEFAULT_OUTPUT.createDirectory=true
21 | outlet.DEFAULT_OUTPUT.derived=true
22 | outlet.DEFAULT_OUTPUT.directory=./src-gen
23 | outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true
24 | outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false
25 | outlet.DEFAULT_OUTPUT.keepLocalHistory=true
26 | outlet.DEFAULT_OUTPUT.override=true
27 | outlet.DEFAULT_OUTPUT.sourceFolder.xtend-gen.directory=
28 | outlet.DEFAULT_OUTPUT.sourceFolder.xtend-gen.ignore=
29 | outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=
30 | targetJavaVersion=JAVA5
31 | useJavaCompilerCompliance=false
32 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.8
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.source=1.8
13 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.xtend.core.Xtend.prefs:
--------------------------------------------------------------------------------
1 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/main.directory=
2 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/main.ignore=
3 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/test.directory=
4 | //outlet.DEFAULT_OUTPUT.sourceFolder.build/xtend/test.ignore=
5 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=build/xtend/main
6 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.ignore=
7 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/main/resources.directory=build/xtend/main
8 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=build/xtend/test
9 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.ignore=
10 | //outlet.DEFAULT_OUTPUT.sourceFolder.src/test/resources.directory=build/xtend/test
11 | BuilderConfiguration.is_project_specific=true
12 | ValidatorConfiguration.is_project_specific=true
13 | autobuilding=true
14 | eclipse.preferences.version=1
15 | generateGeneratedAnnotation=false
16 | generateSuppressWarnings=true
17 | generatedAnnotationComment=
18 | includeDateInGenerated=false
19 | org.eclipse.xtend.core.Xtend.useProjectSettings=true
20 | outlet.DEFAULT_OUTPUT.cleanDirectory=false
21 | outlet.DEFAULT_OUTPUT.cleanupDerived=true
22 | outlet.DEFAULT_OUTPUT.createDirectory=true
23 | outlet.DEFAULT_OUTPUT.derived=true
24 | outlet.DEFAULT_OUTPUT.directory=xtend-gen
25 | outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true
26 | outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false
27 | outlet.DEFAULT_OUTPUT.keepLocalHistory=false
28 | outlet.DEFAULT_OUTPUT.override=true
29 | outlet.DEFAULT_OUTPUT.sourceFolder.xtend-gen.directory=
30 | outlet.DEFAULT_OUTPUT.sourceFolder.xtend-gen.ignore=
31 | outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=true
32 | targetJavaVersion=JAVA8
33 | useJavaCompilerCompliance=false
34 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.xtext.java.Java.prefs:
--------------------------------------------------------------------------------
1 | #Tue Mar 21 11:54:13 GMT 2017
2 | includeDateInGenerated=false
3 | BuilderConfiguration.is_project_specific=true
4 | eclipse.preferences.version=1
5 | generateGeneratedAnnotation=false
6 | useJavaCompilerCompliance=false
7 | generateSuppressWarnings=true
8 | ValidatorConfiguration.is_project_specific=true
9 | targetJavaVersion=Java8
10 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | script:
3 | - ./gradlew check -i --stacktrace
4 | jdk:
5 | - openjdk15
6 | - openjdk13
7 | - openjdk11
8 | - openjdk8
9 | install: travis_wait 30 ./gradlew installDist -i --stacktrace
10 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2016, The Blang Development Team
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5 |
6 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7 |
8 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9 |
10 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Summary
2 | -------
3 |
4 | **Prospective/current users**: please vist the [project web page](https://www.stat.ubc.ca/~bouchard/blang/index.html) for more information as well as our [JSS paper](https://www.jstatsoft.org/article/view/v103i11).
5 |
6 | **Docker image**: [link to documentation](https://github.com/UBC-Stat-ML/containers/tree/main/blang)
7 |
8 | **New feature:** Blang can now run on 1000s of machines using MPI via [the Pigeons-Blang bridge](https://julia-tempering.github.io/Pigeons.jl/dev/reference/#Pigeons.BlangTarget)
9 |
10 | **Blang developers**: in addition to the above resources, see also the [documentation repository](https://github.com/UBC-Stat-ML/blangDoc) for more information.
11 |
12 | This is one of the repositories hosting Blang's code. This one contains the Blang's SDK (Software Development Kit), including:
13 |
14 | - Basic datatypes suitable for sampling.
15 | - Infrastructure to create new data types and distributions.
16 | - Inference algorithms for such datatypes, such as [Adaptive Non-Reversible Parallel Tempering](https://www.stat.ubc.ca/~bouchard/pub/Syed2019NRPT.pdf) and Sequential Change of Measure.
17 | - Standard probability distributions.
18 | - MCMC testing infrastructure.
19 | - Runtime to perform static analysis to infer the factor graph and its sparsity patterns.
20 | - Automated post-processing facilities (MCMC diagnostic, trace/density/pmf/summaries generation, etc).
21 |
22 | See [this readme](https://github.com/UBC-Stat-ML/blangDoc/blob/master/README.md) for a roadmap of the other key repositories (language infrastructure, examples, supporting libraries, etc)
23 |
24 | **Citing Blang**: if you find Blang useful for your work, consider citing our [JSS paper](https://www.jstatsoft.org/article/view/v103i11):
25 |
26 | ```
27 | Alexandre Bouchard-Côté, Kevin Chern, Davor Cubranic, Sahand Hosseini, Justin Hume, Matteo Lepur, Zihui Ouyang, Giorgio Sgarbi (2022)
28 | Journal of Statistical Software 103:1–98
29 | ```
30 |
--------------------------------------------------------------------------------
/doc/blang.js:
--------------------------------------------------------------------------------
1 | define(function(require, exports, module) {
2 | "use strict";
3 |
4 | var oop = require("../lib/oop");
5 | var mText = require("./text");
6 | var mTextHighlightRules = require("./text_highlight_rules");
7 |
8 | var HighlightRules = function() {
9 | var keywords = "as|case|catch|default|do|else|extends|extension|false|finally|for|generate|if|import|indicator|instanceof|is|laws|logf|model|new|null|package|param|random|return|static|super|switch|synchronized|throw|true|try|typeof|val|var|while";
10 | this.$rules = {
11 | "start": [
12 | {token: "comment", regex: "\\/\\/.*$"},
13 | {token: "comment", regex: "\\/\\*", next : "comment"},
14 | {token: "string", regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},
15 | {token: "string", regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},
16 | {token: "constant.numeric", regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},
17 | {token: "constant.numeric", regex: "0[xX][0-9a-fA-F]+\\b"},
18 | {token: "lparen", regex: "[\\[({]"},
19 | {token: "rparen", regex: "[\\])}]"},
20 | {token: "keyword", regex: "\\b(?:" + keywords + ")\\b"}
21 | ],
22 | "comment": [
23 | {token: "comment", regex: ".*?\\*\\/", next : "start"},
24 | {token: "comment", regex: ".+"}
25 | ]
26 | };
27 | };
28 | oop.inherits(HighlightRules, mTextHighlightRules.TextHighlightRules);
29 |
30 | var Mode = function() {
31 | this.HighlightRules = HighlightRules;
32 | };
33 | oop.inherits(Mode, mText.Mode);
34 | Mode.prototype.$id = "xtext/bl";
35 | Mode.prototype.getCompletions = function(state, session, pos, prefix) {
36 | return [];
37 | }
38 |
39 | return {
40 | Mode: Mode
41 | };
42 |
43 |
44 | });
45 |
--------------------------------------------------------------------------------
/doc/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ## First, setup the ace hack
4 |
5 | # copy blang file
6 | cp blang.js ace-master/lib/ace/mode/
7 | cp xtend.js ace-master/lib/ace/mode/
8 |
9 | cd ace-master
10 | npm clean
11 | npm install
12 | node Makefile.dryice.js
13 | cd ..
14 |
15 | rm -rf www/ace
16 | cp -r ace-master/build/src/ www/ace
17 |
18 |
19 | ## Then, generate the actual documentation
20 |
21 | # Rebuild source
22 | cd ..
23 | ./setup-cli.sh
24 | cd -
25 |
26 | # Run the document generator
27 | cd www
28 | java -cp ../../build/install/blang/lib/\* blang.runtime.internals.doc.MakeHTMLDoc
29 | cd -
30 |
31 |
32 | ##### Javadocs
33 |
34 | ## DSL
35 |
36 | cd ../../blangDSL/ca.ubc.stat.blang.parent
37 | ./gradlew assemble
38 | cd -
39 |
40 | rm -rf www/javadoc-dsl
41 | mv ../../blangDSL/ca.ubc.stat.blang.parent/ca.ubc.stat.blang/build/docs/javadoc www/javadoc-dsl
42 |
43 |
44 |
45 | ## xlinear
46 |
47 | cd ../../xlinear
48 | ./gradlew assemble
49 | cd -
50 |
51 | rm -rf www/javadoc-xlinear
52 | mv ../../xlinear/build/docs/javadoc www/javadoc-xlinear
53 |
54 |
55 | ## inits
56 |
57 | cd ../../inits
58 | ./gradlew assemble
59 | cd -
60 |
61 | rm -rf www/javadoc-inits
62 | mv ../../inits/build/docs/javadoc www/javadoc-inits
63 |
64 |
65 | ## SDK
66 |
67 | cd ..
68 | ./gradlew assemble
69 | cd -
70 |
71 | rm -rf www/javadoc-sdk
72 | mv ../build/docs/javadoc www/javadoc-sdk
73 |
74 |
--------------------------------------------------------------------------------
/doc/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | remote='s2:~/public_html/blang/'
4 | chmod -R 755 www
5 | rsync -t --rsh=/usr/bin/ssh --recursive --perms --group www/ $remote; echo "Finished pushing blang documentation site" &
--------------------------------------------------------------------------------
/doc/download-deps.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # ACE
4 | rm -rf ace-master
5 | git clone https://github.com/ajaxorg/ace.git
6 | mv ace ace-master
7 | cd ace-master
8 | git reset --hard c3403f1fbdf22cfff2cb1dda584b8e04467cd372
9 | cd -
10 |
11 |
12 | # Bootstrap
13 | rm -rf bootstrap
14 | rm -rf www/dist
15 | git clone https://github.com/twbs/bootstrap.git
16 | cd bootstrap
17 | git reset --hard v3.3.7
18 | cp -r dist ../www/
19 | cd -
--------------------------------------------------------------------------------
/doc/eclipse-release-assembly/assemble.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 |
4 | # nb: eclipse executable in Eclipse.app/Contents/MacOS
5 | # list features: ./eclipse -clean -purgeHistory -application org.eclipse.equinox.p2.director -noSplash -repository https://www.stat.ubc.ca/~bouchard/maven/blang-eclipse-plugin-latest/ -list
6 |
7 | CUR=`pwd`
8 |
9 | cd ../..
10 | ./setup-cli.sh
11 | cd -
12 |
13 |
14 | blang_folder=blang
15 | rm -rf $blang_folder
16 | mkdir $blang_folder
17 |
18 | ### Setup eclipse
19 |
20 | cp -r plain-eclipse/Eclipse.app $blang_folder/BlangIDE.app
21 |
22 | $blang_folder/BlangIDE.app/Contents/MacOS/eclipse \
23 | -clean -purgeHistory \
24 | -application org.eclipse.equinox.p2.director \
25 | -noSplash \
26 | -repository https://www.stat.ubc.ca/~bouchard/maven/blang-eclipse-plugin-latest/ \
27 | -installIUs ca.ubc.stat.blang.feature.feature.group
28 |
29 | sudo codesign --force --sign - $blang_folder/BlangIDE.app
30 |
31 |
32 | ### Setup blang-related projects in workspace
33 |
34 | cd $blang_folder
35 | mkdir workspace
36 | cd workspace
37 |
38 | create-blang-gradle-project --name blangExample --githubOrganization UBC-Stat-ML
39 |
40 | git clone https://github.com/UBC-Stat-ML/blangSDK.git
41 |
42 |
43 | ### Package things up into a zip
44 |
45 | cd $CUR
46 |
47 | zip -r $blang_folder $blang_folder
48 | mkdir ../www/downloads
49 | mv ${blang_folder}.zip ../www/downloads/blang-mac-latest.zip
50 |
51 | rm -rf $blang_folder
52 |
--------------------------------------------------------------------------------
/doc/eclipse-release-assembly/plain-eclipse/download-eclipse-xtext.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | wget https://ftp.osuosl.org/pub/eclipse/technology/epp/downloads/release/2020-12/R/eclipse-dsl-2020-12-R-macosx-cocoa-x86_64.dmg
4 |
5 | echo "Unpack and put Eclipse.app in here"
--------------------------------------------------------------------------------
/doc/www/GitHub-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UBC-Stat-ML/blangSDK/b8642c9c2a0adab8a5b6da96f2a7889f1b81b6cc/doc/www/GitHub-logo.png
--------------------------------------------------------------------------------
/doc/www/ide.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UBC-Stat-ML/blangSDK/b8642c9c2a0adab8a5b6da96f2a7889f1b81b6cc/doc/www/ide.jpg
--------------------------------------------------------------------------------
/doc/www/jumbotron-narrow.css:
--------------------------------------------------------------------------------
1 | /* Space out content a bit */
2 | body {
3 | padding-top: 20px;
4 | padding-bottom: 20px;
5 | }
6 |
7 | /* Everything but the jumbotron gets side spacing for mobile first views */
8 | .header,
9 | .marketing,
10 | .footer {
11 | padding-right: 15px;
12 | padding-left: 15px;
13 | }
14 |
15 | /* Custom page header */
16 | .header {
17 | padding-bottom: 20px;
18 | border-bottom: 1px solid #e5e5e5;
19 | }
20 | /* Make the masthead heading the same height as the navigation */
21 | .header h3 {
22 | margin-top: 0;
23 | margin-bottom: 0;
24 | line-height: 40px;
25 | }
26 |
27 | /* Custom page footer */
28 | .footer {
29 | padding-top: 19px;
30 | color: #777;
31 | border-top: 1px solid #e5e5e5;
32 | }
33 |
34 | /* Customize container */
35 | @media (min-width: 768px) {
36 | .container {
37 | max-width: 730px;
38 | }
39 | }
40 | .container-narrow > hr {
41 | margin: 30px 0;
42 | }
43 |
44 | /* Main marketing message and sign up button */
45 | .jumbotron {
46 | text-align: center;
47 | border-bottom: 1px solid #e5e5e5;
48 | }
49 |
50 | .jumbotron-bg {
51 | colour = white;
52 | background-image:url('jupiter.jpg');
53 | background-repeat: no-repeat;
54 | background-size: cover;
55 | }
56 |
57 | .jumbotron-bg h1 {
58 | color: white;
59 | text-shadow: 2px 2px 4px #000000;
60 | }
61 |
62 | .jumbotron span{
63 | background: black;
64 | }
65 |
66 | .jumbotron-bg p{
67 | color: white;
68 | text-shadow: 2px 2px 4px #000000;
69 | }
70 |
71 | .jumbotron .btn {
72 | padding: 14px 24px;
73 | font-size: 21px;
74 | }
75 |
76 | .marketing div {
77 | font-size: 18px;
78 | }
79 |
80 |
81 | /* Supporting marketing content */
82 | .marketing {
83 | margin: 40px 0;
84 | }
85 | .marketing p + h4 {
86 | margin-top: 28px;
87 | }
88 |
89 | /* Responsive: Portrait tablets and up */
90 | @media screen and (min-width: 768px) {
91 | /* Remove the padding we set earlier */
92 | .header,
93 | .marketing,
94 | .footer {
95 | padding-right: 0;
96 | padding-left: 0;
97 | }
98 | /* Space out the masthead */
99 | .header {
100 | margin-bottom: 30px;
101 | }
102 | /* Remove the bottom border on the jumbotron for visual effect */
103 | .jumbotron {
104 | border-bottom: 0;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/doc/www/jupiter.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UBC-Stat-ML/blangSDK/b8642c9c2a0adab8a5b6da96f2a7889f1b81b6cc/doc/www/jupiter.jpg
--------------------------------------------------------------------------------
/doc/xtend.js:
--------------------------------------------------------------------------------
1 | define(function(require, exports, module) {
2 | "use strict";
3 |
4 | var oop = require("../lib/oop");
5 | var mText = require("./text");
6 | var mTextHighlightRules = require("./text_highlight_rules");
7 |
8 | var HighlightRules = function() {
9 | var keywords = "this|it|null|abstract|annotation|boolean|case|catch|char|class|create|def|default|do|double|enum|else|extends|extension|final|finally|float|for|if|implements|import|int|interface|long|new|override|package|private|protected|return|short|static|super|switch|throw|throws|try|typeof|val|var|void|while|FOR|ENDFOR|IF|ENDIF|ELSEIF|BEFORE|AFTER|SEPARATOR";
10 | this.$rules = {
11 | "start": [
12 | {token: "comment", regex: "\\/\\/.*$"},
13 | {token: "comment", regex: "\\/\\*", next : "comment"},
14 | {token: "string", regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},
15 | {token: "string", regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},
16 | {token: "constant.numeric", regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},
17 | {token: "constant.numeric", regex: "0[xX][0-9a-fA-F]+\\b"},
18 | {token: "lparen", regex: "[\\[({]"},
19 | {token: "rparen", regex: "[\\])}]"},
20 | {token: "keyword", regex: "\\b(?:" + keywords + ")\\b"}
21 | ],
22 | "comment": [
23 | {token: "comment", regex: ".*?\\*\\/", next : "start"},
24 | {token: "comment", regex: ".+"}
25 | ]
26 | };
27 | };
28 | oop.inherits(HighlightRules, mTextHighlightRules.TextHighlightRules);
29 |
30 | var Mode = function() {
31 | this.HighlightRules = HighlightRules;
32 | };
33 | oop.inherits(Mode, mText.Mode);
34 | Mode.prototype.$id = "xtend";
35 | Mode.prototype.getCompletions = function(state, session, pos, prefix) {
36 | return [];
37 | }
38 |
39 | return {
40 | Mode: Mode
41 | };
42 |
43 |
44 | });
45 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UBC-Stat-ML/blangSDK/b8642c9c2a0adab8a5b6da96f2a7889f1b81b6cc/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk11
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "blang" // Do not change to blangSDK: this value is hardcoded in the blang command-line infrastructure
2 |
--------------------------------------------------------------------------------
/setup-cli.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo
4 | echo " INSTALLING BLANG (COMMAND LINE INTERFACE)"
5 | echo " This may take some time as dependencies"
6 | echo " are being downloaded"
7 | echo
8 |
9 | # some weird gradle-xtext-blang problem may be caused by deamon trying to
10 | # handle 2 Blang versions, try to avoid this restarting the daemon after a Blang update
11 | ./gradlew --stop || exit 1
12 |
13 | ./gradlew clean || exit 1
14 | ./gradlew installDist || exit 1
15 |
16 | # Fix problem arising if eclipse is used jointly
17 | mkdir build/xtend/test
18 | mkdir build/blang/test
19 |
20 | echo
21 | echo " INSTALLATION WAS SUCCESSFUL"
22 | echo " Type 'blang' to try it"
23 | echo
24 |
25 | if hash blang 2>/dev/null; then
26 | echo
27 | else
28 | echo "NOTE: We are adding a line into ~/.bash_profile or ~/.zshenv to make the blang CLI command"
29 | echo " accessible from any directory (as blang is not found in PATH right now)."
30 | echo
31 | to_add="$(pwd)/build/install/blang/bin/"
32 | existing='$PATH'
33 | line="export PATH=${existing}:${to_add}"
34 | export PATH=$PATH:${to_add}
35 | if [[ $(basename $SHELL) == "zsh" ]]; then
36 | echo $line >>~/.zshenv
37 | elif [[ $(basename $SHELL) == "bash" ]]; then
38 | echo $line >>~/.bash_profile
39 | else
40 | echo "Default shell is not Bash nor Zsh."
41 | echo "Please add $(to_add) to PATH manually."
42 | fi
43 | fi
44 |
--------------------------------------------------------------------------------
/setup-eclipse.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ./gradlew assemble eclipse
4 |
5 | # Fix some stuff that get broken everytime
6 | git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree checkout -- .settings/ca.ubc.stat.blang.BlangDsl.prefs .settings/org.eclipse.jdt.core.prefs .settings/org.eclipse.xtend.core.Xtend.prefs .settings/org.eclipse.xtext.java.Java.prefs
7 | mkdir -p build
8 | mkdir -p build/blang
9 | mkdir -p build/blang/test
10 | mkdir -p build/blang/main
11 | mkdir -p build/xtend/main
12 | mkdir -p build/xtend/test
13 |
14 | echo Done
15 |
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Bernoulli.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Any random variable taking values in \(\{0, 1\}\). */
4 | model Bernoulli {
5 | random IntVar realization
6 |
7 | /** Probability \(p \in [0, 1]\) that the realization is one. */
8 | param RealVar probability
9 |
10 | laws {
11 | realization | probability ~ Categorical({
12 | if (probability < 0.0 || probability > 1.0) invalidParameter
13 | return fixedSimplex(1.0 - probability, probability)
14 | })
15 | }
16 |
17 | generate (rand) {
18 | if (rand.bernoulli(probability)) 1 else 0
19 | }
20 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Beta.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | import blang.distributions.internals.Helpers
4 |
5 | /** Beta random variable on the open interval \((0, 1)\). */
6 | model Beta {
7 | random RealVar realization
8 |
9 | /** Higher values brings mean closer to one. \(\alpha > 0 \) */
10 | param RealVar alpha
11 |
12 | /** Higher values brings mean closer to zero. \(\beta > 0 \) */
13 | param RealVar beta
14 |
15 | laws {
16 | logf(alpha, realization) {
17 | if (realization <= 0.0 || realization >= 1.0) return NEGATIVE_INFINITY
18 | if (alpha <= 0.0) return NEGATIVE_INFINITY
19 | Helpers::checkDirichletOrBetaParam(alpha)
20 | return (alpha - 1.0) * log(realization)
21 | }
22 | logf(beta, realization) {
23 | if (realization <= 0.0 || realization >= 1.0) return NEGATIVE_INFINITY
24 | if (beta <= 0.0) return NEGATIVE_INFINITY
25 | Helpers::checkDirichletOrBetaParam(beta)
26 | return (beta - 1.0) * log1p(-realization)
27 | }
28 | logf(alpha, beta) {
29 | if (alpha <= 0.0) return NEGATIVE_INFINITY
30 | if (beta <= 0.0) return NEGATIVE_INFINITY
31 | return lnGamma(alpha + beta)
32 | }
33 | logf(alpha) {
34 | if (alpha <= 0.0) return NEGATIVE_INFINITY
35 | return - lnGamma(alpha)
36 | }
37 | logf(beta) {
38 | if (beta <= 0.0) return NEGATIVE_INFINITY
39 | return - lnGamma(beta)
40 | }
41 | }
42 |
43 | generate(rand) {
44 | rand.beta(alpha, beta)
45 | }
46 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/BetaBinomial.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** A sum of \(n\) iid Bernoulli variables, with a marginalized Beta prior on the success probability. Values in \(\{0, 1, 2, \dots, n\}\). */
4 | model BetaBinomial{
5 | random IntVar realization
6 |
7 | /** The number \(n\) of Bernoulli variables being summed. \(n > 0\) */
8 | param IntVar numberOfTrials
9 |
10 | /** Higher values brings mean closer to one. \(\alpha > 0 \) */
11 | param RealVar alpha
12 |
13 | /** Higher values brings mean closer to zero. \(\beta > 0 \) */
14 | param RealVar beta
15 |
16 | laws{
17 | logf(realization,numberOfTrials,alpha,beta) {
18 | if (alpha <= 0.0 || beta <= 0.0) return NEGATIVE_INFINITY
19 | if (realization < 0.0) return NEGATIVE_INFINITY
20 | if (numberOfTrials <= 0.0 || realization > numberOfTrials) return NEGATIVE_INFINITY
21 | return lnGamma(numberOfTrials+1)
22 | +lnGamma(realization+alpha)
23 | +lnGamma(numberOfTrials-realization+beta)
24 | +lnGamma(alpha+beta)
25 | -lnGamma(realization+1)
26 | -lnGamma(numberOfTrials-realization+1)
27 | -lnGamma(numberOfTrials+alpha+beta)
28 | -lnGamma(alpha)
29 | -lnGamma(beta)
30 | }
31 | }
32 | generate (rand){ rand.betaBinomial(alpha,beta,numberOfTrials)}
33 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/BetaNegativeBinomial.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Negative Binomial Distribution with a marginalized Beta prior. Values in \(\{0, 1, 2, \dots\}\). */
4 | model BetaNegativeBinomial {
5 | random IntVar k
6 |
7 | /** Number of failures until experiment is stopped (generalized to the reals). \(r > 0\) */
8 | param RealVar r
9 |
10 | /** Higher values brings mean accept probability closer to one. \(\alpha > 0 \) */
11 | param RealVar alpha
12 |
13 | /** Higher values brings mean accept probability closer to zero. \(\beta > 0 \) */
14 | param RealVar beta
15 |
16 | laws {
17 | logf(r, k) {
18 | if (k < 0) NEGATIVE_INFINITY
19 | else if (r <= 0.0) NEGATIVE_INFINITY
20 | else logGamma(r + k)
21 | }
22 | logf(alpha, beta, r, k) {
23 | if (alpha <= 0.0) NEGATIVE_INFINITY
24 | else if (beta <= 0.0) NEGATIVE_INFINITY
25 | else if (k < 0) NEGATIVE_INFINITY
26 | else if (r <= 0.0) NEGATIVE_INFINITY
27 | else logBeta(alpha + k, beta + r) // Fixes an error in wikipedia
28 | }
29 | logf(k) {
30 | if (k < 0) NEGATIVE_INFINITY
31 | else -logFactorial(k)
32 | }
33 | logf(r) {
34 | if (r <= 0.0) NEGATIVE_INFINITY
35 | else -logGamma(r)
36 | }
37 | logf(alpha, beta) {
38 | if (alpha <= 0.0) NEGATIVE_INFINITY
39 | else if (beta <= 0.0) NEGATIVE_INFINITY
40 | else -logBeta(alpha, beta)
41 | }
42 | }
43 |
44 | generate (rand) {
45 | val p = rand.beta(alpha, beta)
46 | return rand.negativeBinomial(r, p)
47 | }
48 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Binomial.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** A sum of \(n\) iid Bernoulli variables. Values in \(\{0, 1, 2, \dots, n\}\). */
4 | model Binomial {
5 | random IntVar numberOfSuccesses
6 |
7 | /** The number \(n\) of Bernoulli variables being summed. \(n > 0\) */
8 | param IntVar numberOfTrials
9 |
10 | /** The parameter \(p \in [0, 1]\) shared by all the Bernoulli variables (probability that they be equal to 1). */
11 | param RealVar probabilityOfSuccess
12 |
13 | laws {
14 | logf(numberOfSuccesses, numberOfTrials, probabilityOfSuccess) {
15 | if (probabilityOfSuccess < 0.0 || probabilityOfSuccess > 1.0) return NEGATIVE_INFINITY
16 | if (numberOfSuccesses < 0) return NEGATIVE_INFINITY
17 | if (numberOfTrials <= 0 || numberOfSuccesses > numberOfTrials) return NEGATIVE_INFINITY
18 | return numberOfSuccesses * log(probabilityOfSuccess) + (numberOfTrials - numberOfSuccesses) * log(1.0 - probabilityOfSuccess)
19 | }
20 | logf(numberOfTrials, numberOfSuccesses) {
21 | if (numberOfSuccesses < 0) return NEGATIVE_INFINITY
22 | if (numberOfTrials <= 0 || numberOfSuccesses > numberOfTrials) return NEGATIVE_INFINITY
23 | return logBinomial(numberOfTrials, numberOfSuccesses)
24 | }
25 | }
26 |
27 | generate (rand) {
28 | rand.binomial(numberOfTrials, probabilityOfSuccess)
29 | }
30 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Categorical.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Any random variable over a finite set \(\{0, 1, 2, \dots, n-1\}\). */
4 | @Samplers(CategoricalSampler)
5 | model Categorical {
6 | random IntVar realization
7 |
8 | /** Vector of probabilities \((p_0, p_1, \dots, p_{n-1})\) for each of the \(n\) integers. */
9 | param Simplex probabilities
10 |
11 | laws {
12 | logf(probabilities, realization) {
13 | log(probabilities.get(realization))
14 | }
15 | realization is Constrained
16 | }
17 |
18 | generate(rand) {
19 | rand.categorical(probabilities.vectorToArray)
20 | }
21 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/ChiSquared.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Chi Squared random variable. Values in \((0, \infty)\). */
4 | model ChiSquared {
5 | random RealVar realization
6 |
7 | /** The degrees of freedom \(\nu\). \( \nu > 0 \) */
8 | param IntVar nu
9 |
10 | laws {
11 | logf(nu){
12 | if (nu <= 0) return NEGATIVE_INFINITY
13 | return - (nu / 2.0) * log(2) - lnGamma(nu / 2.0)
14 | }
15 | logf(realization, nu){
16 | if (nu <= 0) return NEGATIVE_INFINITY
17 | if (realization <= 0) return NEGATIVE_INFINITY
18 | return (nu / 2.0 - 1) * log(realization)
19 | }
20 | logf(realization){
21 | if (realization <= 0) return NEGATIVE_INFINITY
22 | return - realization / 2.0
23 | }
24 | }
25 |
26 | generate(rand) {
27 | rand.chisquared(nu)
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/ContinuousUniform.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Uniform random variable over a close interval \([m, M]\). */
4 | model ContinuousUniform {
5 | random RealVar realization
6 |
7 | /** The left end point \(m\) of the interval. \(m \in (-\infty, M)\) */
8 | param RealVar min
9 |
10 | /** The right end point \(M\) of the interval. \(M \in (m, \infty)\) */
11 | param RealVar max
12 |
13 | laws {
14 | logf(min, max) {
15 | if (max - min <= 0.0) return NEGATIVE_INFINITY
16 | return - log(max - min)
17 | }
18 | logf(realization, min, max) {
19 | if (min <= realization && realization <= max) return 0.0
20 | else return NEGATIVE_INFINITY
21 | }
22 | }
23 |
24 | generate(rand) {
25 | rand.uniform(min, max)
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Dirichlet.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | import blang.distributions.internals.Helpers
4 |
5 | /** The Dirichlet distribution over vectors of probabilities \((p_0, p_1, \dots, p_{n-1})\). \(p_i \in (0, 1), \sum_i p_i = 1.\) */
6 | model Dirichlet {
7 | random Simplex realization
8 |
9 | /** Vector \((\alpha_0, \alpha_1, \dots, \alpha_{n-1})\) such that increasing the \(i\)th component increases the mean of entry \(p_i\). */
10 | param Matrix concentrations
11 |
12 | laws {
13 | logf(concentrations, realization) {
14 | var sum = 0.0
15 | for (int dim : 0 ..< concentrations.nEntries) {
16 | val concentration = concentrations.get(dim)
17 | if (concentration < 0.0) return NEGATIVE_INFINITY
18 | Helpers::checkDirichletOrBetaParam(concentration)
19 | sum += (concentration - 1.0) * log(realization.get(dim))
20 | }
21 | return sum
22 | }
23 | logf(concentrations) {
24 | var sum = 0.0
25 | for (int dim : 0 ..< concentrations.nEntries) {
26 | val concentration = concentrations.get(dim)
27 | if (concentration < 0.0) return NEGATIVE_INFINITY
28 | sum += - lnGamma(concentration)
29 | }
30 | return sum + lnGamma(concentrations.sum)
31 | }
32 | realization is Constrained
33 | }
34 |
35 | generate(rand) {
36 | rand.dirichletInPlace(concentrations, realization)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/DiscreteUniform.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Uniform random variable over the contiguous set of integers \(\{m, m+1, \dots, M-1\}\). */
4 | @Samplers(UniformSampler)
5 | model DiscreteUniform {
6 | random IntVar realization
7 |
8 | /** The left point of the set (inclusive). \(m \in (-\infty, M)\) */
9 | param IntVar minInclusive
10 |
11 | /** The right point of the set (exclusive). \(M \in (m, \infty)\) */
12 | param IntVar maxExclusive
13 |
14 | laws {
15 | logf(minInclusive, maxExclusive) {
16 | if (maxExclusive - minInclusive <= 0.0) return NEGATIVE_INFINITY
17 | return -log(maxExclusive - minInclusive)
18 | }
19 | logf(realization, minInclusive, maxExclusive) {
20 | if (minInclusive <= realization &&
21 | realization < maxExclusive) return 0.0
22 | else return NEGATIVE_INFINITY
23 | }
24 | }
25 |
26 | generate(rand) {
27 | rand.discreteUniform(minInclusive, maxExclusive)
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Exponential.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Exponential random variable. Values in \((0, \infty)\) */
4 | model Exponential {
5 | random RealVar realization
6 |
7 | /** The rate \(\lambda\), inversely proportional to the mean. \( \lambda > 0 \) */
8 | param RealVar rate
9 |
10 | laws {
11 | realization | rate ~ Gamma(1.0, rate)
12 | }
13 |
14 | generate (rand) {
15 | rand.exponential(rate)
16 | }
17 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/F.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The F-distribution. Also known as Fisher-Snedecor distribution. Values in \((0, +\infty) \)*/
4 | model F {
5 | random RealVar realization
6 |
7 | /** The degrees of freedom \( d_1 \) and \( d_2 \) . \( d_1, d_2 > 0 \) */
8 | param RealVar d1, d2
9 |
10 | laws {
11 | logf(d1, d2) {
12 | if (d1 <= 0.0) return NEGATIVE_INFINITY
13 | if (d2 <= 0.0) return NEGATIVE_INFINITY
14 | return 0.5 * (d1*log(d1) + d2*log(d2)) + lnGamma(d1/2) + lnGamma(d2/2) - lnGamma((d1 + d2)/2)
15 | }
16 |
17 | logf(d1, realization) {
18 | if (d1 <= 0.0) return NEGATIVE_INFINITY
19 | if ((d1 == 1) && (realization <= 0.0)) return NEGATIVE_INFINITY
20 | if (realization < 0.0) return NEGATIVE_INFINITY
21 | return ( (d1 / 2) - 1.0) * log(realization)
22 | }
23 |
24 | logf(d1, d2, realization) {
25 | if (d1 <= 0.0) return NEGATIVE_INFINITY
26 | if (d2 <= 0.0) return NEGATIVE_INFINITY
27 | if ((d1 == 1) && (realization <= 0.0)) return NEGATIVE_INFINITY
28 | if (realization < 0.0) return NEGATIVE_INFINITY
29 | return - 0.5 * (d1 + d2) * log( (d1 * realization) + d2)
30 | }
31 | }
32 |
33 | generate(rand) {
34 | rand.fDist(d1, d2)
35 | }
36 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Gamma.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Gamma random variable. Values in \((0, \infty)\). */
4 | model Gamma {
5 | random RealVar realization
6 |
7 | /** The shape \(\alpha\) is proportional to the mean and variance. \( \alpha > 0 \) */
8 | param RealVar shape
9 |
10 | /** The rate \(\beta\) is inverse proportional to the mean and quadratically inverse proportional to the variance. \( \beta > 0 \) */
11 | param RealVar rate
12 |
13 | laws {
14 | logf(shape, rate, realization) {
15 | if (shape <= 0.0 || rate <= 0) return NEGATIVE_INFINITY
16 | if (realization <= 0.0) return NEGATIVE_INFINITY
17 | return (shape - 1.0) * log(realization * rate)
18 | }
19 | logf(realization, rate) {
20 | if (rate <= 0) return NEGATIVE_INFINITY
21 | if (realization <= 0.0) return NEGATIVE_INFINITY
22 | return - realization * rate
23 | }
24 | logf(shape) {
25 | if (shape <= 0.0) return NEGATIVE_INFINITY
26 | return - lnGamma(shape)
27 | }
28 | logf(rate) {
29 | if (rate <= 0.0) return NEGATIVE_INFINITY
30 | return log(rate)
31 | }
32 | }
33 |
34 | generate(rand) {
35 | rand.gamma(shape, rate)
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/GammaMeanParam.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | model GammaMeanParam {
4 | random RealVar realization
5 | param RealVar mean
6 | param RealVar variance
7 |
8 | laws {
9 | realization | mean, variance ~ Gamma(mean * mean / variance, mean / variance)
10 | }
11 |
12 | generate (rand) {
13 | rand.gamma(mean * mean / variance, mean / variance)
14 | }
15 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Geometric.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The number of unsuccessful Bernoulli trials until a success. Values in \(\{0, 1, 2, \dots\}\) */
4 | model Geometric{
5 | random IntVar realization
6 |
7 | /** The probability of success for each Bernoulli trial. */
8 | param RealVar p
9 |
10 | laws {
11 | logf(p, realization) {
12 | if (p <= 0 || p >= 1) return NEGATIVE_INFINITY
13 | if (realization < 0) return NEGATIVE_INFINITY
14 | return realization*log(1-p) + log(p)
15 | }
16 | }
17 | generate(rand){ rand.geometric(p) }
18 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Gompertz.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The Gompertz distribution. Values in \([0, \infty) \). */
4 | model Gompertz {
5 | random RealVar realization
6 |
7 | /** The shape parameter \(\nu \). \(\nu > 0 \) */
8 | param RealVar shape
9 |
10 | /** The scale parameter \(b\). \(b > 0 \) */
11 | param RealVar scale
12 |
13 | laws {
14 | logf(shape, scale) {
15 | if (shape <= 0.0) return NEGATIVE_INFINITY
16 | if (scale <= 0.0) return NEGATIVE_INFINITY
17 | return log(shape / scale)
18 | }
19 | logf(realization, scale, shape) {
20 | if (realization < 0.0) return NEGATIVE_INFINITY
21 | if (scale <= 0.0) return NEGATIVE_INFINITY
22 | if (shape <= 0.0) return NEGATIVE_INFINITY
23 | return (realization / scale) - (shape * (exp(realization / scale) - 1))
24 | }
25 | }
26 |
27 | generate(rand) {
28 | rand.gompertz(shape, scale)
29 | }
30 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Gumbel.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The Gumbel Distribution. Values in \( \mathbb{R} \)*/
4 | model Gumbel {
5 | random RealVar realization
6 |
7 | /** The location parameter \(\mu \). \( \mu \in \mathbb{R} \) */
8 | param RealVar location
9 |
10 | /** The scale parameter \(\beta \). \( \beta > 0 \)*/
11 | param RealVar scale
12 |
13 | laws {
14 | logf(location, scale) {
15 | if (scale <= 0.0) return NEGATIVE_INFINITY
16 | return - log(scale)
17 | }
18 | logf(location, scale, realization) {
19 | if (scale <= 0.0) return NEGATIVE_INFINITY
20 | return - exp((location - realization) / scale) + ((location - realization) / scale)
21 | }
22 | }
23 |
24 | generate(rand) {
25 | rand.gumbel(location, scale)
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/HalfStudentT.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** HalfStudentT random variable. Values in \((0, \infty)\) */
4 | model HalfStudentT{
5 | random RealVar realization
6 |
7 | /** A degree of freedom parameter \(\nu\). \( \nu > 0 \) */
8 | param RealVar nu
9 |
10 | /** A scale parameter \(\sigma\). \( \sigma > 0 \). */
11 | param RealVar sigma
12 |
13 | laws{
14 | logf(nu){
15 | if (nu <= 0.0) return NEGATIVE_INFINITY
16 | return log(2.0) + lnGamma((nu + 1)/ 2.0) - lnGamma(nu / 2.0) - 0.5 * log(nu * PI)
17 | }
18 | logf(sigma){
19 | if (sigma <= 0.0) return NEGATIVE_INFINITY
20 | return - log(sigma)
21 | }
22 | logf(nu, sigma, realization){
23 | if (realization < 0.0) return NEGATIVE_INFINITY
24 | if (sigma <= 0.0) return NEGATIVE_INFINITY
25 | if (nu <= 0.0) return NEGATIVE_INFINITY
26 | return -((nu + 1.0) / 2.0) * log(1.0 + 1.0 / nu * pow(realization / sigma, 2))
27 | }
28 | }
29 | generate(rand){
30 | rand.halfstudentt(nu, sigma)
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/HyperGeometric.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** A population of size \(N\), \(K\) of which are marked, and drawing without replacement \(n\) samples from the population; the HyperGeometric models the number in the sample that are marked. */
4 | model HyperGeometric{
5 |
6 | random IntVar numberOfSuccess
7 |
8 | /** Number sampled. \(n\) */
9 | param IntVar numberOfDraws
10 |
11 | /** Population size. \(N\) */
12 | param IntVar population
13 |
14 | /** Number marked in the population. \(K\) */
15 | param IntVar populationConditioned
16 |
17 | laws{
18 | logf(populationConditioned, numberOfSuccess){
19 | if(numberOfSuccess<0) return NEGATIVE_INFINITY
20 | if(populationConditioned<=0 || numberOfSuccess > populationConditioned) return NEGATIVE_INFINITY
21 | return logBinomial(populationConditioned,numberOfSuccess)
22 | }
23 | logf(population, numberOfDraws){
24 | if(numberOfDraws<0) return NEGATIVE_INFINITY
25 | if(population<=0 || numberOfDraws > population) return NEGATIVE_INFINITY
26 | return -logBinomial(population, numberOfDraws)
27 | }
28 | logf(populationConditioned,numberOfSuccess,population,numberOfDraws){
29 | if(numberOfDraws-numberOfSuccess<0) return NEGATIVE_INFINITY
30 | if(population-populationConditioned<=0 || numberOfDraws-numberOfSuccess > population-populationConditioned)
31 | return NEGATIVE_INFINITY
32 | return logBinomial(population-populationConditioned,numberOfDraws-numberOfSuccess)
33 | }
34 | }
35 | generate (rand){
36 | rand.hyperGeometric(numberOfDraws,population,populationConditioned)
37 | }
38 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Laplace.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The Laplace Distribution over \(\mathbb{R}\) */
4 | model Laplace {
5 | random RealVar realization
6 |
7 | /** The mean parameter. */
8 | param RealVar location
9 |
10 | /** The scale parameter \( b \), equal to the square root of half of the variance. \( b > 0 \) */
11 | param RealVar scale
12 |
13 | laws {
14 | logf(realization, location, scale) {
15 | if (scale <= 0) return NEGATIVE_INFINITY
16 | return -log(2 * scale) - abs(realization - location) / scale
17 | }
18 | }
19 |
20 | generate(rand) { rand.laplace(location, scale) }
21 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/LnUniform.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The random variable \(X = e^Y\) where \(Y \sim \text{ContinuousUniform}[m, M]\). */
4 | model LnUniform {
5 | random RealVar realization
6 |
7 | /** The left end point \(m\) of the interval. \(m \in (-\infty, M)\) */
8 | param RealVar min
9 |
10 | /** The right end point \(M\) of the interval. \(M \in (m, \infty)\) */
11 | param RealVar max
12 |
13 |
14 | laws {
15 | realization | min, max ~ LogUniform(min, max, Math::E)
16 | }
17 |
18 | generate (rand) {
19 | val u = rand.uniform(min, max)
20 | return pow(Math::E, u)
21 | }
22 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/LogLogistic.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** A log-logistic distribution is the probability distribution of a random variable whose logarithm has a logistic distribution. Values in \([0, +\infty) \)*/
4 | model LogLogistic {
5 | random RealVar realization
6 |
7 | /** The scale parameter \(\alpha\) and also the median. \(\alpha > 0 \) */
8 | param RealVar scale
9 |
10 | /** The shape parameter \(\beta\). \(\beta > 0 \) */
11 | param RealVar shape
12 |
13 | laws {
14 | logf(scale, shape) {
15 | if (scale <= 0.0) return NEGATIVE_INFINITY
16 | if (shape <= 0.0) return NEGATIVE_INFINITY
17 | return log(shape) - (shape*log(scale))
18 | }
19 | logf(scale, shape, realization) {
20 | if (realization < 0.0) return NEGATIVE_INFINITY
21 | if (scale <= 0.0) return NEGATIVE_INFINITY
22 | if (shape <= 0.0) return NEGATIVE_INFINITY
23 | return shape*log(realization) - log(realization)
24 | }
25 | logf(scale, shape, realization) {
26 | if (realization < 0.0) return NEGATIVE_INFINITY
27 | if (scale <= 0.0) return NEGATIVE_INFINITY
28 | if (shape <= 0.0) return NEGATIVE_INFINITY
29 | return -2 * log(1 + pow((realization / scale), shape))
30 | }
31 | }
32 |
33 | generate(rand){
34 | rand.logLogistic(scale, shape)
35 | }
36 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/LogPotential.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Not really a distribution, but rather a way to handle undirected model (AKA random fields). See Ising under the Examples page. */
4 | model LogPotential {
5 | /** The log of the current value of this potential. */
6 | param RealVar logPotential
7 |
8 | laws {
9 | logf(logPotential) {
10 | return logPotential
11 | }
12 | }
13 |
14 | generate (rand) { throw new RuntimeException }
15 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/LogUniform.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** The random variable \(X = b^Y\) where \(Y \sim \text{ContinuousUniform}[m, M]\). */
4 | model LogUniform {
5 | random RealVar realization
6 |
7 | /** The left end point \(m\) of the interval. \(m \in (-\infty, M)\) */
8 | param RealVar min
9 |
10 | /** The right end point \(M\) of the interval. \(M \in (m, \infty)\) */
11 | param RealVar max
12 |
13 | /** The base \(b\). \(b > 0\) */
14 | param RealVar base
15 |
16 | laws {
17 | logf(min, max) {
18 | if (max - min <= 0.0) return NEGATIVE_INFINITY
19 | return - log(max - min)
20 | }
21 | logf(realization, min, max, base) {
22 | if (base <= 0) return NEGATIVE_INFINITY
23 | if (realization <= 0) return NEGATIVE_INFINITY
24 | val logr = log(realization)
25 | val logb = log(base)
26 | val transformed = logr / logb
27 | if (min <= transformed && transformed <= max) return -logr - log(logb)
28 | else return NEGATIVE_INFINITY
29 | }
30 | }
31 |
32 | generate (rand) {
33 | val u = rand.uniform(min, max)
34 | return pow(base, u)
35 | }
36 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Logistic.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** A random variable with a cumulative distribution given by the logistic function. Values in \( \mathbb{R} \) */
4 | model Logistic {
5 | random RealVar realization
6 |
7 | /** The mean. \(\mu \in \mathbb{R}\) */
8 | param RealVar location
9 |
10 | /** The scale parameter. \(s > 0\) */
11 | param RealVar scale
12 |
13 | laws {
14 | logf(scale) {
15 | if (scale <= 0.0) return NEGATIVE_INFINITY
16 | return - log(scale)
17 | }
18 | logf(scale, location, realization) {
19 | if (scale <= 0.0) return NEGATIVE_INFINITY
20 | return (location - realization) / scale
21 | }
22 | logf(scale, location, realization) {
23 | if (scale <= 0.0) return NEGATIVE_INFINITY
24 | return - 2 * log(1.0 + exp( (location - realization) / scale))
25 | }
26 | }
27 |
28 | generate(rand) {
29 | rand.logisticDist(location, scale)
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/MultivariateNormal.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Arbitrary linear transformations of \(n\) iid standard normal random variables. */
4 | model MultivariateNormal {
5 | random Matrix realization
6 |
7 | /** An \(n \times 1\) vector \(\mu\). \(\mu \in \mathbb{R}^n\) */
8 | param Matrix mean
9 | // Note: no need to mark as constrained since CholeskyDecomposition is read-only
10 | // so won't attempt to do naive sampling by default
11 | /** Inverse covariance matrix \(\Lambda\), a positive definite \(n \times n\) matrix. */
12 | param CholeskyDecomposition precision
13 |
14 | laws {
15 | logf(double dim = realization.nEntries) {
16 | - 0.5 * dim * log(2.0*PI)
17 | }
18 | logf(precision) {
19 | 0.5 * precision.logDet
20 | }
21 | logf(mean, precision, realization) {
22 | val Matrix centered = mean - realization
23 | val Matrix L = precision.L
24 | // by doing left to right this is quadratic not cubic:
25 | return - 0.5 * (centered.transpose * L * L.transpose * centered).doubleValue
26 | }
27 | }
28 |
29 | generate(rand) {
30 | realization.setTo(rand.multivariateNormal(mean, precision))
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/NegativeBinomial.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Number of successes in a sequence of iid Bernoulli until \(r\) failures occur. Values in \(\{0, 1, 2, \dots\}\). */
4 | model NegativeBinomial {
5 | random IntVar k
6 |
7 | /** Number of failures until experiment is stopped (generalized to the reals). \(r > 0\) */
8 | param RealVar r
9 |
10 | /** Probability of success of each experiment. \(p \in (0, 1)\) */
11 | param RealVar p
12 |
13 | laws {
14 | logf(k, r) {
15 | if (r <= 0 || k < 0) return NEGATIVE_INFINITY
16 | val result = logBinomial(k+r-1.0, k)
17 | if (result.isNaN)
18 | return NEGATIVE_INFINITY // E.g: if k = 0 and r = 1.4761528506003524E-63, logBinomial gives -INF
19 | return result
20 | }
21 | logf(r, k, p) {
22 | if (p <= 0.0 || p >= 1.0) return NEGATIVE_INFINITY
23 | if (r <= 0 || k < 0) return NEGATIVE_INFINITY
24 | return k * log(p) + r * log(1.0 - p)
25 | }
26 | }
27 |
28 | generate(rand) {
29 | rand.negativeBinomial(r, p)
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/NegativeBinomialMeanParam.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | model NegativeBinomialMeanParam {
4 | random IntVar k
5 | param RealVar mean, overdispersion
6 |
7 | laws {
8 | k | mean, overdispersion ~ NegativeBinomial(
9 | mean * mean / overdispersion,
10 | 1.0 - mean/(mean + overdispersion)
11 | )
12 | }
13 |
14 | generate (rand) {
15 | rand.negativeBinomial(mean * mean / overdispersion, 1.0 - mean/(mean + overdispersion))
16 | }
17 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/Normal.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | /** Normal random variables. Values in \(\mathbb{R}\) */
4 | model Normal {
5 | random RealVar realization
6 |
7 | /** Mean \(\mu\). \(\mu \in \mathbb{R}\) */
8 | param RealVar mean
9 |
10 | /** Variance \(\sigma^2\). \(\sigma^2 > 0\) */
11 | param RealVar variance
12 |
13 | laws {
14 | logf() {
15 | - 0.5 * log(2.0*PI)
16 | }
17 | logf(variance) {
18 | if (variance <= 0.0) return NEGATIVE_INFINITY
19 | return - 0.5 * log(variance)
20 | }
21 | logf(mean, variance, realization) {
22 | if (variance <= 0.0) return NEGATIVE_INFINITY
23 | return - 0.5 * pow(mean - realization, 2) / variance
24 | }
25 | }
26 |
27 | generate(rand) {
28 | rand.normal(mean, variance)
29 | }
30 | }
--------------------------------------------------------------------------------
/src/main/java/blang/distributions/NormalField.bl:
--------------------------------------------------------------------------------
1 | package blang.distributions
2 |
3 | import briefj.collections.UnorderedPair
4 | import blang.types.Precision
5 | import briefj.Indexer
6 |
7 | /** A mean-zero normal, sparse-precision Markov random field.
8 | * For small problem, use MultivariateNormal instead,
9 | * but for problems with a large, sparse precision matrix, this implementation
10 | * allows the user to specify a 'support'
11 | * for the precision, outside of which the precision is guaranteed to be zero. This
12 | * can speed up sampling considerably.
13 | */
14 | @Samplers(EllipticalSliceSampler)
15 | model NormalField {
16 | /** Precision matrix structure.
17 | * precision.support is assumed to be constant.
18 | * TODO: add some construct that test this exponentially less and less frequently
19 | */
20 | param Precision precision
21 | random Plated realization
22 |
23 | laws {
24 | for (UnorderedPair pair : precision.support) {
25 | logf(
26 | precision,
27 | pair,
28 | RealVar x0 = realization.get(precision.plate.index(pair.first)),
29 | RealVar x1 = realization.get(precision.plate.index(pair.second))
30 | ) {
31 | if (pair.first == pair.second) {
32 | return - 0.5 * precision.get(pair) * x0 * x0
33 | } else {
34 | // 0.5 * 2 = 1 (because we iterate over set of unordered pairs)
35 | return - precision.get(pair) * x0 * x1
36 | }
37 | }
38 | }
39 | logf(int dim = precision.plate.indices.size) {
40 | - dim * log(2*PI) / 2.0
41 | }
42 | logf(precision) {
43 | 0.5 * precision.logDet
44 | }
45 | }
46 |
47 | generate (rand) {
48 | val Precision