Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<h1>Sum of IID lognormal distributions</h1>
<p>Drag the slider for number of distributions to sum.</p>

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="2" class="slider" id="myRange">
  <p># of IIDs: <span id="demo"></span></p>
</div>
<div id="vis"></div>
<div class="slidecontainer">
  <input type="range" min="1" max="98" value="25" class="slider" id="p50Range">
  <p>p50: <span id="demo1"></span></p>
</div>
<div class="slidecontainer">
  <input type="range" min="2" max="99" value="50" class="slider" id="p90Range">
  <p>p90: <span id="demo2"></span></p>
</div>
</body>
<script>
 
</script>

</html>
              
            
!

CSS

              
                
  <style>
    .slidecontainer {
      width: 100%;
    }

    .slider {
      -webkit-appearance: none;
      width: 100%;
      height: 25px;
      background: #d3d3d3;
      outline: none;
      opacity: 0.7;
      -webkit-transition: .2s;
      transition: opacity .2s;
    }

    .slider:hover {
      opacity: 1;
    }

    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 25px;
      height: 25px;
      background: #04AA6D;
      cursor: pointer;
    }

    .slider::-moz-range-thumb {
      width: 25px;
      height: 25px;
      background: #04AA6D;
      cursor: pointer;
    }
  </style>

  <style media="screen">
    /* Add space between Vega-Embed links  */
    .vega-actions a {
      margin-right: 5px;
    }
  </style>
              
            
!

JS

              
                
function genMetalog(data, iids,p50,p90) {
    var defaults = data
    // lognormals need the 90p and 50p OR or derive from mu sigma
    // let p90 = EXP(sigma*NORMSINV(0.9)+mu)
    // let p50 EXP(Input_mu)
    let qShape = p90 / p50;
    let seedPerDist = 1
    let numberOfTrials = 1000;
    // Find nearest lower and higher qShape value in array 
    result = data.reduce(function (r, a, i, aa) {
        return i && Math.abs(aa[r].qShape - qShape) < Math.abs(a.qShape - qShape) ? r : i;
    }, -1);
    let lowShape, highShape;
    let lowShapeIndex, highShapeIndex;
    let beta ,alpha;
    if (qShape == data[result].qShape) { 
        lowShape = data[result].qShape;
        highShape = data[result].qShape;
        lowShapeIndex = result;
        highShapeIndex = result;
    } else if (qShape > data[result].qShape) {
        lowShape = data[result].qShape;
        highShape = data[result + 1].qShape;
        lowShapeIndex = result;
        highShapeIndex = result + 1;
        // console.log("qShape is greater than ", qShape, data[result].qShape, lowShape, highShape);
    } else if (qShape < data[result].qShape) {
        lowShape = data[result - 1].qShape;
        highShape = data[result].qShape;
        lowShapeIndex = result - 1;
        highShapeIndex = result;
        // console.log("qShape is less than ", qShape, data[result].qShape, lowShape, highShape);
    }
    // Find nearest lower and higher numberOfIds in array
    function x(numIidsCols, qty) { // find lower key
        var prev = -1;
        var i;
        for (i in numIidsCols) {
            var n = parseInt(i);
            if ((prev != -1) && (qty < n)) {
                if (prev == qty) {
                    n = prev
                }
                const introp = [prev, n];
                return introp;
            } else
                prev = n;
        }
    }
    const iidRange = x(data[0].data[0], iids)
    let lowNumberOfIds = iidRange[0]
    let highNumberOfIds = iidRange[1]
    // Get all 9 aCoeffs for each numberOfIds (lower and higher)
    let aCoeffLower = [
        [],
        []
    ];
    let aCoeffHighShape = [
        [],
        []
    ];
    for (let i = 0; i < data[result].data.length; i++) { 
        // foreach acoeff in table there are 9 total
        // find the key that matches the lowernumberOfIds and get value field
        aCoeffLower[0][i] = data[lowShapeIndex].data[i][lowNumberOfIds];
        aCoeffLower[1][i] = data[lowShapeIndex].data[i][highNumberOfIds];
        aCoeffHighShape[0][i] = data[highShapeIndex].data[i][lowNumberOfIds];
        aCoeffHighShape[1][i] = data[highShapeIndex].data[i][highNumberOfIds];
    }
    // console.log(aCoeffLower, aCoeffHighShape);
    try {
         beta = (iids - lowNumberOfIds) / (highNumberOfIds - lowNumberOfIds)
         if (isNaN(beta)) {
             beta = 1
          }
    } catch (err) {
      //  console.log('beta Not a Number!');
    } 
    try {
        alpha = (qShape - lowShape) / (highShape - lowShape)
   } catch (err) {
        alpha = 1
   }  

  //  console.log(`beta: ${beta}, alpha ${alpha}`)
    // interpolate aCoeffs =beta*L5#+(1-beta)*K5#
    let finalACoeffsTable = [
        [],
        []
    ];

    for (let i = 0; i < aCoeffLower[0].length; i++) { 
      //  console.log(aCoeffLower[1][i], aCoeffLower[0][i])
        finalACoeffsTable[0][i] = beta * aCoeffLower[1][i] + (1 - beta) * aCoeffLower[0][i];
    }
  //  console.log(finalACoeffsTable);

    for (let i = 0; i < aCoeffHighShape[0].length; i++) { 
      //  console.log(aCoeffHighShape[1][i], aCoeffHighShape[0][i])
        finalACoeffsTable[1][i] = beta * aCoeffHighShape[1][i] + (1 - beta) * aCoeffHighShape[0][i];
    };
  //  console.log(finalACoeffsTable);
    // final step =(alpha*$N14+(1-alpha)*$N5)
    let finalACoeffs = [];

    for (let i = 0; i < finalACoeffsTable[0].length; i++) { // TODO lowShapeIndex and highShapeIndex instead!! twice
      //  console.log(aCoeffHighShape[1][i], aCoeffHighShape[0][i])
        finalACoeffs[i] = alpha * finalACoeffsTable[1][i] + (1 - alpha) * finalACoeffsTable[0][i];
    };
    // this will be the acoeffs and shape to call metalog function with
    // console.log(finalACoeffs);

    let trialsVector = [];
    var samples = [];

    for (var distTrials = 0; distTrials < numberOfTrials; distTrials++) {
        samples[distTrials] = HDRando(seedPerDist, distTrials);
    }
    for (let i = 0; i < samples.length; i++) {
        trialsVector[i] = iids * p50 * metalog(samples[i], finalACoeffs, 0)
    }

    return trialsVector
}
// Version: 0.1
// Author: KMac
// Date: Nov 9, 2021
// TODO replace HDRando and use npm i hdr2, make sure seeds are used properly


