@datagrok/compute 0.4.1 → 0.6.3

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.4.1",
4
+ "version": "0.6.3",
5
5
  "description": "",
6
6
  "dependencies": {
7
7
  "cash-dom": "latest",
8
8
  "codemirror": "^5.64.0",
9
- "datagrok-api": ">=0.95.8",
9
+ "datagrok-api": ">=0.99.0",
10
10
  "dayjs": "latest",
11
11
  "exceljs": "^4.3.0",
12
12
  "file-saver": "^2.0.5",
package/scripts/pMax.js CHANGED
@@ -2,23 +2,22 @@
2
2
  //description: pMax Filtration Model
3
3
  //language: javascript
4
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}
5
+ //input: dataframe inputTable {caption: Input table; viewer: Grid(block: 50)} [Should contain columns Time (min), Vol (mL), P1 (psi), P2 (psi)]
6
+ //input: dataframe reportingParameters {caption: Reporting parameters; viewer: Grid(block: 50)}
7
+ //input: double batchVolume = 100 {caption: Batch volume; units: L} [Batch volume]
8
+ //input: double batchTime = 2 {caption: Batch time; units: hours} [Batch time]
9
+ //input: double targetPressure = 20 {caption: Target pressure; 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
+ //output: dataframe Filter1 {caption: Primary filter; viewer: Scatter Plot(block: 50, showDataframeFormulaLines: "true"); category: OUTPUT}
16
+ //output: dataframe Guessed1 {caption: Guessed primary filter; viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); category: OUTPUT}
17
+ //output: dataframe t1 {caption: Primary filter results; viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); category: OUTPUT}
18
+ //output: dataframe Filter2 {caption: Secondary filter; viewer: Scatter Plot(block: 50, showDataframeFormulaLines: "true"); category: OUTPUT}
19
+ //output: dataframe Guessed2 {caption: Guessed secondary filter; viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); category: OUTPUT}
20
+ //output: dataframe t2 {caption: Secondary filter results; viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); category: OUTPUT}
22
21
 
23
22
  function gaussianElimination(input, orderOfPolynomialRegression) {
24
23
  const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
@@ -67,13 +66,13 @@ function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegressio
67
66
  }
68
67
 
69
68
  function predictPolynomialRegression(coefficients, x) {
70
- let result = coefficients[0];
69
+ let y = coefficients[0];
71
70
  for (let i = coefficients.length - 1; i > 0; i--)
72
- result += coefficients[i] * Math.pow(x, i);
73
- return result;
71
+ y += coefficients[i] * Math.pow(x, i);
72
+ return y;
74
73
  }
75
74
 
76
- function equasionString(xColName, yColName, coefficients) {
75
+ function equationString(xColName, yColName, coefficients) {
77
76
  let s = '';
78
77
  for (let [index, coefficient] of coefficients.slice(1).reverse().entries()) {
79
78
  s += String(coefficient);
@@ -120,23 +119,21 @@ Filter1 = DG.DataFrame.fromColumns([df1.col(colNames1['tp1']), df1.col(colNames1
120
119
  Filter2 = DG.DataFrame.fromColumns([df1.col(colNames1['tp2']), df1.col(colNames1['res2'])]);
121
120
  const coefficients1 = polynomialRegressionCoefficients(df1.col(colNames1['tp1']), df1.col(colNames1['res1']), orderOfPolynomialRegression);
122
121
  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
122
 
126
123
  Filter1.meta.addFormulaLine({
127
- title: 'Parabola',
128
- equation: equasionString(colNames1['tp1'], colNames1['res1'], coefficients1),
124
+ title: 'Third-order polynomial regression',
125
+ equation: equationString(colNames1['tp1'], colNames1['res1'], coefficients1),
129
126
  zindex: -30,
130
127
  color: '#ff0000',
131
- width: 2
128
+ width: 3
132
129
  });
133
130
 
134
131
  Filter2.meta.addFormulaLine({
135
- title: 'Parabola',
136
- equation: equasionString(colNames1['tp2'], colNames1['res2'], coefficients2),
132
+ title: 'Third-order polynomial regression',
133
+ equation: equationString(colNames1['tp2'], colNames1['res2'], coefficients2),
137
134
  zindex: -30,
138
135
  color: '#ff0000',
139
- width: 2
136
+ width: 3
140
137
  });
141
138
 
142
139
  const df2 = DG.DataFrame.create(lengthOfSecondTable);
@@ -170,22 +167,25 @@ guessedMaxP1 = predictPolynomialRegression(coefficients1, processLoading1) * pro
170
167
  guessedMaxP2 = predictPolynomialRegression(coefficients2, processLoading2) * processFlux2;
171
168
  guessedProcessFlux1 = processFlow1 / aMinFilter1Guessed, guessedProcessFlux2 = processFlow2 / aMinFilter2Guessed;
172
169
 
170
+ const names = ['Amin (m²)', 'Amin w SF (m²)', 'Trial Loading (L/m²)', 'Process Loading (L/m²)', 'Max P (psi)', 'Trial Flux (LMH)', 'Process Flux (LMH)', 'Process Flow (L/hr)'];
171
+ const guessedNames = ['Amin (m²)', 'Process Loading (L/m²)', 'Max P (psi)', 'Process Flux (LMH)'];
172
+
173
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])
174
+ DG.Column.fromStrings('Name', names),
175
+ DG.Column.fromFloat32Array('Value', [amin1, aminSF1, trialLoading1, processLoading1, maxP1, trialFlux1, processFlux1, processFlow1])
176
176
  ]);
177
177
 
178
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])
179
+ DG.Column.fromStrings('Name', names),
180
+ DG.Column.fromFloat32Array('Value', [amin2, aminSF2, trialLoading2, processLoading2, maxP2, trialFlux2, processFlux2, processFlow2])
181
181
  ]);
