Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <body onload="run();">
  
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style src="style.css"></style>

  <div style="height:10px;"></div>
  <h2>Dynamic Reactor Simulation</h2>
  <p>Proof-of concept using RK4 algorithm and Chart.js to solve a differential-algebraic system of equations</p>
  <p>One-dimensional Isothermal & Isobaric simulation of Ammonia Production </p>
  <p>0.5 N<sub>2</sub> + 1.5 H<sub>2</sub> ⇌ NH<sub>3</sub></p>
  <p>Inlet composition: </p>

  <span>N<sub>2</sub>:</span> <input type="number" min="0" max="1" step="0.1" value="0.5" id="input_x_N2" class="inputBox">
  <span>H<sub>2</sub>:</span> <input type="number" min="0" max="1" step="0.1" value="0.5" id="input_x_H2" class="inputBox">
  <span>NH<sub>3</sub>:</span> <input type="number" min="0" max="1" step="0.1" value="0.0" id="input_x_NH3" class="inputBox">

  <div class="slidecontainer" style="margin-top:30px;">
    <span>Resolution:</span> <input type="range" min="1" max="200" value="100" class="slider" id="myRange"> <span id="sliderValue"></span>
  </div>

  <!-- script to display slider value -->
  <script>
    var slider = document.getElementById("myRange");
    var output = document.getElementById("sliderValue");
    output.innerHTML = slider.value; // Display the default slider value
    // Update the current slider value (each time you drag the slider handle)
    slider.oninput = function() {
      output.innerHTML = this.value;
      console.log(document.getElementById("myRange").value);
    }
  </script>

  <div style="height:30px;"></div>

  <div style="margin: auto; padding: 20px; width:70vw; height:auto; background-color:aliceblue;"><canvas id="myChart"></canvas></div>
  <div style="height:20px;"></div>
  <div style="margin: auto; padding: 20px; width:70vw; height:auto; background-color:aliceblue; display:none;"><canvas id="myChart2"></canvas></div>
  <div style="height:20px;"></div>

  <button id="button" onclick="run();">Graph</button>
  <div style="height:20px;"></div>

  <script src="script.js"></script>
 </body>
              
            
!

CSS

              
                body {
  background: #222;
  color: white;
  text-align: center;
  font-family: "Raleway", sans-serif;
}

.slidecontainer {
  width: 100%; /* Width of the outside container */
}

/* The slider itself */
.slider {
  -webkit-appearance: none; /* Override default CSS styles */
  appearance: none;
  width: 20%; /* Full-width */
  height: 10px; /* Specified height */
  background: #d3d3d3; /* Grey background */
  outline: none; /* Remove outline */
  opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
  -webkit-transition: 0.2s; /* 0.2 seconds transition on hover */
  transition: opacity 0.2s;
  border-radius: 20px;
  cursor: pointer;
}

/* Mouse-over effects */
.slider:hover {
  opacity: 1; /* Fully shown on mouse-over */
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  border-radius: 30px;
  width: 25px; /* Set a specific slider handle width */
  height: 25px; /* Slider handle height */
  background: grey; /* Green background */
  cursor: pointer; /* Cursor on hover */
}

.slider::-moz-range-thumb {
  width: 25px; /* Set a specific slider handle width */
  height: 25px; /* Slider handle height */
  background: grey; /* Green background */
  cursor: pointer; /* Cursor on hover */
}

/* Number input box styles */
.inputBox {
  background-color: transparent;
  color: white;
  padding: 5px;
  border: none;
  outline: 2px solid white;
  margin-right: 10px;
}

/* Global button styles */
button {
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 10px;
  padding-bottom: 10px;
  font-size: large;
  color: white;
  background-color: #222;
  border: none;
  outline: 4px solid white;
  border-radius: 10px;
  transition: all 0.1s ease-in-out;
}

button:hover {
  cursor: pointer;
  background-color: #333;
  transform: scale(0.95);
}

              
            
!

JS

              
                //             by: Alexander Reeves

const ctx = document.getElementById("myChart");
const ctx2 = document.getElementById("myChart2");

var myChart = new Chart(ctx, {});
var myChart2 = new Chart(ctx2, {});

var labels = []; // labels for x axis

var t = 0; // time variable in s

// ----------- Assign Parameters -----------

// must be 'var' if parameters are changed during runtime ( see updateParameters() )
var T = 723.15; // Temperature in K -> isothermal case
var xN2_in = document.getElementById("input_x_N2").value; // inlet composition of component N2
var xH2_in = document.getElementById("input_x_H2").value; // inlet composition of component H2
var xNH3_in = document.getElementById("input_x_NH3").value; // inlet composition of component NH3
var V = 10; // reactor volume in m^3
var R = 8.314; // universal gas constant J/K⋅mol
var P = 100000 * 150; // pressure in Pa -> isobaric
var F_in = 100000; //(P*V)/(R*T);       // inlet molar flowrate in mol/s (approx defined as total reactor content)

