@datagrok/compute 0.2.8 → 0.5.1

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.
@@ -0,0 +1,262 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as ui from 'datagrok-api/ui';
3
+ import * as DG from 'datagrok-api/dg';
4
+
5
+ export class OutliersSelectionViewer extends DG.JsViewer {
6
+ constructor() {
7
+ super();
8
+ }
9
+
10
+ // override to handle property changes
11
+ onPropertyChanged(prop: any) {
12
+ grok.shell.info(`${prop.name}: ${prop.get(this)}`);
13
+ }
14
+
15
+ onTableAttached() {
16
+ if (this.dataFrame) {
17
+ this.initialRender();
18
+ }
19
+ }
20
+
21
+ render() {
22
+
23
+ }
24
+
25
+ initialRender() {
26
+ if (!this.dataFrame) {
27
+ this.root.innerHTML = '';
28
+ return;
29
+ }
30
+
31
+ const inputData = this.dataFrame;
32
+ const IS_OUTLIER_COL_LABEL = 'isOutlier';
33
+ const OUTLIER_RATIONALE_COL_LABEL = 'Rationale';
34
+ const OUTLIER_COUNT_COL_LABEL = 'Count';
35
+ const IS_GROUP_CONFIRMED_LABEL = 'isConfirmed';
36
+ const FLUX = 't/V (hr/(L/m²))';
37
+ const DEFAULT_TEST_AREA = 3.5;
38
+
39
+ if (!inputData.columns.byName(IS_OUTLIER_COL_LABEL)) {
40
+ inputData.columns
41
+ .add(DG.Column.fromBitSet(IS_OUTLIER_COL_LABEL, DG.BitSet.create(inputData.rowCount, () => false)));
42
+ }
43
+
44
+ if (!inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL)) {
45
+ inputData.columns
46
+ .add(DG.Column.fromStrings(OUTLIER_RATIONALE_COL_LABEL, Array.from({length: inputData.rowCount}, () => '')));
47
+ }
48
+
49
+ if (!inputData.columns.byName(FLUX)) {
50
+ (inputData.columns as DG.ColumnList).addNew(FLUX, 'double').init((index) => (inputData.cell(index, 'time (min)').value/60.0) / ((inputData.cell(index, 'filtrate volume (mL)').value/1000.0) / (DEFAULT_TEST_AREA / 10000.0)));
51
+ }
52
+
53
+ const initialData = inputData.clone();
54
+
55
+ const clearTable = () => {
56
+ return DG.DataFrame.fromColumns([
57
+ DG.Column.fromStrings(OUTLIER_RATIONALE_COL_LABEL, []),
58
+ DG.Column.fromInt32Array(OUTLIER_COUNT_COL_LABEL, new Int32Array([])),
59
+ DG.Column.fromStrings('Actions', []),
60
+ DG.Column.fromBitSet(IS_GROUP_CONFIRMED_LABEL, DG.BitSet.create(0, () => false)),
61
+ ]);
62
+ };
63
+
64
+ const groupsListGrid = DG.Viewer.grid(clearTable());
65
+ groupsListGrid.root.style.width = '100%';
66
+ groupsListGrid.columns.setVisible([OUTLIER_RATIONALE_COL_LABEL, OUTLIER_COUNT_COL_LABEL, 'Actions']);
67
+
68
+ groupsListGrid.onCellPrepare((gc) => {
69
+ if (!gc.isTableCell) {
70
+ return;
71
+ }
72
+
73
+ const confirmBtn = () => ui.div(
74
+ ui.iconFA('check', () => {
75
+ if (!groupsListGrid.dataFrame) return;
76
+
77
+ const newRationale =
78
+ groupsListGrid.dataFrame?.cell(groupsListGrid.dataFrame.rowCount-1, OUTLIER_RATIONALE_COL_LABEL).value;
79
+
80
+ inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
81
+ inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, true);
82
+ inputData.set(
83
+ OUTLIER_RATIONALE_COL_LABEL,
84
+ selectedIndex,
85
+ newRationale,
86
+ );
87
+ });
88
+ inputData.selection.setAll(false);
89
+ }, 'Confirm the outliers'), {style: {'text-align': 'center', 'margin': '6px'}},
90
+ );
91
+
92
+ const cancelBtn = () => ui.div(
93
+ ui.iconFA('times', () => {
94
+ if (!groupsListGrid.dataFrame) return;
95
+
96
+ groupsListGrid.dataFrame.rows.removeAt(groupsListGrid.dataFrame.rowCount-1);
97
+ inputData.selection.setAll(false);
98
+ }, 'Cancel the outliers'), {style: {'text-align': 'center', 'margin': '6px'}},
99
+ );
100
+
101
+ const deleteBtn = (rationale: string) => ui.div(
102
+ ui.icons.delete(() => {
103
+ for (let i = 0; i < inputData.rowCount; i++) {
104
+ if (inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i) === rationale) {
105
+ inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).set(i, '');
106
+ inputData.columns.byName(IS_OUTLIER_COL_LABEL).set(i, false);
107
+ }
108
+ }
109
+ }, 'Remove the outliers group'), {style: {'text-align': 'center', 'margin': '6px'}},
110
+ );
111
+
112
+ if (gc.gridColumn.name === 'Actions') {
113
+ gc.gridColumn.cellType = 'html';
114
+ gc.style.element =
115
+ ui.divH([
116
+ ...!gc.grid.dataFrame?.get(IS_GROUP_CONFIRMED_LABEL, gc.gridRow) ?
117
+ [confirmBtn(), cancelBtn()] :
118
+ [deleteBtn(gc.grid.dataFrame?.get(OUTLIER_RATIONALE_COL_LABEL, gc.gridRow))],
119
+ ]);
120
+ }
121
+ });
122
+
123
+ groupsListGrid.onCellValueEdited.subscribe((editedCell) => {
124
+ if (!groupsListGrid.dataFrame || editedCell.gridColumn.name !== OUTLIER_RATIONALE_COL_LABEL) return;
125
+
126
+ if (!(groupsListGrid.dataFrame.columns as DG.ColumnList)
127
+ .byName(IS_GROUP_CONFIRMED_LABEL).get(editedCell.gridRow)) return;
128
+
129
+ const uniqueValues= new Set<string>();
130
+ for (let i = 0; i < groupsListGrid.dataFrame?.rowCount; i++) {
131
+ const record = groupsListGrid.dataFrame?.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
132
+ uniqueValues.add(record);
133
+ }
134
+
135
+ for (let i = 0; i < inputData.rowCount; i++) {
136
+ const currentCellValue = inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
137
+ if (currentCellValue != '' && !uniqueValues.has(currentCellValue)) {
138
+ inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).set(i, editedCell.cell.value);
139
+ }
140
+ }
141
+ });
142
+
143
+ const updateGroupsTable = () => {
144
+ const uniqueValues: {[key:string]: number} = {};
145
+ for (let i = 0; i < inputData.rowCount; i++) {
146
+ const record = inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
147
+ const count = uniqueValues[record];
148
+ if (record != '') {
149
+ count ?
150
+ uniqueValues[record]++ :
151
+ uniqueValues[record] = 1;
152
+ }
153
+ }
154
+ groupsListGrid.dataFrame = clearTable();
155
+ groupsListGrid.columns.setVisible([OUTLIER_RATIONALE_COL_LABEL, OUTLIER_COUNT_COL_LABEL, 'Actions']);
156
+
157
+ Object.keys(uniqueValues).map((key: string) => {
158
+ groupsListGrid.dataFrame?.rows.addNew([key, uniqueValues[key], '', true]);
159
+ });
160
+ };
161
+
162
+ inputData.onDataChanged.subscribe(updateGroupsTable);
163
+ inputData.onSelectionChanged.subscribe(() => {
164
+ if (!groupsListGrid.dataFrame || !inputData.selection.trueCount) return;
165
+
166
+ const isConfirmedColumn = (groupsListGrid.dataFrame.columns as DG.ColumnList)
167
+ .byName(IS_GROUP_CONFIRMED_LABEL).toList();
168
+
169
+ if (isConfirmedColumn.some((value) => value === false)) {
170
+ groupsListGrid.dataFrame.set(
171
+ OUTLIER_COUNT_COL_LABEL,
172
+ groupsListGrid.dataFrame.rowCount-1,
173
+ inputData.selection.trueCount,
174
+ );
175
+ } else {
176
+ const newRow = groupsListGrid.dataFrame.rows.addNew(['Manual', inputData.selection.trueCount, '', false]);
177
+ groupsListGrid.dataFrame.currentCell = groupsListGrid.dataFrame.cell(newRow.idx, OUTLIER_RATIONALE_COL_LABEL);
178
+ }
179
+ });
180
+
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
+ inputData.selection.setAll(false);
232
+
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
+ updateGroupsTable();
242
+ resetSelectedBtn.classList.add('disabled');
243
+
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';
250
+
251
+ this.root.replaceWith(
252
+ ui.divV([
253
+ info,
254
+ ui.divV([
255
+ ui.divH([
256
+ resetSelectedBtn, resetAllBtn, autoOutlierGroupBtn,
257
+ ], {style: {'text-align': 'center', 'justify-content': 'center'}}),
258
+ groupsListGrid.root,
259
+ ], {style: {'height': '75%'}}),
260
+ ], {style: {'height': '100%', 'min-width': '230px'}}));
261
+ }
262
+ }
@@ -1,14 +1,20 @@
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 {_package} from './package';
4
+ import {_package} from '../package';
5
5
 
