@datagrok/curves 1.12.2 → 1.13.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/CLAUDE.md +118 -15
  3. package/README.md +51 -4
  4. package/dist/package-test.js +8819 -5223
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3014 -1659
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +2 -2
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/data-to-curves.ts +11 -6
  12. package/src/fit/fit-chart-data.ts +330 -0
  13. package/src/fit/fit-grid-cell-handler.ts +102 -235
  14. package/src/fit/fit-inspection.ts +3 -3
  15. package/src/fit/fit-interaction.ts +181 -0
  16. package/src/fit/fit-layout.ts +64 -0
  17. package/src/fit/fit-legend.ts +292 -0
  18. package/src/fit/fit-options.ts +222 -0
  19. package/src/fit/fit-parser.ts +16 -5
  20. package/src/fit/fit-renderer.ts +180 -469
  21. package/src/fit/fit-statistics.ts +154 -0
  22. package/src/fit/multi-curve-viewer.ts +48 -22
  23. package/src/fit/render-utils.ts +208 -150
  24. package/src/package-api.ts +78 -0
  25. package/src/package-test.ts +7 -0
  26. package/src/package.g.ts +59 -11
  27. package/src/package.ts +97 -18
  28. package/src/tests/calculated-columns-tests.ts +299 -0
  29. package/src/tests/converter-tests.ts +23 -0
  30. package/src/tests/curve-data.ts +82 -0
  31. package/src/tests/fit-cache-tests.ts +128 -0
  32. package/src/tests/fit-tests.ts +344 -4
  33. package/src/tests/legend-tests.ts +243 -0
  34. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  35. package/src/tests/panel-renderer-tests.ts +502 -0
  36. package/src/tests/project-tests.ts +99 -0
  37. package/src/tests/statistics-tests.ts +127 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +410 -109
  40. package/test-record-1.mp4 +0 -0
@@ -2,34 +2,50 @@
2
2
  import * as DG from 'datagrok-api/dg';
3
3
  import {
4
4
  FitConfidenceIntervals,
5
- IFitChartData,
6
5
  IFitSeries,
7
- statisticsProperties
6
+ LogOptions,
8
7
  } from '@datagrok-libraries/statistics/src/fit/fit-curve';
9
8
  import {
10
9
  getSeriesConfidenceInterval,
11
- getSeriesStatistics,
12
- LogOptions
10
+ getSeriesFit,
11
+ toDataSpace,
13
12
  } from '@datagrok-libraries/statistics/src/fit/fit-data';
14
13
  import {Viewport} from '@datagrok-libraries/utils/src/transform';
15
14
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
16
15
  import {BoxPlotStatistics, calculateBoxPlotStatistics} from '@datagrok-libraries/statistics/src/box-plot-statistics';
17
16
  import {StringUtils} from '@datagrok-libraries/utils/src/string-utils';
18
- import {FitFunction} from '@datagrok-libraries/statistics/src/fit/new-fit-API';
19
-
17
+ import {FitFunction, getStatistic, getStatisticProperty} from '@datagrok-libraries/statistics/src/fit/fit-engine';
18
+
19
+
20
+ /** How often what is drawn reports where it went, which is enough to tell a busy corner from a free one. */
21
+ export const CURVE_SAMPLE_PX_STEP = 8;
22
+ const STATISTICS_FONT = '11px Roboto, "Roboto Local"';
23
+ const STATISTICS_LINE_PX = 15;
24
+
25
+ /** Where a piece of text ends up, so the legend does not take a corner the plot already writes in. */
26
+ function reportText(drawnAt: DG.Point[] | undefined, g: CanvasRenderingContext2D, text: string,
27
+ x: number, y: number): void {
28
+ if (!drawnAt)
29
+ return;
30
+ const width = g.measureText(text).width;
31
+ for (let at = x; at <= x + width; at += CURVE_SAMPLE_PX_STEP)
32
+ drawnAt.push(new DG.Point(at, y));
33
+ }
20
34
 
21
35
  export enum ColorType {
22
36
  POINT = 'pointColor',
23
37
  OUTLIER = 'outlierColor',
24
38
  FIT_LINE = 'fitLineColor',
25
39
  }
26
- export type SeriesColorType = `${ColorType}` | string;
40
+ export type SeriesColorType = `${ColorType}`;
27
41
 
28
42
  interface FitRenderOptions {
29
43
  viewport: Viewport;
30
44
  screenBounds?: DG.Rect;
31
45
  ratio?: number;
32
46
  seriesIdx?: number;
47
+ /** Collects where the chart put ink, which is how the legend finds a free corner. */
48
+ drawnAt?: DG.Point[];
33
49
  }
34
50
 