function updateParameters() {
  // parameters can be re-assigned dynamically via if statements related to the decision variable
  // example:
  //if (t >= 100) { F_in = F_in*1.2 }  // 20% increase in inlet flowrate at time 100s
  //if (t >= 2) { P = (t-2)/(4-2)*100000*10 }  // Gradual pressure change from P_initial to 10 bar over time from 2s to 4s { (t-t_start)/(t_end-t_start) * target_value }
}

// ----------- Initialize Model variables -----------

// algebraic:
var var_x = 0; // example
var x_N2 = 1; // molar fraction of N2
var x_H2 = 0; // molar fraction of H2
var x_NH3 = 0; // molar fraction of NH3
var M_t = 0; // total mass in system
//var M_N2 = 0;       // molar holdup of N2
//var M_H2 = 0;       // molar holdup of H2
//var M_NH3 = 0;      // molar holdup of NH3
var r = 0; // reaction rate (Ammonia production: N_2 + 3H_2 => 2NH_3) in kmol/(m3*s)
var p_N2 = 0; // partial pressure of component i
var p_H2 = 0; // partial pressure of component i
var p_NH3 = 0; // partial pressure of component i
//var P = 100000;          // total pressure in system
var rho = 0; // molar density in system
var F_out = 0; //F_in/100;   // constant flowrate

// differential vbles arrays:
var M_N2 = [F_in * 1]; // molar holdup of N2
var M_H2 = [0]; // molar holdup of H2
var M_NH3 = [0]; // molar holdup of N2

// ----------- Initialize dataset arrays (for graphing) -----------

var graph_x_N2 = [];
var graph_x_H2 = [];
var graph_x_NH3 = [];

// ############### Algebraic Equations ###############

function solveAlgebraic(i) {
  M_t = M_N2[i] + M_H2[i] + M_NH3[i];
  x_N2 = M_N2[i] / M_t;
  x_H2 = M_H2[i] / M_t;
  x_NH3 = M_NH3[i] / M_t;
  p_N2 = x_N2 * P;
  p_H2 = x_H2 * P;
  p_NH3 = x_NH3 * P;
  r =
    (Math.exp(-91000 / (R * T)) * Math.pow(p_N2, 0.5) * Math.pow(p_H2, 1.5) -
      2.57 * Math.pow(10, 5) * Math.exp(-140000 / (R * T)) * p_NH3) /
    1000; // rate equation kmol/(m3*s) -> /1000 for mol

  rho = M_t / V;
  F_out = M_t; // outlet flowrate = reactor content -> no increase or loss

  console.log("r: " + r);
  console.log("x_H2: " + x_H2);
  console.log("p_H2: " + p_H2);

  //console.log('Algebraic variables: ');
  //console.log('Variable X: '+var_x);
}

// ############### ODE Equations ###############

function f_diff(t, y, functionSelect) {
  t == 0;
  y == 0;

  // return the value of y' for the selected function from the ODE function array
  if (functionSelect == 1) {
    return F_in * xN2_in - F_out * x_N2 + -0.5 * r * V;
  }
  if (functionSelect == 2) {
    return F_in * xH2_in - F_out * x_H2 + -1.5 * r * V;
  }
  if (functionSelect == 3) {
    return F_in * xNH3_in - F_out * x_NH3 + 1 * r * V;
  } else {
    return 0;
  }
}

// ############### ODE Solver ###############

function rk4iter(t, y, h, functionSelect) {
  // compute the four RK coefficients using the RHS of the diff eq.
  k1 = f_diff(t, y, functionSelect);
  k2 = f_diff(t + h / 2, y + (k1 * h) / 2, functionSelect);
  k3 = f_diff(t + h / 2, y + (k2 * h) / 2, functionSelect);
  k4 = f_diff(t + h, y + k3 * h, functionSelect);

  // compute the y value at the end of the iteration
  return y + ((k1 + 2 * k2 + 2 * k3 + k4) * h) / 6;
}

function rk4(n, t_end) {
  h = t_end / n; // compute the step size along the x-axis

  // add initial conditions to array
  t = 0; // initial value of x is 0

  labels.push(0);

  // loop until x reaches its target value
  for (var i = 1; i <= n; i++) {
    // check parameter states
    updateParameters();

    // re-solve algebraic values for each iteration
    solveAlgebraic(i - 1);

    // Perform iterations of the RK4 algorithm
    M_N2[i] = rk4iter(t, M_N2[i - 1], h, 1);
    M_H2[i] = rk4iter(t, M_H2[i - 1], h, 2);
    M_NH3[i] = rk4iter(t, M_NH3[i - 1], h, 3);

    // check for exceptions
    if (M_N2[i] < 0) {
      M_N2[i] = 0.0001;
      //r = 0;
    }
    if (M_H2[i] < 0) {
      M_H2[i] = 0.0001;
      //r = 0;
    }
    if (M_NH3[i] < 0) {
      M_NH3[i] = 0.0001;
      //r = 0;
    }

    t += h; // time step

    // record the x and y values for this iteration
    console.log(t + "s, " + M_N2[i] + ", " + M_H2[i] + ", " + M_NH3[i]);

    // Add data to the plot as well.
    labels.push(t.toFixed(2));

    // Add additional graphing variables
    graph_x_N2.push(x_N2);
    graph_x_H2.push(x_H2);
    graph_x_NH3.push(x_NH3);
  }
}