182
182
 
183
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])
184
+ DG.Column.fromStrings('Name', guessedNames),
185
+ DG.Column.fromFloat32Array('Value', [guessedAmin1, guessedProcessLoading1, guessedMaxP1, guessedProcessFlux1])
186
186
  ]);
187
187
 
188
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])
189
+ DG.Column.fromStrings('Name', guessedNames),
190
+ DG.Column.fromFloat32Array('Value', [guessedAmin2, guessedProcessLoading2, guessedMaxP2, guessedProcessFlux2])
191
191
  ]);
package/scripts/vMaxJS.js CHANGED
@@ -2,68 +2,97 @@
2
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
3
  //language: javascript
4
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]
5
+ //input: dataframe inputTable {caption: Input table; viewer: OutliersSelectionViewer(block: 25) | Scatter Plot(block: 75, filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195, showRegressionLine: "true")}
6
+ //input: dataframe reportingParameters {caption: Reporting parameters; viewer: Grid()}
7
+ //input: double testFilterArea = 3.5 {caption: Test filter area; units: cm²} [Test filter area]
8
+ //input: double desiredVolumeOfBatch = 25 {caption: Desired batch volume; units: L} [Desired batch volume]
9
+ //input: double desiredProcessTime = 0.5 {caption: Desired process time; units: hr} [Desired process time]
10
+ //input: double sf = 1.5 {caption: Safety factor} [Safety factor]
11
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;
12
+ //output: dataframe regressionTable {caption: Regression table; viewer: Scatter Plot(block: 75, filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195, showRegressionLine: "true"); category: OUTPUT}
13
+ //output: dataframe trialData {caption: Trial data; viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); category: OUTPUT}
14
+ //output: dataframe fluxDecayDf {caption: Flux decay experimental results; viewer: Scatter Plot(description: "Absolute flux decay", y: "J (LMH)", block: 50, filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195) | Scatter Plot(description: "Relative flux decay", y: "J/Jo", block: 50, filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195); category: OUTPUT}
15
+ //output: dataframe experimentalResultsSummary {viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); caption: Experimental results summary; category: OUTPUT}
16
+ //output: dataframe recommendations {viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); caption: Recommendations; category: OUTPUT}
17
+ //output: dataframe sampleCharacteristics {viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); caption: Sample characteristics; category: OUTPUT}
18
+ //output: dataframe filter {viewer: Grid(block: 25, showColumnLabels: false, showRowHeader: false); caption: Filter; category: OUTPUT}
19
+
20
+ // inputTable = grok.shell.tables[0];
21
+ // reportingParameters = grok.shell.tables[1];
22
+ // testFilterArea = 3.5;
23
+ // desiredVolumeOfBatch = 25;
24
+ // desiredProcessTime = 0.5;
25
+ // sf = 1.5;
26
+
27
+ const expectedInputColNames = {
28
+ "time": "time (min)",
29
+ "volume": "filtrate volume (mL)",
30
+ "isOutlier": "isOutlier"
31
+ };
32
+
33
+ const expectedReportParamsNames = {
34
+ 1: "Filter family",
35
+ 2: "Filter name",
36
+ 3: "Pore rating (μm)",
37
+ 4: "Effective membr. area (cm^2)",
38
+ 5: "Membr material",
39
+ 6: "Catalog nr",
40
+ 7: "Date",
41
+ 8: "Prior step",
42
+ 9: "Prot conc. (mg/mL)",
43
+ 10: "Density (g/L)",
44
+ 11: "Turbidity (NTU)",
45
+ 12: "Installed device",
46
+ 13: "Project name",
47
+ 14: "Filtration stage",
48
+ 15: "ELN reference",
49
+ 16: "Bioreactor ID",
50
+ 17: "Bioreactor PCV (%)",
51
+ 18: "Bioreactor turbidity (NTU)",
52
+ 19: "Filter feed turbidity (NTU)",
53
+ 20: "Filter feed PCV (%)",
54
+ 21: "Filter feed pH",
55
+ 22: "Filter feed LDH (U/L)",
56
+ 23: "Filter feed conductivity (mS/cm)"
57
+ };
58
+
23
59
  function gaussianElimination(input, orderOfPolynomialRegression) {
24
- const n = input.length - 1; const coefficients = [orderOfPolynomialRegression];
60
+ const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
25
61
  for (let i = 0; i < n; i++) {
26
62
  let maxrow = i;
27
- for (let j = i + 1; j < n; j++) {
28
- if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow])) {
63
+ for (let j = i + 1; j < n; j++)
64
+ if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow]))
29
65
  maxrow = j;
