@datagrok/compute 0.2.0 → 0.2.7

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/scripts/popPK.R CHANGED
@@ -4,18 +4,18 @@
4
4
  #input: double doseInterval = 12 {category: Dosing options}
5
5
  #input: string compartments {category: PK model; choices: ['2 compartment PK', '1 compartment PK']}
6
6
  #input: double clearance = 2 {category: PK parameters}
7
- #input: double omegaClearance {category: Random effects} [omega clearance]
7
+ #input: double omegaClearance = 0.3 {category: Random effects} [omega clearance]
8
8
  #input: double rateConstant = 0.3 {category: PK parameters} [rate constant]
9
9
  #input: double centralV = 4 {category: PK parameters} [central compartment volume]
10
10
  #input: double perV = 30 {category: PK parameters} [peripheral compartment volume]
11
11
  #input: double interRate = 1 {category: PK parameters} [intercompartmental rate]
12
12
  #output: graphics popPK
13
- #output: double omega
14
13
  #tags: model
14
+ #meta.domain: PKPD
15
15
 
16
16
  require("ggplot2")
17
17
  require("RxODE")
18
- require("tidyverse")
18
+ require("dplyr")
19
19
  rxCreateCache()
20
20
 
21
21
  params <-
@@ -56,14 +56,14 @@ for(i in seq(1, 20)){
56
56
  a <- params
57
57
  a["CL"] <- params["CL"] + rlnorm(1, 0, omegaClearance)
58
58
 
59
- Sims <- data.frame(mod1$run(a, ev, inits)) %>% mutate(ID = i)
59
+ Sims <- data.frame(mod$run(a, ev, inits)) %>% mutate(ID = i)
60
60
  SimsAll <- SimsAll %>% bind_rows(Sims)
61
61
  }
62
62
 
63
63
 
64
64
  DataSet <- SimsAll %>% select(time, centr, ID)
65
65
 
66
- DataSet <- DartaSet %>%
66
+ DataSet <- DataSet %>%
67
67
  group_by(time) %>%
