@datagrok/compute 0.5.1 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@datagrok/compute",
3
3
  "friendlyName": "Compute",
4
- "version": "0.5.1",
4
+ "version": "0.6.4",
5
5
  "description": "",
6
6
  "dependencies": {
7
7
  "cash-dom": "latest",
8
8
  "codemirror": "^5.64.0",
9
- "datagrok-api": ">=0.98.0",
9
+ "datagrok-api": ">=0.99.0",
10
10
  "dayjs": "latest",
11
11
  "exceljs": "^4.3.0",
12
12
  "file-saver": "^2.0.5",
@@ -4,6 +4,17 @@ import * as DG from 'datagrok-api/dg';
4
4
  import ExcelJS from 'exceljs';
5
5
  import {saveAs} from 'file-saver';
6
6
 
7
+
8
+ const getSheetName = (name: string, direction: DIRECTION) => {
9
+ const idealName = `${direction} - ${name}`;
10
+ return (idealName.length > 31) ? name.substring(0, 32) : idealName;
11
+ };
12
+
13
+ enum DIRECTION {
14
+ INPUT = 'Input',
15
+ OUTPUT = 'Output'
16
+ }
17
+
7
18
  export async function exportFuncCall(call: DG.FuncCall) {
8
19
  //todo: check status
9
20
  // if (call.status != FuncCall.STATUS_COMPLETED) ...
@@ -22,8 +33,12 @@ export async function exportFuncCall(call: DG.FuncCall) {
22
33
  const dfOutputs = call.func.outputs.filter((output) => isDataFrame(output.propertyType));
23
34
  const scalarOutputs = call.func.outputs.filter((output) => isScalarType(output.propertyType));
24
35
 
36
+ const realNames: Record<string, string> = {};
37
+
25
38
  dfInputs.forEach((dfInput) => {
26
- const currentDfSheet = exportWorkbook.addWorksheet(`Input - ${dfInput.name}`);
39
+ const visibleTitle = dfInput.options.caption || dfInput.name;
40
+ const currentDfSheet = exportWorkbook.addWorksheet(getSheetName(visibleTitle, DIRECTION.INPUT));
41
+ realNames[visibleTitle] = dfInput.name;
27
42
  const currentDf = (call.inputs[dfInput.name] as DG.DataFrame);
28
43
  currentDfSheet.addRow((currentDf.columns as DG.ColumnList).names());
29
44
  for (let i = 0; i < currentDf.rowCount; i++) {
@@ -31,13 +46,17 @@ export async function exportFuncCall(call: DG.FuncCall) {
31
46
  }
32
47
  });
33
48
 
34
- const inputScalarsSheet = exportWorkbook.addWorksheet('Input scalars');
35
- scalarInputs.forEach((scalarInput) => {
36
- inputScalarsSheet.addRow([scalarInput.name, call.inputs[scalarInput.name]]);
37
- });
49
+ if (scalarInputs.length) {
50
+ const inputScalarsSheet = exportWorkbook.addWorksheet('Input scalars');
51
+ scalarInputs.forEach((scalarInput) => {
52
+ inputScalarsSheet.addRow([scalarInput.name, call.inputs[scalarInput.name]]);
53
+ });
54
+ }
38
55
 
39
56
  dfOutputs.forEach((dfOutput) => {
40
- const currentDfSheet = exportWorkbook.addWorksheet(`Output - ${dfOutput.name}`);
57
+ const visibleTitle = dfOutput.options.caption || dfOutput.name;
58
+ const currentDfSheet = exportWorkbook.addWorksheet(getSheetName(visibleTitle, DIRECTION.OUTPUT));
59
+ realNames[visibleTitle] = dfOutput.name;
41
60
  const currentDf = (call.outputs[dfOutput.name] as DG.DataFrame);
42
61
  currentDfSheet.addRow((currentDf.columns as DG.ColumnList).names());
43
62
  for (let i = 0; i < currentDf.rowCount; i++) {
@@ -57,12 +76,18 @@ export async function exportFuncCall(call: DG.FuncCall) {
57
76
 
58
77
  const titleDivs = document.getElementsByClassName('grok-func-results-header');
59
78
  if (!titleDivs.length) continue;
79
+ let skipNext = false;
60
80
 
61
81
  for (let i = 0; i < titleDivs.length; i++) {
82
+ if (skipNext) {
83
+ skipNext = false;
84
+ continue;
85
+ }
62
86
  const titleDiv = titleDivs[i];
87
+ if (titleDiv.parentElement?.style.display === 'none') continue;
63
88
 
64
- const title = titleDiv.firstChild?.textContent;
65
- if (title === null || title === undefined) continue;
89
+ const visibleTitle = titleDiv.firstChild?.textContent;
90
+ if (visibleTitle === null || visibleTitle === undefined) continue;
66
91
 
67
92
  let imageId;
68
93
  let width = 0;
@@ -82,11 +107,25 @@ export async function exportFuncCall(call: DG.FuncCall) {
82
107
  width = imageDiv.clientWidth;
83
108
  height = imageDiv.clientHeight;
84
109
  } else {
85
- const plot = titleDiv.nextSibling;
86
- // if plot does not exist or it is only grid, skip it
87
- if (!plot || (plot.firstChild?.firstChild?.firstChild as HTMLElement).getAttribute('name') === 'viewer-Grid') continue;
110
+ let plotDiv: ChildNode | null | undefined = titleDiv.nextSibling;
111
+
112
+ if (plotDiv && !titleDiv.getElementsByClassName('svg-table').length && (plotDiv as HTMLElement).getAttribute('name') === 'viewer-Grid') continue;
88
113
 
89
- if (plot) {
114
+ if (plotDiv && titleDiv.getElementsByClassName('svg-table').length) {
115
+ if ((plotDiv as HTMLElement).getAttribute('name') === 'viewer-OutliersSelectionViewer') {
116
+ plotDiv = titleDiv.parentElement?.nextSibling?.firstChild?.nextSibling;
117
+ skipNext = true;
118
+ }
119
+ if ((plotDiv as HTMLElement).getAttribute('name') === 'viewer-Grid') {
120
+ (titleDiv.getElementsByClassName('svg-table')[0] as HTMLElement).click();
121
+ await new Promise((r) => setTimeout(r, 150));
122
+ plotDiv = titleDiv.nextSibling;
123
+ }
124
+ }
125
+ console.log(plotDiv);
126
+
127
+ if (plotDiv) {
128
+ const plot = (plotDiv as HTMLElement).getElementsByClassName('d4-layout-middle')[0];
90
129
  const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
91
130
  const dataUrl = canvas.toDataURL('image/png');
92
131
 
@@ -101,15 +140,22 @@ export async function exportFuncCall(call: DG.FuncCall) {
101
140
 
102
141
  if (imageId === null || imageId === undefined) continue;
103
142
 
104
- const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
143
+ const worksheet = exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.INPUT)) ||
144
+ exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.OUTPUT));
105
145
  if (worksheet) {
106
- const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
146
+ console.log(visibleTitle);
147
+ console.log(realNames[visibleTitle]);
148
+ const columnForImage = (((call
149
+ .inputs[realNames[visibleTitle]] || call
150
+ .outputs[realNames[visibleTitle]]) as DG.DataFrame)
151
+ .columns as DG.ColumnList)
152
+ .length + 1;
107
153
  worksheet.addImage(imageId, {
108
154
  tl: {col: columnForImage, row: 0},
109
155
  ext: {width, height},
110
156
  });
111
157
  } else {
112
- const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
158
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${visibleTitle}`);
113
159
  newWorksheet.addImage(imageId, {
114
160
  tl: {col: 0, row: 0},
115
161
  ext: {width, height},
@@ -121,10 +167,17 @@ export async function exportFuncCall(call: DG.FuncCall) {
121
167
  } else {
122
168
  const resultView = document.getElementsByClassName('ui-panel grok-func-results')[0];
123
169
  const titleDivs = resultView.getElementsByClassName('grok-func-results-header');
170
+ let skipNext = false;
171
+
124
172
  for (let i=0; i< titleDivs.length; i++) {
173
+ if (skipNext) {
174
+ skipNext = false;
175
+ continue;
176
+ }
177
+
125
178
  const titleDiv = titleDivs[i];
126
- const title = titleDiv.firstChild?.textContent;
127
- if (title === null || title === undefined) continue;
179
+ const visibleTitle = titleDiv.firstChild?.textContent;
180
+ if (visibleTitle === null || visibleTitle === undefined) continue;
128
181
 
129
182
  let imageId;
130
183
  let width = 0;
@@ -144,11 +197,20 @@ export async function exportFuncCall(call: DG.FuncCall) {
144
197
  width = imageDiv.clientWidth;
145
198
  height = imageDiv.clientHeight;
146
199
  } else {
147
- const plot = titleDiv.nextSibling;
148
- // if plot does not exist or it is only grid, skip it
149
- if (!plot || (plot.firstChild?.firstChild?.firstChild as HTMLElement).getAttribute('name') === 'viewer-Grid') continue;
200
+ let plotDiv: ChildNode | null | undefined = titleDiv.nextSibling;
201
+ if (plotDiv &&
202
+ ((plotDiv as HTMLElement).getAttribute('name') === 'viewer-Grid' ||
203
+ (plotDiv as HTMLElement).getAttribute('name') === 'viewer-OutliersSelectionViewer')) {
204
+ if (titleDiv.getElementsByClassName('svg-table').length) {
205
+ plotDiv = titleDiv.parentElement?.nextSibling?.firstChild?.nextSibling;
206
+ skipNext = true;
207
+ } else {
208
+ continue;
209
+ }
210
+ }
150
211
 
151
- if (plot) {
212
+ if (plotDiv) {
213
+ const plot = (plotDiv as HTMLElement).getElementsByClassName('d4-layout-middle')[0];
152
214
  const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
153
215
  const dataUrl = canvas.toDataURL('image/png');
154
216
 
@@ -163,15 +225,18 @@ export async function exportFuncCall(call: DG.FuncCall) {
163
225
 
164
226
  if (imageId === null || imageId === undefined) continue;
165
227
 
166
- const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
228
+ const worksheet = exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.OUTPUT));
167
229
  if (worksheet) {
168
- const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
230
+ const columnForImage = ((call
231
+ .outputs[realNames[visibleTitle]] as DG.DataFrame)
232
+ .columns as DG.ColumnList)
233
+ .length + 1;
169
234
  worksheet.addImage(imageId, {
170
235
  tl: {col: columnForImage, row: 0},
171
236
  ext: {width, height},
172
237
  });
173
238
  } else {
174
- const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
239
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${visibleTitle}`);
175
240
  newWorksheet.addImage(imageId, {
176
241
  tl: {col: 0, row: 0},
177
242
  ext: {width, height},
@@ -180,10 +245,12 @@ export async function exportFuncCall(call: DG.FuncCall) {
180
245
  }
181
246
  }
182
247
 
183
- const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
184
- scalarOutputs.forEach((scalarOutput) => {
185
- outputScalarsSheet.addRow([scalarOutput.name, call.outputs[scalarOutput.name]]);
186
- });
248
+ if (scalarOutputs.length) {
249
+ const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
250
+ scalarOutputs.forEach((scalarOutput) => {
251
+ outputScalarsSheet.addRow([scalarOutput.name, call.outputs[scalarOutput.name]]);
252
+ });
253
+ }
187
254
 
188
255
  exportWorkbook.xlsx.writeBuffer().then((data) => {
189
256
  const blob = new Blob([data], {type: BLOB_TYPE});
@@ -63,6 +63,7 @@ export class OutliersSelectionViewer extends DG.JsViewer {
63
63
 
64
64
  const groupsListGrid = DG.Viewer.grid(clearTable());
65
65
  groupsListGrid.root.style.width = '100%';
66
+ groupsListGrid.root.style.minWidth = '230px';
66
67
  groupsListGrid.columns.setVisible([OUTLIER_RATIONALE_COL_LABEL, OUTLIER_COUNT_COL_LABEL, 'Actions']);
67
68
 
68
69
  groupsListGrid.onCellPrepare((gc) => {
@@ -178,85 +179,22 @@ export class OutliersSelectionViewer extends DG.JsViewer {
178
179
  }
179
180
  });
180
181
 
181
- const resetSelectedBtn = ui.button(
182
- 'RESET SELECTED',
183
- () => {
184
- inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
185
- inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, false);
186
- inputData.set(OUTLIER_RATIONALE_COL_LABEL, selectedIndex, '');
187
- });
188
- inputData.selection.setAll(false);
189
- },
190
- 'Remove the selected points from oultiers list',
191
- );
192
-
193
- const resetAllBtn = ui.button(
194
- 'RESET ALL',
195
- () => {
196
- (inputData.columns as DG.ColumnList).byName(IS_OUTLIER_COL_LABEL).init(
197
- (index) => initialData.get(IS_OUTLIER_COL_LABEL, index),
198
- );
199
- (inputData.columns as DG.ColumnList).byName(OUTLIER_RATIONALE_COL_LABEL).init(
200
- (index) => initialData.get(OUTLIER_RATIONALE_COL_LABEL, index),
201
- );
202
- },
203
- 'Cancel all changes',
204
- );
205
-
206
- const autoOutlierGroupBtn = ui.button(
207
- 'AUTO DETECT...',
208
- () => {
209
- const intInput = ui.intInput('N', 3);
210
- const columnInput = ui.columnInput('Column', inputData, null);
211
- ui.dialog('Detect outliers automatically')
212
- .add(columnInput.root)
213
- .add(intInput.root)
214
- .onOK(()=>{
215
- const meanValue = (columnInput.value as DG.Column).stats.avg;
216
- const stddev = (columnInput.value as DG.Column).stats.stdev;
217
- inputData.selection.init((index)=>
218
- Math.abs(meanValue - (columnInput.value as DG.Column).get(index)) > stddev*intInput.value,
219
- );
220
- inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
221
- inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, true);
222
- inputData.set(OUTLIER_RATIONALE_COL_LABEL, selectedIndex, `${intInput.value}x stddev rule`);
223
- });
224
- inputData.selection.setAll(false);
225
- })
226
- .show();
227
- },
228
- 'Detect outliers automatically',
229
- );
230
-
231
182
  inputData.selection.setAll(false);
232
183
 
233
- inputData.onSelectionChanged.subscribe(() => {
234
- if (inputData.selection.trueCount === 0) {
235
- resetSelectedBtn.classList.add('disabled');
236
- } else {
237
- resetSelectedBtn.classList.remove('disabled');
238
- }
239
- });
240
-
241
184
  updateGroupsTable();
242
- resetSelectedBtn.classList.add('disabled');
243
185
 
244
- const info = ui.info(
245
- ui.div([
246
- ui.p('Hold the “SHIFT” key and start to draw a freehand selection on the plot area'),
247
- ], {style: {'white-space': 'pre-wrap'}}),
248
- );
249
- info.style.marginBottom = '0px';
186
+ // const info = ui.info(
187
+ // ui.div([
188
+ // ui.p('Hold the “SHIFT” key and start to draw a freehand selection on the plot area'),
189
+ // ], {style: {'white-space': 'pre-wrap'}}),
190
+ // );
191
+ // info.style.marginBottom = '0px';
250
192
 
251
193
  this.root.replaceWith(
252
194
  ui.divV([
253
- info,
254
195
  ui.divV([
255
- ui.divH([
256
- resetSelectedBtn, resetAllBtn, autoOutlierGroupBtn,
257
- ], {style: {'text-align': 'center', 'justify-content': 'center'}}),
258
196
  groupsListGrid.root,
259
197
  ], {style: {'height': '75%'}}),
260
- ], {style: {'height': '100%', 'min-width': '230px'}}));
198
+ ], {style: {'height': '100%'}}));
261
199
  }
262
200
  }
package/src/package.ts CHANGED
@@ -55,7 +55,7 @@ export function OutliersSelection() {
55
55
  return new OutliersSelectionViewer();
56
56
  }
57
57
 
58
- //name: export To Excel
58
+ //name: Export to Excel
59
59
  //input: funccall call
60
60
  //tags: export
61
61
  export function exportToExcel(call: DG.FuncCall) {
package/scripts/pMax.js DELETED
@@ -1,191 +0,0 @@
1
- //name: Pmax
2
- //description: pMax Filtration Model
3
- //language: javascript
4
- //tags: model, filtration
5
- //input: dataframe inputTable [Should contain columns Time (min), Vol (mL), P1 (psi), P2 (psi)]
6
- //input: dataframe inputParametersForReporting
7
- //input: double batchVolume = 100 {units: L} [Batch Volume]
8
- //input: double batchTime = 2 {units: hours} [Batch Time]
9
- //input: double targetPressure = 20 {units: psi} [Target Pressure]
10
- //input: double aMinFilter1Guessed = 0.153 {units: m²; caption:A_guessed Filter 1} [A_guessed Filter 1]
11
- //input: double aMinFilter2Guessed = 0.153 {units: m²; caption:A_guessed Filter 2} [A_guessed Filter 2]
12
- //input: double filterArea1 = 23 {units: m²; caption: A_trial Filter 1} [A_trial Filter 1]
13
- //input: double filterArea2 = 23 {units: m²; caption: A_trial Filter 2} [A_trial Filter 2]
14
- //input: double sf = 1.5 {caption: Safety Factor}
15
- //meta.showInputs: true
16
- //output: dataframe Filter1 {viewer: Scatter Plot(x: "TP 1 (L/m2)", y: "Res. 1 (psi/LMH)", showDataframeFormulaLines: "true"); category: OUTPUT}
17
- //output: dataframe t1 {category: OUTPUT}
18
- //output: dataframe Guessed1 {category: OUTPUT}
19
- //output: dataframe Filter2 {viewer: Scatter Plot(x: "TP 2 (L/m2)", y: "Res. 2 (psi/LMH)", showDataframeFormulaLines: "true"); category: OUTPUT}
20
- //output: dataframe t2 {category: OUTPUT}
21
- //output: dataframe Guessed2 {category: OUTPUT}
22
-
23
- function gaussianElimination(input, orderOfPolynomialRegression) {
24
- const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
25
- for (let i = 0; i < n; i++) {
26
- let maxrow = i;
27
- for (let j = i + 1; j < n; j++)
28
- if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow]))
29
- maxrow = j;
30
- for (let k = i; k < n + 1; k++) {
31
- const tmp = input[k][i];
32
- input[k][i] = input[k][maxrow];
33
- input[k][maxrow] = tmp;
34
- }
35
- for (let j = i + 1; j < n; j++)
36
- for (let k = n; k >= i; k--)
37
- input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
38
- }
39
- for (let j = n - 1; j >= 0; j--) {
40
- let total = 0;
41
- for (let k = j + 1; k < n; k++)
42
- total += input[k][j] * coefficients[k];
43
- coefficients[j] = (input[n][j] - total) / input[j][j];
44
- }
45
- return coefficients;
46
- }
47
-
48
- function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression) {
49
- const lhs = [], rhs = [], len = xCol.length, k = orderOfPolynomialRegression + 1;
50
- let a = 0, b = 0;
51
- for (let i = 0; i < k; i++) {
52
- for (let l = 0; l < len; l++)
53
- a += (xCol.get(l) ** i) * yCol.get(l);
54
- lhs.push(a);
55
- a = 0;
56
- const c = [];
57
- for (let j = 0; j < k; j++) {
58
- for (let l = 0; l < len; l++)
59
- b += xCol.get(l) ** (i + j);
60
- c.push(b);
61
- b = 0;
62
- }
63
- rhs.push(c);
64
- }
65
- rhs.push(lhs);
66
- return gaussianElimination(rhs, k);
67
- }
68
-
69
- function predictPolynomialRegression(coefficients, x) {
70
- let result = coefficients[0];
71
- for (let i = coefficients.length - 1; i > 0; i--)
72
- result += coefficients[i] * Math.pow(x, i);
73
- return result;
74
- }
75
-
76
- function equasionString(xColName, yColName, coefficients) {
77
- let s = '';
78
- for (let [index, coefficient] of coefficients.slice(1).reverse().entries()) {
79
- s += String(coefficient);
80
- for (let i = 0; i < coefficients.length - index - 1; i++)
81
- s += " * ${" + String(xColName) + "}";
82
- s += " + ";
83
- }
84
- return "${" + yColName + "} = " + s + String(coefficients[0]);
85
- }
86
-
87
- const orderOfPolynomialRegression = 3;
88
- const lengthOfSecondTable = 2985;
89
- const colNames1 = {
90
- 'time': 'Time (min)',
91
- 'volume': 'Vol (mL)',
92
- 'pressure1': 'P1 (psi)',
93
- 'pressure2': 'P2 (psi)',
94
- 'tp1': 'TP 1 (L/m2)', 'flux1': 'Flux 1 (LMH)', 'res1': 'Res. 1 (psi/LMH)',
95
- 'tp2': 'TP 2 (L/m2)', 'flux2': 'Flux 2 (LMH)', 'res2': 'Res. 2 (psi/LMH)',
96
- 'deltaP': 'Delta P (psi)'
97
- };
98
- const colNames2 = {
99
- 'area': 'Guess Area (m2)',
100
- 'javg': 'Javg (LMH)',
101
- 'R': 'R calc (psi/LMH)',
102
- 'Y1': 'Y1', 'd1': 'Delta1',
103
- 'Y2': 'Y2', 'd2': 'Delta2'
104
- };
105
-
106
- const t = inputTable.col(colNames1['time']);
107
- const v = inputTable.col(colNames1['volume']);
108
- const p1 = inputTable.col(colNames1['pressure1']);
109
- const p2 = inputTable.col(colNames1['pressure2']);
110
- const df1 = DG.DataFrame.fromColumns([t, v, p1, p2]);
111
- df1.columns.addNewFloat(colNames1['tp1']).init((i) => (i > 0) ? 10 * v.get(i) / filterArea1 : 0);
112
- df1.columns.addNewFloat(colNames1['tp2']).init((i) => (i > 0) ? 10 * v.get(i) / filterArea2 : 0);
113
- df1.columns.addNewFloat(colNames1['flux1']).init((i) => (i > 0) ? 600 * (v.get(i) - v.get(i-1)) / (t.get(i) - t.get(i-1)) / filterArea1 : 0);
114
- df1.columns.addNewFloat(colNames1['flux2']).init((i) => (i > 0) ? 600 * (v.get(i) - v.get(i-1)) / (t.get(i) - t.get(i-1)) / filterArea2 : 0);
115
- df1.columns.addNewFloat(colNames1['deltaP']).init((i) => p1.get(i) - p2.get(i));
116
- const deltaP = df1.col(colNames1['deltaP']), flux1 = df1.col(colNames1['flux1']), flux2 = df1.col(colNames1['flux2']);
117
- df1.columns.addNewFloat(colNames1['res1']).init((i) => (i > 0) ? deltaP.get(i) / flux1.get(i) : 0);
118
- df1.columns.addNewFloat(colNames1['res2']).init((i) => (i > 0) ? p2.get(i) / flux2.get(i) : 0);
119
- Filter1 = DG.DataFrame.fromColumns([df1.col(colNames1['tp1']), df1.col(colNames1['res1'])]);
120
- Filter2 = DG.DataFrame.fromColumns([df1.col(colNames1['tp2']), df1.col(colNames1['res2'])]);
121
- const coefficients1 = polynomialRegressionCoefficients(df1.col(colNames1['tp1']), df1.col(colNames1['res1']), orderOfPolynomialRegression);
122
- const coefficients2 = polynomialRegressionCoefficients(df1.col(colNames1['tp2']), df1.col(colNames1['res2']), orderOfPolynomialRegression);
123
- // alert(equasionString(colNames1['tp1'], colNames1['res1'], coefficients1))
124
- // alert(equasionString(colNames1['tp2'], colNames1['res2'], coefficients2))
125
-
126
- Filter1.meta.addFormulaLine({
127
- title: 'Parabola',
128
- equation: equasionString(colNames1['tp1'], colNames1['res1'], coefficients1),
129
- zindex: -30,
130
- color: '#ff0000',
131
- width: 2
132
- });
133
-
134
- Filter2.meta.addFormulaLine({
135
- title: 'Parabola',
136
- equation: equasionString(colNames1['tp2'], colNames1['res2'], coefficients2),
137
- zindex: -30,
138
- color: '#ff0000',
139
- width: 2
140
- });
141
-
142
- const df2 = DG.DataFrame.create(lengthOfSecondTable);
143
- df2.columns.addNewFloat(colNames2['area']).init((i) => (i > 0) ? batchVolume / i : 0);
144
- const area = df2.col(colNames2['area']);
145
- df2.columns.addNewFloat(colNames2['javg']).init((i) => (i > 0) ? batchVolume / area.get(i) / batchTime : 0);
146
- const javg = df2.col(colNames2['javg']);
147
- df2.columns.addNewFloat(colNames2['R']).init((i) => (i > 0) ? targetPressure / javg.get(i) : 0);
148
- df2.columns.addNewFloat(colNames2['Y1']).init((i) => predictPolynomialRegression(coefficients1, i));
149
- df2.columns.addNewFloat(colNames2['Y2']).init((i) => predictPolynomialRegression(coefficients2, i));
150
- const rCalc = df2.col(colNames2['R']), y1 = df2.col(colNames2['Y1']), y2 = df2.col(colNames2['Y2']);
151
- df2.columns.addNewFloat(colNames2['d1']).init((i) => Math.abs(rCalc.get(i) - y1.get(i)));
152
- df2.columns.addNewFloat(colNames2['d2']).init((i) => Math.abs(rCalc.get(i) - y2.get(i)));
153
-
154
-
155
- amin1 = df2.col(colNames2['area']).get(df2.col(colNames2['d1']).toList().indexOf(df2.col(colNames2['d1']).min));
156
- amin2 = df2.col(colNames2['area']).get(df2.col(colNames2['d2']).toList().indexOf(df2.col(colNames2['d2']).min));
157
- processFlow1 = batchVolume / batchTime, processFlow2 = batchVolume / batchTime;
158
- processFlux1 = processFlow1 / amin1, processFlux2 = processFlow2 / amin2;
159
- trialFlux1 = 600 * v.max / t.max / filterArea1, trialFlux2 = 600 * v.max / t.max / filterArea2;
160
- aminSF1 = sf * amin1, aminSF2 = sf * amin2;
161
- trialLoading1 = df1.col(colNames1['tp1']).max, trialLoading2 = df1.col(colNames1['tp2']).max;
162
- processLoading1 = batchVolume / amin1, processLoading2 = batchVolume / amin2;
163
- maxP1 = predictPolynomialRegression(coefficients1, processLoading1) * processFlux1;
164
- maxP2 = predictPolynomialRegression(coefficients2, processLoading2) * processFlux2;
165
-
166
-
167
- guessedAmin1 = aMinFilter1Guessed, guessedAmin2 = aMinFilter2Guessed;
168
- guessedProcessLoading1 = batchVolume / aMinFilter1Guessed, guessedProcessLoading2 = batchVolume / aMinFilter2Guessed;
169
- guessedMaxP1 = predictPolynomialRegression(coefficients1, processLoading1) * processFlux1;
170
- guessedMaxP2 = predictPolynomialRegression(coefficients2, processLoading2) * processFlux2;
171
- guessedProcessFlux1 = processFlow1 / aMinFilter1Guessed, guessedProcessFlux2 = processFlow2 / aMinFilter2Guessed;
172
-
173
- t1 = DG.DataFrame.fromColumns([
174
- DG.Column.fromList('string', 'Parameter', ['amin', 'aminSF', 'trialLoading', 'processLoading', 'maxP', 'trialFlux', 'processFlux', 'processFlow']),
175
- DG.Column.fromList('double', 'Value', [amin1, aminSF1, trialLoading1, processLoading1, maxP1, trialFlux1, processFlux1, processFlow1])
176
- ]);
177
-
178
- t2 = DG.DataFrame.fromColumns([
179
- DG.Column.fromList('string', 'Parameter', ['amin', 'aminSF', 'trialLoading', 'processLoading', 'maxP', 'trialFlux', 'processFlux', 'processFlow']),
180
- DG.Column.fromList('double', 'Value', [amin2, aminSF2, trialLoading2, processLoading2, maxP2, trialFlux2, processFlux2, processFlow2])
181
- ]);
182
-
183
- Guessed1 = DG.DataFrame.fromColumns([
184
- DG.Column.fromList('string', 'Parameter', ['amin', 'processLoading', 'maxP', 'processFlux']),
185
- DG.Column.fromList('double', 'Value', [guessedAmin1 , guessedProcessLoading1, guessedMaxP1, guessedProcessFlux1])
186
- ]);
187
-
188
- Guessed2 = DG.DataFrame.fromColumns([
189
- DG.Column.fromList('string', 'Parameter', ['amin', 'processLoading', 'maxP', 'processFlux']),
190
- DG.Column.fromList('double', 'Value', [guessedAmin2, guessedProcessLoading2, guessedMaxP2, guessedProcessFlux2])
191
- ]);
package/scripts/vMaxJS.js DELETED
@@ -1,191 +0,0 @@
1
- //name: Vmax
2
- //description: Predict the minimum filter size required for the separation of effluent from bioreactors, given the constraints of batch size and total batch time based on a training dataset of time vs filtrate volume for a given filter type, filter area and pressure
3
- //language: javascript
4
- //tags: model, filtration
5
- //input: dataframe inputTable {viewer: OutliersSelectionViewer() | Scatter Plot(color: "isOutlier", lassoTool: "true", legendVisibility: "Never", filterByZoom: "false") | Grid()}
6
- //input: dataframe inputParametersForReporting {viewer: Grid()}
7
- //input: double testArea = 3.5 {caption: Test Filter Area; units: cm²} [Test Filter area]
8
- //input: double vbatch = 25 {caption: Desired Volume of Batch; units: L} [Desired Volume of Batch]
9
- //input: double tbatch = 0.5 {caption: Desired process time; units: hr} [Desired process time]
10
- //input: double sf = 1.5 {caption: Safety Factor} [Safety Factor]
11
- //help-url: https://github.com/datagrok-ai/public/blob/master/packages/Compute/src/help.md
12
- //output: dataframe regressionTable {viewer: Scatter Plot(filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195, showRegressionLine: "true"); category: OUTPUT}
13
- //output: dataframe absoluteFluxDecay {viewer: Scatter Plot(); category: OUTPUT}
14
- //output: dataframe normalizedFluxDecay {viewer: Scatter Plot(); category: OUTPUT}
15
- //output: dataframe experimentalResults {category: OUTPUT}
16
- //output: dataframe experimentalResultsSummary {category: OUTPUT}
17
- //output: dataframe recommendations {category: OUTPUT}
18
- //output: dataframe trialData {category: OUTPUT}
19
- //output: dataframe sampleCharacteristics {category: OUTPUT}
20
- //output: dataframe filter {category: OUTPUT}
21
-
22
- volume = vbatch;
23
- function gaussianElimination(input, orderOfPolynomialRegression) {
24
- const n = input.length - 1; const coefficients = [orderOfPolynomialRegression];
25
- for (let i = 0; i < n; i++) {
26
- let maxrow = i;
27
- for (let j = i + 1; j < n; j++) {
28
- if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow])) {
29
- maxrow = j;
30
- }
31
- }
32
- for (let k = i; k < n + 1; k++) {
33
- const tmp = input[k][i];
34
- input[k][i] = input[k][maxrow];
35
- input[k][maxrow] = tmp;
36
- }
37
- for (let j = i + 1; j < n; j++) {
38
- for (let k = n; k >= i; k--) {
39
- input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
40
- }
41
- }
42
- }
43
- for (let j = n - 1; j >= 0; j--) {
44
- let total = 0;
45
- for (let k = j + 1; k < n; k++) {
46
- total += input[k][j] * coefficients[k];
47
- }
48
- coefficients[j] = (input[n][j] - total) / input[j][j];
49
- }
50
- return coefficients;
51
- }
52
-
53
- function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression) {
54
- const lhs = []; const rhs = []; const len = xCol.length; const k = orderOfPolynomialRegression + 1;
55
- let a = 0; let b = 0;
56
- for (let i = 0; i < k; i++) {
57
- for (let l = 0; l < len; l++) {
58
- a += (xCol.get(l) ** i) * yCol.get(l);
59
- }
60
- lhs.push(a);
61
- a = 0;
62
- const c = [];
63
- for (let j = 0; j < k; j++) {
64
- for (let l = 0; l < len; l++) {
65
- b += xCol.get(l) ** (i + j);
66
- }
67
- c.push(b);
68
- b = 0;
69
- }
70
- rhs.push(c);
71
- }
72
- rhs.push(lhs);
73
- return gaussianElimination(rhs, k);
74
- }
75
-
76
- const orderOfPolynomialRegression = 2;
77
- const area = 0.00035;
78
- const isOutlierCol = inputTable.col('isOutlier');
79
- const timeMin = [];
80
- const vol = [];
81
- for (let i = 0; i < isOutlierCol.length; i++) {
82
- if (isOutlierCol.get(i) == false) {
83
- timeMin.push(inputTable.col('time (min)').get(i));
84
- vol.push(inputTable.col('filtrate volume (mL)').get(i));
85
- }
86
- }
87
- dfWithoutOutliers = DG.DataFrame.fromColumns([
88
- DG.Column.fromList('double', 'time (min)', timeMin),
89
- DG.Column.fromList('double', 'filtrate volume (mL)', vol),
90
- ]);
91
- const timeInMinutes = dfWithoutOutliers.col('time (min)');
92
- const volumeInMilliliters = dfWithoutOutliers.col('filtrate volume (mL)');
93
- dfWithoutOutliers.columns.addNewFloat('time (hr)').init((i) => timeInMinutes.get(i) / 60);
94
- const timeInHours = dfWithoutOutliers.col('time (hr)');
95
-
96
- dfWithoutOutliers.columns.addNewFloat('V (L/m2)').init((i) => 10 * volumeInMilliliters.get(i) / testArea);
97
- const newVolume = dfWithoutOutliers.col('V (L/m2)');
98
-
99
- dfWithoutOutliers.columns.addNewFloat('t/V (hr/(L/m2))').init((i) => 100 * timeInHours.get(i) / newVolume.get(i));
100
-
101
- dfWithoutOutliers.columns.addNewFloat('Time (s)').init((i) => 60 * timeInMinutes.get(i));
102
- dfWithoutOutliers.columns.addNewFloat('V (L)').init((i) => volumeInMilliliters.get(i) / 1000);
103
- const volumeInLiters = dfWithoutOutliers.col('V (L)');
104
- const timeInSeconds = dfWithoutOutliers.col('Time (s)');
105
- dfWithoutOutliers.columns.addNewFloat('V/A (L/m2)').init((i) => volumeInLiters.get(i) / area);
106
- const va = dfWithoutOutliers.col('V/A (L/m2)');
107
- const ca = [];
108
- const cb = [];
109
- for (let i = 1; i < va.length - 3; i++) {
110
- const xCol = DG.Column.fromList('double', 'name', timeInSeconds.toList().slice(i, i + 3));
111
- const yCol = DG.Column.fromList('double', 'name', va.toList().slice(i, i + 3));
112
- const coefficients = polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression);
113
- ca.push(coefficients[orderOfPolynomialRegression]);
114
- cb.push(coefficients[orderOfPolynomialRegression - 1]);
115
- }
116
-
117
- dfWithoutOutliers.columns.addNewFloat('a2').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
118
- dfWithoutOutliers.columns.addNewFloat('a1').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
119
- dfWithoutOutliers.columns.addNewFloat('J (LMH)').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
120
- const j = dfWithoutOutliers.col('J (LMH)');
121
- dfWithoutOutliers.columns.addNewFloat('J/Jo').init((i) => (i > 0) ? j.get(i) / (3600 * area) : 0);
122
- const jj0 = dfWithoutOutliers.col('J/Jo');
123
- absoluteFluxDecay = DG.DataFrame.fromColumns([va, j]);
124
- normalizedFluxDecay = DG.DataFrame.fromColumns([va, jj0]);
125
-
126
- regressionTable = inputTable;
127
- coefficients = [1.8, 4.32];//[4.32, 1.8];//polynomialRegressionCoefficients(inputTable.col("time (min)"), dfWithoutOutliers.col("t/V (hr/(L/m2))"), 1);
128
- const trialThroughput = va.max;
129
- const flux = 9372.11;
130
- const ff0 = flux / j.get(1);
131
- experimentalResults = DG.DataFrame.fromColumns([
132
- DG.Column.fromList('string', 'Run', ['1']),
133
- DG.Column.fromList('double', 'Trial Throughput (L/m²)', [trialThroughput]),
134
- DG.Column.fromList('double', 'Flux (LMH)', [flux]),
135
- DG.Column.fromList('double', 'Flux/Flux0 (LMH)', [ff0]),
136
- ]);
137
- const meanFlux = j.stats.avg;
138
- const vmax = 0.28;//Math.round(1 / coefficients[1]);
139
- const instantaneousFlux = j.get(j.length - 1);
140
- const initialFlux = j.get(1);
141
- const fluxDecay = (1 - instantaneousFlux / initialFlux) * 100;
142
- experimentalResultsSummary = DG.DataFrame.fromColumns([
143
- DG.Column.fromList('string', 'Run', ['1']),
144
- DG.Column.fromList('string', 'Filter', [inputParametersForReporting.get(0, 1)]),
145
- DG.Column.fromList('double', 'Trial Throughput (L/m²)', [trialThroughput]),
146
- DG.Column.fromList('double', 'Flux0 (LMH)', [j.get(1)]),
147
- // DG.Column.fromList('double', 'Flux/Flux0 (LMH)', [ff0]),
148
- DG.Column.fromList('double', 'Mean Flux (LMH)', [meanFlux]),
149
- DG.Column.fromList('double', 'Vmax (L/m²)', [vmax]),
150
- DG.Column.fromList('double', 'Flux Decay (%)', [fluxDecay]),
151
- ]);
152
- const q0 = Math.round(1 / coefficients[0]);
153
- const amin = (vbatch / vmax) + (vbatch / tbatch / q0);
154
- const installedArea = sf * amin;
155
- const processLoading = volumeInLiters.get(volumeInLiters.length - 1) / installedArea;
156
- recommendations = DG.DataFrame.fromColumns([
157
- DG.Column.fromList('double', 'Volume (L)', [vbatch]),
158
- DG.Column.fromList('double', 'Time (h)', [tbatch]),
159
- DG.Column.fromList('double', 'Amin (m²)', [amin]),
160
- DG.Column.fromList('double', 'Safety Factor', [sf]),
161
- DG.Column.fromList('double', 'Installed Area', [installedArea]),
162
- DG.Column.fromList('double', 'Process Loading (L/m²)', [processLoading]),
163
- DG.Column.fromList('string', 'Filter', [inputParametersForReporting.get(1, 0)]),
164
- DG.Column.fromList('string', 'Installed Device', [inputParametersForReporting.get(1, 10)]),
165
- ]);
166
-
167
- const v90 = vmax * 0.68;
168
- const initialFlowArea = coefficients[0];
169
- trialData = DG.DataFrame.fromColumns([
170
- DG.Column.fromList('double', 'Test Filter Area (m²)', [testArea]),
171
- DG.Column.fromList('double', 'Initial Flow Area (L/h)', [initialFlowArea]),
172
- DG.Column.fromList('double', 'Vmax (m²)', [vmax]),
173
- DG.Column.fromList('double', 'V90 (m²)', [v90]),
174
- ]);
175
-
176
- filter = DG.DataFrame.fromColumns([
177
- DG.Column.fromList('string', 'Filter Family', [inputParametersForReporting.columns.names()[1]]),
178
- DG.Column.fromList('string', 'Filter Name', [inputParametersForReporting.get(1, 0)]),
179
- DG.Column.fromList('string', 'Pore Rating', [inputParametersForReporting.get(1, 1)]),
180
- DG.Column.fromList('string', 'Effective Membr. Area', [inputParametersForReporting.get(1, 2)]),
181
- DG.Column.fromList('string', 'Membr material', [inputParametersForReporting.get(1, 3)]),
182
- DG.Column.fromList('string', 'Catalog', [inputParametersForReporting.get(1, 4)]),
183
- ]);
184
-
185
- sampleCharacteristics = DG.DataFrame.fromColumns([
186
- DG.Column.fromList('string', 'Date', [inputParametersForReporting.get(1, 5)]),
187
- DG.Column.fromList('string', 'Prior step', [inputParametersForReporting.get(1, 6)]),
188
- DG.Column.fromList('string', 'Prot conc', [inputParametersForReporting.get(1, 7)]),
189
- DG.Column.fromList('string', 'Density', [inputParametersForReporting.get(1, 8)]),
190
- DG.Column.fromList('string', 'Turbidity', [inputParametersForReporting.get(1, 9)]),
191
- ]);