Click to show TOC

Introduction

This is a very simple TryITjs file. It has only one page.

Code example

This is a simple code example to create a javascript array and display it.

Press the RUN button to execute the code (you can eddit the code and run again if you like)

 
 
   
Simple array of strings
 

What just happened, if you execute the code above it will display the array just created.

Note: the last expression array is displayed.

Content of basic.try (generated this content)

Showing a .try file

Below you will find the contents of basic.try file use to generate this page

!head
  ~~lt%%title~~gt%%First Tryit~~lt%%/title~~gt%%
  ~~lt%%link rel="stylesheet" href="/ref/stylesheets/tryit.css" /~~gt%%
  @@include tools/head.try

!md 
  # Introduction
  This is a very simple **TryITjs** file. It has only one page.

  ## Code example

  This is a simple code example to create a javascript array and display it.

  Press the RUN button to execute the code (you can eddit the code and run again if you like)


!tryit Simple array of strings
  var array = [ 'a String', 1 , { name: 'tryit'} ]; // array with a `string`, `number`, and an `object`
  array // the last expression is always displayed (except if the value is undefined) 


!md
  **What just happened**, if you execute the code above it will display the array just created. 

  __Note: the last expression `array` is displayed.__




  ## Content of basic.try (generated this content)
  ### Showing a .try file

  Below you will find the contents of basic.try file use to generate this page


  ```tryit
     @@include SHOW basic.try
  ```
  ### Showing a .try file

  The code snippet below will render the contents of a try file. Note, the __@@include__ must be followed by the
  word __ESCAPE__ to let the processor know the contents of the file is for display (ESCAPE tells the system not to process the contents as .try instructions )