30
- }
31
- }
32
66
  for (let k = i; k < n + 1; k++) {
33
67
  const tmp = input[k][i];
34
68
  input[k][i] = input[k][maxrow];
35
69
  input[k][maxrow] = tmp;
36
70
  }
37
- for (let j = i + 1; j < n; j++) {
38
- for (let k = n; k >= i; k--) {
71
+ for (let j = i + 1; j < n; j++)
72
+ for (let k = n; k >= i; k--)
39
73
  input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
40
- }
41
- }
42
74
  }
43
75
  for (let j = n - 1; j >= 0; j--) {
44
76
  let total = 0;
45
- for (let k = j + 1; k < n; k++) {
77
+ for (let k = j + 1; k < n; k++)
46
78
  total += input[k][j] * coefficients[k];
47
- }
48
79
  coefficients[j] = (input[n][j] - total) / input[j][j];
49
80
  }
50
81
  return coefficients;
51
82
  }
52
83
 
53
84
  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;
85
+ const lhs = [], rhs = [], len = xCol.length, k = orderOfPolynomialRegression + 1;
86
+ let a = 0, b = 0;
56
87
  for (let i = 0; i < k; i++) {
57
- for (let l = 0; l < len; l++) {
88
+ for (let l = 0; l < len; l++)
58
89
  a += (xCol.get(l) ** i) * yCol.get(l);
59
- }
60
90
  lhs.push(a);
61
91
  a = 0;
62
92
  const c = [];
63
93
  for (let j = 0; j < k; j++) {
64
- for (let l = 0; l < len; l++) {
94
+ for (let l = 0; l < len; l++)
65
95
  b += xCol.get(l) ** (i + j);
66
- }
67
96
  c.push(b);
68
97
  b = 0;
69
98
  }
@@ -75,117 +104,105 @@ function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegressio
75
104
 
76
105
  const orderOfPolynomialRegression = 2;
77
106
  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));
