Run prettier on monorepo + fix crashing playground

This commit is contained in:
Sam Nolan 2022-04-12 15:41:36 +10:00
parent 26433c5289
commit 440bfabffa
36 changed files with 452 additions and 388 deletions

View File

@ -1,14 +1,13 @@
--- ---
name: Developer friction when contributing to Squiggle name: Developer friction when contributing to Squiggle
about: Did your yarn scripts fail? Did the CI diverge from a README? Have a testing-related task? Etc. about: Did your yarn scripts fail? Did the CI diverge from a README? Have a testing-related task? Etc.
labels: 'ops & testing' labels: "ops & testing"
--- ---
# Description: # Description:
# The OS and version, yarn version, etc. in which this came up # The OS and version, yarn version, etc. in which this came up
_delete this section if testing task_ _delete this section if testing task_
# Desired behavior # Desired behavior

View File

@ -1,7 +1,6 @@
--- ---
name: Idea or feature request name: Idea or feature request
about: Where would you like to see Squiggle go over the next few months, several months, or few years? about: Where would you like to see Squiggle go over the next few months, several months, or few years?
--- ---
# Description # Description

View File

@ -1,14 +1,13 @@
--- ---
name: Regarding the programming language name: Regarding the programming language
about: Interpreter, parser, syntax, semantics, and including distributions about: Interpreter, parser, syntax, semantics, and including distributions
labels: 'programming language' labels: "programming language"
--- ---
<!-- mark one with an x -->
- _ Is refactor <!-- mark one with an x -->
- _ Is new feature
- _ Concerns documentation - \_ Is refactor
- \_ Is new feature
- \_ Concerns documentation
# Description of suggestion or shortcoming: # Description of suggestion or shortcoming:

View File

@ -1,18 +1,17 @@
--- ---
name: Bug reports for Squiggle users name: Bug reports for Squiggle users
about: Rendering oddly, trouble with the playground, something like this? about: Rendering oddly, trouble with the playground, something like this?
labels: 'bug' labels: "bug"
--- ---
# Description: # Description:
# Steps to reproduce: # Steps to reproduce:
1. 1.
2. 2.
3. 3.
# Expected behavior: # Expected behavior:
# What I got instead: # What I got instead:

View File

@ -1,14 +1,13 @@
name: Squiggle packages check name: Squiggle packages check
on: on:
push: # Delete this line if there becomes a scarcity of build minutes. push: # Delete this line if there becomes a scarcity of build minutes.
pull_request: pull_request:
branches: branches:
- master - master
- staging - staging
jobs: jobs:
pre_check: pre_check:
name: Precheck for skipping redundant jobs name: Precheck for skipping redundant jobs
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -43,15 +42,15 @@ jobs:
shell: bash shell: bash
working-directory: packages/squiggle-lang working-directory: packages/squiggle-lang
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Install dependencies from monorepo level - name: Install dependencies from monorepo level
run: cd ../../ && yarn run: cd ../../ && yarn
- name: Build rescript codebase - name: Build rescript codebase
run: yarn build run: yarn build
- name: Run tests - name: Run tests
run: yarn test run: yarn test
- name: Run webpack - name: Run webpack
run: yarn bundle run: yarn bundle
components-build-test: components-build-test:
name: Components build and test name: Components build and test
@ -63,15 +62,15 @@ jobs:
shell: bash shell: bash
working-directory: packages/components working-directory: packages/components
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Install dependencies from monorepo level - name: Install dependencies from monorepo level
run: cd ../../ && yarn run: cd ../../ && yarn
- name: Build rescript codebase in squiggle-lang - name: Build rescript codebase in squiggle-lang
run: cd ../squiggle-lang && yarn build run: cd ../squiggle-lang && yarn build
- name: Run webpack - name: Run webpack
run: yarn bundle run: yarn bundle
- name: Build storybook - name: Build storybook
run: yarn build run: yarn build
website-build: website-build:
name: Website build name: Website build
@ -83,10 +82,10 @@ jobs:
shell: bash shell: bash
working-directory: packages/website working-directory: packages/website
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Install dependencies from monorepo level - name: Install dependencies from monorepo level
run: cd ../../ && yarn run: cd ../../ && yarn
- name: Build rescript in squiggle-lang - name: Build rescript in squiggle-lang
run: cd ../squiggle-lang && yarn build run: cd ../squiggle-lang && yarn build
- name: Build website assets - name: Build website assets
run: yarn build run: yarn build

View File