6
+ /**
7
+ * @param inputData The data to select the outliers in
8
+ * @returns Two dataframes: 1) with selected outliers and 2) with removed outliers
9
+ * @deprecated Use the OutliersSelectionViewer instead
10
+ */
6
11
  export async function selectOutliersManually(inputData: DG.DataFrame) {
7
12
  const IS_OUTLIER_COL_LABEL = 'isOutlier';
8
13
  const OUTLIER_RATIONALE_COL_LABEL = 'Rationale';
9
14
  const OUTLIER_COUNT_COL_LABEL = 'Count';
10
15
  const IS_GROUP_CONFIRMED_LABEL = 'isConfirmed';
11
- const FLUX = 't/V (hr/L)';
16
+ const FLUX = 't/V (hr/(L/m²))';
17
+ const DEFAULT_TEST_AREA = 3.5;
12
18
 
13
19
  if (!inputData.columns.byName(IS_OUTLIER_COL_LABEL)) {
14
20
  inputData.columns
@@ -21,7 +27,7 @@ export async function selectOutliersManually(inputData: DG.DataFrame) {
21
27
  }
22
28
 
23
29
  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));
30
+ (inputData.columns as DG.ColumnList).addNew(FLUX, 'double').init((index) => (inputData.cell(index, 'time (min)').value/60.0) / ((inputData.cell(index, 'filtrate volume (mL)').value/1000.0) / (DEFAULT_TEST_AREA / 10000.0)));
25
31
  }
