@datagrok/compute 0.2.1 → 0.2.5

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/README.md CHANGED
@@ -1,236 +1,13 @@
1
1
  # Compute
2
2
 
3
- A next-generation environment for scientific computing.
4
- It leverages a number of the core Datagrok features, such as
5
- [in-memory data engine](../../help/develop/performance.md#in-memory-database),
6
- [interactive visualizations](../../help/explore/exploratory-data-analysis.md),
7
- [data access](../../help/home.md#access),
8
- [machine learning](../../help/home.md#learn),
9
- and [enterprise features](../../help/home.md#deploy-and-integrate)
10
- to enable developing, publishing, discovering, and using scientific applications:
11
-
12
- 1. [Cross-language support](#cross-language-support)
13
- 2. [Scalable computations](#scalable-computations)
14
- 3. [Web-based UI](#user-interface) that could be [autogenerated](#autogenerated-ui),
15
- [customized](#custom-ui), and [templates]
16
- 4. [One-touch deployment]
17
- 1. [Model versioning]
18
- 5. [Data sources]
19
- 6. [Metadata]
20
- 7. [Integration]: [API], [embedding]
21
- 8. [Logging, audit, and traceability]
22
- 9. [Leveraging the platform]
23
- 1. [Privileges and visibility]
24
- 2. [Usage analysis]
25
- 3. [Exploratory data analysis]
26
- 10. [Roadmap]
27
- 1. [Repository of curated scientific methods]
28
-
29
-
30
- * Composable (an output of one function becomes an input to the other)
31
- * Could be connected to any data source (db, web service, file, etc)
32
- * Logging, audit, traceability
33
- * Privileges and visibility
34
-
35
- `Compute` package:
36
-
37
- * Enables a full lifecycle of models: create, tune, share, use, validate
38
- * Provides for easy to use and highly automated evaluation and computation environment
39
- * Enables contextual process for the Design of Experiment (sensitivity analysis and more)
40
-
41
- In addition, Datagrok platform supports a UI layout markup, so that the model function becomes
42
- a GUI-rich application with no manual coding.
43
-
44
- Project planning board: [link](https://github.com/datagrok-ai/public/projects/8).
45
-
46
- ## Cross-language support
47
-
48
- The basic unit of execution is a [function](https://datagrok.ai/help/overview/functions/function),
49
- which could be written in [any language that Datagrok supports](https://datagrok.ai/help/develop/scripting)
50
- , such as `Python`, `R`,
51
- `Julia`, `Matlab/Octave`, `JavaScript`, and others. No matter which language is used,
52
- each function has the following properties:
53
- * Advanced support for input and output parameters
54
- * Typed (cross-language support for scalars, vectors, dataframes, images)
55
- * Intraspectable
56
- * Metadata-annotated
57
- * Dynamic discovery
58
- * Polymorphic execution (platform doesn't care which language the function is implemented in)
59
- * Function-level [metadata]
60
-
61
- These properties unlock plenty
62
- of interesting features covered below, such as
63
- [scalable computations](#scalable-computations),
64
- [reproducibility],
65
- [automatic UI generation](#autogenerated-ui),
66
- [audit],
67
- [sensitivity analysis],
68
- [optimization], and others.
69
-
70
- ## Scalable computations
71
-
72
- Depending on the underlying language, a function could be executed on the client side,
73
- server side, both, or either.
74
-
75
- `JavaScript` and `C++` (compiled to [WebAssembly](https://webassembly.org/)) could be executed
76
- right in the browser. The upside to that is unmatched responsiveness, data locality, and
77
- computation locality. The downside is that many of the popular statistical and modeling
78
- methods are not currently available in these languages yet. Note that while the computations are
79
- performed locally, the proper audit and traceability still works (both input and output
80
- parameters could be sent to the server for historic reasons).
81
-
82
- `R`, `Python`, `Julia`, `Matlab`, and `Octave` are powerful languages with the mature
83
- ecosystem of scientific libraries, and existing models implemented previously inside the
84
- organization. They could only be executed on a server, and as such
85
- the question of scalable computation arises. Datagrok takes care of that by using the
86
- `message queue` architecture. When each server-based function is invoked, its parameters
87
- are saved to a queue; one of the worker processes then picks a task (such as running a Python
88
- function), executes it, and puts the results back. This architecture guarantees the following:
89
-
90
- * The platform won't get overloaded by trying to execute too many tasks at once
91
- * Scaling is as simple as adding more workers (which could be hosted externally if necessary)
92
- * A queue serves as a basis for [audit] and [traceability]
93
-
94
-
95
- ## One-touch deployment
96
-
97
- ## User interface
98
-
99
- Our goal is not computations for the sake of it, but
100
- rather helping **users** derive actionable insights, and support the decision-making process.
101
- The UI should be as easy to use as possible, tailored to the user needs, and
102
- be specific for the tasks. On the other hand, it should be clean, universal, and easy enough
103
- to be developed by a scientist without a deep understanding of the Datagrok platform.
104
- To satisfy these seemingly contradictory requirements, we developed a hybrid approach to
105
- building the UI, where the model author has full control over choosing how custom the UI
106
- for the speficic model should be. In the most standard case, there is no need to write
107
- a single line of code, as the UI is
108
- [automatically generated](#autogenerated-ui) based on the function signature.
109
- On the other end of the spectrum, you have the possibility to take everything in your own
110
- hands and develop a completely [custom UI](#custom-ui). Anything in between is also possible.
111
-
112
- ### Autogenerated UI
113
-
114
- Very often, a UI for the model is nothing more than the input fields for the
115
- corresponding function's parameters. When this is the case, Datagrok generates the UI automatically
116
- by constructing the corresponding input fields and output area with graphics and results,
117
- and bringing it to life by making it interactive. Additional parameters' metadata, such
118
- as units, category, description, input type (slider/combo box/etc), and others
119
- are also taken into account.
120
-
121
- The following picture demonstrates a working PK/PD model implemented in R
122
- with the autogenerated UI (look at the script header area for details). While it looks
123
- very similar to the traditional Shiny app, the R script does not have to deal with
124
- the UI at all, which not only simplifies the development and maintenance, but also
125
- provides for the uniform experience.
126
-
127
- A visual tool for annotating function parameters is
128
- [currently in the development](#https://github.com/datagrok-ai/public/issues/184).
129
-
130
- ![](help/ui-auto-generation.png)
131
-
132
- Learn more: [function parameters](https://datagrok.ai/help/overview/functions/func-params-enhancement)
133
-
134
- ### Custom UI
135
-
136
- On the other side of the spectrum, if necessary the UI could be developed
137
- from scratch without any limitations, using either vanilla JavaScript,
138
- a framework of your choice such as React, or
139
- [Datagrok UI toolkit](../../help/develop/js-api.md#ui). No matter what
140
- you choose, Datagrok [JS API](https://datagrok.ai/help/develop/develop) could always be used.
141
-
142
- ## One-touch deployment
143
-
144
-
145
-
146
- ## Analytical blocks
147
-
148
- No matter which domain you are working with, which language your program in,
149
- or what type of model you build, quite often you need the same set of tools (including visual tools) to
150
- efficiently work with data. Naturally, it makes sense to implement these algorithms
151
- just once, and then use them everywhere. Here are some examples:
152
-
153
- 1. Imputation of missing values
154
- 2. Outlier detection
155
- 3. Time series analysis
156
- 4. Validators
157
-
158
- The fact that the typical analysis is an introspectable workflow consisting of functions
159
- passing the data helps us deal with that in a declarative manner.
160
-
161
- ## Privileges and visibility
162
-
163
- Datagrok has the built-in [role-based privileges system](https://datagrok.ai/help/govern/authorization)
164
- that is used to define who can see, execute, or edit models.
165
-
166
- ## Roadmap
167
-
168
- 1. **UI markup**
169
-
170
- Annotate function inputs and outputs to produce highly interactive, visually reach GUI:
171
-
172
- * arrange inputs and outputs in blocks and tabs
173
- * add captions, units of measure and other information to inputs and outputs
174
- * automatically produce additional plots with Datagrok
175
- [viewers](https://datagrok.ai/help/visualize/viewers)
176
-
177
- 2. **Input providers**
178
-
179
- Produce inputs to functions in-place as outputs of other functions (aka input providers),
180
- including:
181
-
182
- * queries to databases
183
- * dialog-based functions (outlier detection, data annotation)
184
- * queries to OpenAPI and REST endpoints
185
- * other computing functions with or without GUI
186
-
187
- These may include UI parts as well. The input provider is specified as part of the Universal UI
188
- markup.
189
-
190
- 3. **Persistent, sharable historical runs**
191
-
192
- It is already possible to provide a link to a function (with specified input parameters in
193
- the URI), which will open a function view and run it.
194
-
195
- Once a certain version of a specific function is run with specific inputs, the result should
196
- be stored in the immutable database log along with the inputs. Later it will be used to verify
197
- the grounds for decisions made from these calculations.
198
-
199
- 4. **Sensitivity analysis**
200
-
201
- * Sample inputs:
202
- * by specified number of samples
203
- * by a specified distribution or within a range
204
- * for a specified set of scalar inputs and/or columns of the matrix input
205
- * Produce variability analysis for outputs based on the sampled inputs
206
- * Visualize the results of analysis with Datagrok viewers
207
-
208
- 5. **Modeling input parameters**
209
-
210
- Solve an inversion problem: identify input conditions leading to specified output constraints.
211
-
212
- 6. **Outlier detection and annotation**
213
-
214
- * Automatic outliers detection
215
- * Manual outliers markup and annotation
216
- * Used as an input provider in other functions
217
-
218
- 7. **Model Repository and discoverability**
219
-
220
- 8. **Scaling on demand**
221
-
222
- 9. **Asynchronous computation**
223
-
224
- 10. **Export and reporting**
225
-
226
- 11. **REST endpoints**
227
-
228
- 12. **Data annotation**
229
-
230
- 13. **Test data for functions**
231
-
232
- 14. **Functions versioning**
233
-
234
- 15. **Audit**
235
-
236
- Most of the features are implemented in this package, some of them are part of the platform.
3
+ Provides additional analytical and UI blocks for
4
+ [Datagrok scientific computing](../../help/compute/compute.md)
5
+
6
+ * Model browser
7
+ * Outlier selector tool
8
+ * Universal export tool
9
+ * Step-by-step wizard for onboarding new models
10
+ * Model renderers
11
+ * Function views
12
+ * Function parameter grid
13
+ * A set of examples
package/package.json CHANGED
@@ -1,18 +1,20 @@
1
1
  {
2
2
  "name": "@datagrok/compute",
3
3
  "friendlyName": "Compute",
4
- "version": "0.2.1",
4
+ "version": "0.2.5",
5
5
  "description": "",
6
6
  "dependencies": {
7
7
  "cash-dom": "latest",
8
- "datagrok-api": "../../js-api",
8
+ "datagrok-api": ">=0.95.8",
9
9
  "dayjs": "latest",
10
10
  "exceljs": "^4.3.0",
11
11
  "file-saver": "^2.0.5",
12
12
  "ts-loader": "latest",
13
- "typescript": "latest"
13
+ "typescript": "latest",
14
+ "wu": "latest"
14
15
  },
15
16
  "devDependencies": {
17
+ "@types/wu": "latest",
16
18
  "@types/file-saver": "^2.0.3",
17
19
  "@typescript-eslint/eslint-plugin": "^5.1.0",
18
20
  "@typescript-eslint/parser": "^5.1.0",
@@ -22,12 +24,13 @@
22
24
  "webpack-cli": "latest"
23
25
  },
24
26
  "scripts": {
25
- "debug-compute": "webpack & grok publish",
27
+ "link-api": "npm link datagrok-api",
28
+ "debug-compute": "webpack & grok publish dev --release",
26
29
  "release-compute": "grok publish --rebuild --release",
27
30
  "build-compute": "webpack",
28
31
  "build": "webpack",
29
- "debug-compute-dev": "grok publish dev --rebuild",
30
- "release-compute-dev": "grok publish dev --rebuild --release",
32
+ "debug-compute-dev": "webpack && grok publish dev --rebuild",
33
+ "release-compute-dev": "grok publish dev --release",
31
34
  "debug-compute-local": "grok publish local --rebuild",
32
35
  "release-compute-local": "grok publish local --rebuild --release",
33
36
  "debug-compute-localhost": "grok publish localhost --rebuild",
@@ -1,6 +1,8 @@
1
1
  #name: Fab Arm Exchange
2
2
  #language: python
3
- #tags: model
3
+ #tags: model, simulation
4
+ #meta.modality: Antibody
5
+ #meta.domain: Manufacturing
4
6
  #input: double meaConcentration = 60 {category:FAE Reaction Parameters; units:mM; caption:2-MEA Concentration} [2-MEA Concentration]
5
7
  #input: double phOfFaeReaction = 7.5 {category:FAE Reaction Parameters; caption:pH of FAE Reaction} [pH of FAE Reaction]
6
8
  #input: double faeReactionTime = 3 {category:FAE Reaction Parameters; units:hr; caption:FAE Reaction Time} [FAE Reaction Time]
@@ -1,12 +1,14 @@
1
1
  //name: Heat Exchange
2
2
  //language: javascript
3
- //tags: model
3
+ //tags: model, simulation
4
+ //meta.modality: Small molecule
4
5
  //input: int len = 1000
5
6
  //input: double k = 1.2
6
7
  //output: dataframe simulation {viewer: Line Chart(multiAxis: "true")}
7
8
  //output: double finalTemperature
8
9
  //output: double finalSaturation
9
10
  //output: double finalConcentration
11
+ //meta.domain: Manufacturing
10
12
 
11
13
  function sigmoid(z) {
12
14
  return 1 / (1 + Math.exp(-z));
@@ -0,0 +1,24 @@
1
+ #name: IntervalsFromECG
2
+ #description: Identify the beats in an ECG signal and compute the IBIs
3
+ #language: python
4
+ #tags: model
5
+ #input: double samplingFrequency = 2048
6
+ #input: int bpmMax = 120 [Maximal expected heart rate (in beats per minute): (1 < bpm_max <= 400)]
7
+ #input: double delta = 0 [Threshold for the peak detection. By default it is computed from the signal (adaptive thresholding)]
8
+ #input: double k = 0.7 [Ratio at which the signal range is multiplied (when delta = 0), (0 < k < 1)]
9
+ #output: graphics Intervals
10
+
11
+ import pyphysio as ph
12
+ import matplotlib.pyplot as plt
13
+ from pyphysio.tests import TestData
14
+
15
+ ecg_data = TestData.ecg()
16
+
17
+ ecg = ph.EvenlySignal(values=ecg_data, sampling_freq=samplingFrequency, signal_type = 'ecg')
18
+
19
+ extracted = ph.BeatFromECG(bpm_max=bpmMax, delta=delta, k=k)(ecg)
20
+
21
+ Intervals = plt.plot(extracted)
22
+ plt.title('RR intervals')
23
+ plt.xlabel('Interval index')
24
+ plt.ylabel('Seconds')
@@ -1,5 +1,5 @@
1
- //name: Logistic map
2
- //tags: model, NonlinearDynamics
1
+ //name: Logistic Map
2
+ //tags: model, simulation
3
3
  //description: Archetypal example of how complex, chaotic behaviour can arise from very simple non-linear dynamical equations.
4
4
  //language: javascript
5
5
  //input: int iterations = 1000 [Number of iterations per point]
@@ -7,6 +7,7 @@
7
7
  //input: double spacing = 0.001 [Spacing between points on domain (r-axis)]
8
8
  //input: double res = 8 [Largest n-cycle visible]
9
9
  //output: dataframe df {viewer: Scatter plot(title: "Logistic map")}
10
+ //meta.domain: Nonlinear dynamics
10
11
 
11
12
  function getRandomNumberInRange(min, max) {
12
13
  return Math.random() * (max - min) + min;
@@ -1,5 +1,6 @@
1
- //name: Lorenz attractor
2
- //tags: model, NonlinearDynamics
1
+ //name: Lorenz Attractor
2
+ //tags: model, simulation
3
+ //meta.domain: Nonlinear dynamics
3
4
  //description: Set of chaotic solutions of the system for weather prediction. It illustrates the phenomenon known as the Butterfly effect or (more technically) sensitive dependence on initial conditions
4
5
  //language: javascript
5
6
  //input: int iterations = 1000
@@ -1,5 +1,6 @@
1
- //name: Lotka-Volterra Model
2
- //tags: model, NonlinearDynamics
1
+ //name: Lotka-Volterra
2
+ //tags: model, simulation
3
+ //meta.domain: Nonlinear dynamics
3
4
  //description: Model describes the dynamics of biological systems in which two species interact, one as a predator and the other as prey.
4
5
  //language: javascript
5
6
  //input: double x0 = 0.5 [Initial conditions for prey population]
@@ -1,11 +1,13 @@
1
- #name: Maximal Volume
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
2
3
  #language: r
3
4
  #tags: model
4
5
  #input: dataframe test_data {editor: Compute:manualOutlierSelectionDialog; editor-button: Outliers...}
5
- #input: double test_area = 2.5 {caption: Filter Area; units: cm²} [Filter area]
6
- #input: double test_pressure = 21 {caption: Pressure; units: psi} [Pressure]
7
- #input: double vbatch = 11 {caption: VBatch; units: L} [Desired batch size to process]
8
- #input: double tbatch = 0.8 {caption: TBatch; units: hr} [Desired process time]
6
+ #input: double test_area = 3.5 {caption: Filter Area; units: cm²} [Filter area]
7
+ #input: double vbatch = 25 {caption: VBatch; units: L} [Desired batch size to process]
8
+ #input: double tbatch = 0.5 {caption: TBatch; units: hr} [Desired process time]
9
+ #input: double sf = 1.5 {caption: Safety Factor} [Safety Factor]
10
+ #output: dataframe processedData {viewer: Scatter Plot(x: "time (hr)", y: "t/V (hr/(L/m2))", showRegressionLine: "true"); category: Raw Plot}
9
11
  #output: double vmax { category: Lin Reg Param }
10
12
  #output: double q0 { category: Lin Reg Param }
11
13
  #output: double slope_est { category: Lin Reg Param }
@@ -19,19 +21,33 @@
19
21
  #output: double resid_ss { category: Lin Reg Param }
20
22
  #output: double expl_ss { category: Lin Reg Param }
21
23
  #output: double ss_tot { category: Lin Reg Param }
22
- #output: double amin { category: Min Filter Area }
24
+ #output: double amin { category: Recommendation }
23
25
 
24
- vmax <- 3
25
- q0 <- 6
26
- slope_est <- vbatch / test_area
27
- slope_err <- 3
28
- icept_est <- slope_err / test_area
29
- icept_err <- 2
30
- rsq <- 2
31
- f_stat <- test_pressure * test_area
32
- df <- 5
33
- sigma <- 4
34
- resid_ss <- 2
35
- expl_ss <- 7
36
- ss_tot <- 5
37
- amin <- vbatch / tbatch
26
+ a <- as.data.frame(test_data)
27
+ a <- a[!a$isOutlier=='true',]
28
+ processedData <- a
29
+ processedData$time..min. <- processedData$time..min. / 60
30
+ names(processedData)[names(processedData) == "time..min."] <- "time (hr)"
31
+ processedData$filtrate.volume..mL. <- (processedData$filtrate.volume..mL./1000)/(test_area/10000)
32
+ names(processedData)[names(processedData) == "filtrate.volume..mL."] <- "V (L/m2)"
33
+ processedData["t/V (hr/(L/m2))"] <- processedData$`time (hr)` / processedData$`V (L/m2)`
34
+
35
+ lin_mod <- lm(`t/V (hr/(L/m2))` ~ `time (hr)`, data=processedData)
36
+ lin_mod_sum <- summary(lin_mod)
37
+ coeff <- lin_mod_sum$coefficients
38
+ slope_est <- coeff["`time (hr)`", "Estimate"]
39
+ slope_err <- coeff["`time (hr)`", "Std. Error"]
40
+ icept_est <- coeff["(Intercept)", "Estimate"]
41
+ icept_err <- coeff["(Intercept)", "Std. Error"]
42
+ rsq <- lin_mod_sum$r.squared
43
+ ad_rsq <- lin_mod_sum$adj.r.squared
44
+ f_stat <- lin_mod_sum$fstatistic[1]
45
+ df <- lin_mod_sum$df[2]
46
+ sigma <- lin_mod_sum$sigma
47
+ resid_ss <- sum(lin_mod_sum$residuals^2)
48
+ expl_ss <- sum((fitted(lin_mod) - mean(processedData$`t/V (hr/(L/m2))`))^2)
49
+ vmax <- round(1 / slope_est)
50
+ q0 <- round(1 / icept_est)
51
+ amin <- (vbatch / vmax) + (vbatch / tbatch / q0)
52
+ amin <- round(amin, digits = 1)
53
+ ss_tot <- resid_ss + expl_ss
@@ -0,0 +1,163 @@
1
+ //name: PmaxScript
2
+ //description: pMax Filtration Model
3
+ //language: javascript
4
+ //tags: model
5
+ //input: dataframe inputTable [Should contain columns Time (min), Vol (mL), P1 (psi), P2 (psi)]
6
+ //input: double batchVolume = 100 {units: L} [Batch Volume]
7
+ //input: double batchTime = 2 {units: hours} [Batch Time]
8
+ //input: double targetPressure = 20 {units: psi} [Target Pressure]
9
+ //input: double aMinFilter1Guessed = 0.153 {units: m²; caption:Amin Filter 1 guessed} [Amin Filter 1 guessed]
10
+ //input: double aMinFilter2Guessed = 0.153 {units: m²; caption:Amin Filter 2 guessed} [Amin Filter 2 guessed]
11
+ //input: double filterArea1 = 23 {units: m²} [Filter Area 1]
12
+ //input: double filterArea2 = 23 {units: m²} [Filter Area 2]
13
+ //input: double sf1 = 1.5 {caption: SF1}
14
+ //input: double sf2 = 1.5 {caption: SF2}
15
+ //input: int orderOfPolynomialRegression = 3 {caption: Order Of Polynomial Regression} [Order Of Polynomial Regression]
16
+ //output: dataframe Filter1 {viewer: Scatter Plot(x: "TP 1 (L/m2)", y: "Res. 1 (psi/LMH)", showRegressionLine: "true"); category: PRIMARY FILTER}
17
+ //output: dataframe Filter2 {viewer: Scatter Plot(x: "TP 2 (L/m2)", y: "Res. 2 (psi/LMH)", showRegressionLine: "true"); category: SECONDARY FILTER}
18
+ //output: double amin1 {units: m²; caption: Amin; category: PRIMARY FILTER}
19
+ //output: double amin2 {units: m²; caption: Amin; category: SECONDARY FILTER}
20
+ //output: double aminSF1 {units: m²; caption: Amin SF; category: PRIMARY FILTER}
21
+ //output: double aminSF2 {units: m²; caption: Amin SF; category: SECONDARY FILTER}
22
+ //output: double trialLoading1 {units: L/m²; caption: Trial Loading; category: PRIMARY FILTER}
23
+ //output: double trialLoading2 {units: L/m²; caption: Trial Loading; category: SECONDARY FILTER}
24
+ //output: double processLoading1 {units: L/m²; caption: Process Loading; category: PRIMARY FILTER}
25
+ //output: double processLoading2 {units: L/m²; caption: Process Loading; category: SECONDARY FILTER}
26
+ //output: double maxP1 {units: psi; caption: Max P; category: PRIMARY FILTER}
27
+ //output: double maxP2 {units: psi; caption: Max P; category: SECONDARY FILTER}
28
+ //output: double trialFlux1 {units: LMH; caption: Trial Flux; category: PRIMARY FILTER}
29
+ //output: double trialFlux2 {units: LMH; caption: Trial Flux; category: SECONDARY FILTER}
30
+ //output: double processFlux1 {units: LMH; caption: Process Flux; category: PRIMARY FILTER}
31
+ //output: double processFlux2 {units: LMH; caption: Process Flux; category: SECONDARY FILTER}
32
+ //output: double processFlow1 {units: L/hr; caption: Process Flow; category: PRIMARY FILTER}
33
+ //output: double processFlow2 {units: L/hr; caption: Process Flow; category: SECONDARY FILTER}
34
+ //output: double guessedAmin1 {units: m²; caption: Guessed Amin; category: PRIMARY FILTER}
35
+ //output: double guessedAmin2 {units: m²; caption: Guessed Amin; category: SECONDARY FILTER}
36
+ //output: double guessedProcessLoading1 {units: L/m²; caption: Guessed Process Loading; category: PRIMARY FILTER}
37
+ //output: double guessedProcessLoading2 {units: L/m²; caption: Guessed Process Loading; category: SECONDARY FILTER}
38
+ //output: double guessedMaxP1 {units: psi; caption: Guessed Max P; category: PRIMARY FILTER}
39
+ //output: double guessedMaxP2 {units: psi; caption: Guessed Max P; category: SECONDARY FILTER}
40
+ //output: double guessedProcessFlux1 {units: LMH; caption: Guessed Process Flux; category: PRIMARY FILTER}
41
+ //output: double guessedProcessFlux2 {units: LMH; caption: Guessed Process Flux; category: SECONDARY FILTER}
42
+
43
+ function gaussianElimination(input, orderOfPolynomialRegression) {
44
+ const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
45
+ for (let i = 0; i < n; i++) {
46
+ let maxrow = i;
47
+ for (let j = i + 1; j < n; j++)
48
+ if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow]))
49
+ maxrow = j;
50
+ for (let k = i; k < n + 1; k++) {
51
+ const tmp = input[k][i];
52
+ input[k][i] = input[k][maxrow];
53
+ input[k][maxrow] = tmp;
54
+ }
55
+ for (let j = i + 1; j < n; j++)
56
+ for (let k = n; k >= i; k--)
57
+ input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
58
+ }
59
+ for (let j = n - 1; j >= 0; j--) {
60
+ let total = 0;
61
+ for (let k = j + 1; k < n; k++)
62
+ total += input[k][j] * coefficients[k];
63
+ coefficients[j] = (input[n][j] - total) / input[j][j];
64
+ }
65
+ return coefficients;
66
+ }
67
+
68
+ function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression) {
69
+ const lhs = [], rhs = [], len = xCol.length, k = orderOfPolynomialRegression + 1;
70
+ let a = 0, b = 0;
71
+ for (let i = 0; i < k; i++) {
72
+ for (let l = 0; l < len; l++)
73
+ a += (xCol.get(l) ** i) * yCol.get(l);
74
+ lhs.push(a);
75
+ a = 0;
76
+ const c = [];
77
+ for (let j = 0; j < k; j++) {
78
+ for (let l = 0; l < len; l++)
79
+ b += xCol.get(l) ** (i + j);
80
+ c.push(b);
81
+ b = 0;
82
+ }
83
+ rhs.push(c);
84
+ }
85
+ rhs.push(lhs);
86
+ return gaussianElimination(rhs, k);
87
+ }
88
+
89
+ function predictPolynomialRegression(coefficients, x) {
90
+ let result = coefficients[0];
91
+ for (let i = coefficients.length - 1; i > 0; i--)
92
+ result += coefficients[i] * Math.pow(x, i);
93
+ return result;
94
+ }
95
+
96
+ const lengthOfSecondTable = 2985;
97
+ const colNames1 = {
98
+ 'time': 'Time (min)',
99
+ 'volume': 'Vol (mL)',
100
+ 'pressure1': 'P1 (psi)',
101
+ 'pressure2': 'P2 (psi)',
102
+ 'tp1': 'TP 1 (L/m2)', 'flux1': 'Flux 1 (LMH)', 'res1': 'Res. 1 (psi/LMH)',
103
+ 'tp2': 'TP 2 (L/m2)', 'flux2': 'Flux 2 (LMH)', 'res2': 'Res. 2 (psi/LMH)',
104
+ 'deltaP': 'Delta P (psi)'
105
+ };
106
+ const colNames2 = {
107
+ 'area': 'Guess Area (m2)',
108
+ 'javg': 'Javg (LMH)',
109
+ 'R': 'R calc (psi/LMH)',
110
+ 'Y1': 'Y1', 'd1': 'Delta1',
111
+ 'Y2': 'Y2', 'd2': 'Delta2'
112
+ };
113
+
114
+ const t = inputTable.col(colNames1['time']);
115
+ const v = inputTable.col(colNames1['volume']);
116
+ const p1 = inputTable.col(colNames1['pressure1']);
117
+ const p2 = inputTable.col(colNames1['pressure2']);
118
+ const df1 = DG.DataFrame.fromColumns([t, v, p1, p2]);
119
+ df1.columns.addNewFloat(colNames1['tp1']).init((i) => (i > 0) ? 10 * v.get(i) / filterArea1 : 0);
120
+ df1.columns.addNewFloat(colNames1['tp2']).init((i) => (i > 0) ? 10 * v.get(i) / filterArea2 : 0);
121
+ df1.columns.addNewFloat(colNames1['flux1']).init((i) => (i > 0) ? 600 * (v.get(i) - v.get(i-1)) / (t.get(i) - t.get(i-1)) / filterArea1 : 0);
122
+ df1.columns.addNewFloat(colNames1['flux2']).init((i) => (i > 0) ? 600 * (v.get(i) - v.get(i-1)) / (t.get(i) - t.get(i-1)) / filterArea2 : 0);
123
+ df1.columns.addNewFloat(colNames1['deltaP']).init((i) => p1.get(i) - p2.get(i));
124
+ const deltaP = df1.col(colNames1['deltaP']), flux1 = df1.col(colNames1['flux1']), flux2 = df1.col(colNames1['flux2']);
125
+ df1.columns.addNewFloat(colNames1['res1']).init((i) => (i > 0) ? deltaP.get(i) / flux1.get(i) : 0);
126
+ df1.columns.addNewFloat(colNames1['res2']).init((i) => (i > 0) ? p2.get(i) / flux2.get(i) : 0);
127
+ Filter1 = DG.DataFrame.fromColumns([df1.col(colNames1['tp1']), df1.col(colNames1['res1'])]);
128
+ Filter2 = DG.DataFrame.fromColumns([df1.col(colNames1['tp2']), df1.col(colNames1['res2'])]);
129
+ const coefficients1 = polynomialRegressionCoefficients(df1.col(colNames1['tp1']), df1.col(colNames1['res1']), orderOfPolynomialRegression);
130
+ const coefficients2 = polynomialRegressionCoefficients(df1.col(colNames1['tp2']), df1.col(colNames1['res2']), orderOfPolynomialRegression);
131
+
132
+
133
+ const df2 = DG.DataFrame.create(lengthOfSecondTable);
134
+ df2.columns.addNewFloat(colNames2['area']).init((i) => (i > 0) ? batchVolume / i : 0);
135
+ const area = df2.col(colNames2['area']);
136
+ df2.columns.addNewFloat(colNames2['javg']).init((i) => (i > 0) ? batchVolume / area.get(i) / batchTime : 0);
137
+ const javg = df2.col(colNames2['javg']);
138
+ df2.columns.addNewFloat(colNames2['R']).init((i) => (i > 0) ? targetPressure / javg.get(i) : 0);
139
+ df2.columns.addNewFloat(colNames2['Y1']).init((i) => predictPolynomialRegression(coefficients1, i));
140
+ df2.columns.addNewFloat(colNames2['Y2']).init((i) => predictPolynomialRegression(coefficients2, i));
141
+ const rCalc = df2.col(colNames2['R']), y1 = df2.col(colNames2['Y1']), y2 = df2.col(colNames2['Y2']);
142
+ df2.columns.addNewFloat(colNames2['d1']).init((i) => Math.abs(rCalc.get(i) - y1.get(i)));
143
+ df2.columns.addNewFloat(colNames2['d2']).init((i) => Math.abs(rCalc.get(i) - y2.get(i)));
144
+
145
+
146
+ amin1 = df2.col(colNames2['area']).get(df2.col(colNames2['d1']).toList().indexOf(df2.col(colNames2['d1']).min));
147
+ amin2 = df2.col(colNames2['area']).get(df2.col(colNames2['d2']).toList().indexOf(df2.col(colNames2['d2']).min));
148
+ processFlow1 = batchVolume / batchTime, processFlow2 = batchVolume / batchTime;
149
+ processFlux1 = processFlow1 / amin1, processFlux2 = processFlow2 / amin2;
150
+ trialFlux1 = 600 * v.max / t.max / filterArea1, trialFlux2 = 600 * v.max / t.max / filterArea2;
151
+ aminSF1 = sf1 * amin1, aminSF2 = sf2 * amin2;
152
+ trialLoading1 = df1.col(colNames1['tp1']).max, trialLoading2 = df1.col(colNames1['tp2']).max;
153
+ processLoading1 = batchVolume / amin1, processLoading2 = batchVolume / amin2;
154
+ maxP1 = predictPolynomialRegression(coefficients1, processLoading1) * processFlux1;
155
+ maxP2 = predictPolynomialRegression(coefficients2, processLoading2) * processFlux2;
156
+
157
+
158
+ guessedAmin1 = aMinFilter1Guessed, guessedAmin2 = aMinFilter2Guessed;
159
+ guessedProcessLoading1 = batchVolume / aMinFilter1Guessed, guessedProcessLoading2 = batchVolume / aMinFilter2Guessed;
160
+ guessedMaxP1 = predictPolynomialRegression(coefficients1, processLoading1) * processFlux1;
161
+ guessedMaxP2 = predictPolynomialRegression(coefficients2, processLoading2) * processFlux2;
162
+ guessedProcessFlux1 = processFlow1 / aMinFilter1Guessed, guessedProcessFlux2 = processFlow2 / aMinFilter2Guessed;
163
+
package/scripts/pkpd.R CHANGED
@@ -13,6 +13,7 @@
13
13
  #output: graphics PKPD
14
14
  #output: double Cmax {units: nM}
15
15
  #tags: model
16
+ #meta.domain: PKPD
16
17
 
17
18
  require("ggplot2")
18
19
  require("RxODE")
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,115 @@
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://datagrok.ai/help/access/parameterized-queries
13
+ //output: dataframe regressionTable {viewer: Scatter Plot(x: "time (min)", y: "filtrate volume (mL)", filter: "!${isOutlier}", showFilteredOutPoints: "true", color: "isOutlier", showRegressionLine: "true"); category: OUTPUT}
14
+ //output: dataframe absoluteFluxDecay {viewer: Scatter Plot(x: "V/A (L/m2)", y: "J (LMH)", showRegressionLine: "true"); category: OUTPUT}
15
+ //output: dataframe normalizedFluxDecay {viewer: Scatter Plot(x: "V/A (L/m2)", y: "J/Jo", showRegressionLine: "true"); category: OUTPUT}
16
+ //output: double volume {caption: Volume, L; category: OUTPUT}
17
+
18
+ volume = vbatch;
19
+ function gaussianElimination(input, orderOfPolynomialRegression) {
20
+ const n = input.length - 1, coefficients = [orderOfPolynomialRegression];
21
+ for (let i = 0; i < n; i++) {
22
+ let maxrow = i;
23
+ for (let j = i + 1; j < n; j++)
24
+ if (Math.abs(input[i][j]) > Math.abs(input[i][maxrow]))
25
+ maxrow = j;
26
+ for (let k = i; k < n + 1; k++) {
27
+ const tmp = input[k][i];
28
+ input[k][i] = input[k][maxrow];
29
+ input[k][maxrow] = tmp;
30
+ }
31
+ for (let j = i + 1; j < n; j++)
32
+ for (let k = n; k >= i; k--)
33
+ input[k][j] -= (input[k][i] * input[i][j]) / input[i][i];
34
+ }
35
+ for (let j = n - 1; j >= 0; j--) {
36
+ let total = 0;
37
+ for (let k = j + 1; k < n; k++)
38
+ total += input[k][j] * coefficients[k];
39
+ coefficients[j] = (input[n][j] - total) / input[j][j];
40
+ }
41
+ return coefficients;
42
+ }
43
+
44
+ function polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression) {
45
+ const lhs = [], rhs = [], len = xCol.length, k = orderOfPolynomialRegression + 1;
46
+ let a = 0, b = 0;
47
+ for (let i = 0; i < k; i++) {
48
+ for (let l = 0; l < len; l++)
49
+ a += (xCol.get(l) ** i) * yCol.get(l);
50
+ lhs.push(a);
51
+ a = 0;
52
+ const c = [];
53
+ for (let j = 0; j < k; j++) {
54
+ for (let l = 0; l < len; l++)
55
+ b += xCol.get(l) ** (i + j);
56
+ c.push(b);
57
+ b = 0;
58
+ }
59
+ rhs.push(c);
60
+ }
61
+ rhs.push(lhs);
62
+ return gaussianElimination(rhs, k);
63
+ }
64
+
65
+ const area = 0.00035;
66
+ const isOutlierCol = inputTable.col("isOutlier");
67
+ let timeMin = [];
68
+ let vol = [];
69
+ for (let i = 0; i < isOutlierCol.length; i++) {
70
+ if (isOutlierCol.get(i) == false) {
71
+ timeMin.push(inputTable.col("time (min)").get(i));
72
+ vol.push(inputTable.col("filtrate volume (mL)").get(i));
73
+ }
74
+ }
75
+ dfWithoutOutliers = DG.DataFrame.fromColumns([
76
+ DG.Column.fromList('double', "time (min)", timeMin),
77
+ DG.Column.fromList('double', "filtrate volume (mL)", vol)
78
+ ]);
79
+ const timeInMinutes = dfWithoutOutliers.col("time (min)");
80
+ const volumeInMilliliters = dfWithoutOutliers.col("filtrate volume (mL)");
81
+ dfWithoutOutliers.columns.addNewFloat('time (hr)').init((i) => timeInMinutes.get(i) / 60);
82
+ const timeInHours = dfWithoutOutliers.col("time (hr)");
83
+
84
+ dfWithoutOutliers.columns.addNewFloat('V (L/m2)').init((i) => 10 * volumeInMilliliters.get(i) / testArea);
85
+ const newVolume = dfWithoutOutliers.col('V (L/m2)');
86
+
87
+ dfWithoutOutliers.columns.addNewFloat("t/V (hr/(L/m2))").init((i) => timeInHours.get(i) / newVolume.get(i));
88
+
89
+ dfWithoutOutliers.columns.addNewFloat("Time (s)").init((i) => 60 * timeInMinutes.get(i));
90
+ dfWithoutOutliers.columns.addNewFloat("V (L)").init((i) => volumeInMilliliters.get(i) / 1000);
91
+ const volumeInLiters = dfWithoutOutliers.col('V (L)');
92
+ const timeInSeconds = dfWithoutOutliers.col('Time (s)');
93
+ dfWithoutOutliers.columns.addNewFloat('V/A (L/m2)').init((i) => volumeInLiters.get(i) / area);
94
+ const va = dfWithoutOutliers.col('V/A (L/m2)');
95
+ let ca = [];
96
+ let cb = [];
97
+ for (let i = 1; i < va.length - 3; i++) {
98
+ let xCol = DG.Column.fromList('double', 'name', timeInSeconds.toList().slice(i, i + 3));
99
+ let yCol = DG.Column.fromList('double', 'name', va.toList().slice(i, i + 3));
100
+ let coefficients = polynomialRegressionCoefficients(xCol, yCol, orderOfPolynomialRegression);
101
+ ca.push(coefficients[orderOfPolynomialRegression]);
102
+ cb.push(coefficients[orderOfPolynomialRegression - 1]);
103
+ }
104
+
105
+ dfWithoutOutliers.columns.addNewFloat('a2').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
106
+ dfWithoutOutliers.columns.addNewFloat('a1').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
107
+ dfWithoutOutliers.columns.addNewFloat('J (LMH)').init((i) => (i > 0) ? 3600 * (2 * ca[i] * timeInSeconds.get(i) + cb[i]) : 0);
108
+ const j = dfWithoutOutliers.col('J (LMH)');
109
+ dfWithoutOutliers.columns.addNewFloat('J/Jo').init((i) => (i > 0) ? j.get(i) / (3600 * area) : 0);
110
+ const jj0 = dfWithoutOutliers.col('J/Jo');
111
+ absoluteFluxDecay = DG.DataFrame.fromColumns([va, j]);
112
+ normalizedFluxDecay = DG.DataFrame.fromColumns([va, jj0]);
113
+
114
+ regressionTable = inputTable;
115
+ // coefficients = polynomialRegressionCoefficients(inputTable.col("time (hr)"), dfWithoutOutliers.col("t/V (hr/(L/m2))"), 1);
@@ -36,29 +36,59 @@ export async function exportFuncCall(call: DG.FuncCall) {
36
36
  inputScalarsSheet.addRow([scalarInput.name, call.inputs[scalarInput.name]]);
37
37
  });
38
38
 
39
- for await (const dfOutput of dfOutputs) {
39
+ dfOutputs.forEach((dfOutput) => {
40
40
  const currentDfSheet = exportWorkbook.addWorksheet(`Output - ${dfOutput.name}`);
41
41
  const currentDf = (call.outputs[dfOutput.name] as DG.DataFrame);
42
42
  currentDfSheet.addRow((currentDf.columns as DG.ColumnList).names());
43
43
  for (let i = 0; i < currentDf.rowCount; i++) {
44
44
  currentDfSheet.addRow([...currentDf.row(i).cells].map((cell: DG.Cell) => cell.value));
45
45
  }
46
+ });
46
47
 
47
- // TODO: change to API call when it will be available. Currently, it does not work if the plot is not visible.
48
- // In addition, it does not track the scatterplot's source dataframe
49
- const plot = document.getElementsByName('viewer-Scatter-plot')[0];
50
-
51
- const canvas = await DG.HtmlUtils.renderToCanvas(plot);
52
- const dataUrl = canvas.toDataURL('image/png');
53
- const testImageId = exportWorkbook.addImage({
54
- base64: dataUrl,
55
- extension: 'png',
56
- });
57
- currentDfSheet.addImage(testImageId, {
58
- tl: {col: (currentDf.columns as DG.ColumnList).length + 1, row: 0},
59
- ext: {width: canvas.width, height: canvas.height},
60
- });
61
- };
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) continue;
67
+
68
+ const canvas = await DG.HtmlUtils.renderToCanvas(plot as HTMLElement);
69
+ const dataUrl = canvas.toDataURL('image/png');
70
+ const testImageId = exportWorkbook.addImage({
71
+ base64: dataUrl,
72
+ extension: 'png',
73
+ });
74
+ const worksheet = exportWorkbook.getWorksheet(`Output - ${title}`);
75
+
76
+ if (worksheet) {
77
+ const columnForImage = ((call.outputs[title] as DG.DataFrame).columns as DG.ColumnList).length + 1;
78
+ worksheet.addImage(testImageId, {
79
+ tl: {col: columnForImage, row: 0},
80
+ ext: {width: canvas.width, height: canvas.height},
81
+ });
82
+ } else {
83
+ const newWorksheet = exportWorkbook.addWorksheet(`Output - Plot - ${title}`);
84
+ newWorksheet.addImage(testImageId, {
85
+ tl: {col: 0, row: 0},
86
+ ext: {width: canvas.width, height: canvas.height},
87
+ });
88
+ }
89
+ }
90
+ }
91
+ (selectedByUser as HTMLElement).click();
62
92
 
63
93
  const outputScalarsSheet = exportWorkbook.addWorksheet('Output scalars');
64
94
  scalarOutputs.forEach((scalarOutput) => {
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,17 +19,23 @@ 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) {
@@ -46,27 +53,30 @@ export class ModelHandler extends DG.ObjectHandler {
46
53
  }
47
54
 
48
55
  renderDetails(x: DG.Script) {
49
- return ui.tableFromMap({'Created': x.createdOn, 'By': x.author});
56
+ return ui.divV([ui.render(x.author), ui.render(x.createdOn)], {style: {lineHeight: '150%'}});
50
57
  }
51
58
 
52
59
  renderTooltip(x: DG.Script) {
53
- return ui.divText(`${x.name} is in the air!`);
60
+ return ui.divText(`${x.friendlyName}`);
54
61
  }
55
62
 
56
63
  renderCard(x: DG.Script, context?: any): HTMLElement {
57
64
  let card = ui.bind(x, ui.divV([
58
- ui.h2(x.friendlyName),
65
+ ui.h2(this.renderMarkup(x)),
66
+ ui.divText(x.description, 'ui-description'),
59
67
  this.renderDetails(x),
60
68
  ], 'd4-gallery-item'), {contextMenu: false});
61
69
  card.ondblclick = (e) => {
62
- let view = DG.FunctionView.createFromFunc(x);
63
- if (grok.shell.v.parentCall.func.name == 'modelCatalog')
64
- view.parentCall = grok.shell.v.parentCall;
65
- grok.shell.addView(view);
70
+ ModelHandler.openModel(x);
66
71
  }
67
72
  return card;
68
73
  }
69
74
 
75
+ static openModel(x: DG.Script, parentView?: DG.ViewBase) {
76
+ let view = DG.FunctionView.createFromFunc(x);
77
+ grok.shell.addView(view);
78
+ }
79
+
70
80
  init() {
71
81
  this.registerParamFunc('Open', async (t: DG.Script) => {
72
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, {
package/src/package.ts CHANGED
@@ -7,6 +7,7 @@ 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
 
11
12
  let initCompleted: boolean = false;
12
13
  export const _package = new DG.Package();
@@ -16,30 +17,6 @@ export function test() {
16
17
  grok.shell.info(_package.webRoot);
17
18
  }
18
19
 
19
- //tags: init, autostart
20
- export function init() {
21
- if (initCompleted)
22
- return;
23
- DG.ObjectHandler.register(new ModelHandler());
24
- grok.events.onAccordionConstructed.subscribe((acc: DG.Accordion) => {
25
- const ent = acc.context;
26
- if (ent == null)
27
- return;
28
- if (ent.type != 'script')
29
- return;
30
- let restPane = acc.getPane('REST');
31
- if (!restPane)
32
- acc.addPane('REST', () => ui.wait(async () => (await renderRestPanel(ent)).root));
33
- });
34
- initCompleted = true;
35
- }
36
-
37
- //name: Model Catalog
38
- //tags: app
39
- export function modelCatalog() {
40
- grok.shell.addView(new ModelCatalogView());
41
- }
42
-
43
20
  //name: manualOutlierDetectionDialog
44
21
  //input: dataframe inputData
45
22
  //output: dataframe augmentedInput
@@ -48,7 +25,7 @@ export async function manualOutlierSelectionDialog(inputData: DG.DataFrame) {
48
25
  const call = grok.functions.getCurrentCall();
49
26
 
50
27
  const IS_OUTLIER_COL_LABEL = 'isOutlier';
51
- const OUTLIER_REASON_COL_LABEL = 'Reason';
28
+ const OUTLIER_REASON_COL_LABEL = 'Rationale';
52
29
 
53
30
  if (call.options['interactive']) {
54
31
  const {augmentedInput, editedInput} = await selectOutliersManually(inputData);
@@ -130,4 +107,72 @@ function getCookie(name: string): string | undefined{
130
107
  "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
131
108
  ));
132
109
  return matches ? decodeURIComponent(matches[1]) : undefined;
133
- }
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
@@ -1,8 +0,0 @@
1
- #name: High-titer field
2
- #language: python
3
- #input: double a
4
- #input: double b
5
- #output: double c
6
- #tags: model
7
-
8
- c = a / b
package/scripts/pMax.py DELETED
@@ -1,8 +0,0 @@
1
- #name: pMax
2
- #language: python
3
- #input: double a
4
- #input: double b
5
- #output: double c
6
- #tags: model
7
-
8
- c = a / b