@ -13,16 +13,16 @@ name: "CodeQL"
on: on:
push: push:
branches: branches:
- master - master
- staging - staging
pull_request: pull_request:
# The branches below must be a subset of the branches above # The branches below must be a subset of the branches above
branches: branches:
- master - master
- staging - staging
schedule: schedule:
- cron: '42 19 * * 0' - cron: "42 19 * * 0"
jobs: jobs:
analyze: analyze:
@ -36,39 +36,39 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: [ 'javascript' ] language: ["javascript"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support # Learn more about CodeQL language support at https://git.io/codeql-language-support
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v2 uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v1 uses: github/codeql-action/init@v1
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file. # By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file. # Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main # queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@v1 uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell. # Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl # 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project # and modify them (or add more) to build your code if your project
# uses a compiled language # uses a compiled language
#- run: | #- run: |
# make bootstrap # make bootstrap
# make release # make release
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1 uses: github/codeql-action/analyze@v1

9
.prettierignore Normal file
View File

@ -0,0 +1,9 @@
.direnv
*.bs.js
*.gen.tsx
packages/*/dist
packages/components/storybook-static
node_modules
packages/*/node_modules
packages/website/.docusaurus
packages/squiggle-lang/lib

View File

@ -2,9 +2,9 @@ _The current document was written quickly and not exhaustively, yet, it's unfini
# Contributing to Squiggle # Contributing to Squiggle
We welcome contributions from developers, especially people in react/typescript, rescript, and interpreters/parsers. We also are keen to hear issues filed by users! We welcome contributions from developers, especially people in react/typescript, rescript, and interpreters/parsers. We also are keen to hear issues filed by users!
Squiggle is currently pre-alpha. Squiggle is currently pre-alpha.
# Quick links # Quick links
@ -12,41 +12,43 @@ Squiggle is currently pre-alpha.
- The team presently communicates via the **EA Forecasting and Epistemics** slack (channels `#squiggle` and `#squiggle-ops`), you can track down an invite by reaching out to Ozzie Gooen - The team presently communicates via the **EA Forecasting and Epistemics** slack (channels `#squiggle` and `#squiggle-ops`), you can track down an invite by reaching out to Ozzie Gooen
- [Squiggle documentation](https://www.squiggle-language.com/docs/Language) - [Squiggle documentation](https://www.squiggle-language.com/docs/Language)
- [Rescript documentation](https://rescript-lang.org/docs/manual/latest/introduction) - [Rescript documentation](https://rescript-lang.org/docs/manual/latest/introduction)
- You can email `quinn@quantifieduncertainty.org` if you need assistance in onboarding or if you have questions - You can email `quinn@quantifieduncertainty.org` if you need assistance in onboarding or if you have questions
# Bug reports # Bug reports
Anyone (with a github account) can file an issue at any time. Please allow Quinn, Sam, and Ozzie to triage, but otherwise just follow the suggestions in the issue templates. Anyone (with a github account) can file an issue at any time. Please allow Quinn, Sam, and Ozzie to triage, but otherwise just follow the suggestions in the issue templates.
# Project structure # Project structure
Squiggle is a **monorepo** with four **packages**. Squiggle is a **monorepo** with four **packages**.
- **components** is where we improve reactive interfacing with Squiggle - **components** is where we improve reactive interfacing with Squiggle
- **playground** is the site `playground.squiggle-language.com` - **playground** is the site `playground.squiggle-language.com`
- **squiggle-lang** is where the magic happens: probability distributions, the interpreter, etc. - **squiggle-lang** is where the magic happens: probability distributions, the interpreter, etc.
- **website** is the site `squiggle-language.com` - **website** is the site `squiggle-language.com`
# Deployment ops # Deployment ops
We use netlify, and it should only concern Quinn, Sam, and Ozzie. We use netlify, and it should only concern Quinn, Sam, and Ozzie.
# Development environment, building, testing, dev server # Development environment, building, testing, dev server
You need `yarn`. You need `yarn`.
Being a monorepo, where packages are connected by dependency, it's important to follow `README.md`s closely. Each package has it's own `README.md`, which is where the bulk of information is. Being a monorepo, where packages are connected by dependency, it's important to follow `README.md`s closely. Each package has it's own `README.md`, which is where the bulk of information is.
We aspire for `ci.yaml` and `README.md`s to be in one-to-one correspondence. We aspire for `ci.yaml` and `README.md`s to be in one-to-one correspondence.
## If you're on NixOS ## If you're on NixOS
You'll need to run a command like this in order to get `yarn build` to run, especially in `packages/squiggle-lang`. You'll need to run a command like this in order to get `yarn build` to run, especially in `packages/squiggle-lang`.
```sh ```sh
patchelf --set-interpreter $(patchelf --print-interpreter $(which mkdir)) ./node_modules/gentype/gentype.exe patchelf --set-interpreter $(patchelf --print-interpreter $(which mkdir)) ./node_modules/gentype/gentype.exe
``` ```
See [here](https://github.com/NixOS/nixpkgs/issues/107375) See [here](https://github.com/NixOS/nixpkgs/issues/107375)
# Pull request protocol # Pull request protocol
Please work against `staging` branch. **Do not** work against `master`. Please do not merge without approval from some subset of Quinn, Sam, and Ozzie; they will be auto-pinged. Please work against `staging` branch. **Do not** work against `master`. Please do not merge without approval from some subset of Quinn, Sam, and Ozzie; they will be auto-pinged.

View File

@ -1,9 +1,10 @@
# Squiggle # Squiggle
![Packages check](https://github.com/QURIresearch/squiggle/actions/workflows/ci.yaml/badge.svg) ![Packages check](https://github.com/QURIresearch/squiggle/actions/workflows/ci.yaml/badge.svg)
[![npm version](https://badge.fury.io/js/@quri%2Fsquiggle-lang.svg)](https://www.npmjs.com/package/@quri/squiggle-lang) [![npm version](https://badge.fury.io/js/@quri%2Fsquiggle-lang.svg)](https://www.npmjs.com/package/@quri/squiggle-lang)
[![npm version](https://badge.fury.io/js/@quri%2Fsquiggle-components.svg)](https://www.npmjs.com/package/@quri/squiggle-components) [![npm version](https://badge.fury.io/js/@quri%2Fsquiggle-components.svg)](https://www.npmjs.com/package/@quri/squiggle-components)
This is an experimental DSL/language for making probabilistic estimates. The full story can be found [here](https://www.lesswrong.com/s/rDe8QE5NvXcZYzgZ3). This is an experimental DSL/language for making probabilistic estimates. The full story can be found [here](https://www.lesswrong.com/s/rDe8QE5NvXcZYzgZ3).
## Our deployments ## Our deployments
@ -12,40 +13,42 @@ This is an experimental DSL/language for making probabilistic estimates. The ful
- **old playground**: https://playground.squiggle-language.com - **old playground**: https://playground.squiggle-language.com
## Packages ## Packages
This monorepo has several packages that can be used for various purposes. All
This monorepo has several packages that can be used for various purposes. All
the packages can be found in `packages`. the packages can be found in `packages`.
- `@quri/squiggle-lang` in `packages/squiggle-lang` contains the core language, particularly - `@quri/squiggle-lang` in `packages/squiggle-lang` contains the core language, particularly
an interface to parse squiggle expressions and return descriptions of distributions an interface to parse squiggle expressions and return descriptions of distributions
or results. or results.
- `@quri/squiggle-components` in `packages/components` contains React components that - `@quri/squiggle-components` in `packages/components` contains React components that
can be passed squiggle strings as props, and return a presentation of the result can be passed squiggle strings as props, and return a presentation of the result
of the calculation. of the calculation.
- `@quri/squiggle-website` in `packages/website` The main descriptive website for squiggle, - `@quri/squiggle-website` in `packages/website` The main descriptive website for squiggle,
it is hosted at `squiggle-language.com`. it is hosted at `squiggle-language.com`.
The playground depends on the components library which then depends on the language. This means that if you wish to work on the components library, you will need to build (no need to bundle) the language, and as of this writing playground doesn't really work. The playground depends on the components library which then depends on the language. This means that if you wish to work on the components library, you will need to build (no need to bundle) the language, and as of this writing playground doesn't really work.
# Develop # Develop
For any project in the repo, begin by running `yarn` in the top level (TODO: is this true?) For any project in the repo, begin by running `yarn` in the top level (TODO: is this true?)
``` sh ```sh
yarn yarn
``` ```
See `packages/*/README.md` to work with whatever project you're interested in. See `packages/*/README.md` to work with whatever project you're interested in.
## `codium` for `rescript` ## `codium` for `rescript`
If you have `nix` installed with `flakes` enabled, you can build a `codium` in this repo for `rescript` development, if you don't want to pollute your machine's global editor with another mode/extension. If you have `nix` installed with `flakes` enabled, you can build a `codium` in this repo for `rescript` development, if you don't want to pollute your machine's global editor with another mode/extension.
``` sh ```sh
nix develop nix develop
codium codium
``` ```
The `nix develop` shell also provides `yarn`. The `nix develop` shell also provides `yarn`.
# Contributing # Contributing
See `CONTRIBUTING.md`.
See `CONTRIBUTING.md`.

View File

@ -8,7 +8,8 @@
"packages/*" "packages/*"
], ],
"resolutions": { "resolutions": {
"@types/react": "^17.0.43" "@types/react": "^18.0.1",
"react": "^18.0.0"
}, },
"packageManager": "yarn@1.22.17" "packageManager": "yarn@1.22.17"
} }

View File

@ -1,5 +0,0 @@
dist
build
node_modules
storybook-static
.storybook

View File

@ -1,31 +1,37 @@
//const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); //const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const custom = require('../webpack.config.js'); const custom = require("../webpack.config.js");
module.exports = { module.exports = {
webpackFinal: async (config) => { webpackFinal: async (config) => {
config.resolve.alias = custom.resolve.alias; config.resolve.alias = custom.resolve.alias;
return { ...config, module: { ...config.module, rules: config.module.rules.concat(custom.module.rules.filter(x => x.loader === "ts-loader")) } }; return {
...config,
module: {
...config.module,
rules: config.module.rules.concat(
custom.module.rules.filter((x) => x.loader === "ts-loader")
),
},
};
}, },
"stories": [ stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
"../src/**/*.stories.mdx", addons: [
"../src/**/*.stories.@(js|jsx|ts|tsx)"
],
"addons": [
"@storybook/addon-links", "@storybook/addon-links",
"@storybook/addon-essentials", "@storybook/addon-essentials",
"@storybook/preset-create-react-app" "@storybook/preset-create-react-app",
], ],
"framework": "@storybook/react", framework: "@storybook/react",
"core": { core: {
"builder": "webpack5" builder: "webpack5",
}, },
typescript: { typescript: {
check: false, check: false,
checkOptions: {}, checkOptions: {},
reactDocgen: 'react-docgen-typescript', reactDocgen: "react-docgen-typescript",
reactDocgenTypescriptOptions: { reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true, shouldExtractLiteralValuesFromEnum: true,
propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true), propFilter: (prop) =>
prop.parent ? !/node_modules/.test(prop.parent.fileName) : true,
}, },
}, },
} };

View File

@ -6,4 +6,4 @@ export const parameters = {
date: /Date$/, date: /Date$/,
}, },
}, },
} };