function metalog(y, a, bl = "", bu = "") {
    // y = array of unis, a = aacoeffs
    //km console.log("how many of aCoeffs ", a.length);
    function convert_to_float(a) {
        // Using parseFloat() method
        var floatValue = parseFloat(a);
        // Return float value
        return floatValue;
    }
  let vector = [];
     let np_a = a; 
    for (let index = 1; index < (a.length + 1); ++index) { //cant start with 0 coeeffs for each aCoeff
        vector.push(basis(y, index));
    }
    let wrappedVector = [vector];
    let wrappedNp_x = [np_a];
    let wrappedNp_a = wrappedNp_x[0].map(e => [e])
    let mky = multiply(wrappedVector, wrappedNp_a);
    // console.log("mm array of unis with acoeffs HERE ", mky); // Important check point

    // Unbounded
    if (typeof (bl) == String && typeof (bu) == String) {
        return mky; // working
    }
    if (
        (typeof bl === "string" || bl instanceof String) &&
        (typeof bu === "string" || bu instanceof String)
    ) {
        return mky; // TODO not tested!! may not be needed for hackathon
    }
    // Bounded lower
    else if (typeof bl !== "string" && typeof bu == "string") {
        convert_to_float(bl);
        return bl + Math.exp(mky); // TODO not tested!! may not be needed for hackathon
    }
    // Bounded upper
    else if (typeof bl == "string" && typeof bu != "string") {
        convert_to_float(bu);
        return bu - Math.exp(-mky); // TODO not tested!! may not be needed for hackathon
    }
    // Bounded
    else if (typeof bl != "string" && typeof bu != "string") {
        return bl + (bu * Math.exp(mky)) / (1 + Math.exp(mky)); // TODO not tested!! may not be needed for hackathon
    }
}

function basis(y, t) { // y must be uniform 0-1
    // console.log("aCoeff position in basis ", t, y);
    //console.log("y in basis ", y);
    let ret = 0;
    if (t === 1) {
        ret = 1;
    } else if (t === 2) {
        ret = Math.log(y / (1 - y));
        if (isNaN(ret)) {
        }
    } else if (t === 3) {
        ret = (y - 0.5) * Math.log(y / (1 - y));
        if (isNaN(ret)) {
            console.log("ret when t3 ", y, ret);
        }
    } else if (t === 4) {
        ret = y - 0.5;
        if (isNaN(ret)) {
        }
    } else if (t >= 5 && t % 2 === 1) {
        ret = Math.pow(y - 0.5, Math.floor((t - 1) / 2));
        if (isNaN(ret)) {
        }
    } // requires js int division
    else if (t >= 6 && t % 2 === 0) {
        ret = Math.pow(y - 0.5, Math.floor((t - 1) / 2)) * Math.log(y / (1 - y));
        if (isNaN(ret)) {
        }
    } // requires js int division need to check if this is correct
    return ret;
}
// TODO IMPORTANT - update this to use hdr2 see nmp i hdr2
// hubbardresearch.com for more info. This is a function that generates the random numbers with seeds.
// TODO update this to use all the seeds from the U01/RNG ie use HRDv2. Move into own package?
function HDRando(seed, PM_Index) {
    const largePrime = 2147483647;
    const million = 1000000;
    const tenMillion = 10000000;
    // We need this in js unles we find a modulo function
    function MOD(n, m) {
        var remain = n % m;
        return Math.floor(remain >= 0 ? remain : remain + m);
    }
    let randi =
        (MOD(
                (MOD(
                        (seed + million) ^ (2 + (seed + million) * (PM_Index + tenMillion)),
                        99999989
                    ) +
                    1000007) *
                (MOD(
                        (PM_Index + tenMillion) ^
                        (2 +
                            (PM_Index + tenMillion) *
                            MOD(
                                (seed + million) ^
                                (2 + (seed + million) * (PM_Index + tenMillion)),
                                99999989
                            )),
                        99999989
                    ) +
                    1000013),
                largePrime
            ) +
            0.5) /
        largePrime;
    return randi;
}
// HELPER FUNCTIONS: Removed need for jstat