107
+ const timeInMinutesCol = inputTable.col(expectedInputColNames['time']);
108
+ const volumeInMillilitersCol = inputTable.col(expectedInputColNames['volume']);
109
+ const isOutlierCol = inputTable.col(expectedInputColNames["isOutlier"]);
110
+
111
+ let df = DG.DataFrame.fromColumns([timeInMinutesCol, volumeInMillilitersCol, isOutlierCol]);
112
+ df.columns.addNewFloat('time (hr)').init((i) => timeInMinutesCol.get(i) / 60);
113
+ const timeInHours = df.col('time (hr)');
114
+ df.columns.addNewFloat('V (L/m2)').init((i) => 10 * volumeInMillilitersCol.get(i) / testFilterArea);
115
+ const newVolume = df.col('V (L/m2)');
116
+ df.columns.addNewFloat('t/V (hr/(L/m2))').init((i) => 100 * timeInHours.get(i) / newVolume.get(i));
117
+ df.columns.addNewFloat('Time (s)').init((i) => 60 * timeInMinutesCol.get(i));
118
+ df.columns.addNewFloat('V (L)').init((i) => volumeInMillilitersCol.get(i) / 1000);
119
+ const volumeInLiters = df.col('V (L)');
120
+ const timeInSeconds = df.col('Time (s)');
121
+ df.columns.addNewFloat('V/A (L/m2)').init((i) => volumeInLiters.get(i) / area);
122
+ const va = df.col('V/A (L/m2)');
123
+
124
+ const slopes = [], intercepts = [];
125
+ const windowLength = 3;
126
+ for (let i = 0; i < inputTable.rowCount - windowLength; i++) {
127
+ const xCol = DG.Column.fromFloat32Array('name', timeInSeconds.toList().slice(i, i + windowLength));
128
+ const yCol = DG.Column.fromFloat32Array('name', va.toList().slice(i, i + windowLength));
112
129
  const coefficients = polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression);
113
- ca.push(coefficients[orderOfPolynomialRegression]);
114
- cb.push(coefficients[orderOfPolynomialRegression - 1]);
130
+ slopes.push(coefficients[orderOfPolynomialRegression]);
131
+ intercepts.push(coefficients[orderOfPolynomialRegression - 1]);
115
132
  }
116
133
 
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]),
134
+ let newDf = DG.DataFrame.create(inputTable.rowCount - windowLength);
135
+ newDf.columns.addNewFloat('a2').init((i) => (i > 0) ? 3600 * (2 * slopes[i] * timeInSeconds.get(i) + intercepts[i]) : 0);
136
+ newDf.columns.addNewFloat('a1').init((i) => (i > 0) ? 3600 * (2 * slopes[i] * timeInSeconds.get(i) + intercepts[i]) : 0);
137
+ newDf.columns.addNewFloat('J (LMH)').init((i) => (i > 0) ? 3600 * (2 * slopes[i] * timeInSeconds.get(i) + intercepts[i]) : 0);
138
+ const j = newDf.col('J (LMH)');
139
+ newDf.columns.addNewFloat('J/Jo').init((i) => (i > 0) ? j.get(i) / (3600 * area) : 0);
140
+ let jj0 = newDf.col('J/Jo');
141
+ jj0 = DG.Column.fromFloat32Array('J/Jo', jj0.toList().map((e) => 100 * e / jj0.max));
142
+ fluxDecayDf = DG.DataFrame.fromColumns([
143
+ DG.Column.fromStrings('Run', Array(jj0.length - 1).fill('1')),
144
+ DG.Column.fromFloat32Array(va.name, va.toList().slice(1, inputTable.rowCount - windowLength)),
145
+ DG.Column.fromFloat32Array(j.name, j.toList().slice(1, j.length)),
146
+ DG.Column.fromFloat32Array(jj0.name, jj0.toList().slice(1, jj0.length)),
147
+ DG.Column.fromList('bool', isOutlierCol.name, isOutlierCol.toList().slice(1, isOutlierCol.length - windowLength))
148
+ ]);
149
+
150
+ regressionTable = DG.DataFrame.fromColumns([
151
+ timeInMinutesCol,
152
+ volumeInMillilitersCol,
153
+ inputTable.col('t/V (hr/(L/m²))'),
154
+ isOutlierCol
136
155
  ]);
137
- const meanFlux = j.stats.avg;
138
- const vmax = 0.28;//Math.round(1 / coefficients[1]);
156
+
157
+ const timeMin = [], vol = [], isOutlier = [];
158
+ const isOutlierColList = isOutlierCol.toList();
159
+ for (let i = 0; i < inputTable.rowCount - windowLength; i++) {
160
+ if (isOutlierCol.get(i) == false) {
161
+ timeMin.push(timeInMinutesCol.get(i));
162
+ vol.push(volumeInMillilitersCol.get(i));
163
+ isOutlier.push(true in isOutlierColList.slice(i, i + windowLength));
164
+ }
165
+ }
166
+
167
+ coefficients = polynomialRegressionCoefficients(DG.Column.fromFloat32Array("time (min)", timeMin), DG.Column.fromFloat32Array("t/V (hr/(L/m2))", vol), 1);
168
+ const initialFlowRate = coefficients[0];
169
+ const trialThroughput = Math.round(1000 * va.max) / 1000;
170
+ const flux = initialFlowRate / testFilterArea;
171
+ const initialFlux = Math.round(1000 * j.get(1)) / 1000;
172
+ const ff0 = flux / initialFlux;
173
+ const meanFlux = Math.round(1000 * j.stats.avg) / 1000;
174
+ const vmax = Math.round(1000 * coefficients[1]) / 1000;
175
+ const v90 = Math.round(1000 * (vmax * 0.68)) / 1000;
139
176
  const instantaneousFlux = j.get(j.length - 1);