!render-start fast-epi.try
    \ 
    !md
    # Fast risk factor

    This is a more optimized risk factor calculator usin the log(e(x)) = log(Total) property. This linearizes the problem.

    !tryit

            var LogTC = class { 
                constructor(factorEstimates, factorIndicators, realFactor) {
                    if(factorEstimates.factorFlag) {
                        this.factorFlag = factorEstimates.factorFlag;
                        this.logReal = factorEstimates.logReal; 
                    } 
                    else {
                        this.factorFlag = Array.isArray(factorIndicators)? factorIndicators.slice() : factorIndicators();
                        this.logReal = (this.getRisk(realFactor)+Math.log((1 + normalSample())*1.5)); // log(realCost)
                    }
                    this.logCurrent = 0; // log of current cost
                }

                get real() { return Math.exp(this.logReal); }
                get current() { return Math.exp(this.logCurrent); }

                getRisk(factors) {
                    let sumOfFactors = (total, v, i) =~~gt%% total+(v?factors[i]:0);
                    return this.factorFlag.reduce(sumOfFactors, 0);
                }

                getCostIndex(factors) {
                        return sum(this.factorFlag, ((s, v, i) =~~gt%% v?s+factor[i]:s));
                }

                hasRiskFactor(i) {
                    return !!this.factorFlag[i];
                }

                setCurrent(factorEstimates) {
                    this.logCurrent = this.getRisk(factorEstimates);
                }

                // derivitive of the factor with respect to factor[i], this is used to perform a gradient descent
                // search to the optimal value of the factors so that RMS difference of actual cost to computed cost based
                // on the factors is minimized.
                dx(i,scale=1) {
                    if(!this.hasRiskFactor(i)) return 0;
                    return -(this.logCurrent-this.logReal)/scale;
                }
            }



    !tryit
            //           Base comp1 comp2 ...
            var actualFactors = [300, 1.3,  1.05,  1.11, 1.80, 1.52, 1.01].map(x =~~gt%% Math.log(x)); // the actual values of the factors


            // factorEstimates represents the values we are trying to compute from the data 
            // (hopefully the values will be close to the values in ```actualFactors```)
            var factorEstimates =  [ 1,  1,    1,     1,    1, 1, 1];



            function getKeyData(epiList, factorEstimates) {
                epiList.forEach(e =~~gt%% e.setCurrent(factorEstimates));
                let key = epiList.map(e =~~gt%% e.logCurrent);
                let val = epiList.map(e =~~gt%% e.real);
                return [key, val];
            }



            function getTotal(epi) {
                return sum(epi.map(t =~~gt%% t.real));
            }

            // sum the derivitives of factor 'i' 
            // function dx(episodes,i) {
            //     return episodes.reduce((sum,t) =~~gt%% sum+t.dx(i), 0)/episodes.length;
            // }

            // function computeUpdatedFactors(episodes, factorEstimates, ep) {
            //     let res =  factorEstimates.map( (c,i) =~~gt%% c+(dx(episodes,i)*ep));
            //     episodes.forEach(t =~~gt%% t.setCurrent(res));
            //     return res;
            // }


            function Test(epiList, ITER, EPSILON, EPI_COUNT, Episode=LogTC, scaleFn=undefined ) {
                var episodesL;
                if(epiList===undefined) {
                    epiFlags = range(EPI_COUNT).map( () =~~gt%% fill())
                    episodesL = epiFlags.map((fill) =~~gt%% new Episode(factorEstimates,fill, actualFactors));
                }
                else { 
                    episodesL = epiList.map((e) =~~gt%% new Episode(e));
                }
                var total=sum(episodesL.map(t =~~gt%% t.real));;
                //$$.D(dx(episodesL, 3), episodesL.length );
                let tcomp = factorEstimates;
                if(!scaleFn) scaleFn = (i) =~~gt%% episodesL.length;
                else scaleFn = scaleFn(episodesL, tcomp);
                let results = [];
                for(let i=0; i~~lt%% ITER; i++) {
                    tcomp = computeUpdatedFactors(episodesL, tcomp, EPSILON,scaleFn);
                    results.push(tcomp);
                }
                let costToMember = sum(episodesL.map(t =~~gt%% rect(t.real-t.current)));
                let costSaved = sum(episodesL.map(t =~~gt%% rect(t.current-t.real)));
                let outOfPocketMembers = sum(episodesL.map(t =~~gt%% clamp(t.real-t.current)));
                $$.D(sum(episodesL.map(t =~~gt%% t.real-t.current)), costToMember/outOfPocketMembers, costToMember, total, costSaved, 
                        outOfPocketMembers, max(episodesL.map(t =~~gt%% t.real-t.current)));
                return [episodesL,results, [tcomp.map((v,i) =~~gt%% (Math.exp(v)-Math.exp(actualFactors[i]))/Math.exp(actualFactors[i])*100+'%'), expL(tcomp), expL(actualFactors)]];

            }  

            var [epiList, results, rest] = Test(episodes, ITER, 0.05, EPI_COUNT,LogTC, (epiList) =~~gt%% () =~~gt%% epiList.length);
            rest;
                //var t = new C();
                //t.getRisk(actualFactors);
                //$$.D(actualFactors, t.getRisk(actualFactors));
                //t

    !md

            # Factor based optimization
            This section we will show how the multiplicative concept of optimization can be used compute the gradient descent
            algorithm

    !tryit

        var id = document.getElementById('my_dataviz');
        id.innerHTML = '';
        var margin = {top: 10, right: 30, bottom: 30, left: 60},
            width = 1024 - margin.left - margin.right,
            height = 512 - margin.top - margin.bottom;
            // append the svg object to the body of the page
            var svg = d3.select("#my_dataviz")
              .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
              .append("g")
                .attr("transform",
                      "translate(" + margin.left + "," + margin.top + ")")

        //Read the data
        d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/2_TwoNum.csv", function(data) {
        var epi = 1?episodes:epiList; // 
          // Add X axis
          var x = d3.scaleLog()
            .domain([1, 1])
            .range([ 0, width ]);
          svg.append("g")
            .attr("class", "myXaxis")   // Note that here we give a class to the X axis, to be able to call it later and modify it
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x))
            .attr("opacity", "0")
          var [yLow, yHigh] = d3.extent(epi.map(d =~~gt%% d.real));
          // Add Y axis
          var y = d3.scaleLinear()
            //.domain([1, 500000])
            .domain([1, yHigh])
            .range([ height, 0]);
          svg.append("g")
            .call(d3.axisLeft(y));

          // Add dots
          svg.append('g')
            .selectAll("dot")
            //.data(data)
            .data(epi)
            .enter()
            .append("circle")
              // .attr("cx", function (d) { return x(d.GrLivArea); } )
              // .attr("cy", function (d) { return y(d.SalePrice); } )
              .attr("cx", function (d) { return x(d.current); } )
              .attr("cy", function (d) { return y(d.real); } )
              .attr("r", 5)
              .style("fill", "#69b3a2")

          var [xLow, xHigh] = d3.extent(epi.map(d =~~gt%% d.current));
          // new X axis
          //x.domain([0, 4000])
          x.domain([xLow/2, xHigh])
          svg.select(".myXaxis")
            .transition()
            .duration(2000)
            .attr("opacity", "0.75")
            .call(d3.axisBottom(x));

          svg.selectAll("circle")
            .transition()
            .delay(function(d,i){return(i*1)})
            .duration(1000)
            .attr("cx", function (d) { return x(d.current); } )
            .attr("cy", function (d) { return y(d.real); } )
            .attr("opacity", "0.1")
        });
        0

    !html
        ~~lt%%div id="my_dataviz"~~gt%%~~lt%%/div~~gt%%