function multiply(a, b) {
    //console.log("a ", a, "b", b);
    var aNumRows = a.length,
        aNumCols = a[0].length || 0, // if a is a vector
        bNumRows = b.length,
        bNumCols = b[0].length || 0,
        m = new Array(aNumRows); // initialize array of rows
    //console.log("aNumRows ", aNumRows, "aNumCols ", aNumCols,"bNumCols",bNumCols,"bNumCols",bNumCols);
    for (var r = 0; r < aNumRows; ++r) {
        m[r] = new Array(bNumCols); // initialize the current row
        for (var c = 0; c < bNumCols; ++c) {
            //console.log("r ", r, "c ", c);
            m[r][c] = 0; // initialize the current cell
            for (var i = 0; i < aNumCols; ++i) {
                m[r][c] += a[r][i] * b[i][c];
                // console.log("a[r][i] ", a[r][i]);
            }
        }
    }
    return m;
}


var iidslider = document.getElementById("myRange");
  var output = document.getElementById("demo");
  output.innerHTML = iidslider.value;
  var p50slider = document.getElementById("p50Range");
  var p50output = document.getElementById("demo1");
  p50output.innerHTML = p50slider.value;
  var p90slider = document.getElementById("p90Range");
  var p90output = document.getElementById("demo2");
  p90output.innerHTML = p90slider.value;
  let vegaData = {
    chartTable: [{
        a: 1,
        b: 10
      },
      {
        a: 2,
        b: 10
      },
      {
        a: 3,
        b: 10
      },
      {
        a: 4,
        b: 10
      },
    ]
  };
  // Classic example of what not to do in a real app DRY violation
  iidslider.oninput = function () {
    var vlSpec = {
      $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
      data: {
        values: vegaData.chartTable
      },
      "mark": "bar",
      "encoding": {
        "x": {
          "bin": true,
          "field": "b"
        },
        "y": {
          "aggregate": "count"
        }
      }

    };
    output.innerHTML = this.value;

    let trialsOut = genMetalog(table, iidslider.value, p50slider.value, p90slider.value);
    trialsOut.forEach((element, index1) => {
      vegaData.chartTable[index1] = {
        "a": index1,
        "b": element,
      };
    });

    // Assign the specification to a local variable vlSpec.
    // Embed the visualization in the container with id `vis`
    vegaEmbed('#vis', vlSpec);
  }
  p50slider.oninput = function () {
    var vlSpec = {
      $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
      data: {
        values: vegaData.chartTable
      },
      "mark": "bar",
      "encoding": {
        "x": {
          "bin": true,
          "field": "b"
        },
        "y": {
          "aggregate": "count"
        }
      }

    };
    p50output.innerHTML = this.value;
    let trialsOut = genMetalog(table, iidslider.value, p50slider.value, p90slider.value);
    trialsOut.forEach((element, index1) => {
      vegaData.chartTable[index1] = {
        "a": index1,
        "b": element,
      };
    });

    // Assign the specification to a local variable vlSpec.
    // Embed the visualization in the container with id `vis`
    vegaEmbed('#vis', vlSpec);
  }
  p90slider.oninput = function () {
    var vlSpec = {
      $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
      data: {
        values: vegaData.chartTable
      },
      "mark": "bar",
      "encoding": {
        "x": {
          "bin": true,
          "field": "b"
        },
        "y": {
          "aggregate": "count"
        }
      }

    };
    p90output.innerHTML = this.value;
    let trialsOut = genMetalog(table, iidslider.value, p50slider.value, p90slider.value);
    trialsOut.forEach((element, index1) => {
      vegaData.chartTable[index1] = {
        "a": index1,
        "b": element,
      };
    });

    // Assign the specification to a local variable vlSpec.
    // Embed the visualization in the container with id `vis`
    vegaEmbed('#vis', vlSpec);
  }
              
            
!
999px

Console