26
32
 
27
33
  const initialData = inputData.clone();
package/src/package.ts CHANGED
@@ -3,11 +3,13 @@ import * as grok from 'datagrok-api/grok';
3
3
  import * as ui from 'datagrok-api/ui';
4
4
  import * as DG from 'datagrok-api/dg';
5
5
  import {ModelHandler} from './model-handler';
6
- import {selectOutliersManually} from './outliers-selection';
6
+ import {selectOutliersManually} from './outliers-selection/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
10
  import wu from 'wu';
11
+ import {_functionEditor} from './function-editor/function-editor';
12
+ import {OutliersSelectionViewer} from './outliers-selection/outliers-selection-viewer';
11
13
 
12
14
  let initCompleted: boolean = false;
13
15
  export const _package = new DG.Package();
@@ -45,6 +47,14 @@ export async function manualOutlierSelectionDialog(inputData: DG.DataFrame) {
45
47
  });
46
48
  }
47
49
 
50
+ //name: OutliersSelectionViewer
51
+ //description: Creates an outliers selection viewer
52
+ //tags: viewer
53
+ //output: viewer
54
+ export function OutliersSelection() {
55
+ return new OutliersSelectionViewer();
56
+ }
57
+
48
58
  //name: export To Excel
49
59
  //input: funccall call
50
60
  //tags: export
@@ -52,6 +62,75 @@ export function exportToExcel(call: DG.FuncCall) {
52
62
  exportFuncCall(call);
53
63
  }
54
64
 