35
51
  interface FitPointRenderOptions extends FitRenderOptions {
@@ -56,20 +72,32 @@ interface FitConfidenceIntervalRenderOptions extends FitLineRenderOptions {
56
72
 
57
73
  interface FitDroplineRenderOptions extends FitRenderOptions {
58
74
  showDroplines?: boolean;
59
- xValue: number;
75
+ showDroplineLabels?: boolean;
76
+ fitFunc: FitFunction;
60
77
  dataBounds: DG.Rect;
61
78
  curveFunc: (x: number) => number;
62
79
  logOptions: LogOptions;
63
80
  }
64
81
 
82
+ interface FitLabelsRenderOptions {
83
+ names?: string[];
84
+ startLine?: number;
85
+ color: string;
86
+ dataBox: DG.Rect;
87
+ screenBounds?: DG.Rect;
88
+ drawnAt?: DG.Point[];
89
+ }
90
+
65
91
  interface FitStatisticsRenderOptions {
66
92
  statistics?: string[];
93
+ startLine?: number;
67
94
  fitFunc: FitFunction;
68
95
  logOptions: LogOptions;
69
96
  dataBox: DG.Rect;
70
97
  screenBounds?: DG.Rect;
71
98
  dataPoints?: {x: number[], y: number[]};
72
99
  seriesIdx?: number;
100
+ drawnAt?: DG.Point[];
73
101
  }
74
102
 
75
103
  interface FitTitleRenderOptions {
@@ -85,21 +113,13 @@ interface FitAxesLabelsRenderOptions extends FitTitleRenderOptions {
85
113
  yAxisName?: string;
86
114
  }
87
115
 
88
- interface FitLegendRenderOptions {
89
- showLegend?: boolean;
90
- dataBox: DG.Rect;
91
- ratio?: number;
92
- }
93
-
94
- interface FitLegendColumnlabelSeriesRenderOptions extends FitLegendRenderOptions {
95
- columnIdx: number;
96
- drawnCurvesInLegend: number;
97
- showColumnLabel?: boolean;
98
- seriesIdx?: number;
99
- useAuxLegendNames?: boolean;
116
+ /** Checks if the color is valid */
117
+ export function isColorValid(color: string | null | undefined): boolean {
118
+ if (color === undefined || color === null || color === '')
119
+ return false;
120
+ return DG.Color.fromHtml(color) !== undefined;
100
121
  }
101
122
 
102
-
103
123
  export function getSeriesColor(series: IFitSeries, seriesIdx: number, colorType: SeriesColorType): string {
104
124
  const color = DG.Color.toHtml(colorType === 'outlierColor' ? DG.Color.red : DG.Color.getCategoricalColor(seriesIdx));
105
125
  return series[colorType] ? DG.Color.fromHtml(series[colorType]) ? series[colorType] : color : color;
@@ -131,7 +151,7 @@ export function renderPoints(g: CanvasRenderingContext2D, series: IFitSeries, op
131
151
  screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT ? '' : series.showPoints ?? 'points';
132
152
  if (showPoints) {
133
153
  g.strokeStyle = getSeriesColor(series, options.seriesIdx!, ColorType.POINT);
134
- if ((series.connectDots && series.showPoints !== '') || series.showPoints === 'points')
154
+ if (series.connectDots || series.showPoints === 'points')
135
155
  drawPoints(g, series, options);
136
156
  else if (['candlesticks', 'both'].includes(series.showPoints!))
137
157
  drawCandles(g, series, options);
@@ -139,6 +159,16 @@ export function renderPoints(g: CanvasRenderingContext2D, series: IFitSeries, op
139
159
  }
140
160
 
141
161
  /** Performs points drawing */
162
+ /** The two segments of an error bar in screen coordinates, running from the marker's edge outwards so
163
+ * the bar stays readable at any marker size. Null when the deviation is smaller than the marker and
164
+ * would be drawn inside it. */
165
+ export function stdevWhisker(yCenter: number, yTop: number, yBottom: number, radius: number):
166
+ {top: [number, number], bottom: [number, number]} | null {
167
+ if (yCenter - yTop <= radius)
168
+ return null;
169
+ return {top: [yTop, yCenter - radius], bottom: [yCenter + radius, yBottom]};
170
+ }
171
+
142
172
  function drawPoints(g: CanvasRenderingContext2D, series: IFitSeries, options: FitRenderOptions): void {
143
173
  const ratio = options.ratio!;
144
174
  const defaultSize = FitConstants.POINT_PX_SIZE * ratio;
@@ -158,16 +188,32 @@ function drawPoints(g: CanvasRenderingContext2D, series: IFitSeries, options: Fi
158
188
  (p.color ? DG.Color.fromHtml(p.color) ? p.color : pointColor : pointColor);
159
189
  const marker = p.marker ? p.marker as DG.MARKER_TYPE : series.markerType as DG.MARKER_TYPE;
160
190
  const outlierMarker = p.outlierMarker ? p.outlierMarker as DG.MARKER_TYPE : series.outlierMarkerType as DG.MARKER_TYPE;
161
- const size = !connectDots ? p.outlier ? FitConstants.OUTLIER_PX_SIZE * ratio : p.size ? p.size : defaultSize : defaultSize;
191
+ const outlierSize = Math.min(FitConstants.OUTLIER_PX_SIZE * ratio, viewport.screen.height / 10);
192
+ const size = !connectDots ? p.outlier ? outlierSize : p.size ? p.size : defaultSize : defaultSize;
162
193
  const markerToDraw = !connectDots ? p.outlier ? outlierMarker : marker : marker;
163
194
 
164
195
  DG.Paint.marker(g, markerToDraw, xScreen, yScreen, color, size);
165
196
  if (p.stdev && !p.outlier) {
166
- g.strokeStyle = color;
167
- g.beginPath();
168
- g.moveTo(xScreen, viewport.yToScreen(p.y + p.stdev));
169
- g.lineTo(xScreen, viewport.yToScreen(p.y - p.stdev));
170
- g.stroke();
197
+ const radius = size / 2;
198
+ const whisker = stdevWhisker(yScreen, viewport.yToScreen(p.y + p.stdev),
199
+ viewport.yToScreen(p.y - p.stdev), radius);
200
+ if (whisker) {
201
+ options.drawnAt?.push(new DG.Point(xScreen, whisker.top[0]), new DG.Point(xScreen, whisker.bottom[1]));
202
+ g.strokeStyle = color;
203
+ // set rather than inherited: the fit line and the droplines both leave a width behind
204
+ g.lineWidth = ratio;
205
+ g.beginPath();
206
+ g.moveTo(xScreen, whisker.top[0]);
207
+ g.lineTo(xScreen, whisker.top[1]);
208
+ g.moveTo(xScreen, whisker.bottom[0]);
209
+ g.lineTo(xScreen, whisker.bottom[1]);
210
+ // caps as wide as the marker, so the extent reads at a glance
211
+ g.moveTo(xScreen - radius, whisker.top[0]);
212
+ g.lineTo(xScreen + radius, whisker.top[0]);
213
+ g.moveTo(xScreen - radius, whisker.bottom[1]);
214
+ g.lineTo(xScreen + radius, whisker.bottom[1]);
215
+ g.stroke();
216
+ }
171
217
  }
172
218
  }
173
219
  }
@@ -233,13 +279,11 @@ function drawCandlestickBorder(g: CanvasRenderingContext2D, x: number, adjacentV
233
279
  function getRenderingVariables(renderOptions: FitConfidenceIntervalRenderOptions | FitLineRenderOptions) {
234
280
  const logX = renderOptions.logOptions.logX;
235
281
  const logY = renderOptions.logOptions.logY;
236
- const screenBounds = renderOptions.screenBounds;
237
- const axesLeftPxMargin = renderOptions.showAxes ? renderOptions.showAxesLabels ?
238
- FitConstants.AXES_LEFT_PX_MARGIN_WITH_AXES_LABELS : FitConstants.AXES_LEFT_PX_MARGIN : 0;
239
- const axesRightPxMargin = renderOptions.showAxes ? FitConstants.AXES_RIGHT_PX_MARGIN : 0;
240
- const xMin = screenBounds.x + axesLeftPxMargin;
241
- const xMax = screenBounds.x + screenBounds.width - axesRightPxMargin;
242
282
  const viewport = renderOptions.viewport;
283
+ // the box the viewport maps onto, so a curve stops where the axes do instead of running under
284
+ // whatever the layout keeps to the side of it
285
+ const xMin = viewport.screen.left;
286
+ const xMax = viewport.screen.maxX;
243
287
  return {logX, logY, xMin, xMax, viewport};
244
288
  }
245
289
 
@@ -257,6 +301,9 @@ export function renderFitLine(g: CanvasRenderingContext2D, series: IFitSeries, r
257
301
  for (let i = xMin; i <= xMax; i++) {
258
302
  const xForY = logX ? Math.log10(viewport.xToWorld(i)) : viewport.xToWorld(i);
259
303
  const y = logY ? viewport.yToScreen(Math.pow(10, curveFunc(xForY))) : viewport.yToScreen(curveFunc(xForY));
304
+ if (renderOptions.drawnAt && i % CURVE_SAMPLE_PX_STEP === 0)
305
+ renderOptions.drawnAt.push(new DG.Point(i, y));
306
+
260
307
  if (i === xMin)
261
308
  g.moveTo(i, y);
262
309
  else
@@ -277,7 +324,7 @@ export function renderConfidenceIntervals(g: CanvasRenderingContext2D, series: I
277
324
  const logOptions = renderOptions.logOptions;
278
325
  const viewport = renderOptions.viewport;
279
326
  const screenBounds = renderOptions.screenBounds;
280
- const dataPoints = series.dataPoints;
327
+ const dataPoints = renderOptions.dataPoints;
281
328
 
282
329
  const confidenceIntervals = getSeriesConfidenceInterval(series, renderOptions.fitFunc!, renderOptions.userParamsFlag!, dataPoints, logOptions);
283
330
  drawConfidenceInterval(g, {viewport: viewport, logOptions: logOptions, showAxes: showAxes, showAxesLabels: showAxesLabels,
@@ -300,6 +347,8 @@ function drawConfidenceInterval(g: CanvasRenderingContext2D, renderOptions: FitC
300
347
  for (let i = xMin; i <= xMax; i++) {
301
348
  const xForY = logX ? Math.log10(viewport.xToWorld(i)) : viewport.xToWorld(i);
302
349
  const y = logY ? viewport.yToScreen(Math.pow(10, confIntervalFunc(xForY))) : viewport.yToScreen(confIntervalFunc(xForY));
350
+ if (renderOptions.drawnAt && i % CURVE_SAMPLE_PX_STEP === 0)
351
+ renderOptions.drawnAt.push(new DG.Point(i, y));
303
352
  if (i === xMin)
304
353
  g.moveTo(i, y);
305
354
  else
@@ -335,66 +384,142 @@ function fillConfidenceInterval(g: CanvasRenderingContext2D, renderOptions: FitC
335
384
  g.fill();
336
385
  }
337
386
 
387
+ /** The travelled fraction an ICxx / ECxx name asks for, or undefined when the name is not one. */
388
+ export function droplineFraction(name: string): number | undefined {
389
+ const match = /^(?:IC|EC)(\d{1,2}(?:\.\d+)?)$/i.exec(name);
390
+ const percent = match ? parseFloat(match[1]) : NaN;
391
+ return percent > 0 && percent < 100 ? percent / 100 : undefined;
392
+ }
393
+
338
394
  export function renderDroplines(g: CanvasRenderingContext2D, series: IFitSeries, renderOptions: FitDroplineRenderOptions): void {
339
- if ((series.showFitLine ?? true) && series.droplines && renderOptions.showDroplines!) {
340
- g.save();
341
- g.strokeStyle = 'blue';
342
- g.lineWidth = renderOptions.ratio!;
343
- g.beginPath();
344
- g.setLineDash([5, 5]);
345
- const viewport = renderOptions.viewport;
346
- const dataBounds = renderOptions.dataBounds;
347
- const curveFunc = renderOptions.curveFunc;
348
- const logOptions = renderOptions.logOptions;
349
- for (let j = 0; j < series.droplines.length; j++) {
350
- const droplineName = series.droplines[j];
351
- if (droplineName === 'IC50') {
352
- drawDropline(g, {viewport: viewport, xValue: series.parameters![2], dataBounds: dataBounds,
353
- curveFunc: curveFunc, logOptions: logOptions});
354
- }
355
- }
356
- g.stroke();
357
- g.restore();
395
+ if (!(series.showFitLine ?? true) || !series.droplines?.length || !series.parameters || !renderOptions.showDroplines)
396
+ return;
397
+ g.save();
398
+ g.strokeStyle = 'blue';
399
+ g.lineWidth = renderOptions.ratio!;
400
+ g.beginPath();
401
+ g.setLineDash([5, 5]);
402
+ const drawn: {name: string, screenY: number}[] = [];
403
+ for (const name of series.droplines) {
404
+ const fraction = droplineFraction(name);
405
+ const x = fraction === undefined ? undefined :
406
+ renderOptions.fitFunc.inverse(Float32Array.from(series.parameters), fraction);
407
+ const screenY = x === undefined ? null : drawDropline(g, x, renderOptions);
408
+ if (screenY !== null)
409
+ drawn.push({name: name, screenY: screenY});
410
+ }
411
+ g.stroke();
412
+ // a single line is unambiguous; several are told apart by where each one leaves the axis, which
413
+ // is why the caption sits there rather than under the curve
414
+ if (series.droplines.length > 1 && renderOptions.showDroplineLabels) {
415
+ g.setLineDash([]);
416
+ g.fillStyle = 'blue';
417
+ g.font = '10px Roboto, "Roboto Local"';
418
+ g.textAlign = 'left';
419
+ const left = renderOptions.viewport.xToScreen(renderOptions.dataBounds.minX) + 2;
420
+ for (const dropline of drawn)
421
+ g.fillText(dropline.name, left, dropline.screenY - 3);
358
422
  }
423
+ g.restore();
359
424
  }
360
425
 
361
426
  /** Performs a dropline drawing */
362
- function drawDropline(g: CanvasRenderingContext2D, renderOptions: FitDroplineRenderOptions): void {
427
+ /** Draws one dropline, returning the screen y it leaves the axis at - or null when it falls off the plot. */
428
+ function drawDropline(g: CanvasRenderingContext2D, x: number, renderOptions: FitDroplineRenderOptions): number | null {
363
429
  const logX = renderOptions.logOptions.logX;
364
430
  const logY = renderOptions.logOptions.logY;
365
- const xValue = logX ? Math.pow(10, renderOptions.xValue) : renderOptions.xValue;
431
+ const xValue = logX ? Math.pow(10, x) : x;
366
432
  const viewport = renderOptions.viewport;
367
433
  const dataBounds = renderOptions.dataBounds;
434
+ if (xValue < dataBounds.minX || xValue > dataBounds.maxX)
435
+ return null;
368
436
 
369
437
  const xForY = logX ? Math.log10(xValue) : xValue;
370
438
  const y = logY ? Math.pow(10, renderOptions.curveFunc(xForY)) : renderOptions.curveFunc(xForY);
371
439
  const screenX = viewport.xToScreen(xValue);
372
440
  const screenY = viewport.yToScreen(y);
373
- g.moveTo(viewport.xToScreen(dataBounds.minX), screenY);
441
+ const left = viewport.xToScreen(dataBounds.minX);
442
+ const bottom = viewport.yToScreen(dataBounds.minY);
443
+ g.moveTo(left, screenY);
374
444
  g.lineTo(screenX, screenY);
375
- g.lineTo(screenX, viewport.yToScreen(dataBounds.minY));
445
+ g.lineTo(screenX, bottom);
446
+ if (renderOptions.drawnAt) {
447
+ for (let x = left; x <= screenX; x += CURVE_SAMPLE_PX_STEP)
448
+ renderOptions.drawnAt.push(new DG.Point(x, screenY));
449
+ for (let y2 = screenY; y2 <= bottom; y2 += CURVE_SAMPLE_PX_STEP)
450
+ renderOptions.drawnAt.push(new DG.Point(screenX, y2));
451
+ }
452
+ return screenY;
376
453
  }
377
454
 
378
- export function renderStatistics(g: CanvasRenderingContext2D, series: IFitSeries, renderOptions: FitStatisticsRenderOptions): void {
455
+ // formatNumber is fixed at 2 decimals, which renders a sub-micromolar IC50 as "0.00"
456
+ function formatStatistic(value: number): string {
457
+ return value !== 0 && (Math.abs(value) < 0.001 || Math.abs(value) >= 1e6) ?
458
+ DG.format(value, 'scientific') : StringUtils.formatNumber(value);
459
+ }
460
+
461
+ /** Draws one series' statistics from `startLine`, returning the lines used so the next can continue
462
+ * below. Lines falling outside the plot are dropped. */
463
+ /** Draws the named labels from `labels` starting at `startLine`, returning the lines used so the
464
+ * caller can continue below. Same line budget as the statistics - a cell has room for about five. */
465
+ export function renderLabels(g: CanvasRenderingContext2D, labels: {[key: string]: string | number | boolean} | undefined,
466
+ renderOptions: FitLabelsRenderOptions): number {
467
+ const screenBounds = renderOptions.screenBounds!;
468
+ const names = screenBounds.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ||
469
+ screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT ? [] : renderOptions.names;
470
+ if (!labels || !names || names.length === 0)
471
+ return 0;
472
+ const dataBox = renderOptions.dataBox;
473
+ g.font = STATISTICS_FONT;
474
+ let line = renderOptions.startLine ?? 0;
475
+ for (const name of names) {
476
+ const value = labels[name];
477
+ if (value === undefined || value === null)
478
+ continue;
479
+ const y = dataBox.y + STATISTICS_LINE_PX * (line + 1);
480
+ if (y > dataBox.maxY)
481
+ break;
482
+ g.fillStyle = renderOptions.color;
483
+ g.textAlign = 'left';
484
+ const text = `${name}: ${typeof value === 'number' ? formatStatistic(value) : value}`;
485
+ g.fillText(text, dataBox.x + 5, y);
486
+ reportText(renderOptions.drawnAt, g, text, dataBox.x + 5, y);
487
+ line++;
488
+ }
489
+ return line - (renderOptions.startLine ?? 0);
490
+ }
491
+
492
+ export function renderStatistics(g: CanvasRenderingContext2D, series: IFitSeries, renderOptions: FitStatisticsRenderOptions): number {
379
493
  const screenBounds = renderOptions.screenBounds!;
380
494
  const statistics = screenBounds.width < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_WIDTH ||
381
495
  screenBounds.height < FitConstants.MIN_POINTS_AND_STATS_VISIBILITY_PX_HEIGHT ? [] : renderOptions.statistics;
382
- if ((series.showFitLine ?? true) && statistics && statistics.length > 0) {
383
- const dataBox = renderOptions.dataBox;
384
- const dataPoints = renderOptions.dataPoints;
385
- const seriesStatistics = getSeriesStatistics(series, renderOptions.fitFunc, dataPoints, renderOptions.logOptions);
386
- const color = getSeriesColor(series, renderOptions.seriesIdx!, ColorType.FIT_LINE);
387
- for (let i = 0; i < statistics.length; i++) {
388
- const statName = statistics[i];
389
- const prop = statisticsProperties.find((p) => p.name === statName);
390
- if (prop) {
391
- const s = StringUtils.formatNumber(prop.get(seriesStatistics));
392
- g.fillStyle = color;
393
- g.textAlign = 'left';
394
- g.fillText(prop.name + ': ' + s, dataBox.x + 5, dataBox.y + 20 + 20 * i);
395
- }
396
- }
496
+ if (!((series.showFitLine ?? true) && statistics && statistics.length > 0))
497
+ return 0;
498
+ const dataBox = renderOptions.dataBox;
499
+ const dataPoints = renderOptions.dataPoints;
500
+ const fitFunc = renderOptions.fitFunc!;
501
+ const fit = toDataSpace(getSeriesFit(series, fitFunc, dataPoints, renderOptions.logOptions),
502
+ renderOptions.logOptions);
503
+ const color = getSeriesColor(series, renderOptions.seriesIdx!, ColorType.FIT_LINE);
504
+ g.font = STATISTICS_FONT;
505
+ let line = renderOptions.startLine ?? 0;
506
+ for (const statName of statistics) {
507
+ const value = getStatistic(fit, statName);
508
+ const prop = getStatisticProperty(fitFunc, statName);
509
+ // skip statistics this fit function does not produce instead of rendering NaN
510
+ if (value === undefined || !prop)
511
+ continue;
512
+ const y = dataBox.y + STATISTICS_LINE_PX * (line + 1);
513
+ if (y > dataBox.maxY)
514
+ break;
515
+ g.fillStyle = color;
516
+ g.textAlign = 'left';
517
+ const text = `${prop.friendlyName}: ${formatStatistic(value)}`;
518
+ g.fillText(text, dataBox.x + 5, y);
519
+ reportText(renderOptions.drawnAt, g, text, dataBox.x + 5, y);
520
+ line++;
397
521
  }
522
+ return line - (renderOptions.startLine ?? 0);
398
523
  }
399
524
 
400
525
  export function renderTitle(g: CanvasRenderingContext2D, renderOptions: FitTitleRenderOptions): void {
@@ -413,82 +538,15 @@ export function renderAxesLabels(g: CanvasRenderingContext2D, renderOptions: Fit
413
538
  g.font = '11px Roboto, "Roboto Local"';
414
539
  g.textAlign = 'center';
415
540
  g.fillStyle = 'black';
416
- g.fillText(renderOptions.xAxisName!, dataBox.midX - 5, screenBounds.maxY - FitConstants.X_AXIS_LABEL_BOTTOM_PX_MARGIN);
417
- g.translate(screenBounds.x, screenBounds.y);
418
- g.rotate(-Math.PI / 2);
419
- const axesTopPxMargin = renderOptions.showTitle ? FitConstants.AXES_TOP_PX_MARGIN_WITH_TITLE : FitConstants.AXES_TOP_PX_MARGIN;
420
- g.fillText(renderOptions.yAxisName!, -(dataBox.height / 2 + axesTopPxMargin + 15), 15);
421
- g.restore();
422
- }
423
- }
424
-
425
- export function renderLegend(g: CanvasRenderingContext2D, data: IFitChartData, renderOptions: FitLegendRenderOptions): void {
426
- if (renderOptions.showLegend) {
427
- const dataBox = renderOptions.dataBox;
428
- const ratio = renderOptions.ratio;
429
- g.font = '11px Roboto, "Roboto Local"';
430
- const columnNames = [...new Set(data.series?.map((series) => series.columnName))]
431
- .filter((colName) => colName !== null && colName !== undefined);
432
- let drawnCurvesInLegend = 0;
433
- for (let i = 0; i < columnNames.length; i++) {
434
- const colName = columnNames[i];
435
- if (data.chartOptions?.showColumnLabel)
436
- renderColumnLabel(g, colName!, {dataBox: dataBox, columnIdx: i, drawnCurvesInLegend});
437
-
438
- const series = data.series?.filter((series) => series.columnName === colName);
439
- for (let j = 0; j < series?.length!; j++) {
440
- const currentSeries = series![j];
441
- if (currentSeries.name === '' || currentSeries.name === null || currentSeries.name === undefined)
442
- continue;
443
- renderLegendSeries(g, currentSeries, {dataBox: dataBox, ratio: ratio, useAuxLegendNames: data.chartOptions?.useAuxLegendNames,
444
- columnIdx: i, drawnCurvesInLegend, showColumnLabel: data.chartOptions?.showColumnLabel, seriesIdx: j});
445
- drawnCurvesInLegend++;
446
- }
541
+ if (renderOptions.xAxisName)
542
+ g.fillText(renderOptions.xAxisName, dataBox.midX, screenBounds.maxY - FitConstants.X_AXIS_LABEL_BOTTOM_PX_MARGIN);
543
+ if (renderOptions.yAxisName) {
544
+ g.save();
545
+ g.translate(screenBounds.x, screenBounds.y);
546
+ g.rotate(-Math.PI / 2);
547
+ const axesTopPxMargin = renderOptions.showTitle ? FitConstants.AXES_TOP_PX_MARGIN_WITH_TITLE : FitConstants.AXES_TOP_PX_MARGIN;
548
+ g.fillText(renderOptions.yAxisName, -(dataBox.height / 2 + axesTopPxMargin), 15);
549
+ g.restore();
447
550
  }
448
- g.restore();
449
551
  }
450
552
  }
451
-
452
- function renderColumnLabel(g: CanvasRenderingContext2D, colName: string, renderOptions: FitLegendColumnlabelSeriesRenderOptions): void {
453
- const dataBox = renderOptions.dataBox;
454
- g.beginPath();
455
- g.fillStyle = 'black';
456
- const colNameWidth = g.measureText(colName!).width;
457
- g.fillText(colName!, dataBox.maxX - colNameWidth, dataBox.y + FitConstants.LEGEND_TOP_PX_MARGIN +
458
- (renderOptions.columnIdx * FitConstants.LEGEND_RECORD_PX_HEIGHT + FitConstants.LEGEND_RECORD_PX_HEIGHT * renderOptions.drawnCurvesInLegend));
459
- }
460
-
461
- function renderLegendSeries(g: CanvasRenderingContext2D, series: IFitSeries, renderOptions: FitLegendColumnlabelSeriesRenderOptions): void {
462
- const dataBox = renderOptions.dataBox;
463
- const columnIdx = renderOptions.columnIdx;
464
- const ratio = renderOptions.ratio!;
465
- const showColumnLabel = renderOptions.showColumnLabel;
466
- const drawnCurvesInLegend = renderOptions.drawnCurvesInLegend;
467
- const pointColor = getSeriesColor(series, renderOptions.seriesIdx!, ColorType.POINT);
468
- const fitLineColor = getSeriesColor(series, renderOptions.seriesIdx!, ColorType.FIT_LINE);
469
- g.beginPath();
470
- g.strokeStyle = fitLineColor;
471
- g.lineWidth = 2 * ratio;
472
- const nameToRender = renderOptions.useAuxLegendNames ? series.auxLegendName ?? series.name! : series.name!;
473
- const textWidth = g.measureText(nameToRender).width;
474
- g.moveTo(dataBox.maxX - textWidth - FitConstants.LEGEND_RECORD_LINE_PX_WIDTH - FitConstants.LEGEND_RECORD_LINE_RIGHT_PX_MARGIN,
475
- dataBox.y + FitConstants.LEGEND_TOP_PX_MARGIN - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN +
476
- (showColumnLabel ? FitConstants.LEGEND_RECORD_PX_HEIGHT * (columnIdx + 1) : 0) +
477
- FitConstants.LEGEND_RECORD_PX_HEIGHT * drawnCurvesInLegend);
478
- g.lineTo(dataBox.maxX - textWidth - FitConstants.LEGEND_RECORD_LINE_RIGHT_PX_MARGIN,
479
- dataBox.y + FitConstants.LEGEND_TOP_PX_MARGIN - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN +
480
- (showColumnLabel ? FitConstants.LEGEND_RECORD_PX_HEIGHT * (columnIdx + 1) : 0) +
481
- FitConstants.LEGEND_RECORD_PX_HEIGHT * drawnCurvesInLegend);
482
- let pointsMarkerValue = series.points && series.points.length > 0 ? series.points[0].marker : null;
483
- pointsMarkerValue = series.points && series.points.every((p) => p.marker === pointsMarkerValue && p.marker != null) ? pointsMarkerValue : null;
484
- const marker = pointsMarkerValue != null ? pointsMarkerValue as DG.MARKER_TYPE : series.markerType ? series.markerType as DG.MARKER_TYPE : DG.MARKER_TYPE.CIRCLE;
485
- const legendMarkerSize = Math.floor(FitConstants.POINT_PX_SIZE * ratio * 1.5);
486
- DG.Paint.marker(g, marker,
487
- dataBox.maxX - textWidth - FitConstants.LEGEND_RECORD_LINE_RIGHT_PX_MARGIN - FitConstants.LEGEND_RECORD_LINE_PX_WIDTH - legendMarkerSize,
488
- dataBox.y + FitConstants.LEGEND_TOP_PX_MARGIN - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN + (showColumnLabel ? FitConstants.LEGEND_RECORD_PX_HEIGHT * (columnIdx + 1) : 0) + FitConstants.LEGEND_RECORD_PX_HEIGHT * drawnCurvesInLegend,
489
- pointColor, legendMarkerSize);
490
- g.fillStyle = fitLineColor;
491
- g.fillText(nameToRender, dataBox.maxX - textWidth, dataBox.y + FitConstants.LEGEND_TOP_PX_MARGIN + (showColumnLabel ?
492
- FitConstants.LEGEND_RECORD_PX_HEIGHT * (columnIdx + 1) : 0) + FitConstants.LEGEND_RECORD_PX_HEIGHT * drawnCurvesInLegend);
493
- g.stroke();
494
- }
@@ -46,6 +46,17 @@ export namespace funcs {
46
46
  return await grok.functions.call('Curves:InitCurves', {});
47
47
  }
48
48
 
49
+ /**
50
+ * Group well-level assay data by compound, assay, target, and run, then fit a dose-response curve per group.
51
+ * @param {DG.Column} concentrationCol - Concentration (dose) column
52
+ * @param {DG.Column} readoutCol - Readout (response) column
53
+ * @param {DG.Column} batchIDCol - Batch identifier column
54
+ * @param {DG.Column} assayCol - Assay name column
55
+ * @param {DG.Column} runIDCol - Run identifier column
56
+ * @param {DG.Column} compoundIDCol - Compound identifier column
57
+ * @param {DG.Column} targetEntityCol - Target entity column
58
+ * @param {DG.Column} excludeOutliersCol - Boolean column marking points to exclude as outliers
59
+ */
49
60
  export async function dataToCurves(df: DG.DataFrame , concentrationCol: DG.Column , readoutCol: DG.Column , batchIDCol: DG.Column , assayCol: DG.Column , runIDCol: DG.Column , compoundIDCol: DG.Column , targetEntityCol: DG.Column , excludeOutliersCol: DG.Column | null, parentTable: DG.DataFrame | null, fitParamColumns: any | null, reportedIC50Column: string | null, reportedQualifiedIC50Column: string | null, experimentIDColumn: string | null, qualifierColumn: string | null, additionalColumns: any | null, wellLevelJoinCol: string | null, parentLevelJoinCol: string | null, wellLevelAdditionalColumns?: any | null): Promise<DG.DataFrame> {
50
61
  return await grok.functions.call('Curves:DataToCurves', { df, concentrationCol, readoutCol, batchIDCol, assayCol, runIDCol, compoundIDCol, targetEntityCol, excludeOutliersCol, parentTable, fitParamColumns, reportedIC50Column, reportedQualifiedIC50Column, experimentIDColumn, qualifierColumn, additionalColumns, wellLevelJoinCol, parentLevelJoinCol, wellLevelAdditionalColumns });
51
62
  }
@@ -54,14 +65,77 @@ export namespace funcs {
54
65
  return await grok.functions.call('Curves:DataToCurvesTopMenu', {});
55
66
  }
56
67
 
68
+ /**
69
+ * Extract a fit statistic (e.g. IC50, AUC, R²) from a curve series into a calculated column.
70
+ * @param {DG.Column} curveColumn - Curve column to read
71
+ * semType: fit
72
+ * @param {string} propName - Fit statistic to extract (e.g. ic50, auc, rSquared)
73
+ * @param {number} seriesNumber - Zero-based index of the curve series
74
+ */
75
+ export async function curveStatistic(table: DG.DataFrame , curveColumn: DG.Column , propName: string , seriesNumber: number ): Promise<DG.Column> {
76
+ return await grok.functions.call('Curves:CurveStatistic', { table, curveColumn, propName, seriesNumber });
77
+ }
78
+
79
+ /**
80
+ * Aggregate a fit statistic across all series of a curve into a calculated column.
81
+ * @param {DG.Column} curveColumn - Curve column to read
82
+ * semType: fit
83
+ * @param {string} propName - Fit statistic to aggregate
84
+ * @param {string} aggrType - Aggregation applied across the series of each curve
85
+ * choices: ["avg","med","min","max","q1","q2","q3"]
86
+ */
87
+ export async function curveAggrStatistic(table: DG.DataFrame , curveColumn: DG.Column , propName: string , aggrType: string ): Promise<DG.Column> {
88
+ return await grok.functions.call('Curves:CurveAggrStatistic', { table, curveColumn, propName, aggrType });
89
+ }
90
+
91
+ /**
92
+ * Extract a fit statistic (e.g. IC50, AUC, R²) from a specific curve series into a new column.
93
+ * @param {string} colName - Name of the curve column to read
94
+ * @param {string} propName - Fit statistic to extract. interceptX is IC50, top and bottom are max/min Y
95
+ * choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]
96
+ * @param {number} seriesNumber - Zero-based index of the curve series
97
+ */
57
98
  export async function addStatisticsColumn(table: DG.DataFrame , colName: string , propName: string , seriesNumber: number ): Promise<DG.Column> {
58
99
  return await grok.functions.call('Curves:AddStatisticsColumn', { table, colName, propName, seriesNumber });
59
100
  }
60
101
 
102
+ /**
103
+ * Aggregate a fit statistic across all series of a curve into a new column.
104
+ * @param {string} colName - Name of the curve column to read
105
+ * @param {string} propName - Fit statistic to aggregate. interceptX is IC50, top and bottom are max/min Y
106
+ * choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]
107
+ * @param {string} aggrType - Aggregation applied across the series of each curve
108
+ * choices: ["min","max","avg","med","q1","q2","q3"]
109
+ */
61
110
  export async function addAggrStatisticsColumn(table: DG.DataFrame , colName: string , propName: string , aggrType: string ): Promise<DG.Column> {
62
111
  return await grok.functions.call('Curves:AddAggrStatisticsColumn', { table, colName, propName, aggrType });
63
112
  }
64
113
 
114
+ /**
115
+ * Extracts a fit statistic from one series of a curve column into a new column.
116
+ * @param {DG.Column} curvesCol - Column of fitted curves
117
+ * semType: fit
118
+ * @param {string} statistic - interceptX is IC50, top and bottom are max/min Y
119
+ * choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]
120
+ * @param {number} seriesNumber - Zero-based index of the curve series
121
+ */
122
+ export async function addCurveStatistic(table: DG.DataFrame , curvesCol: DG.Column , statistic: string , seriesNumber: number ): Promise<DG.Column> {
123
+ return await grok.functions.call('Curves:AddCurveStatistic', { table, curvesCol, statistic, seriesNumber });
124
+ }
125
+
126
+ /**
127
+ * Aggregates a fit statistic across all series of a curve column into a new column.
128
+ * @param {DG.Column} curvesCol - Column of fitted curves
129
+ * semType: fit
130
+ * @param {string} statistic - interceptX is IC50, top and bottom are max/min Y
131
+ * choices: ["rSquared","auc","interceptX","interceptY","slope","top","bottom"]
132
+ * @param {string} aggregation - Applied across the series of each curve
133
+ * choices: ["med","avg","min","max","q1","q2","q3"]
134
+ */
135
+ export async function addAggrCurveStatistic(table: DG.DataFrame , curvesCol: DG.Column , statistic: string , aggregation: string ): Promise<DG.Column> {
136
+ return await grok.functions.call('Curves:AddAggrCurveStatistic', { table, curvesCol, statistic, aggregation });
137
+ }
138
+
65
139
  /**
66
140
  * Returns XML 3DX curve converter function
67
141
  */
@@ -87,6 +161,10 @@ export namespace funcs {
87
161
  return await grok.functions.call('Curves:PreviewPzfx', { file });
88
162
  }
89
163
 
164
+ /**
165
+ * Open a GraphPad Prism (.pzfx) file as data tables, fitting XY curve tables.
166
+ * @param {any} bytes - Raw bytes of the .pzfx file
167
+ */
90
168
  export async function pzfxFileHandler(bytes: any ): Promise<any> {
91
169
  return await grok.functions.call('Curves:PzfxFileHandler', { bytes });
92
170
  }
@@ -7,7 +7,14 @@ import './tests/converter-tests';
7
7
  import './tests/curves-cell-renderer-tests';
8
8
  import './tests/transform-tests';
9
9
  import './tests/fit-tests';
10
+ import './tests/statistics-tests';
10
11
  import './tests/pzfx-tests';
12
+ import './tests/calculated-columns-tests';
13
+ import './tests/panel-renderer-tests';
14
+ import './tests/multi-curve-viewer-tests';
15
+ import './tests/legend-tests';
16
+ import './tests/fit-cache-tests';
17
+ import './tests/project-tests';
11
18
 
12
19
  export const _package = new DG.Package();
13
20
  export {tests};