140
- const initialFlux = j.get(1);
141
- const fluxDecay = (1 - instantaneousFlux / initialFlux) * 100;
177
+ const fluxDecay = Math.round(1000 * (1 - instantaneousFlux / initialFlux) * 100) / 1000;
178
+ const names = reportingParameters.col('Parameter name').toList();
179
+ const values = reportingParameters.col('Parameter value').toList();
180
+ const q0 = 1 / coefficients[0];
181
+ const amin = Math.round(1000 * (desiredVolumeOfBatch / vmax) + (desiredVolumeOfBatch / desiredProcessTime / q0)) / 1000;
182
+ const installedArea = Math.round(1000 * sf * amin) / 1000;
183
+ const processLoading = Math.round(1000 * volumeInLiters.get(volumeInLiters.length - 1) / installedArea) / 1000;
184
+
142
185
  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]),
186
+ DG.Column.fromStrings('Name', ['Run', 'Filter', 'Trial Throughput (L/m²)', 'Flux0 (LMH)', 'Mean Flux (LMH)', 'Vmax (L/m²)', 'Flux Decay (%)']),
187
+ DG.Column.fromStrings('Value', ['1', values[names.indexOf(expectedReportParamsNames[1])], String(trialThroughput), String(initialFlux), String(meanFlux), String(vmax), String(fluxDecay)])
151
188
  ]);
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;
189
+
156
190
  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)]),
191
+ DG.Column.fromStrings('Name', ['Volume (L)', 'Time (h)', 'Amin (m²)', 'Safety Factor', 'Installed Area', 'Process Loading (L/m²)', expectedReportParamsNames[1], expectedReportParamsNames[12]]),
192
+ DG.Column.fromStrings('Value', [String(desiredVolumeOfBatch), String(desiredProcessTime), String(amin), String(sf), String(installedArea), String(processLoading), values[names.indexOf(expectedReportParamsNames[1])], values[names.indexOf(expectedReportParamsNames[12])]])
165
193
  ]);
166
194
 
167
- const v90 = vmax * 0.68;
168
- const initialFlowArea = coefficients[0];
169
195
  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]),
196
+ DG.Column.fromStrings('Name', ['Test Filter Area (m²)', 'Initial Flow Rate (L/h)', 'Vmax (m²)', 'V90 (m²)']),
197
+ DG.Column.fromStrings('Value', [String(Math.round(1000 * testFilterArea) / 1000), String(Math.round(1000 * initialFlowRate) / 1000), String(vmax), String(v90)])
174
198
  ]);
175
199
 
176
200
  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)]),
201
+ DG.Column.fromStrings('Name', [expectedReportParamsNames[1], expectedReportParamsNames[2], expectedReportParamsNames[3], expectedReportParamsNames[4], expectedReportParamsNames[5], expectedReportParamsNames[6]]),
202
+ DG.Column.fromStrings('Value', [values[names.indexOf(expectedReportParamsNames[1])], values[names.indexOf(expectedReportParamsNames[2])], values[names.indexOf(expectedReportParamsNames[3])], values[names.indexOf(expectedReportParamsNames[4])], values[names.indexOf(expectedReportParamsNames[5])], values[names.indexOf(expectedReportParamsNames[6])]])
183
203
  ]);
184
204
 
185
205
  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