65
+ //name: Function Editor
66
+ export function functionEditor() {
67
+ const sampleScript = `
68
+ #name: Chemical Space Using tSNE
69
+ #description: Chemical space using t-distributed Stochastic Neighbor Embedding
70
+ #help-url: https://datagrok.ai/help/domains/chem/functions/tsne
71
+ #language: python
72
+ #sample: chem/smiles_coordinates.csv
73
+ #tags: demo, chem, rdkit
74
+ #input: dataframe t1 {columns:numerical} [first input data table]
75
+ #input: dataframe t2 {columns:numerical} [second input data table]
76
+ #input: column x {type:numerical; table:t1} [x axis column name]
77
+ #input: column y {type:numerical} [y axis column name]
78
+ #input: column date {type:datetime; format:mm/dd/yyyy} [date column name]
79
+ #input: column_list numdata {type:numerical; table:t1} [numerical columns names]
80
+ #input: int numcomp = 2 {range:2-7} [number of components]
81
+ #input: bool center = true [number of components]
82
+ #input: string type = high {choices: ["high", "low"]} [type of filter]
83
+ #output: dataframe result {action:join(t1)} [pca components]
84
+ #output: graphics scatter [scatter plot]
85
+
86
+ import numba
87
+ import hdbscan
88
+ import numpy as np
89
+ import matplotlib.pyplot as plt
90
+ from sklearn.manifold import TSNE
91
+ from rdkit import Chem
92
+ from rdkit.Chem import AllChem
93
+ from rdkit.Chem import Draw
94
+ from rdkit.Chem import DataStructs
95
+
96
+ smiles = data[smiles]
97
+ mols = [Chem.MolFromSmiles(mol) for mol in smiles]
98
+ mols = [mol for mol in mols if mol is not None]
99
+ for mol in mols:
100
+ AllChem.Compute2DCoords(mol)
101
+ X = []
102
+ for mol in mols:
103
+ arr = np.zeros((0,))
104
+ fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2)
105
+ DataStructs.ConvertToNumpyArray(fp, arr)
106
+ X.append(arr)
107
+
108
+ @numba.njit()
109
+ def tanimoto_dist(a, b):
110
+ dotprod = np.dot(a, b)
111
+ tc = dotprod / (np.sum(a) + np.sum(b) - dotprod)
112
+ return 1.0 - tc
113
+
114
+ tsne = TSNE(n_components=components, metric=tanimoto_dist)
115
+ tsne_X = tsne.fit_transform(X)
116
+ cluster_tsne = hdbscan.HDBSCAN(min_cluster_size=minClusterSize, gen_min_span_tree=True)
117
+ cluster_tsne.fit(tsne_X)
118
+
119
+ plt.figure(0)
120
+ cluster_tsne.minimum_spanning_tree_.plot(
121
+ edge_cmap='viridis', edge_alpha=0.6,
122
+ node_size=90, edge_linewidth=2)
123
+
124
+ plt.figure(1)
125
+ cluster_tsne.single_linkage_tree_.plot(cmap='viridis', colorbar=True)
126
+
127
+ plt.figure(2)
128
+ plt.scatter(tsne_X.T[0], tsne_X.T[1], c=cluster_tsne.labels_, cmap='plasma')
129
+ plt.title('Chemical space')
130
+ `;
131
+ _functionEditor(sampleScript);
132
+ }
133
+
55
134
  /* eslint-disable */
56
135
 
57
136
  //description: A spreadsheet that lets you interactively edit parameters and evaluate functions
package/webpack.config.js CHANGED
@@ -11,6 +11,10 @@ module.exports = {
11
11
  module: {
12
12
  rules: [
13
13
  {test: /\.tsx?$/, loader: 'ts-loader'},
14
+ {
15
+ test: /\.css$/,
16
+ use: ['style-loader', 'css-loader'],
17
+ },
14
18
  ],
15
19
  },
16
20
  devtool: 'inline-source-map',
@@ -23,7 +27,7 @@ module.exports = {
23
27
  'rxjs/operators': 'rxjs.operators',
24
28
  'cash-dom': '$',
25
29
  'dayjs': 'dayjs',
26
- 'wu': 'wu'
30
+ 'wu': 'wu',
27
31
  },
28
32
  output: {
29
33
  filename: '[name].js',