View File

@ -15,10 +15,10 @@
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"react": "^18.0.0", "react": "^18.0.0",
"react-ace": "9.5.0",
"react-dom": "^18.0.0", "react-dom": "^18.0.0",
"react-scripts": "5.0.0", "react-scripts": "5.0.0",
"react-vega": "^7.5.0", "react-vega": "^7.5.0",
"react-ace": "9.5.0",
"styled-components": "^5.3.5", "styled-components": "^5.3.5",
"tsconfig-paths-webpack-plugin": "^3.5.2", "tsconfig-paths-webpack-plugin": "^3.5.2",
"typescript": "^4.6.3", "typescript": "^4.6.3",
@ -63,9 +63,6 @@
] ]
}, },
"devDependencies": { "devDependencies": {
"@types/styled-components": "^5.1.24",
"css-loader": "^6.7.1",
"style-loader": "^3.3.1",
"@babel/plugin-proposal-private-property-in-object": "^7.16.7", "@babel/plugin-proposal-private-property-in-object": "^7.16.7",
"@storybook/addon-actions": "^6.4.20", "@storybook/addon-actions": "^6.4.20",
"@storybook/addon-essentials": "^6.4.20", "@storybook/addon-essentials": "^6.4.20",
@ -75,9 +72,13 @@
"@storybook/node-logger": "^6.4.20", "@storybook/node-logger": "^6.4.20",
"@storybook/preset-create-react-app": "^4.1.0", "@storybook/preset-create-react-app": "^4.1.0",
"@storybook/react": "^6.4.20", "@storybook/react": "^6.4.20",
"@types/styled-components": "^5.1.24",
"@types/webpack": "^4.41.32", "@types/webpack": "^4.41.32",
"css-loader": "^6.7.1",
"prettier": "^2.6.2", "prettier": "^2.6.2",
"react-codejar": "^1.1.2", "react-codejar": "^1.1.2",
"speed-measure-webpack-plugin": "^1.5.0",
"style-loader": "^3.3.1",
"ts-loader": "^9.2.8", "ts-loader": "^9.2.8",
"webpack": "^5.72.0", "webpack": "^5.72.0",
"webpack-cli": "^4.9.2", "webpack-cli": "^4.9.2",

View File

@ -1,10 +1,8 @@
import * as React from "react"; import * as React from "react";
import _ from "lodash"; import _ from "lodash";
import type { Spec } from "vega"; import type { Spec } from "vega";
import type { import type { Distribution } from "@quri/squiggle-lang";
Distribution, import { distributionErrorToString } from "@quri/squiggle-lang";
} from "@quri/squiggle-lang";
import { distributionErrorToString } from '@quri/squiggle-lang';
import { createClassFromSpec } from "react-vega"; import { createClassFromSpec } from "react-vega";
import * as chartSpecification from "../vega-specs/spec-distributions.json"; import * as chartSpecification from "../vega-specs/spec-distributions.json";
@ -16,12 +14,14 @@ type DistributionChartProps = {
distribution: Distribution; distribution: Distribution;
width: number; width: number;
height: number; height: number;
} };
export const DistributionChart: React.FC<DistributionChartProps> = ({ distribution, width, height }: DistributionChartProps) => { export const DistributionChart: React.FC<DistributionChartProps> = ({
console.log("Making shape") distribution,
width,
height,
}: DistributionChartProps) => {
let shape = distribution.shape(); let shape = distribution.shape();
console.log(shape)
if (shape.tag === "Ok") { if (shape.tag === "Ok") {
return ( return (
<SquiggleVegaChart <SquiggleVegaChart
@ -31,8 +31,7 @@ export const DistributionChart: React.FC<DistributionChartProps> = ({ distributi
actions={false} actions={false}
/> />
); );
} } else {
else{
return <> {distributionErrorToString(shape.value)} </>; return <> {distributionErrorToString(shape.value)} </>;
} }
}; };

View File

@ -7,10 +7,10 @@ const ShowError = styled.div`
padding: 0.4em 0.8em; padding: 0.4em 0.8em;
`; `;
export const Error: React.FC<{ heading: string; children: React.ReactNode }> = ({ export const ErrorBox: React.FC<{
heading = "Error", heading: string;
children, children: React.ReactNode;
}) => { }> = ({ heading = "Error", children }) => {
return ( return (
<ShowError> <ShowError>
<h3>{heading}</h3> <h3>{heading}</h3>

View File

@ -5,15 +5,13 @@ import type { Distribution, errorValue, result } from "@quri/squiggle-lang";
import { createClassFromSpec } from "react-vega"; import { createClassFromSpec } from "react-vega";
import * as percentilesSpec from "../vega-specs/spec-percentiles.json"; import * as percentilesSpec from "../vega-specs/spec-percentiles.json";
import { DistributionChart } from "./DistributionChart"; import { DistributionChart } from "./DistributionChart";
import { Error } from "./Error"; import { ErrorBox } from "./ErrorBox";
let SquigglePercentilesChart = createClassFromSpec({ let SquigglePercentilesChart = createClassFromSpec({
spec: percentilesSpec as Spec, spec: percentilesSpec as Spec,
}); });
type distPlusFn = ( type distPlusFn = (a: number) => result<Distribution, errorValue>;
a: number
) => result<Distribution, errorValue>
const _rangeByCount = (start: number, stop: number, count: number) => { const _rangeByCount = (start: number, stop: number, count: number) => {
const step = (stop - start) / (count - 1); const step = (stop - start) / (count - 1);
@ -22,11 +20,26 @@ const _rangeByCount = (start: number, stop: number, count: number) => {
return result; return result;
}; };
function unwrap<a, b>( x: result<a, b>): a { function unwrap<a, b>(x: result<a, b>): a {
if(x.tag === "Ok"){ if (x.tag === "Ok") {
return x.value return x.value;
} else {
throw Error("FAILURE TO UNWRAP");
} }
} }
function mapFilter<a, b>(xs: a[], f: (x: a) => b | undefined): b[] {
let initial: b[] = [];
return xs.reduce((previous, current) => {
let value: b | undefined = f(current);
if (value !== undefined) {
return previous.concat([value]);
} else {
return previous;
}
}, initial);
}
export const FunctionChart: React.FC<{ export const FunctionChart: React.FC<{
distPlusFn: distPlusFn; distPlusFn: distPlusFn;
diagramStart: number; diagramStart: number;
@ -44,46 +57,45 @@ export const FunctionChart: React.FC<{
let mouseItem = distPlusFn(mouseOverlay); let mouseItem = distPlusFn(mouseOverlay);
let showChart = let showChart =
mouseItem.tag === "Ok" ? ( mouseItem.tag === "Ok" ? (
<DistributionChart distribution={mouseItem.value} width={400} height={140} /> <DistributionChart
distribution={mouseItem.value}
width={400}
height={140}
/>
) : ( ) : (
<></> <></>
); );
let data1 = _rangeByCount(diagramStart, diagramStop, diagramCount); let data1 = _rangeByCount(diagramStart, diagramStop, diagramCount);
let valueData = data1 let valueData = mapFilter(data1, (x) => {
.map((x) => { let result = distPlusFn(x);
let result = distPlusFn(x); if (result.tag === "Ok") {
if (result.tag === "Ok") { return { x: x, value: result.value };
return { x: x, value: result.value }; }
} else return null; }).map(({ x, value }) => {
}) return {
.filter((x) => x !== null) x: x,
.map(({ x, value }) => { p1: unwrap(value.inv(0.01)),
return { p5: unwrap(value.inv(0.05)),
x: x, p10: unwrap(value.inv(0.12)),
p1: unwrap(value.inv(0.01)), p20: unwrap(value.inv(0.2)),
p5: unwrap(value.inv(0.05)), p30: unwrap(value.inv(0.3)),
p10: unwrap(value.inv(0.12)), p40: unwrap(value.inv(0.4)),
p20: unwrap(value.inv(0.20)), p50: unwrap(value.inv(0.5)),
p30: unwrap(value.inv(0.30)), p60: unwrap(value.inv(0.6)),
p40: unwrap(value.inv(0.40)), p70: unwrap(value.inv(0.7)),
p50: unwrap(value.inv(0.50)), p80: unwrap(value.inv(0.8)),
p60: unwrap(value.inv(0.60)), p90: unwrap(value.inv(0.9)),
p70: unwrap(value.inv(0.70)), p95: unwrap(value.inv(0.95)),
p80: unwrap(value.inv(0.80)), p99: unwrap(value.inv(0.99)),
p90: unwrap(value.inv(0.90)), };
p95: unwrap(value.inv(0.95)), });
p99: unwrap(value.inv(0.99)),
};
});
let errorData = data1 let errorData = mapFilter(data1, (x) => {
.map((x) => { let result = distPlusFn(x);
let result = distPlusFn(x); if (result.tag === "Error") {
if (result.tag === "Error") { return { x: x, error: result.value };
return { x: x, error: result.value }; }
} else return null; });
})
.filter((x) => x !== null);
let error2 = _.groupBy(errorData, (x) => x.error); let error2 = _.groupBy(errorData, (x) => x.error);
return ( return (
<> <>
@ -94,11 +106,10 @@ export const FunctionChart: React.FC<{
/> />
{showChart} {showChart}
{_.keysIn(error2).map((k) => ( {_.keysIn(error2).map((k) => (
<Error heading={k}> <ErrorBox heading={k}>
{`Values: [${error2[k].map((r) => r.x.toFixed(2)).join(",")}]`} {`Values: [${error2[k].map((r) => r.x.toFixed(2)).join(",")}]`}
</Error> </ErrorBox>
))} ))}
</> </>
); );
}; };

View File

@ -2,97 +2,97 @@ import * as React from "react";
import _ from "lodash"; import _ from "lodash";
const orderOfMagnitudeNum = (n: number) => { const orderOfMagnitudeNum = (n: number) => {
return Math.pow(10, n); return Math.pow(10, n);
}; };
// 105 -> 3 // 105 -> 3
const orderOfMagnitude = (n: number) => { const orderOfMagnitude = (n: number) => {
return Math.floor(Math.log(n) / Math.LN10 + 0.000000001); return Math.floor(Math.log(n) / Math.LN10 + 0.000000001);
}; };
function withXSigFigs(number: number, sigFigs: number) { function withXSigFigs(number: number, sigFigs: number) {
const withPrecision = number.toPrecision(sigFigs); const withPrecision = number.toPrecision(sigFigs);
const formatted = Number(withPrecision); const formatted = Number(withPrecision);
return `${formatted}`; return `${formatted}`;
} }
class NumberShowerBuilder { class NumberShowerBuilder {
number: number; number: number;
precision: number; precision: number;
constructor(number: number, precision = 2) { constructor(number: number, precision = 2) {
this.number = number; this.number = number;
this.precision = precision; this.precision = precision;
}
convert() {
const number = Math.abs(this.number);
const response = this.evaluate(number);
if (this.number < 0) {
response.value = "-" + response.value;
}
return response;
}
metricSystem(number: number, order: number) {
const newNumber = number / orderOfMagnitudeNum(order);
const precision = this.precision;
return `${withXSigFigs(newNumber, precision)}`;
}
evaluate(number: number) {
if (number === 0) {
return { value: this.metricSystem(0, 0) };
} }
convert() { const order = orderOfMagnitude(number);
const number = Math.abs(this.number); if (order < -2) {
const response = this.evaluate(number); return { value: this.metricSystem(number, order), power: order };
if (this.number < 0) { } else if (order < 4) {
response.value = "-" + response.value; return { value: this.metricSystem(number, 0) };
} } else if (order < 6) {
return response; return { value: this.metricSystem(number, 3), symbol: "K" };
} } else if (order < 9) {
return { value: this.metricSystem(number, 6), symbol: "M" };
metricSystem(number: number, order: number) { } else if (order < 12) {
const newNumber = number / orderOfMagnitudeNum(order); return { value: this.metricSystem(number, 9), symbol: "B" };
const precision = this.precision; } else if (order < 15) {
return `${withXSigFigs(newNumber, precision)}`; return { value: this.metricSystem(number, 12), symbol: "T" };
} } else {
return { value: this.metricSystem(number, order), power: order };
evaluate(number: number) {
if (number === 0) {
return { value: this.metricSystem(0, 0) };
}
const order = orderOfMagnitude(number);
if (order < -2) {
return { value: this.metricSystem(number, order), power: order };
} else if (order < 4) {
return { value: this.metricSystem(number, 0) };
} else if (order < 6) {
return { value: this.metricSystem(number, 3), symbol: "K" };
} else if (order < 9) {
return { value: this.metricSystem(number, 6), symbol: "M" };
} else if (order < 12) {
return { value: this.metricSystem(number, 9), symbol: "B" };
} else if (order < 15) {
return { value: this.metricSystem(number, 12), symbol: "T" };
} else {
return { value: this.metricSystem(number, order), power: order };
}
} }
}
} }
export function numberShow(number: number, precision = 2) { export function numberShow(number: number, precision = 2) {
const ns = new NumberShowerBuilder(number, precision); const ns = new NumberShowerBuilder(number, precision);
return ns.convert(); return ns.convert();
} }
export interface NumberShowerProps { export interface NumberShowerProps {
number: number; number: number;
precision?: number precision?: number;
} }
export let NumberShower: React.FC<NumberShowerProps> = ({ export let NumberShower: React.FC<NumberShowerProps> = ({
number, number,
precision = 2 precision = 2,
}: NumberShowerProps) => { }: NumberShowerProps) => {
let numberWithPresentation = numberShow(number, precision); let numberWithPresentation = numberShow(number, precision);
return ( return (
<span>
{numberWithPresentation.value}
{numberWithPresentation.symbol}
{numberWithPresentation.power ? (
<span> <span>
{numberWithPresentation.value} {"\u00b710"}
{numberWithPresentation.symbol} <span style={{ fontSize: "0.6em", verticalAlign: "super" }}>
{numberWithPresentation.power ? ( {numberWithPresentation.power}
<span> </span>
{"\u00b710"}
<span style={{ fontSize: "0.6em", verticalAlign: "super" }}>
{numberWithPresentation.power}
</span>
</span>
) : (
<></>
)}
</span> </span>
); ) : (
} <></>
)}
</span>
);
};

View File

@ -1,13 +1,10 @@
import * as React from "react"; import * as React from "react";
import _ from "lodash"; import _ from "lodash";
import { run, errorValueToString } from "@quri/squiggle-lang"; import { run, errorValueToString } from "@quri/squiggle-lang";
import type { import type { samplingParams, exportEnv } from "@quri/squiggle-lang";
samplingParams,
exportEnv,
} from "@quri/squiggle-lang";
import { NumberShower } from "./NumberShower"; import { NumberShower } from "./NumberShower";
import { DistributionChart } from "./DistributionChart"; import { DistributionChart } from "./DistributionChart";
import { Error } from "./Error"; import { ErrorBox } from "./ErrorBox";
export interface SquiggleChartProps { export interface SquiggleChartProps {
/** The input string for squiggle */ /** The input string for squiggle */
@ -37,9 +34,6 @@ export const SquiggleChart: React.FC<SquiggleChartProps> = ({
squiggleString = "", squiggleString = "",
sampleCount = 1000, sampleCount = 1000,
outputXYPoints = 1000, outputXYPoints = 1000,
diagramStart = 0,
diagramStop = 10,
diagramCount = 20,
environment = [], environment = [],
onEnvChange = () => {}, onEnvChange = () => {},
width = 500, width = 500,
@ -47,18 +41,16 @@ export const SquiggleChart: React.FC<SquiggleChartProps> = ({
}: SquiggleChartProps) => { }: SquiggleChartProps) => {
let samplingInputs: samplingParams = { let samplingInputs: samplingParams = {
sampleCount: sampleCount, sampleCount: sampleCount,
xyPointLength: outputXYPoints xyPointLength: outputXYPoints,
}; };
let result = run(squiggleString, samplingInputs, environment); let result = run(squiggleString, samplingInputs, environment);
console.log(result)
if (result.tag === "Ok") { if (result.tag === "Ok") {
onEnvChange(environment); onEnvChange(environment);
let chartResult = result.value; let chartResult = result.value;
if (chartResult.tag === "number") { if (chartResult.tag === "number") {
return <NumberShower precision={3} number={chartResult.value} />; return <NumberShower precision={3} number={chartResult.value} />;
} else if (chartResult.tag === "distribution") { } else if (chartResult.tag === "distribution") {
console.log("Is a distribution")
return ( return (
<DistributionChart <DistributionChart
distribution={chartResult.value} distribution={chartResult.value}
@ -66,14 +58,19 @@ export const SquiggleChart: React.FC<SquiggleChartProps> = ({
width={width} width={width}
/> />
); );
console.log("NOT THIS LINE") } else {
return (
<ErrorBox heading="No Viewer">
{"We don't currently have a viewer for this type: " + chartResult.tag}
</ErrorBox>
);
} }
else { } else {
console.log("Is a distribution")
return <Error heading="No Viewer">{"We don't currently have a viewer for this type: " + chartResult.tag}</Error>;
}
} else if (result.tag === "Error") {
// At this point, we came across an error. What was our error? // At this point, we came across an error. What was our error?
return <Error heading={"Parse Error"}>{errorValueToString(result.value)}</Error>; return (
<ErrorBox heading={"Parse Error"}>
{errorValueToString(result.value)}
</ErrorBox>
);
} }
}; };

View File

@ -3,7 +3,7 @@ import * as ReactDOM from "react-dom";
import { SquiggleChart } from "./SquiggleChart"; import { SquiggleChart } from "./SquiggleChart";
import { CodeEditor } from "./CodeEditor"; import { CodeEditor } from "./CodeEditor";
import type { exportEnv } from "@quri/squiggle-lang"; import type { exportEnv } from "@quri/squiggle-lang";
import styled from 'styled-components' import styled from "styled-components";
export interface SquiggleEditorProps { export interface SquiggleEditorProps {
/** The input string for squiggle */ /** The input string for squiggle */

View File

@ -36,10 +36,8 @@ interface Props {
initialSquiggleString?: string; initialSquiggleString?: string;
} }
let SquigglePlayground: FC<Props> = ({initialSquiggleString=""}: Props) => { let SquigglePlayground: FC<Props> = ({ initialSquiggleString = "" }: Props) => {
let [squiggleString, setSquiggleString] = useState( let [squiggleString, setSquiggleString] = useState(initialSquiggleString);
initialSquiggleString
);
let [sampleCount, setSampleCount] = useState(1000); let [sampleCount, setSampleCount] = useState(1000);
let [outputXYPoints, setOutputXYPoints] = useState(1000); let [outputXYPoints, setOutputXYPoints] = useState(1000);
let [pointDistLength, setPointDistLength] = useState(1000); let [pointDistLength, setPointDistLength] = useState(1000);

View File

@ -1,5 +1,8 @@
export { SquiggleChart } from "./components/SquiggleChart"; export { SquiggleChart } from "./components/SquiggleChart";
export { SquiggleEditor, renderSquiggleEditorToDom } from "./components/SquiggleEditor"; export {
SquiggleEditor,
renderSquiggleEditorToDom,
} from "./components/SquiggleEditor";
import SquigglePlayground, { import SquigglePlayground, {
renderSquigglePlaygroundToDom, renderSquigglePlaygroundToDom,
} from "./components/SquigglePlayground"; } from "./components/SquigglePlayground";

View File

@ -3,4 +3,4 @@ import { Meta } from "@storybook/addon-docs";
<Meta title="Squiggle/Introduction" /> <Meta title="Squiggle/Introduction" />
This is the component library for Squiggle. These are React This is the component library for Squiggle. These are React
components, and can be used in any application that you see fit. components, and can be used in any application that you see fit.

View File

@ -14,10 +14,10 @@ It uses the symbols "K", "M", "B", and "T", to represent thousands, millions, bi
name="Ten Thousand" name="Ten Thousand"
args={{ args={{
number: 10000, number: 10000,
precision: 2 precision: 2,
}} }}
> >
{args => <NumberShower {...args}/>} {(args) => <NumberShower {...args} />}
</Story> </Story>
</Canvas> </Canvas>
@ -26,10 +26,10 @@ It uses the symbols "K", "M", "B", and "T", to represent thousands, millions, bi
name="Ten Billion" name="Ten Billion"
args={{ args={{
number: 10000000000, number: 10000000000,
precision: 2 precision: 2,
}} }}
> >
{args => <NumberShower {...args}/>} {(args) => <NumberShower {...args} />}
</Story> </Story>
</Canvas> </Canvas>
@ -38,10 +38,10 @@ It uses the symbols "K", "M", "B", and "T", to represent thousands, millions, bi
name="1.2*10^15" name="1.2*10^15"
args={{ args={{
number: 1200000000000000, number: 1200000000000000,
precision: 2 precision: 2,
}} }}
> >
{args => <NumberShower {...args}/>} {(args) => <NumberShower {...args} />}
</Story> </Story>
</Canvas> </Canvas>
@ -50,10 +50,10 @@ It uses the symbols "K", "M", "B", and "T", to represent thousands, millions, bi
name="1.35*10^-13" name="1.35*10^-13"
args={{ args={{
number: 0.000000000000135, number: 0.000000000000135,
precision: 2 precision: 2,
}} }}
> >
{args => <NumberShower {...args}/>} {(args) => <NumberShower {...args} />}
</Story> </Story>
</Canvas> </Canvas>

View File

@ -50,7 +50,8 @@ could be continuous, discrete or mixed.
<Story <Story
name="Mixed" name="Mixed"
args={{ args={{
squiggleString: "mm(0, 1, 3, 5, 8, normal(8, 1), [0.1, 0.3, 0.4, 0.35, 0.2, 0.8])", squiggleString:
"mm(0, 1, 3, 5, 8, normal(8, 1), [0.1, 0.3, 0.4, 0.35, 0.2, 0.8])",
}} }}
> >
{Template.bind({})} {Template.bind({})}
@ -75,7 +76,7 @@ to allow large and small numbers being printed cleanly.
## Functions ## Functions
Full functions can be returned. These plot out the results of distributions between a set of x-coordinates. Full functions can be returned. These plot out the results of distributions between a set of x-coordinates.
The default is show 10 points between 0 and 10. The default is show 10 points between 0 and 10.

View File

@ -160,7 +160,7 @@
"shape": { "shape": {
"value": "circle" "value": "circle"
}, },
"size": [{"value": 30}], "size": [{ "value": 30 }],
"tooltip": { "tooltip": {
"signal": "datum.y" "signal": "datum.y"
} }

View File

@ -96,11 +96,11 @@
"signals": [ "signals": [
{ {
"name": "mousemove", "name": "mousemove",
"on": [{"events": "mousemove", "update": "invert('xscale', x())"}] "on": [{ "events": "mousemove", "update": "invert('xscale', x())" }]
}, },
{ {
"name": "mouseout", "name": "mouseout",
"on": [{"events": "mouseout", "update": "invert('xscale', x())"}] "on": [{ "events": "mouseout", "update": "invert('xscale', x())" }]
} }
], ],
"axes": [ "axes": [
@ -132,7 +132,7 @@
"type": "rule", "type": "rule",
"encode": { "encode": {
"update": { "update": {
"xscale": {"scale": "xscale", "signal": "mousemove"} "xscale": { "scale": "xscale", "signal": "mousemove" }
} }
} }
}, },

View File

@ -5,10 +5,12 @@
}, },
"module": "commonjs", "module": "commonjs",
"jsx": "react", "jsx": "react",
"skipLibCheck": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"noImplicitAny": false, "noImplicitAny": false,
"esModuleInterop": true, "esModuleInterop": true,
"removeComments": true, "removeComments": true,
"strict": true,
"preserveConstEnums": true, "preserveConstEnums": true,
"composite": true, "composite": true,
"outDir": "./dist", "outDir": "./dist",
@ -16,7 +18,10 @@
"declaration": true, "declaration": true,
"sourceMap": true "sourceMap": true
}, },
"files": ["src/vega-specs/spec-distributions.json", "src/vega-specs/spec-percentiles.json"], "files": [
"src/vega-specs/spec-distributions.json",
"src/vega-specs/spec-percentiles.json"
],
"target": "ES6", "target": "ES6",
"include": ["src/**/*", "src/*"], "include": ["src/**/*", "src/*"],
"exclude": ["node_modules", "**/*.spec.ts", "webpack.config.js"], "exclude": ["node_modules", "**/*.spec.ts", "webpack.config.js"],

View File

@ -3,13 +3,15 @@ const path = require("path");
module.exports = { module.exports = {
mode: "production", mode: "production",
devtool: "source-map", devtool: "source-map",
profile: true,
entry: "./src/index.ts", entry: "./src/index.ts",
module: { module: {
rules: [ rules: [
{ {
test: /\.tsx?$/, test: /\.tsx?$/,
loader: "ts-loader", loader: "ts-loader",
options: { projectReferences: true }, include: path.resolve(__dirname, "src"),
options: { projectReferences: true, transpileOnly: true },
exclude: /node_modules/, exclude: /node_modules/,
}, },
{ {

View File

@ -1,3 +0,0 @@
*.bs.js
*.gen.tsx
dist

View File

@ -1,10 +1,15 @@
import { run, Distribution, resultMap, squiggleExpression } from "../src/js/index"; import {
run,
Distribution,
resultMap,
squiggleExpression,
} from "../src/js/index";
let testRun = (x: string): squiggleExpression => { let testRun = (x: string): squiggleExpression => {
let result = run(x, {sampleCount: 100, xyPointLength: 100}); let result = run(x, { sampleCount: 100, xyPointLength: 100 });
expect(result.tag).toEqual("Ok") expect(result.tag).toEqual("Ok");
if(result.tag === "Ok") { if (result.tag === "Ok") {
return result.value return result.value;
} }
}; };
@ -16,7 +21,7 @@ describe("Simple calculations and results", () => {
test("mean(normal(5,2))", () => { test("mean(normal(5,2))", () => {
expect(testRun("mean(normal(5,2))")).toEqual({ expect(testRun("mean(normal(5,2))")).toEqual({
tag: "number", tag: "number",
value: 5 value: 5,
}); });
}); });
test("10+10", () => { test("10+10", () => {

View File

@ -1,11 +1,26 @@
import * as _ from 'lodash' import * as _ from "lodash";
import type { import type {
exportEnv, exportEnv,
exportDistribution, exportDistribution,
} from "../rescript/ProgramEvaluator.gen"; } from "../rescript/ProgramEvaluator.gen";
export type { exportEnv, exportDistribution }; export type { exportEnv, exportDistribution };
import { genericDist, samplingParams, evaluate, expressionValue, errorValue, distributionError, toPointSet, continuousShape, discreteShape, distributionErrorToString } from "../rescript/TypescriptInterface.gen"; import {
export { makeSampleSetDist, errorValueToString, distributionErrorToString } from "../rescript/TypescriptInterface.gen"; genericDist,
samplingParams,
evaluate,
expressionValue,
errorValue,
distributionError,
toPointSet,
continuousShape,
discreteShape,
distributionErrorToString,
} from "../rescript/TypescriptInterface.gen";
export {
makeSampleSetDist,
errorValueToString,
distributionErrorToString,
} from "../rescript/TypescriptInterface.gen";
import { import {
Constructors_mean, Constructors_mean,
Constructors_sample, Constructors_sample,
@ -32,11 +47,11 @@ import {
Constructors_pointwiseLogarithm, Constructors_pointwiseLogarithm,
Constructors_pointwisePower, Constructors_pointwisePower,
} from "../rescript/Distributions/DistributionOperation/DistributionOperation.gen"; } from "../rescript/Distributions/DistributionOperation/DistributionOperation.gen";
export type {samplingParams, errorValue} export type { samplingParams, errorValue };
export let defaultSamplingInputs: samplingParams = { export let defaultSamplingInputs: samplingParams = {
sampleCount: 10000, sampleCount: 10000,
xyPointLength: 10000 xyPointLength: 10000,
}; };
export type result<a, b> = export type result<a, b> =
@ -60,17 +75,24 @@ export function resultMap<a, b, c>(
} }
} }
function Ok<a,b>(x: a): result<a,b> { function Ok<a, b>(x: a): result<a, b> {
return {"tag": "Ok", value: x} return { tag: "Ok", value: x };
} }
type tagged<a, b> = {tag: a, value: b} type tagged<a, b> = { tag: a; value: b };
function tag<a,b>(x: a, y: b) : tagged<a, b>{ function tag<a, b>(x: a, y: b): tagged<a, b> {
return { tag: x, value: y} return { tag: x, value: y };
} }
export type squiggleExpression = tagged<"symbol", string> | tagged<"string", string> | tagged<"array", squiggleExpression[]> | tagged<"boolean", boolean> | tagged<"distribution", Distribution> | tagged<"number", number> | tagged<"record", {[key: string]: squiggleExpression }> export type squiggleExpression =
| tagged<"symbol", string>
| tagged<"string", string>
| tagged<"array", squiggleExpression[]>
| tagged<"boolean", boolean>
| tagged<"distribution", Distribution>
| tagged<"number", number>
| tagged<"record", { [key: string]: squiggleExpression }>;
export function run( export function run(
squiggleString: string, squiggleString: string,
samplingInputs?: samplingParams, samplingInputs?: samplingParams,
@ -79,15 +101,20 @@ export function run(
let si: samplingParams = samplingInputs let si: samplingParams = samplingInputs
? samplingInputs ? samplingInputs
: defaultSamplingInputs; : defaultSamplingInputs;
let result : result<expressionValue, errorValue> = evaluate(squiggleString); let result: result<expressionValue, errorValue> = evaluate(squiggleString);
return resultMap(result, x => createTsExport(x, si)); return resultMap(result, (x) => createTsExport(x, si));
} }
function createTsExport(
function createTsExport(x: expressionValue, sampEnv: samplingParams): squiggleExpression { x: expressionValue,
sampEnv: samplingParams
): squiggleExpression {
switch (x.tag) { switch (x.tag) {
case "EvArray": case "EvArray":
return tag("array", x.value.map(x => createTsExport(x, sampEnv))); return tag(
"array",
x.value.map((x) => createTsExport(x, sampEnv))
);
case "EvBool": case "EvBool":
return tag("boolean", x.value); return tag("boolean", x.value);
case "EvDistribution": case "EvDistribution":
@ -95,26 +122,32 @@ function createTsExport(x: expressionValue, sampEnv: samplingParams): squiggleEx
case "EvNumber": case "EvNumber":
return tag("number", x.value); return tag("number", x.value);
case "EvRecord": case "EvRecord":
return tag("record", _.mapValues(x.value, x => createTsExport(x, sampEnv))) return tag(
"record",
_.mapValues(x.value, (x) => createTsExport(x, sampEnv))
);
case "EvString":
return tag("string", x.value);
case "EvSymbol":
return tag("symbol", x.value);
} }
} }
export function resultExn<a, c>(r: result<a, c>): a | c { export function resultExn<a, c>(r: result<a, c>): a | c {
return r.value; return r.value;
} }
export type point = { x: number, y: number} export type point = { x: number; y: number };
export type shape = { export type shape = {
continuous: point[] continuous: point[];
discrete: point[] discrete: point[];
} };
function shapePoints(x : continuousShape | discreteShape): point[]{ function shapePoints(x: continuousShape | discreteShape): point[] {
let xs = x.xyShape.xs; let xs = x.xyShape.xs;
let ys = x.xyShape.ys; let ys = x.xyShape.ys;
return _.zipWith(xs, ys, (x, y) => ({x, y})) return _.zipWith(xs, ys, (x, y) => ({ x, y }));
} }
export class Distribution { export class Distribution {
@ -127,7 +160,9 @@ export class Distribution {
return this; return this;
} }
mapResultDist(r: result<genericDist, distributionError>): result<Distribution, distributionError> { mapResultDist(
r: result<genericDist, distributionError>
): result<Distribution, distributionError> {
return resultMap(r, (v: genericDist) => new Distribution(v, this.env)); return resultMap(r, (v: genericDist) => new Distribution(v, this.env));
} }
@ -157,31 +192,35 @@ export class Distribution {
); );
} }
shape() : result<shape, distributionError> { shape(): result<shape, distributionError> {
let pointSet = toPointSet(this.t, {xyPointLength: this.env.xyPointLength, sampleCount: this.env.sampleCount}, null); let pointSet = toPointSet(
if(pointSet.tag === "Ok"){ this.t,
{
xyPointLength: this.env.xyPointLength,
sampleCount: this.env.sampleCount,
},
undefined
);
if (pointSet.tag === "Ok") {
let distribution = pointSet.value; let distribution = pointSet.value;
if(distribution.tag === "Continuous"){ if (distribution.tag === "Continuous") {
return Ok({ return Ok({
continuous: shapePoints(distribution.value), continuous: shapePoints(distribution.value),
discrete: [] discrete: [],
}) });
} } else if (distribution.tag === "Discrete") {
else if(distribution.tag === "Discrete"){
return Ok({ return Ok({
discrete: shapePoints(distribution.value), discrete: shapePoints(distribution.value),
continuous: [] continuous: [],
}) });
} } else {
else if(distribution.tag === "Mixed"){
return Ok({ return Ok({
discrete: shapePoints(distribution.value.discrete), discrete: shapePoints(distribution.value.discrete),
continuous: shapePoints(distribution.value.continuous) continuous: shapePoints(distribution.value.continuous),
}) });
} }
} } else {
else { return pointSet;
return pointSet
} }
} }
@ -197,7 +236,10 @@ export class Distribution {
); );
} }
truncate(left: number, right: number): result<Distribution, distributionError> { truncate(
left: number,
right: number
): result<Distribution, distributionError> {
return this.mapResultDist( return this.mapResultDist(
Constructors_truncate({ env: this.env }, this.t, left, right) Constructors_truncate({ env: this.env }, this.t, left, right)
); );
@ -209,11 +251,10 @@ export class Distribution {
toString(): string { toString(): string {
let result = Constructors_toString({ env: this.env }, this.t); let result = Constructors_toString({ env: this.env }, this.t);
if(result.tag === "Ok"){ if (result.tag === "Ok") {
return result.value return result.value;
} } else {
else { return distributionErrorToString(result.value);
return distributionErrorToString(result.value)
} }
} }
@ -245,7 +286,9 @@ export class Distribution {
); );
} }
algebraicLogarithm(d2: Distribution): result<Distribution, distributionError> { algebraicLogarithm(
d2: Distribution
): result<Distribution, distributionError> {
return this.mapResultDist( return this.mapResultDist(
Constructors_algebraicLogarithm({ env: this.env }, this.t, d2.t) Constructors_algebraicLogarithm({ env: this.env }, this.t, d2.t)
); );
@ -281,7 +324,9 @@ export class Distribution {
); );
} }
pointwiseLogarithm(d2: Distribution): result<Distribution, distributionError> { pointwiseLogarithm(
d2: Distribution
): result<Distribution, distributionError> {
return this.mapResultDist( return this.mapResultDist(
Constructors_pointwiseLogarithm({ env: this.env }, this.t, d2.t) Constructors_pointwiseLogarithm({ env: this.env }, this.t, d2.t)
); );

View File

@ -1 +1 @@
export type Dict_t<T> = { [key: string]: T } export type Dict_t<T> = { [key: string]: T };

View File

@ -7,6 +7,7 @@
"removeComments": true, "removeComments": true,
"preserveConstEnums": true, "preserveConstEnums": true,
"sourceMap": true, "sourceMap": true,
"strict": true,
"outDir": "./dist", "outDir": "./dist",
"declarationDir": "./dist", "declarationDir": "./dist",
"declaration": true, "declaration": true,

View File

@ -1 +0,0 @@
.docusaurus

View File

@ -4025,28 +4025,10 @@
dependencies: dependencies:
"@types/react" "*" "@types/react" "*"
"@types/react@*": "@types/react@*", "@types/react@17.0.43", "@types/react@^16.9.19", "@types/react@^18.0.1":
version "17.0.44" version "17.0.43"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.44.tgz#c3714bd34dd551ab20b8015d9d0dbec812a51ec7" resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.43.tgz#4adc142887dd4a2601ce730bc56c3436fdb07a55"
integrity sha512-Ye0nlw09GeMp2Suh8qoOv0odfgCoowfM/9MG6WeRD60Gq9wS90bdkdRtYbRkNhXOpG4H+YXGvj4wOWhAC0LJ1g== integrity sha512-8Q+LNpdxf057brvPu1lMtC5Vn7J119xrP1aq4qiaefNioQUYANF/CYeK4NsKorSZyUGJ66g0IM+4bbjwx45o2A==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
csstype "^3.0.2"
"@types/react@^16.9.19":
version "16.14.24"
resolved "https://registry.yarnpkg.com/@types/react/-/react-16.14.24.tgz#f2c5e9fa78f83f769884b83defcf7924b9eb5c82"
integrity sha512-e7U2WC8XQP/xfR7bwhOhNFZKPTfW1ph+MiqtudKb8tSV8RyCsovQx2sNVtKoOryjxFKpHPPC/yNiGfdeVM5Gyw==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
csstype "^3.0.2"
"@types/react@^18.0.1":
version "18.0.1"
resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.1.tgz#1b2e02fb7613212518733946e49fb963dfc66e19"
integrity sha512-VnWlrVgG0dYt+NqlfMI0yUYb8Rdl4XUROyH+c6gq/iFCiZ805Vi//26UW38DHnxQkbDhnrIWTBiy6oKZqL11cw==
dependencies: dependencies:
"@types/prop-types" "*" "@types/prop-types" "*"
"@types/scheduler" "*" "@types/scheduler" "*"
@ -15495,6 +15477,13 @@ spdy@^4.0.2:
select-hose "^2.0.0" select-hose "^2.0.0"
spdy-transport "^3.0.0" spdy-transport "^3.0.0"
speed-measure-webpack-plugin@^1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/speed-measure-webpack-plugin/-/speed-measure-webpack-plugin-1.5.0.tgz#caf2c5bee24ab66c1c7c30e8daa7910497f7681a"
integrity sha512-Re0wX5CtM6gW7bZA64ONOfEPEhwbiSF/vz6e2GvadjuaPrQcHTQdRGsD8+BE7iUOysXH8tIenkPCQBEcspXsNg==
dependencies:
chalk "^4.1.0"
split-string@^3.0.1, split-string@^3.0.2: split-string@^3.0.1, split-string@^3.0.2:
version "3.1.0" version "3.1.0"
resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2"