- ]);
206
+ DG.Column.fromStrings('Name', [expectedReportParamsNames[7], expectedReportParamsNames[8], expectedReportParamsNames[9], expectedReportParamsNames[10], expectedReportParamsNames[11]]),
207
+ DG.Column.fromStrings('Value', [values[names.indexOf(expectedReportParamsNames[7])].slice(0, 10), values[names.indexOf(expectedReportParamsNames[8])], values[names.indexOf(expectedReportParamsNames[9])], values[names.indexOf(expectedReportParamsNames[10])], values[names.indexOf(expectedReportParamsNames[11])]])
208
+ ]);
@@ -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,9 +107,22 @@ 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 plot: ChildNode | null | undefined = titleDiv.nextSibling;
111
+
112
+ if (plot && !titleDiv.getElementsByClassName('svg-table').length && (plot as HTMLElement).getAttribute('name') === 'viewer-Grid') continue;
113
+
114
+ if (plot && titleDiv.getElementsByClassName('svg-table').length) {
115
+ if ((plot as HTMLElement).getAttribute('name') === 'viewer-OutliersSelectionViewer') {
116
+ plot = titleDiv.parentElement?.nextSibling?.firstChild?.nextSibling;
117
+ skipNext = true;
118
+ }
119
+ if ((plot as HTMLElement).getAttribute('name') === 'viewer-Grid') {
120
+ (titleDiv.getElementsByClassName('svg-table')[0] as HTMLElement).click();
121
+ await new Promise((r) => setTimeout(r, 150));
122
+ plot = titleDiv.nextSibling;
123
+ }
124
+ }
125
+ console.log(plot);
88
126
 