!render-end
!md
  ## Files included

  Including a file using `@@include filePathOrURL` will copy the contents into the file. The basic.try file includes
  the __tools/head.try__, you can see it's content below.

  ```tryit
     @@include ESCAPE tools/head.try
  ```

Showing a .try file

The code snippet below will render the contents of a try file. Note, the @@include must be followed by the word ESCAPE to let the processor know the contents of the file is for display (ESCAPE tells the system not to process the contents as .try instructions )

fast-epi.try
!md
# Fast risk factor

This is a more optimized risk factor calculator usin the log(e(x)) = log(Total) property. This linearizes the problem.
!tryit
var LogTC = class { 
    constructor(factorEstimates, factorIndicators, realFactor) {
        if(factorEstimates.factorFlag) {
            this.factorFlag = factorEstimates.factorFlag;
            this.logReal = factorEstimates.logReal; 
        } 
        else {
            this.factorFlag = Array.isArray(factorIndicators)? factorIndicators.slice() : factorIndicators();
            this.logReal = (this.getRisk(realFactor)+Math.log((1 + normalSample())*1.5)); // log(realCost)
        }
        this.logCurrent = 0; // log of current cost
    }

    get real() { return Math.exp(this.logReal); }
    get current() { return Math.exp(this.logCurrent); }

    getRisk(factors) {
        let sumOfFactors = (total, v, i) => total+(v?factors[i]:0);
        return this.factorFlag.reduce(sumOfFactors, 0);
    }

    getCostIndex(factors) {
            return sum(this.factorFlag, ((s, v, i) => v?s+factor[i]:s));
    }

    hasRiskFactor(i) {
        return !!this.factorFlag[i];
    }

    setCurrent(factorEstimates) {
        this.logCurrent = this.getRisk(factorEstimates);
    }

    // derivitive of the factor with respect to factor[i], this is used to perform a gradient descent
    // search to the optimal value of the factors so that RMS difference of actual cost to computed cost based
    // on the factors is minimized.
    dx(i,scale=1) {
        if(!this.hasRiskFactor(i)) return 0;
        return -(this.logCurrent-this.logReal)/scale;
    }
}


!tryit
//           Base comp1 comp2 ...
var actualFactors = [300, 1.3,  1.05,  1.11, 1.80, 1.52, 1.01].map(x => Math.log(x)); // the actual values of the factors


// factorEstimates represents the values we are trying to compute from the data 
// (hopefully the values will be close to the values in ```actualFactors```)
var factorEstimates =  [ 1,  1,    1,     1,    1, 1, 1];



function getKeyData(epiList, factorEstimates) {
    epiList.forEach(e => e.setCurrent(factorEstimates));
    let key = epiList.map(e => e.logCurrent);
    let val = epiList.map(e => e.real);
    return [key, val];
}



function getTotal(epi) {
    return sum(epi.map(t => t.real));
}

// sum the derivitives of factor 'i' 
// function dx(episodes,i) {
//     return episodes.reduce((sum,t) => sum+t.dx(i), 0)/episodes.length;
// }

// function computeUpdatedFactors(episodes, factorEstimates, ep) {
//     let res =  factorEstimates.map( (c,i) => c+(dx(episodes,i)*ep));
//     episodes.forEach(t => t.setCurrent(res));
//     return res;
// }