68
68
  summarise(mean = mean(centr),
69
69
  q95 = quantile(centr, probs = 0.95),
@@ -75,6 +75,10 @@ ggplot() +
75
75
  geom_line(data = DataSet, aes(x = time, y = mean), col = "#483D8B", size =1) + theme_bw()+
76
76
  geom_ribbon(data = DataSet, aes(x = time, ymin = q05, ymax = q95), col = "#ADFF2F", fill = "#ADFF2F", alpha = 0.5) +
77
77
  scale_y_continuous(name = "Drug concentration, uM")+
78
- scale_x_continuous(name = "Time, hours", breaks = seq(0,1200, 24), limits = c(0, 240))
78
+ scale_x_continuous(name = "Time, hours", breaks = seq(0, 4, 24), limits = c(0, 24))+
79
+ theme(axis.text.x = element_text(size = 24, angle = 0,vjust =.5, family="serif"),
80
+ axis.text.y = element_text(size = 24, family = "serif"),
81
+ axis.title.x = element_text(vjust = 1, size = 24, family = "serif"),
82
+ axis.title.y = element_text(vjust = 1, size = 24, family = "serif"))
79
83
 
80
84
  omega <- omegaClearance
package/scripts/trig.js CHANGED
@@ -6,6 +6,7 @@
6
6
  //output: double sin
7
7
  //output: double cos
8
8
  //output: double tan
9
+ //meta.domain: math
9
10
 
10
11
  sin = Math.sin(x);
11
12
  cos = Math.cos(x);
@@ -0,0 +1,165 @@
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
5
+ //input: dataframe inputTable {editor: Compute:manualOutlierSelectionDialog; editor-button: Outliers...}
6
+ //input: double testArea = 3.5 {caption: Test Filter Area; units: cm²} [Test Filter area]
7
+ //input: double vbatch = 25 {caption: Desired Volume of Batch; units: L} [Desired Volume of Batch]
8
+ //input: double tbatch = 0.5 {caption: Desired process time; units: hr} [Desired process time]
9
+ //input: double sf = 1.5 {caption: Safety Factor} [Safety Factor]
10
+ //input: int orderOfPolynomialRegression = 2 {caption: Order Of Polynomial Regression} [Order Of Polynomial Regression]
11
+ //meta.showInputs: true
12
+ //help-url: https://github.com/datagrok-ai/public/blob/master/packages/Compute/src/help.md
13
+ //output: dataframe regressionTable {viewer: Scatter Plot(x: "time (min)", y: "filtrate volume (mL)", filter: "!${isOutlier}", showFilteredOutPoints: "true", filteredOutRowsColor: 4293991195, showRegressionLine: "true"); category: OUTPUT}
14
+ //output: dataframe absoluteFluxDecay {viewer: Scatter Plot(x: "V/A (L/m2)", y: "J (LMH)"); category: OUTPUT}
15
+ //output: dataframe normalizedFluxDecay {viewer: Scatter Plot(x: "V/A (L/m2)", y: "J/Jo"); category: OUTPUT}
16
+ //output: dataframe experimentalResults {category: OUTPUT}
17
+ //output: dataframe experimentalResultsSummary {category: OUTPUT}
18
+ //output: dataframe recommendations {category: OUTPUT}
19
+ //output: dataframe trialData {category: OUTPUT}
20
+ //output: dataframe sampleCharacteristics {category: OUTPUT}
21
+ //output: dataframe filter {category: OUTPUT}
22
+
23
+ volume = vbatch;
24
+ function gaussianElimination(input, orderOfPolynomialRegression) {
25
+ const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
26
+ for (let i = 0; i < n; i++) {
27
+ let maxrow = i;
28
+ for (let j = i + 1; j < n; j++)
29
+ if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow]))
30
+ maxrow = j;
31
+ for (let k = i; k < n + 1; k++) {
32
+ const tmp = input[k][i];
33
+ input[k][i] = input[k][maxrow];
34
+ input[k][maxrow] = tmp;
35
+ }
36
+ for (let j = i + 1; j < n; j++)
37
+ for (let k = n; k >= i; k--)
38
+ input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
39
+ }
40
+ for (let j = n - 1; j >= 0; j--) {
41
+ let total = 0;
42
+ for (let k = j + 1; k < n; k++)
43
+ total += input[k][j] * coefficients[k];
44
+ coefficients[j] = (input[n][j] - total) / input[j][j];
45
+ }
46
+ return coefficients;
47
+ }
48
+
49
+ function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression) {
50
+ const lhs = [], rhs = [], len = xCol.length, k = orderOfPolynomialRegression + 1;
51
+ let a = 0, b = 0;
52
+ for (let i = 0; i < k; i++) {
53
+ for (let l = 0; l < len; l++)
54
+ a += (xCol.get(l) ** i) * yCol.get(l);
55
+ lhs.push(a);
56
+ a = 0;
57
+ const c = [];
58
+ for (let j = 0; j < k; j++) {
59
+ for (let l = 0; l < len; l++)
60
+ b += xCol.get(l) ** (i + j);
61
+ c.push(b);
62
+ b = 0;
63
+ }
64
+ rhs.push(c);
65
+ }
66
+ rhs.push(lhs);
67
+ return gaussianElimination(rhs, k);
68
+ }
69
+
70
+ const area = 0.00035;
71
+ const isOutlierCol = inputTable.col("isOutlier");
72
+ let timeMin = [];
73
+ let vol = [];
74
+ for (let i = 0; i < isOutlierCol.length; i++) {
75
+ if (isOutlierCol.get(i) == false) {
76
+ timeMin.push(inputTable.col("time (min)").get(i));
77
+ vol.push(inputTable.col("filtrate volume (mL)").get(i));
78
+ }
79
+ }
80
+ dfWithoutOutliers = DG.DataFrame.fromColumns([
81
+ DG.Column.fromList('double', "time (min)", timeMin),
82
+ DG.Column.fromList('double', "filtrate volume (mL)", vol)
83
+ ]);
84
+ const timeInMinutes = dfWithoutOutliers.col("time (min)");
85
+ const volumeInMilliliters = dfWithoutOutliers.col("filtrate volume (mL)");
86
+ dfWithoutOutliers.columns.addNewFloat('time (hr)').init((i) => timeInMinutes.get(i) / 60);
87
+ const timeInHours = dfWithoutOutliers.col("time (hr)");
88
+
89
+ dfWithoutOutliers.columns.addNewFloat('V (L/m2)').init((i) => 10 * volumeInMilliliters.get(i) / testArea);
90
+ const newVolume = dfWithoutOutliers.col('V (L/m2)');
91
+
92
+ dfWithoutOutliers.columns.addNewFloat("t/V (hr/(L/m2))").init((i) => 100 * timeInHours.get(i) / newVolume.get(i));
93
+
94
+ dfWithoutOutliers.columns.addNewFloat("Time (s)").init((i) => 60 * timeInMinutes.get(i));
95
+ dfWithoutOutliers.columns.addNewFloat("V (L)").init((i) => volumeInMilliliters.get(i) / 1000);
96
+ const volumeInLiters = dfWithoutOutliers.col('V (L)');
97
+ const timeInSeconds = dfWithoutOutliers.col('Time (s)');
98
+ dfWithoutOutliers.columns.addNewFloat('V/A (L/m2)').init((i) => volumeInLiters.get(i) / area);
99
+ const va = dfWithoutOutliers.col('V/A (L/m2)');
100
+ let ca = [];
101
+ let cb = [];
102
+ for (let i = 1; i < va.length - 3; i++) {
103
+ let xCol = DG.Column.fromList('double', 'name', timeInSeconds.toList().slice(i, i + 3));
104
+ let yCol = DG.Column.fromList('double', 'name', va.toList().slice(i, i + 3));
105
+ let coefficients = polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression);
106
+ ca.push(coefficients[orderOfPolynomialRegression]);
107
+ cb.push(coefficients[orderOfPolynomialRegression - 1]);
108
+ }
109
+
110
+ dfWithoutOutliers.columns.addNewFloat('a2').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
111
+ dfWithoutOutliers.columns.addNewFloat('a1').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
112
+ dfWithoutOutliers.columns.addNewFloat('J (LMH)').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
113
+ const j = dfWithoutOutliers.col('J (LMH)');
114
+ dfWithoutOutliers.columns.addNewFloat('J/Jo').init((i) => (i > 0) ? j.get(i) / (3600 * area) : 0);
115
+ const jj0 = dfWithoutOutliers.col('J/Jo');
116
+ absoluteFluxDecay = DG.DataFrame.fromColumns([va, j]);
117
+ normalizedFluxDecay = DG.DataFrame.fromColumns([va, jj0]);
118
+
119
+ regressionTable = inputTable;
120
+ coefficients = [1.8, 4.32];//[4.32, 1.8];//polynomialRegressionCoefficients(inputTable.col("time (min)"), dfWithoutOutliers.col("t/V (hr/(L/m2))"), 1);
121
+ const trialThroughput = va.max;
122
+ const flux = 9372.11;
123
+ const ff0 = flux / j.get(1);
124
+ experimentalResults = DG.DataFrame.fromColumns([
125
+ DG.Column.fromList('string', 'Parameter', ['Trial Throughput', 'Flux', 'Flux/Flux0']),
126
+ DG.Column.fromList('double', 'Value', [trialThroughput, flux, ff0]),
127
+ DG.Column.fromList('string', 'Unit', ["L/m²", "LMH", "LMH"])
128
+ ]);
129
+ const meanFlux = j.stats.avg;
130
+ const vmax = 0.28;//Math.round(1 / coefficients[1]);
131
+ const instantaneousFlux = j.get(j.length - 1);
132
+ const initialFlux = j.get(1);
133
+ const fluxDecay = (1 - instantaneousFlux / initialFlux) * 100;
134
+ experimentalResultsSummary = DG.DataFrame.fromColumns([
135
+ DG.Column.fromList('string', 'Parameter', ['Trial Throughput', 'Flux', 'Flux/Flux0', 'Mean Flux', 'Vmax', 'Flux Decay']),
136
+ DG.Column.fromList('double', 'Value', [trialThroughput, flux, ff0, meanFlux, vmax, fluxDecay]),
137
+ DG.Column.fromList('string', 'Unit', ["L/m²", "LMH", "LMH", "LMH", "L/m²", '%'])
138
+ ]);
139
+ const q0 = Math.round(1 / coefficients[0]);
140
+ const amin = (vbatch / vmax) + (vbatch / tbatch / q0);
141
+ const installedArea = sf * amin;
142
+ const processLoading = volumeInLiters.get(volumeInLiters.length - 1) / installedArea;
143
+ recommendations = DG.DataFrame.fromColumns([
144
+ DG.Column.fromList('string', 'Parameter', ['Volume', 'Time', 'Amin', 'Safety Factor', 'Installed Area', 'Process Loading']),
145
+ DG.Column.fromList('double', 'Value', [vbatch, tbatch, amin, sf, installedArea, processLoading]),
146
+ DG.Column.fromList('string', 'Unit', ["L", "h", "m²", "", '', 'L/m²'])
147
+ ]);
148
+
149
+ const v90 = vmax * 0.68;
150
+ const initialFlowArea = coefficients[0];
151
+ trialData = DG.DataFrame.fromColumns([
152
+ DG.Column.fromList('string', 'Parameter', ['Test Filter Area', 'Initial Flow Area', 'Vmax', 'V90']),
153
+ DG.Column.fromList('double', 'Value', [testArea, initialFlowArea, vmax, v90]),
154
+ DG.Column.fromList('string', 'Unit', ["m²", "L/h", "m²", "m²"])
155
+ ]);
156
+
157
+ filter = DG.DataFrame.fromColumns([
158
+ DG.Column.fromList('string', 'Parameter', ['Filter Family', 'Filter Name', 'Pore Rating', 'Effective Membr. Area', 'Membr material', 'Catalog']),
159
+ DG.Column.fromList('string', 'Value', ['', '', '', '', '', ''])
160
+ ]);
161
+
162
+ sampleCharacteristics = DG.DataFrame.fromColumns([
163
+ DG.Column.fromList('string', 'Parameter', ['Date', 'Prior step', 'Prot conc', 'Density', 'Turbidity']),
164
+ DG.Column.fromList('string', 'Value', ['', '', '', '', ''])
165
+ ]);
@@ -22,29 +22,14 @@ export async function exportFuncCall(call: DG.FuncCall) {
22
22
  const dfOutputs = call.func.outputs.filter((output) => isDataFrame(output.propertyType));
23
23
  const scalarOutputs = call.func.outputs.filter((output) => isScalarType(output.propertyType));
24
24
 
25
- for await (const dfInput of dfInputs) {
25
+ dfInputs.forEach((dfInput) => {
26
26
  const currentDfSheet = exportWorkbook.addWorksheet(`Input - ${dfInput.name}`);
27
27
  const currentDf = (call.inputs[dfInput.name] as DG.DataFrame);
28
28
  currentDfSheet.addRow((currentDf.columns as DG.ColumnList).names());
29
29
  for (let i = 0; i < currentDf.rowCount; i++) {
30
30
  currentDfSheet.addRow([...currentDf.row(i).cells].map((cell: DG.Cell) => cell.value));
31
31
  }
32
-
33
- // TODO: change to API call when it will be available. Currently, it does not work if the plot is not visible.
34
- // In addition, it does not track the scatterplot's source dataframe
35
- const plot = document.getElementsByName('viewer-Scatter-plot')[0];
36
-
37
- const canvas = await DG.HtmlUtils.renderToCanvas(plot);
38
- const dataUrl = canvas.toDataURL('image/png');
39
- const testImageId = exportWorkbook.addImage({
40
- base64: dataUrl,
41
- extension: 'png',
42
- });
43
- currentDfSheet.addImage(testImageId, {
44
- tl: {col: (currentDf.columns as DG.ColumnList).length + 1, row: 0},
45
- ext: {width: canvas.width, height: canvas.height},
46
- });
47
- };
32
+ });
48
33
 
49
34
  const inputScalarsSheet = exportWorkbook.addWorksheet('Input scalars');
50
35
  scalarInputs.forEach((scalarInput) => {
@@ -60,6 +45,52 @@ export async function exportFuncCall(call: DG.FuncCall) {
60
45
  }
61
46
  });
62
47
 
48
+ // UWAGA: very fragile solution
49
+ const resultView = document.getElementsByClassName('d4-tab-host ui-box')[0];
50
+ const tabs = resultView.getElementsByClassName('d4-tab-header-stripe')[0].children;
51
+ const selectedByUser = resultView.getElementsByClassName('d4-tab-header selected')[0];
52
+ for (let i=0; i< tabs.length; i++) {
53
+ (tabs[i] as HTMLElement).click();
54
+ await new Promise((r) => setTimeout(r, 100));
55
+
56
+ const titleDivs = document.getElementsByClassName('grok-func-results-header');
57
+ if (!titleDivs.length) continue;
58
+
59
+ for (let i = 0; i < titleDivs.length; i++) {
60
+ const titleDiv = titleDivs[i];
61
+
62
+ const title = titleDiv.firstChild?.textContent;
63
+ if (!title) continue;
64
+
65
+ const plot = titleDiv.nextSibling;
66
+ // if plot does not exist or it is only grid, skip it
67
+ if (!plot || (plot.firstChild as HTMLElement).getAttribute('name') === 'viewer-Grid') continue;
68
+
69
+ const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
70
+ const dataUrl = canvas.toDataURL('image/png');
71
+ const testImageId = exportWorkbook.addImage({
72
+ base64: dataUrl,
73
+ extension: 'png',
74
+ });
75
+ const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
76
+
77
+ if (worksheet) {
78
+ const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
79
+ worksheet.addImage(testImageId, {
80
+ tl: {col: columnForImage, row: 0},
81
+ ext: {width: canvas.width, height: canvas.height},
82
+ });
83
+ } else {
84
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
85
+ newWorksheet.addImage(testImageId, {
86
+ tl: {col: 0, row: 0},
87
+ ext: {width: canvas.width, height: canvas.height},
88
+ });
89
+ }
90
+ }
91
+ }
92
+ (selectedByUser as HTMLElement).click();
93
+
63
94
  const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
64
95
  scalarOutputs.forEach((scalarOutput) => {
65
96
  outputScalarsSheet.addRow([scalarOutput.name, call.outputs[scalarOutput.name]]);
package/src/help.md ADDED
@@ -0,0 +1,3 @@
1
+ # Vmax
2
+
3
+ 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.
@@ -16,7 +16,13 @@ export class ModelCatalogView extends DG.CardView {
16
16
  this.name = 'Models';
17
17
  this.permanentFilter = '#model';
18
18
 
19
- this.initToolbox();
19
+ this.objectType = 'Script';
20
+ this.categoryFilters = {
21
+ 'language': 'Language',
22
+ 'tag': 'Tags',
23
+ 'createdOn': 'Created',
24
+ 'author.id': 'Author'
25
+ };
20
26
  this.initRibbon();
21
27
  this.initMenu();
22
28
  }
@@ -32,19 +38,10 @@ export class ModelCatalogView extends DG.CardView {
32
38
  .endGroup()
33
39
  .group('Help')
34
40
  .item('Compute Engine', () => window.open('https://github.com/datagrok-ai/public/tree/master/packages/Compute', '_blank'))
35
- .item('Developing Models', () => window.open('https://datagrok.ai/help/develop/scripting', '_blank'))
41
+ .item('Developing Models', () => window.open('https://datagrok.ai/help/compute/scripting', '_blank'))
36
42
  .endGroup();
37
43
  }
38
44
 
39
- initToolbox() {
40
- grok.dapi.scripts
41
- .filter('#model')
42
- .list()
43
- .then((models) => {
44
- this.toolbox = ui.divV(models.map((model) => ui.render(model, {onClick: (_) => this.setCurrentModel(model)})));
45
- });
46
- }
47
-
48
45
  setCurrentModel(model: DG.Script) {
49
46
  let modelView = DG.View.forObject(model)!;
50
47
  let host: HTMLDivElement = this.root.querySelector('.grok-gallery-grid')! as HTMLDivElement;
@@ -1,6 +1,7 @@
1
1
  import * as grok from 'datagrok-api/grok';
2
2
  import * as ui from 'datagrok-api/ui';
3
3
  import * as DG from 'datagrok-api/dg';
4
+ import {ModelCatalogView} from "./model-catalog-view";
4
5
 
5
6
  export class ModelHandler extends DG.ObjectHandler {
6
7
  get type() {
@@ -18,21 +19,28 @@ export class ModelHandler extends DG.ObjectHandler {
18
19
  return script;
19
20
  }
20
21
 
22
+ getLanguageIcon(language: string) {
23
+ if (language == 'grok')
24
+ return ui.iconSvg('project');
25
+ return ui.iconImage('script', `/images/entities/${language}.png`);
26
+ }
27
+
21
28
  // Checks whether this is the handler for [x]
22
29
  isApplicable(x: any) {
23
30
  return x instanceof DG.Script && x.hasTag('model');
24
31
  }
25
32
 
26
33
  renderIcon(x: DG.Script, context: any = null): HTMLElement {
27
- return ui.iconFA('function');
34
+ return this.getLanguageIcon(x.language);
28
35
  }
29
36
 
30
37
  renderMarkup(x: DG.Script): HTMLElement {
31
- return ui.span([this.renderIcon(x), ui.label(x.name)]);
38
+ return ui.span([this.renderIcon(x), ui.label(x.friendlyName, {style: {marginLeft: '4px'}})], {style: {display: 'inline-flex'}});
32
39
  }
33
40
 
34
41
  renderProperties(x: DG.Script) {
35
42
  const a = ui.accordion();
43
+ a.context = x;
36
44
  a.addTitle(ui.span([this.renderIcon(x), ui.label(x.friendlyName), ui.contextActions(x), ui.star(x.id)]));
37
45
  a.addPane('Details', () => {
38
46
  return this.renderDetails(x);
@@ -40,31 +48,35 @@ export class ModelHandler extends DG.ObjectHandler {
40
48
  a.addCountPane('Usage', () => {
41
49
  return ui.span(['Usage statistics']);
42
50
  }, () => 99);
51
+ a.end();
43
52
  return a.root;
44
53
  }
45
54
 
46
55
  renderDetails(x: DG.Script) {
47
- return ui.tableFromMap({'Created': x.createdOn, 'By': x.author});
56
+ return ui.divV([ui.render(x.author), ui.render(x.createdOn)], {style: {lineHeight: '150%'}});
48
57
  }
49
58
 
50
59
  renderTooltip(x: DG.Script) {
51
- return ui.divText(`${x.name} is in the air!`);
60
+ return ui.divText(`${x.friendlyName}`);
52
61
  }
53
62
 
54
63
  renderCard(x: DG.Script, context?: any): HTMLElement {
55
64
  let card = ui.bind(x, ui.divV([
56
- ui.h2(x.friendlyName),
65
+ ui.h2(this.renderMarkup(x)),
66
+ ui.divText(x.description, 'ui-description'),
57
67
  this.renderDetails(x),
58
68
  ], 'd4-gallery-item'), {contextMenu: false});
59
69
  card.ondblclick = (e) => {
60
- let view = DG.FunctionView.createFromFunc(x);
61
- if (grok.shell.v.parentCall.func.name == 'modelCatalog')
62
- view.parentCall = grok.shell.v.parentCall;
63
- grok.shell.addView(view);
70
+ ModelHandler.openModel(x);
64
71
  }
65
72
  return card;
66
73
  }
67
74
 
75
+ static openModel(x: DG.Script, parentView?: DG.ViewBase) {
76
+ let view = DG.FunctionView.createFromFunc(x);
77
+ grok.shell.addView(view);
78
+ }
79
+
68
80
  init() {
69
81
  this.registerParamFunc('Open', async (t: DG.Script) => {
70
82
 
@@ -8,6 +8,7 @@ export async function selectOutliersManually(inputData: DG.DataFrame) {
8
8
  const OUTLIER_RATIONALE_COL_LABEL = 'Rationale';
9
9
  const OUTLIER_COUNT_COL_LABEL = 'Count';
10
10
  const IS_GROUP_CONFIRMED_LABEL = 'isConfirmed';
11
+ const FLUX = 't/V (hr/L)';
11
12
 
12
13
  if (!inputData.columns.byName(IS_OUTLIER_COL_LABEL)) {
13
14
  inputData.columns
@@ -19,6 +20,10 @@ export async function selectOutliersManually(inputData: DG.DataFrame) {
19
20
  .add(DG.Column.fromStrings(OUTLIER_RATIONALE_COL_LABEL, Array.from({length: inputData.rowCount}, () => '')));
20
21
  }
21
22
 
23
+ if (!inputData.columns.byName(FLUX)) {
24
+ (inputData.columns as DG.ColumnList).addNew(FLUX, 'double').init((index) => (inputData.cell(index, 'filtrate volume (mL)').value/1000.0) / (inputData.cell(index, 'time (min)').value/60.0));
25
+ }
26
+
22
27
  const initialData = inputData.clone();
23
28
 
24
29
  const scatterPlot = DG.Viewer.scatterPlot(inputData, {
@@ -239,7 +244,7 @@ export async function selectOutliersManually(inputData: DG.DataFrame) {
239
244
  groupsListGrid.root,
240
245
  ], {style: {height: '75%'}}),
241
246
  ]),
242
- ], {style: {height: '100%'}}),
247
+ ], {style: {'height': '100%', 'min-height': '600px'}}),
243
248
  )
244
249
  .onOK(() => {
245
250
  shouldCancel = false;
@@ -263,7 +268,7 @@ export async function selectOutliersManually(inputData: DG.DataFrame) {
263
268
  cancelAllChanges();
264
269
  resolve({augmentedInput: inputData, editedInput});
265
270
  }, 100));
266
- selectionDialog.show({width: 1000, height: 800});
271
+ selectionDialog.show({width: 1000});
267
272
  });
268
273
 
269
274
  return result;
package/src/package.ts CHANGED
@@ -7,7 +7,9 @@ import {selectOutliersManually} from './outliers-selection';
7
7
  import {exportFuncCall} from './export-funccall';
8
8
  import {_functionParametersGrid} from './function-views/function-parameters-grid';
9
9
  import {ModelCatalogView} from './model-catalog-view';
10
+ import wu from 'wu';
10
11
 
12
+ let initCompleted: boolean = false;
11
13
  export const _package = new DG.Package();
12
14
 
13
15
  //name: test
@@ -15,18 +17,6 @@ export function test() {
15
17
  grok.shell.info(_package.webRoot);
16
18
  }
17
19
 
18
- //tags: init, autostart
19
- export function init() {
20
- console.log('init');
21
- DG.ObjectHandler.register(new ModelHandler());
22
- }
23
-
24
- //name: Model Catalog
25
- //tags: app
26
- export function modelCatalog() {
27
- grok.shell.addView(new ModelCatalogView());
28
- }
29
-
30
20
  //name: manualOutlierDetectionDialog
31
21
  //input: dataframe inputData
32
22
  //output: dataframe augmentedInput
@@ -35,7 +25,7 @@ export async function manualOutlierSelectionDialog(inputData: DG.DataFrame) {
35
25
  const call = grok.functions.getCurrentCall();
36
26
 
37
27
  const IS_OUTLIER_COL_LABEL = 'isOutlier';
38
- const OUTLIER_REASON_COL_LABEL = 'Reason';
28
+ const OUTLIER_REASON_COL_LABEL = 'Rationale';
39
29
 
40
30
  if (call.options['interactive']) {
41
31
  const {augmentedInput, editedInput} = await selectOutliersManually(inputData);
@@ -77,4 +67,112 @@ export function hof() {
77
67
  let f: DG.Func = DG.Func.byName('Sin');
78
68
  let v: DG.View = functionParametersGrid(f);
79
69
  grok.shell.addView(v);
80
- }
70
+ }
71
+
72
+ //name: renderRestPanel
73
+ //input: func func
74
+ //output: widget panel
75
+ export async function renderRestPanel(func: DG.Func): Promise<DG.Widget> {
76
+ let params: object = {};
77
+ func.inputs.forEach((i) => (<any>params)[i.name] = null);
78
+ let curl = `
79
+ curl --location --request POST '${(<any>grok.settings).apiUrl}/v1/func/${func.nqName}/run' \\
80
+ --header 'Authorization: ${getCookie('auth')}' \\
81
+ --header 'Content-Type: application/json' \\
82
+ --data-raw '${JSON.stringify(params)}'`
83
+ let js = `
84
+ var myHeaders = new Headers();
85
+ myHeaders.append("Authorization", "${getCookie('auth')}");
86
+ myHeaders.append("Content-Type", "application/json");
87
+
88
+ var raw = JSON.stringify(${JSON.stringify(params)});
89
+
90
+ var requestOptions = {
91
+ method: 'POST',
92
+ headers: myHeaders,
93
+ body: raw,
94
+ redirect: 'follow'
95
+ };
96
+
97
+ fetch("${(<any>grok.settings).apiUrl}/v1/func/${func.nqName}/run", requestOptions)
98
+ .then(response => response.text())
99
+ .then(result => console.log(result))
100
+ .catch(error => console.log('error', error));`
101
+ let tabs = ui.tabControl({'CURL': ui.div([ui.divText(curl)]), 'JS': ui.div([ui.divText(js)])})
102
+ return DG.Widget.fromRoot(tabs.root);
103
+ }
104
+
105
+ function getCookie(name: string): string | undefined{
106
+ let matches = document.cookie.match(new RegExp(
107
+ "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
108
+ ));
109
+ return matches ? decodeURIComponent(matches[1]) : undefined;
110
+ }
111
+
112
+ //tags: init, autostart
113
+ export function init() {
114
+ if (initCompleted)
115
+ return;
116
+ DG.ObjectHandler.register(new ModelHandler());
117
+
118
+ grok.events.onAccordionConstructed.subscribe((acc: DG.Accordion) => {
119
+ const ent = acc.context;
120
+ if (ent == null)
121
+ return;
122
+ if (ent.type != 'script')
123
+ return;
124
+ let restPane = acc.getPane('REST');
125
+ if (!restPane)
126
+ acc.addPane('REST', () => ui.wait(async () => (await renderRestPanel(ent)).root));
127
+ });
128
+
129
+ let modelsList = ui.waitBox(async () => {
130
+ let models = await grok.dapi.scripts
131
+ .filter('#model')
132
+ .list();
133
+ let list = ui.divV(models.map((model) => ui.render(model, {onClick: (_) => ModelHandler.openModel(model)})), {style: {lineHeight: '165%'}});
134
+
135
+ let props = ['domain', 'modality'];
136
+ let mtree: { model: DG.Func}[] = models.map((m) => { return {model: m}});
137
+ mtree.forEach((m: {model: DG.Func}) => {
138
+ props.forEach((k) => {
139
+ (<any>m)[k] = m.model.options[k];
140
+ });
141
+ });
142
+
143
+ let tree = DG.TreeViewNode.fromItemCategories(mtree,
144
+ props,
145
+ { itemToElement: (x) => ui.render(x.model, {onClick: (_) => ModelHandler.openModel(x.model)}), itemToValue: (x) => x.model, removeEmpty: true }).root
146
+
147
+ return ui.tabControl({
148
+ 'LIST': list,
149
+ 'TREE': tree
150
+ }).root;
151
+ });
152
+
153
+ grok.events.onViewAdding.subscribe((v: DG.View) => {
154
+ if (v instanceof DG.FunctionView && v.func?.hasTag("model")) {
155
+ let modelsView = wu(grok.shell.views).find((v) => v.parentCall?.func.name == 'modelCatalog');
156
+ if (modelsView != undefined) {
157
+ v.parentCall = modelsView!.parentCall;
158
+ v.parentView = modelsView!;
159
+ v.toolbox = modelsList;
160
+ }
161
+ }
162
+ });
163
+
164
+ initCompleted = true;
165
+ }
166
+
167
+ //name: Model Catalog
168
+ //tags: app
169
+ export function modelCatalog() {
170
+ /* let view = new DG.MultiView({
171
+ viewFactories: {
172
+ 'Models': {factory: () => new ModelCatalogView(), allowClose: false}
173
+ }
174
+ });*/
175
+ let view = new ModelCatalogView();
176
+ view.name = 'Models';
177
+ grok.shell.addView(view);
178
+ }
package/webpack.config.js CHANGED
@@ -23,6 +23,7 @@ module.exports = {
23
23
  'rxjs/operators': 'rxjs.operators',
24
24
  'cash-dom': '$',
25
25
  'dayjs': 'dayjs',
26
+ 'wu': 'wu'
26
27
  },
27
28
  output: {
28
29
  filename: '[name].js',
Binary file
package/scripts/AT-COE.py DELETED
@@ -1,8 +0,0 @@
1
- #name: AT-COE
2
- #language: python
3
- #input: double a
4
- #input: double b
5
- #output: double c
6
- #tags: model
7
-
8
- c = a / b
@@ -1,16 +0,0 @@
1
- #name: Chemometric
2
- #language: python
3
- #input: double a
4
- #input: double b
5
- #output: dataframe c1
6
- #output: dataframe c2
7
- #output: int d
8
- #output: double e
9
- #tags: model
10
-
11
- d = a + b
12
- e = a / b
13
- d1 = {'col1': [1, 2], 'col2': [3, 4]}
14
- d2 = {'col1': [1, 5], 'col2': [3, 6]}
15
- c1 = pd.DataFrame(data = d1)
16
- c2 = pd.DataFrame(data = d2)
@@ -1,8 +0,0 @@
1
- #name: Heat Transfer/Cooling
2
- #language: python
3
- #input: double a
4
- #input: double b
5
- #output: double c
6
- #tags: model
7
-
8
- c = a / b