89
127
  if (plot) {
90
128
  const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
@@ -101,15 +139,22 @@ export async function exportFuncCall(call: DG.FuncCall) {
101
139
 
102
140
  if (imageId === null || imageId === undefined) continue;
103
141
 
104
- const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
142
+ const worksheet = exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.INPUT)) ||
143
+ exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.OUTPUT));
105
144
  if (worksheet) {
106
- const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
145
+ console.log(visibleTitle);
146
+ console.log(realNames[visibleTitle]);
147
+ const columnForImage = (((call
148
+ .inputs[realNames[visibleTitle]] || call
149
+ .outputs[realNames[visibleTitle]]) as DG.DataFrame)
150
+ .columns as DG.ColumnList)
151
+ .length + 1;
107
152
  worksheet.addImage(imageId, {
108
153
  tl: {col: columnForImage, row: 0},
109
154
  ext: {width, height},
110
155
  });
111
156
  } else {
112
- const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
157
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${visibleTitle}`);
113
158
  newWorksheet.addImage(imageId, {
114
159
  tl: {col: 0, row: 0},
115
160
  ext: {width, height},
@@ -121,10 +166,17 @@ export async function exportFuncCall(call: DG.FuncCall) {
121
166
  } else {
122
167
  const resultView = document.getElementsByClassName('ui-panel grok-func-results')[0];
123
168
  const titleDivs = resultView.getElementsByClassName('grok-func-results-header');
169
+ let skipNext = false;
170
+
124
171
  for (let i=0; i< titleDivs.length; i++) {
172
+ if (skipNext) {
173
+ skipNext = false;
174
+ continue;
175
+ }
176
+
125
177
  const titleDiv = titleDivs[i];
126
- const title = titleDiv.firstChild?.textContent;
127
- if (title === null || title === undefined) continue;
178
+ const visibleTitle = titleDiv.firstChild?.textContent;
179
+ if (visibleTitle === null || visibleTitle === undefined) continue;
128
180
 
129
181
  let imageId;
130
182
  let width = 0;
@@ -144,9 +196,20 @@ export async function exportFuncCall(call: DG.FuncCall) {
144
196
  width = imageDiv.clientWidth;
145
197
  height = imageDiv.clientHeight;
146
198
  } 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;
199
+ let plot: ChildNode | null | undefined = titleDiv.nextSibling;
200
+
201
+ console.log(plot);
202
+
203
+ if (plot &&
204
+ ((plot as HTMLElement).getAttribute('name') === 'viewer-Grid' ||
205
+ (plot as HTMLElement).getAttribute('name') === 'viewer-OutliersSelectionViewer')) {
206
+ if (titleDiv.getElementsByClassName('svg-table').length) {
207
+ plot = titleDiv.parentElement?.nextSibling?.firstChild?.nextSibling;
208
+ skipNext = true;
209
+ } else {
210
+ continue;
211
+ }
212
+ }
150
213
 
151
214
  if (plot) {
152
215
  const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
@@ -163,15 +226,18 @@ export async function exportFuncCall(call: DG.FuncCall) {
163
226
 
164
227
  if (imageId === null || imageId === undefined) continue;
165
228
 
166
- const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
229
+ const worksheet = exportWorkbook.getWorksheet(getSheetName(visibleTitle, DIRECTION.OUTPUT));
167
230
  if (worksheet) {
168
- const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
231
+ const columnForImage = ((call
232
+ .outputs[realNames[visibleTitle]] as DG.DataFrame)
233
+ .columns as DG.ColumnList)
234
+ .length + 1;
169
235
  worksheet.addImage(imageId, {
170
236
  tl: {col: columnForImage, row: 0},
171
237
  ext: {width, height},
172
238
  });
173
239
  } else {
174
- const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
240
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${visibleTitle}`);
175
241
  newWorksheet.addImage(imageId, {
176
242
  tl: {col: 0, row: 0},
177
243
  ext: {width, height},
@@ -180,10 +246,12 @@ export async function exportFuncCall(call: DG.FuncCall) {
180
246
  }
181
247
  }
182
248
 
183
- const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
184
- scalarOutputs.forEach((scalarOutput) => {
185
- outputScalarsSheet.addRow([scalarOutput.name, call.outputs[scalarOutput.name]]);
186
- });
249
+ if (scalarOutputs.length) {
250
+ const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
251
+ scalarOutputs.forEach((scalarOutput) => {
252
+ outputScalarsSheet.addRow([scalarOutput.name, call.outputs[scalarOutput.name]]);
253
+ });
254
+ }
187
255
 
188
256
  exportWorkbook.xlsx.writeBuffer().then((data) => {
189
257
  const blob = new Blob([data], {type: BLOB_TYPE});
@@ -100,7 +100,8 @@ enum COMMON_TAG_NAME {
100
100
  VALIDATORS = 'validators',
101
101
  CAPTION = 'caption',
102
102
  POSTFIX = 'postfix',
103
- UNITS = 'units'
103
+ UNITS = 'units',
104
+ EDITOR = 'editor',
104
105
  }
105
106
 
106
107
  enum OPTIONAL_TAG_NAME {
@@ -112,21 +113,31 @@ enum OPTIONAL_TAG_NAME {
112
113
  ACTION = 'action',
113
114
  CHOICES = 'choices',
114
115
  SUGGESTIONS = 'suggestions',
115
- SEM_TYPE = 'semType'
116
+ SEM_TYPE = 'semType',
117
+ MIN = 'min',
118
+ MAX = 'max',
116
119
  }
117
120
 
118
121
  type DF_TAG_NAME = COMMON_TAG_NAME | OPTIONAL_TAG_NAME.COLUMNS | OPTIONAL_TAG_NAME.CATEGORICAL;
119
122
  type COLUMN_TAG_NAME = COMMON_TAG_NAME |
120
- OPTIONAL_TAG_NAME.TYPE | OPTIONAL_TAG_NAME.FORMAT |
123
+ OPTIONAL_TAG_NAME.COLUMNS | OPTIONAL_TAG_NAME.FORMAT |
121
124
  OPTIONAL_TAG_NAME.ALLOW_NULLS | OPTIONAL_TAG_NAME.ACTION | OPTIONAL_TAG_NAME.SEM_TYPE
122
125
 
123
126
  type STRING_TAG_NAME = COMMON_TAG_NAME |
124
127
  OPTIONAL_TAG_NAME.CHOICES | OPTIONAL_TAG_NAME.SUGGESTIONS
125
128
 
126
- const DF_TAG_NAMES = [...Object.values(COMMON_TAG_NAME), OPTIONAL_TAG_NAME.COLUMNS, OPTIONAL_TAG_NAME.CATEGORICAL];
127
- const COLUMN_TAG_NAMES = [...Object.values(COMMON_TAG_NAME), OPTIONAL_TAG_NAME.TYPE, OPTIONAL_TAG_NAME.FORMAT,
129
+ type INT_TAG_NAME = COMMON_TAG_NAME | OPTIONAL_TAG_NAME.MIN | OPTIONAL_TAG_NAME.MAX
130
+
131
+ const COMMON_TAG_NAMES = [...Object.values(COMMON_TAG_NAME)];
132
+ const DF_TAG_NAMES = [
133
+ ...Object.values(COMMON_TAG_NAME),
134
+ OPTIONAL_TAG_NAME.COLUMNS,
135
+ OPTIONAL_TAG_NAME.CATEGORICAL,
136
+ OPTIONAL_TAG_NAME.ACTION];
137
+ const COLUMN_TAG_NAMES = [...Object.values(COMMON_TAG_NAME), OPTIONAL_TAG_NAME.COLUMNS, OPTIONAL_TAG_NAME.FORMAT,
128
138
  OPTIONAL_TAG_NAME.ALLOW_NULLS, OPTIONAL_TAG_NAME.ACTION, OPTIONAL_TAG_NAME.SEM_TYPE];
129
139
  const STRING_TAG_NAMES = [...Object.values(COMMON_TAG_NAME), OPTIONAL_TAG_NAME.CHOICES, OPTIONAL_TAG_NAME.SUGGESTIONS];
140
+ const INT_TAG_NAMES = [...Object.values(COMMON_TAG_NAME), OPTIONAL_TAG_NAME.MIN, OPTIONAL_TAG_NAME.MAX];
130
141
 
131
142
  type FuncParamBase = {
132
143
  direction: DIRECTION,
@@ -136,9 +147,12 @@ type FuncParamBase = {
136
147
  }
137
148
 
138
149
  type FuncParam =
139
- FuncParamBase & {
150
+ FuncParamBase & {
140
151
  type: DG.TYPE.BOOL | DG.TYPE.DATE_TIME | DG.TYPE.FLOAT | DG.TYPE.GRAPHICS | DG.TYPE.INT
141
152
  options?: {tag: COMMON_TAG_NAME, value: string}[]
153
+ } | FuncParamBase & {
154
+ type: DG.TYPE.INT
155
+ options?: {tag: COMMON_TAG_NAME, value: string}[]
142
156
  } | FuncParamBase & {
143
157
  type: DG.TYPE.DATA_FRAME,
144
158
  options?: {tag: DF_TAG_NAME, value: string}[]
@@ -151,17 +165,30 @@ type FuncParam =
151
165
  }
152
166
 
153
167
  const generateParamLine = (param: DG.Property, direction: string) => {
154
- const optionTags = `{${
155
- COLUMN_TAG_NAMES
156
- .map((tag) => {
157
- console.log(param.name, tag, param.options(), (param.options() as any)[tag]);
158
- return {tag: tag, val: (param.options() as any)[tag]};
159
- })
160
- .filter((value) => !!value.val)
161
- .map(({tag, val}) => `${tag}:${val}`)
162
- .join('; ')
163
- }}`;
164
- const result =`#${direction}: ${param.propertyType} ${param.name || ''} ${param.defaultValue ? `= ${param.defaultValue}` : ''} ${optionTags} ${param.description ? ` [${param.description}]` : ''}\n`;
168
+ const optionTags = (() => {
169
+ switch (param.propertyType) {
170
+ case DG.TYPE.INT:
171
+ return INT_TAG_NAMES;
172
+ case DG.TYPE.DATA_FRAME:
173
+ return DF_TAG_NAMES;
174
+ case DG.TYPE.COLUMN_LIST:
175
+ case DG.TYPE.COLUMN:
176
+ return COLUMN_TAG_NAMES;
177
+ case DG.TYPE.STRING:
178
+ return STRING_TAG_NAMES;
179
+ default:
180
+ return COMMON_TAG_NAMES;
181
+ }
182
+ })();
183
+ const optionTagsPreview = optionTags
184
+ .map((tag) => {
185
+ // console.log(param.name, tag, JSON.stringify(param.options), param.options[tag]);
186
+ return {tag: tag, val: param.options[tag]};
187
+ })
188
+ .filter((value) => !!value.val)
189
+ .map(({tag, val}) => `${tag}:${val}`)
190
+ .join('; ');
191
+ const result =`#${direction}: ${param.propertyType} ${param.name? `${param.name} ` : ''}${param.defaultValue ? `= ${param.defaultValue} ` : ''}${!!optionTagsPreview.length ? `{${optionTagsPreview}} ` : ''}${param.description ? `[${param.description}]` : ''}\n`;
165
192
  return result;
166
193
  };
167
194
 
@@ -218,7 +245,9 @@ export function _functionEditor(functionCode: string) {
218
245
  addButton.replaceWith(newAddButton);
219
246
  addButton = newAddButton;
220
247
  };
221
- const menu = DG.Menu.popup().items(getNewProps(), onItemClick);
248
+ const menu = DG.Menu.popup().items(getNewProps().map(
249
+ (propName) => functionPropsLabels(propName as FUNC_PROPS_FIELDS),
250
+ ), onItemClick);
222
251
 
223
252
  const shevron = ui.iconFA('chevron-down');
224
253
  const button = ui.button([ui.icons.add(()=>{}), shevron], () => {
@@ -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
  }