function run() {
  // check inputs, give warning
  if (
    Number(document.getElementById("input_x_N2").value) +
      Number(document.getElementById("input_x_H2").value) +
      Number(document.getElementById("input_x_NH3").value) !=
    1
  ) {
    for (
      i = 0;
      i <= document.getElementsByClassName("inputBox").length - 1;
      i++
    ) {
      document.getElementsByClassName("inputBox")[i].style.backgroundColor =
        "red";
    }
    setTimeout(function () {
      for (
        i = 0;
        i <= document.getElementsByClassName("inputBox").length - 1;
        i++
      ) {
        document.getElementsByClassName("inputBox")[i].style.backgroundColor =
          "initial";
      }
    }, 100);
    setTimeout(function () {
      for (
        i = 0;
        i <= document.getElementsByClassName("inputBox").length - 1;
        i++
      ) {
        document.getElementsByClassName("inputBox")[i].style.backgroundColor =
          "red";
      }
    }, 200);
    setTimeout(function () {
      for (
        i = 0;
        i <= document.getElementsByClassName("inputBox").length - 1;
        i++
      ) {
        document.getElementsByClassName("inputBox")[i].style.backgroundColor =
          "initial";
      }
      //location.reload(); //disabled by codepen
    }, 300);
  }

  // empty data
  clearAll();

  // runs 4th order runge kutta method (steps,y_initial,x_end)
  rk4(document.getElementById("myRange").value, 10);

  // re-loads chart.js graph
  loadGraph();
}

// ############### VISUALISATION ###############
//           graphing using Chart.js

function loadGraph() {
  // destroy first chart
  myChart.destroy();
  myChart2.destroy();

  // run Chart.js graph
  graph(labels);

  // empty data
  clearAll();
}

function clearAll() {
  labels = [];

  xN2_in = Number(document.getElementById("input_x_N2").value); // inlet composition of component N2
  xH2_in = Number(document.getElementById("input_x_H2").value); // inlet composition of component H2
  xNH3_in = Number(document.getElementById("input_x_NH3").value); // inlet composition of component NH3

  if (xN2_in + xH2_in + xNH3_in != 1) {
    // in case of incorrect inputs the values are scaled
    xN2_in = 1 - (xH2_in + xNH3_in);
  }

  M_N2 = [F_in]; // molar holdup of N2 (initial condition: 100% nitrogen)
  M_H2 = [0]; // molar holdup of H2
  M_NH3 = [0]; // molar holdup of NH3
  x_N2 = 1; // molar fraction of N2 (initial condition: 100% nitrogen)
  x_H2 = 0; // molar fraction of H2
  x_NH3 = 0; // molar fraction of NH3
  M_t = 0; // total mass in system
  r = 0; // reaction rate (Ammonia production: 0.5N_2 + 1.5H_2 => NH_3)
  p_N2 = 0; // partial pressure of component i
  p_H2 = 0; // partial pressure of component i
  p_NH3 = 0; // partial pressure of component i
  rho = 0; // molar density in system
  F_out = F_in; // constant flowrate

  // clear graphing data
  graph_x_N2 = [];
  graph_x_H2 = [];
  graph_x_NH3 = [];
}

function graph(inputLabels) {
  myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: inputLabels,
      datasets: [
        {
          label: "x_N2",
          data: graph_x_N2,
          borderWidth: 2,
          pointStyle: false
        },
        {
          label: "x_H2",
          data: graph_x_H2,
          borderWidth: 2,
          pointStyle: false
        },
        {
          label: "x_NH3",
          data: graph_x_NH3,
          borderWidth: 2,
          pointStyle: false
        }
      ]
    },
    options: {
      indexAxis: "x",
      scales: {
        y: {
          beginAtZero: true,
        title: {
                display: true,
                text: 'outlet composition'
              }
        },
        x: {
            title: {
                display: true,
                text: 'time (s)'
              }
        }
      }
    }
  });

  myChart2 = new Chart(ctx2, {
    type: "line",
    data: {
      labels: inputLabels,
      datasets: [
        {
          label: "M_N2",
          data: M_N2,
          borderWidth: 2,
          pointStyle: false
        },
        {
          label: "M_H2",
          data: M_H2,
          borderWidth: 2,
          pointStyle: false
        },
        {
          label: "M_NH3",
          data: M_NH3,
          borderWidth: 2,
          pointStyle: false
        }
      ]
    },
    options: {
      indexAxis: "x",
      scales: {
        y: {
          beginAtZero: true,
          title: {
                display: true,
                text: 'outlet flowrate (mol/s)'
              }
        },
        x: {
            title: {
                display: true,
                text: 'time (s)'
              }
        }
      }
    }
  });
}

              
            
!
999px

Console