function Test(epiList, ITER, EPSILON, EPI_COUNT, Episode=LogTC, scaleFn=undefined ) {
    var episodesL;
    if(epiList===undefined) {
        epiFlags = range(EPI_COUNT).map( () => fill())
        episodesL = epiFlags.map((fill) => new Episode(factorEstimates,fill, actualFactors));
    }
    else { 
        episodesL = epiList.map((e) => new Episode(e));
    }
    var total=sum(episodesL.map(t => t.real));;
    //$$.D(dx(episodesL, 3), episodesL.length );
    let tcomp = factorEstimates;
    if(!scaleFn) scaleFn = (i) => episodesL.length;
    else scaleFn = scaleFn(episodesL, tcomp);
    let results = [];
    for(let i=0; i< ITER; i++) {
        tcomp = computeUpdatedFactors(episodesL, tcomp, EPSILON,scaleFn);
        results.push(tcomp);
    }
    let costToMember = sum(episodesL.map(t => rect(t.real-t.current)));
    let costSaved = sum(episodesL.map(t => rect(t.current-t.real)));
    let outOfPocketMembers = sum(episodesL.map(t => clamp(t.real-t.current)));
    $$.D(sum(episodesL.map(t => t.real-t.current)), costToMember/outOfPocketMembers, costToMember, total, costSaved, 
            outOfPocketMembers, max(episodesL.map(t => t.real-t.current)));
    return [episodesL,results, [tcomp.map((v,i) => (Math.exp(v)-Math.exp(actualFactors[i]))/Math.exp(actualFactors[i])*100+'%'), expL(tcomp), expL(actualFactors)]];

}  

var [epiList, results, rest] = Test(episodes, ITER, 0.05, EPI_COUNT,LogTC, (epiList) => () => epiList.length);
rest;
    //var t = new C();
    //t.getRisk(actualFactors);
    //$$.D(actualFactors, t.getRisk(actualFactors));
    //t
!md
# Factor based optimization
This section we will show how the multiplicative concept of optimization can be used compute the gradient descent
algorithm
!tryit
var id = document.getElementById('my_dataviz');
id.innerHTML = '';
var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 1024 - margin.left - margin.right,
    height = 512 - margin.top - margin.bottom;
    // append the svg object to the body of the page
    var svg = d3.select("#my_dataviz")
      .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform",
              "translate(" + margin.left + "," + margin.top + ")")

//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/2_TwoNum.csv", function(data) {
var epi = 1?episodes:epiList; // 
  // Add X axis
  var x = d3.scaleLog()
    .domain([1, 1])
    .range([ 0, width ]);
  svg.append("g")
    .attr("class", "myXaxis")   // Note that here we give a class to the X axis, to be able to call it later and modify it
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .attr("opacity", "0")
  var [yLow, yHigh] = d3.extent(epi.map(d => d.real));
  // Add Y axis
  var y = d3.scaleLinear()
    //.domain([1, 500000])
    .domain([1, yHigh])
    .range([ height, 0]);
  svg.append("g")
    .call(d3.axisLeft(y));

  // Add dots
  svg.append('g')
    .selectAll("dot")
    //.data(data)
    .data(epi)
    .enter()
    .append("circle")
      // .attr("cx", function (d) { return x(d.GrLivArea); } )
      // .attr("cy", function (d) { return y(d.SalePrice); } )
      .attr("cx", function (d) { return x(d.current); } )
      .attr("cy", function (d) { return y(d.real); } )
      .attr("r", 5)
      .style("fill", "#69b3a2")

  var [xLow, xHigh] = d3.extent(epi.map(d => d.current));
  // new X axis
  //x.domain([0, 4000])
  x.domain([xLow/2, xHigh])
  svg.select(".myXaxis")
    .transition()
    .duration(2000)
    .attr("opacity", "0.75")
    .call(d3.axisBottom(x));

  svg.selectAll("circle")
    .transition()
    .delay(function(d,i){return(i*1)})
    .duration(1000)
    .attr("cx", function (d) { return x(d.current); } )
    .attr("cy", function (d) { return y(d.real); } )
    .attr("opacity", "0.1")
});
0
        
!html
<div id="my_dataviz"></div>

Files included

Including a file using @@include filePathOrURL will copy the contents into the file. The basic.try file includes the tools/head.try, you can see it's content below.

!head
~~lt%%meta name="viewport" content="width=device-width, initial-scale=0.7"~~gt%%
~~lt%%script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"~~gt%%~~lt%%/script~~gt%%
~~lt%%link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.2.0/build/styles/solarized-light.min.css"~~gt%%
~~lt%%style~~gt%%
img.screenshot {
  margin-left: 7rem;
  width: 20%;
  height: auto;
  transition: 1s width, 1s height;
}

img.screenshot:hover {
  margin-left: 2rem;
  width: 80%;
  height: auto;

}
~~lt%%/style~~gt%%
!md



Page - 1