@datagrok/curves 1.12.1 → 1.13.0

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 +7963 -4867
  5. package/dist/package-test.js.map +1 -1
  6. package/dist/package.js +3411 -2024
  7. package/dist/package.js.map +1 -1
  8. package/files/demo/Assay_Curves.csv +43 -43
  9. package/package.json +5 -4
  10. package/scripts/calculateMSR.py +16 -7
  11. package/src/fit/curve-converter.ts +8 -1
  12. package/src/fit/data-to-curves.ts +10 -5
  13. package/src/fit/fit-chart-data.ts +323 -0
  14. package/src/fit/fit-grid-cell-handler.ts +98 -231
  15. package/src/fit/fit-inspection.ts +3 -3
  16. package/src/fit/fit-interaction.ts +181 -0
  17. package/src/fit/fit-layout.ts +64 -0
  18. package/src/fit/fit-legend.ts +292 -0
  19. package/src/fit/fit-options.ts +222 -0
  20. package/src/fit/fit-parser.ts +16 -5
  21. package/src/fit/fit-renderer.ts +180 -469
  22. package/src/fit/fit-statistics.ts +154 -0
  23. package/src/fit/multi-curve-viewer.ts +46 -20
  24. package/src/fit/render-utils.ts +208 -150
  25. package/src/package-api.ts +92 -14
  26. package/src/package-test.ts +6 -0
  27. package/src/package.g.ts +70 -15
  28. package/src/package.ts +121 -15
  29. package/src/tests/calculated-columns-tests.ts +299 -0
  30. package/src/tests/converter-tests.ts +29 -0
  31. package/src/tests/curve-data.ts +82 -0
  32. package/src/tests/fit-cache-tests.ts +128 -0
  33. package/src/tests/fit-tests.ts +310 -3
  34. package/src/tests/legend-tests.ts +243 -0
  35. package/src/tests/multi-curve-viewer-tests.ts +100 -0
  36. package/src/tests/panel-renderer-tests.ts +502 -0
  37. package/src/tests/project-tests.ts +99 -0
  38. package/src/tests/transform-tests.ts +3 -2
  39. package/test-console-output-1.log +357 -110
  40. package/test-record-1.mp4 +0 -0
@@ -0,0 +1,292 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import * as ui from 'datagrok-api/ui';
3
+
4
+ import {IFitChartData, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
5
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
+ import {ColorType, getSeriesColor} from './render-utils';
7
+ import {isLegendShown} from './fit-layout';
8
+
9
+ /** Whether the curves get named at all: the plot has to have room for it, and it can be turned off. */
10
+ export function isLegendVisible(data: IFitChartData, screenBounds: DG.Rect): boolean {
11
+ return (data.chartOptions?.showLegend ?? true) && isLegendShown(screenBounds);
12
+ }
13
+
14
+ /** A legend row: one curve, or the name of a column that holds several of them. */
15
+ export interface LegendEntry {
16
+ text: string;
17
+ color: string;
18
+ column?: string;
19
+ pointColor?: string;
20
+ marker?: DG.MARKER_TYPE;
21
+ }
22
+
23
+ interface LegendRow {
24
+ entry: LegendEntry;
25
+ /** What is drawn, shortened to the width the legend allows itself. */
26
+ shown: string;
27
+ box: DG.Rect;
28
+ }
29
+
30
+ const LEGEND_FONT = '11px Roboto, "Roboto Local"';
31
+ /** The legend annotates the plot, so it may not take more than a corner of it. */
32
+ const MAX_LEGEND_WIDTH_FRACTION = 0.55;
33
+ const MAX_LEGEND_HEIGHT_FRACTION = 0.5;
34
+ const LEGEND_PX_PADDING = 3;
35
+ const CORNER_PX_INSET = 4;
36
+ /** Ink this close to a corner still crowds it, which is what tells a free corner from a tight one. */
37
+ const CORNER_PX_CLEARANCE = 14;
38
+ /** Below this a corner counts as free enough, so a stray point cannot move the legend. */
39
+ const CORNER_FREE_ENOUGH = 2;
40
+ /** Once a name is shown whole it takes this much crowding to start shortening it, so that resizing
41
+ * a cell by a few pixels does not flip the legend between the two. */
42
+ const NAME_STICKY_CROWDING = 12;
43
+ const LEGEND_BACKGROUND = 'rgba(255, 255, 255, 0.75)';
44
+ /** The hover may fill most of the window; a tooltip taller than that is off the screen anyway. */
45
+ const TOOLTIP_HEIGHT_FRACTION = 0.75;
46
+ /** A row of a listed legend is a label; the whole of a name is what hovering that one row is for. */
47
+ const MAX_TOOLTIP_ROW_PX = 400;
48
+
49
+ /** How many rows the hover lists before it counts the rest instead. */
50
+ export function maxTooltipRows(): number {
51
+ return Math.max(10, Math.floor(window.innerHeight * TOOLTIP_HEIGHT_FRACTION /
52
+ FitConstants.LEGEND_RECORD_PX_HEIGHT));
53
+ }
54
+
55
+ let measureCanvas: CanvasRenderingContext2D | undefined;
56
+ const lastLayout = new WeakMap<IFitChartData, {box: DG.Rect, rows: LegendRow[], moreBox?: DG.Rect,
57
+ entries: LegendEntry[], corner: number, whole: boolean}>();
58
+
59
+ /** A context of its own, so a row can be measured while hit testing, which has no canvas to draw on. */
60
+ function measure(text: string): number {
61
+ measureCanvas ??= document.createElement('canvas').getContext('2d')!;
62
+ measureCanvas.font = LEGEND_FONT;
63
+ return measureCanvas.measureText(text).width;
64
+ }
65
+
66
+ function ellipsize(text: string, maxWidth: number): string {
67
+ if (measure(text) <= maxWidth)
68
+ return text;
69
+ let trimmed = text;
70
+ while (trimmed.length > 1 && measure(`${trimmed}…`) > maxWidth)
71
+ trimmed = trimmed.slice(0, -1);
72
+ return `${trimmed}…`;
73
+ }
74
+
75
+ /** The marker a series draws its points with, which is what makes a legend row recognizable. */
76
+ function seriesMarker(series: IFitSeries): DG.MARKER_TYPE {
77
+ const first = series.points?.length ? series.points[0].marker : null;
78
+ const shared = series.points?.every((p) => p.marker === first && p.marker != null) ? first : null;
79
+ return (shared ?? series.markerType ?? DG.MARKER_TYPE.CIRCLE) as DG.MARKER_TYPE;
80
+ }
81
+
82
+ function legendName(series: IFitSeries, useAuxLegendNames?: boolean): string | undefined {
83
+ const name = useAuxLegendNames ? series.auxLegendName ?? series.name : series.name;
84
+ return name === '' || name === null ? undefined : name;
85
+ }
86
+
87
+ /** The rows the legend would draw, in order. Colors are taken by the series' own index, so a row
88
+ * matches the curve it names. */
89
+ export function legendEntries(data: IFitChartData): LegendEntry[] {
90
+ const series = data.series ?? [];
91
+ const columns = [...new Set(series.map((s) => s.columnName))].filter((name) => name !== null && name !== undefined);
92
+ const entries: LegendEntry[] = [];
93
+ for (const column of columns) {
94
+ const inColumn = series.map((s, idx) => ({series: s, idx}))
95
+ .filter(({series}) => series.columnName === column && legendName(series, data.chartOptions?.useAuxLegendNames));
96
+ if (inColumn.length === 0)
97
+ continue;
98
+ // a column holding a single curve says nothing that the curve's own row does not
99
+ if (data.chartOptions?.showColumnLabel && inColumn.length > 1)
100
+ entries.push({text: column!, color: 'black'});
101
+ for (const {series, idx} of inColumn) {
102
+ entries.push({text: legendName(series, data.chartOptions?.useAuxLegendNames)!, column: column,
103
+ color: getSeriesColor(series, idx, ColorType.FIT_LINE),
104
+ pointColor: getSeriesColor(series, idx, ColorType.POINT), marker: seriesMarker(series)});
105
+ }
106
+ }
107
+
108
+ // one name in two columns identifies nothing on its own; the same name twice in one column would
109
+ // only get the same prefix twice, so it is left as the data has it
110
+ const columnsByName = new Map<string, Set<string>>();
111
+ for (const entry of entries.filter((e) => e.marker !== undefined && e.column))
112
+ (columnsByName.get(entry.text) ?? columnsByName.set(entry.text, new Set()).get(entry.text)!).add(entry.column!);
113
+ for (const entry of entries) {
114
+ if (entry.marker !== undefined && entry.column && columnsByName.get(entry.text)!.size > 1)
115
+ entry.text = `${entry.column}: ${entry.text}`;
116
+ }
117
+ return entries;
118
+ }
119
+
120
+ /** How far a point is from a box, 0 when inside it. */
121
+ function distanceTo(box: DG.Rect, p: DG.Point): number {
122
+ const dx = Math.max(box.x - p.x, 0, p.x - box.maxX);
123
+ const dy = Math.max(box.y - p.y, 0, p.y - box.maxY);
124
+ return Math.sqrt(dx * dx + dy * dy);
125
+ }
126
+
127
+ /** How much ink a corner has to live with: what falls inside it, or close enough to crowd it. */
128
+ export function cornerCrowding(corner: DG.Rect, drawnAt?: DG.Point[]): number {
129
+ if (!drawnAt?.length)
130
+ return 0;
131
+ const near = corner.inflate(CORNER_PX_CLEARANCE, CORNER_PX_CLEARANCE);
132
+ return drawnAt.filter((p) => near.contains(p.x, p.y)).length;
133
+ }
134
+
135
+ /** The corner the legend takes. The top right one unless another is clearly emptier, so that the
136
+ * legend does not hop about as rows are hovered or the grid scrolls. */
137
+ export function chooseLegendCorner(dataBox: DG.Rect, width: number, height: number,
138
+ drawnAt?: DG.Point[], previous?: number): {rect: DG.Rect, index: number} {
139
+ const corners = [
140
+ new DG.Rect(dataBox.maxX - width - CORNER_PX_INSET, dataBox.y + CORNER_PX_INSET, width, height),
141
+ new DG.Rect(dataBox.x + CORNER_PX_INSET, dataBox.y + CORNER_PX_INSET, width, height),
142
+ new DG.Rect(dataBox.maxX - width - CORNER_PX_INSET, dataBox.maxY - height - CORNER_PX_INSET, width, height),
143
+ new DG.Rect(dataBox.x + CORNER_PX_INSET, dataBox.maxY - height - CORNER_PX_INSET, width, height),
144
+ ];
145
+ // where it already is, or the top right one to begin with
146
+ const held = previous ?? 0;
147
+ if (!drawnAt?.length)
148
+ return {rect: corners[held], index: held};
149
+ const room = corners.map((corner) => ({taken: cornerCrowding(corner, drawnAt),
150
+ clearance: Math.min(...drawnAt.map((p) => distanceTo(corner, p)))}));
151
+ // among corners the curves crowd equally, the one they keep furthest away
152
+ let best = 0;
153
+ for (let i = 1; i < corners.length; i++) {
154
+ if (room[i].taken < room[best].taken ||
155
+ (room[i].taken === room[best].taken && room[i].clearance > room[best].clearance))
156
+ best = i;
157
+ }
158
+ return room[held].taken <= CORNER_FREE_ENOUGH || room[best].taken * 2 >= room[held].taken ?
159
+ {rect: corners[held], index: held} : {rect: corners[best], index: best};
160
+ }
161
+
162
+ /** Where each row goes, in the corner the curves leave freest. */
163
+ function legendLayout(data: IFitChartData, dataBox: DG.Rect, ratio: number,
164
+ drawnAt?: DG.Point[]): {rows: LegendRow[], hidden: number, moreBox?: DG.Rect, entries: LegendEntry[],
165
+ corner: number, whole: boolean} {
166
+ const previous = lastLayout.get(data);
167
+ const entries = legendEntries(data);
168
+ if (entries.length === 0)
169
+ return {rows: [], hidden: 0, entries: entries, corner: 0, whole: true};
170
+
171
+ const glyph = glyphWidth(ratio);
172
+ if (dataBox.width * MAX_LEGEND_WIDTH_FRACTION - glyph <= 0)
173
+ return {rows: [], hidden: 0, entries: entries, corner: 0, whole: true};
174
+
175
+ const fits = Math.floor(dataBox.height * MAX_LEGEND_HEIGHT_FRACTION / FitConstants.LEGEND_RECORD_PX_HEIGHT);
176
+ // the last row goes to saying how much was left out, rather than to one more curve out of many
177
+ const drawn = entries.length > fits ? entries.slice(0, Math.max(1, fits - 1)) : entries;
178
+ const hidden = entries.length - drawn.length;
179
+ const height = FitConstants.LEGEND_RECORD_PX_HEIGHT * (drawn.length + (hidden > 0 ? 1 : 0));
180
+
181
+ // a name is worth showing whole when the corner it would go in has the room to spare; the cap is
182
+ // for the charts where it does not
183
+ const natural = Math.min(glyph + Math.max(...drawn.map((entry) => measure(entry.text)),
184
+ hidden > 0 ? measure(`+${hidden} more`) : 0), dataBox.width - 2 * CORNER_PX_INSET);
185
+ const naturalCorner = chooseLegendCorner(dataBox, natural, height, drawnAt, previous?.corner);
186
+ // what it took to shorten the name last time, so a few pixels of resizing do not flip it back
187
+ const endures = previous?.whole ? NAME_STICKY_CROWDING : CORNER_FREE_ENOUGH;
188
+ const whole = cornerCrowding(naturalCorner.rect, drawnAt) <= endures;
189
+ const allowed = whole ? natural : Math.min(natural, dataBox.width * MAX_LEGEND_WIDTH_FRACTION);
190
+
191
+ const shown = drawn.map((entry) => ellipsize(entry.text, allowed - glyph));
192
+ const width = glyph + Math.max(...shown.map(measure));
193
+ const pick = whole ? naturalCorner : chooseLegendCorner(dataBox, width, height, drawnAt, previous?.corner);
194
+ const block = pick.rect;
195
+ const rows: LegendRow[] = drawn.map((entry, i) => ({entry: entry, shown: shown[i],
196
+ box: new DG.Rect(block.x, block.y + FitConstants.LEGEND_RECORD_PX_HEIGHT * i,
197
+ width, FitConstants.LEGEND_RECORD_PX_HEIGHT)}));
198
+ const moreBox = hidden === 0 ? undefined : new DG.Rect(block.x,
199
+ block.y + FitConstants.LEGEND_RECORD_PX_HEIGHT * rows.length, width, FitConstants.LEGEND_RECORD_PX_HEIGHT);
200
+ return {rows: rows, hidden: hidden, moreBox: moreBox, entries: entries, corner: pick.index, whole: whole};
201
+ }
202
+
203
+ function glyphWidth(ratio: number): number {
204
+ return Math.floor(FitConstants.POINT_PX_SIZE * ratio * 1.5) + FitConstants.LEGEND_RECORD_LINE_PX_WIDTH +
205
+ FitConstants.LEGEND_RECORD_LINE_RIGHT_PX_MARGIN;
206
+ }
207
+
208
+ /** The line and the marker that say which curve a row names. */
209
+ function drawGlyph(g: CanvasRenderingContext2D, entry: LegendEntry, x: number, middle: number, ratio: number): void {
210
+ if (entry.marker === undefined)
211
+ return;
212
+ const markerSize = Math.floor(FitConstants.POINT_PX_SIZE * ratio * 1.5);
213
+ g.beginPath();
214
+ g.strokeStyle = entry.color;
215
+ g.lineWidth = 2 * ratio;
216
+ g.moveTo(x + markerSize, middle);
217
+ g.lineTo(x + markerSize + FitConstants.LEGEND_RECORD_LINE_PX_WIDTH, middle);
218
+ g.stroke();
219
+ DG.Paint.marker(g, entry.marker, x + markerSize / 2, middle, entry.pointColor!, markerSize);
220
+ }
221
+
222
+ /** The legend as a tooltip: the same glyphs and names, for what the plot had no room to say. */
223
+ export function legendTooltipElement(entries: LegendEntry[]): HTMLElement {
224
+ // hovering one row is there to give back the whole of a name the plot shortened, so it is said in
225
+ // full however long; a list of many is a legend, and a legend's rows are labels
226
+ const whole = entries.length === 1;
227
+ const shown = entries.slice(0, maxTooltipRows());
228
+ const rows = shown.map((entry) => {
229
+ const canvas = ui.canvas(glyphWidth(1), FitConstants.LEGEND_RECORD_PX_HEIGHT);
230
+ drawGlyph(canvas.getContext('2d')!, entry, 0, FitConstants.LEGEND_RECORD_PX_HEIGHT / 2, 1);
231
+ const row = ui.divH([canvas, ui.divText(whole ? entry.text : ellipsize(entry.text, MAX_TOOLTIP_ROW_PX),
232
+ {style: {color: entry.color}})]);
233
+ row.style.alignItems = 'center';
234
+ return row;
235
+ });
236
+ if (entries.length > shown.length)
237
+ rows.push(ui.divText(`+${entries.length - shown.length} more`));
238
+ return ui.divV(rows);
239
+ }
240
+
241
+ /** Draws the legend in the corner of the plot, over a backdrop so the curves underneath
242
+ * do not make it unreadable. */
243
+ export function renderLegend(g: CanvasRenderingContext2D, data: IFitChartData, dataBox: DG.Rect, ratio: number,
244
+ drawnAt?: DG.Point[]): void {
245
+ const layout = legendLayout(data, dataBox, ratio, drawnAt);
246
+ const {rows, hidden} = layout;
247
+ if (rows.length === 0)
248
+ return;
249
+ // hovering happens long after the chart was drawn, and only the render knows which corner it chose
250
+ lastLayout.set(data, {box: dataBox, rows: rows, moreBox: layout.moreBox, entries: layout.entries,
251
+ corner: layout.corner, whole: layout.whole});
252
+
253
+ g.save();
254
+ g.font = LEGEND_FONT;
255
+ // the axes labels rendered just before leave textAlign centred
256
+ g.textAlign = 'left';
257
+ const block = rows[0].box;
258
+ const height = FitConstants.LEGEND_RECORD_PX_HEIGHT * (rows.length + (hidden > 0 ? 1 : 0));
259
+ g.fillStyle = LEGEND_BACKGROUND;
260
+ g.fillRect(block.x - LEGEND_PX_PADDING, block.y - LEGEND_PX_PADDING,
261
+ block.width + 2 * LEGEND_PX_PADDING, height + 2 * LEGEND_PX_PADDING);
262
+
263
+ for (const row of rows) {
264
+ const baseline = row.box.maxY - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN;
265
+ drawGlyph(g, row.entry, row.box.x, baseline - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN, ratio);
266
+ g.fillStyle = row.entry.color;
267
+ g.fillText(row.shown, row.box.x + (row.entry.marker === undefined ? 0 : glyphWidth(ratio)), baseline);
268
+ }
269
+
270
+ if (hidden > 0) {
271
+ g.fillStyle = 'black';
272
+ g.fillText(`+${hidden} more`, block.x, rows[rows.length - 1].box.maxY +
273
+ FitConstants.LEGEND_RECORD_PX_HEIGHT - FitConstants.LEGEND_RECORD_LINE_BOTTOM_PX_MARGIN);
274
+ }
275
+ g.restore();
276
+ }
277
+
278
+ /** What the legend could not say at that point: the whole of a shortened name, or the whole legend
279
+ * when the pointer is on the row counting what did not fit. */
280
+ export function legendTooltip(data: IFitChartData, dataBox: DG.Rect, x: number,
281
+ y: number): LegendEntry[] | null {
282
+ const last = lastLayout.get(data);
283
+ // the same data is drawn in the grid and in the enlarged chart, so the rows only apply to the plot
284
+ // they were laid out for
285
+ if (!last || Math.round(last.box.x) !== Math.round(dataBox.x) ||
286
+ Math.round(last.box.width) !== Math.round(dataBox.width))
287
+ return null;
288
+ if (last.moreBox?.contains(x, y))
289
+ return last.entries;
290
+ const row = last.rows.find((r) => r.box.contains(x, y));
291
+ return row && row.shown !== row.entry.text ? [row.entry] : null;
292
+ }
@@ -0,0 +1,222 @@
1
+ /* eslint-disable max-len */
2
+ import * as DG from 'datagrok-api/dg';
3
+ import * as grok from 'datagrok-api/grok';
4
+
5
+ import {getSeriesFitFunction} from '@datagrok-libraries/statistics/src/fit/fit-data';
6
+ import {
7
+ fitChartDataProperties,
8
+ IFitChartData,
9
+ IFitSeries,
10
+ IFitFunctionDescription,
11
+ } from '@datagrok-libraries/statistics/src/fit/fit-curve';
12
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
13
+ import {fitFunctions, fitFunctionDescriptions, fitSeriesProperties, getStatisticProperty, DEFAULT_FIT_FUNCTION} from '@datagrok-libraries/statistics/src/fit/fit-engine';
14
+ import {getColumnChartOptions, getDataFrameChartOptions, CHART_OPTIONS, SERIES_OPTIONS} from './fit-chart-data';
15
+ import {isNativeFormat} from './curve-converter';
16
+
17
+ // Options a statistic can depend on; everything else only repaints. errorModel weights the objective
18
+ // function; mergeSeries does not, since the statistics read the original series.
19
+ const STATISTIC_AFFECTING_OPTIONS = ['logX', 'logY', 'allowXZeroes', 'fitFunction', 'errorModel'];
20
+
21
+ export enum MANIPULATION_LEVEL {
22
+ DATAFRAME = 'Dataframe',
23
+ COLUMN = 'Column',
24
+ CELL = 'Cell'
25
+ }
26
+
27
+ export type ManipulationLevel = `${MANIPULATION_LEVEL}`;
28
+ export type OptionsSection = typeof CHART_OPTIONS | typeof SERIES_OPTIONS;
29
+
30
+ /** Label names this cell carries, plot-level ones first. */
31
+ function labelNames(chartData: IFitChartData): string[] {
32
+ const names = Object.keys(chartData.chartOptions?.labels ?? {});
33
+ for (const series of chartData.series ?? []) {
34
+ for (const name of Object.keys(series.labels ?? {})) {
35
+ if (!names.includes(name))
36
+ names.push(name);
37
+ }
38
+ }
39
+ return names;
40
+ }
41
+
42
+ /** Chart properties with `showStatistics` and `showLabels` offering what this cell actually carries. */
43
+ export function chartPropertiesFor(chartData: IFitChartData): DG.Property[] {
44
+ const names: string[] = [];
45
+ for (const series of chartData.series ?? []) {
46
+ for (const prop of getSeriesFitFunction(series).statisticsProperties) {
47
+ if (!names.includes(prop.name))
48
+ names.push(prop.name);
49
+ }
50
+ }
51
+ const labels = labelNames(chartData);
52
+ // an option with nothing to choose from is an empty row in the panel, and a single curve has
53
+ // nothing to summarise
54
+ const several = (chartData.series?.length ?? 0) > 1;
55
+ return fitChartDataProperties.filter((p) => (p.name !== 'showLabels' || labels.length > 0) &&
56
+ ((p.name !== 'statisticsMode' && p.name !== 'aggrType') || several)).map((p) => {
57
+ if (p.name === 'showStatistics' && names.length > 0) {
58
+ return DG.Property.js('showStatistics', DG.TYPE.STRING_LIST, {description: p.description, choices: names,
59
+ inputType: 'MultiChoice', friendlyName: 'Statistics'});
60
+ }
61
+ if (p.name === 'showLabels') {
62
+ return DG.Property.js('showLabels', DG.TYPE.STRING_LIST, {description: p.description, choices: labels,
63
+ inputType: 'MultiChoice', friendlyName: 'Labels'});
64
+ }
65
+ return p;
66
+ });
67
+ }
68
+
69
+ /** Maps stored statistic names onto the current ones, so `interceptX` still ticks the `ic50` box. */
70
+ export function normalizeStatisticNames(chartData: IFitChartData, names: string[]): string[] {
71
+ const resolved: string[] = [];
72
+ for (const name of names) {
73
+ let mapped = name;
74
+ for (const series of chartData.series ?? []) {
75
+ const prop = getStatisticProperty(getSeriesFitFunction(series), name);
76
+ if (prop) {
77
+ mapped = prop.name;
78
+ break;
79
+ }
80
+ }
81
+ if (!resolved.includes(mapped))
82
+ resolved.push(mapped);
83
+ }
84
+ return resolved;
85
+ }
86
+
87
+ /** Series properties with `fitFunction` naming every registered function, custom ones included. */
88
+ export function seriesPropertiesFor(chartData: IFitChartData,
89
+ customFitFunction: IFitFunctionDescription | null): DG.Property[] {
90
+ // columnName is stamped by the render, not chosen; an ICxx name only resolves for a curve that
91
+ // levels off at both ends
92
+ const properties = fitSeriesProperties.filter((p) => p.name !== 'columnName')
93
+ .filter((p) => p.name !== 'droplines' ||
94
+ (chartData.series ?? []).some((series) => getSeriesFitFunction(series).hasAsymptotes));
95
+ // a custom function registers itself the first time it is used, so the registry is what there is to
96
+ // pick from - read here rather than off fitSeriesProperties, which captured it before any registered
97
+ const choices = [...new Set([...(customFitFunction ? [customFitFunction.name] : []),
98
+ ...Object.keys(fitFunctions)])];
99
+ return properties.map((p) => p.name !== 'fitFunction' ? p :
100
+ DG.Property.js('fitFunction', DG.TYPE.STRING, {category: 'Fitting', choices: choices,
101
+ nullable: false, defaultValue: customFitFunction?.name ?? DEFAULT_FIT_FUNCTION}));
102
+ }
103
+
104
+ /** Records that the user set this option here, so it outranks the value the data declares. */
105
+ function claim(chartData: IFitChartData, options: OptionsSection, propertyName: string): void {
106
+ const names = ((chartData.explicit ??= {})[options] ??= []);
107
+ if (!names.includes(propertyName))
108
+ names.push(propertyName);
109
+ }
110
+
111
+ /** Drops the claim, leaving the value. Returns whether anything was claimed. */
112
+ function unclaim(chartData: IFitChartData, options: OptionsSection, propertyName: string): boolean {
113
+ const names = chartData.explicit?.[options];
114
+ if (!names?.includes(propertyName))
115
+ return false;
116
+ names.splice(names.indexOf(propertyName), 1);
117
+ return true;
118
+ }
119
+
120
+ /** A custom fit function is stored as the notation that describes it, not as its name: the name only
121
+ * resolves while something else in the session carries the function, which a saved table may not. */
122
+ function storedValue(propertyName: string, value: any): any {
123
+ return propertyName === 'fitFunction' && typeof value === 'string' && fitFunctionDescriptions[value] ?
124
+ fitFunctionDescriptions[value] : value;
125
+ }
126
+
127
+ function changePlotOptions(chartData: IFitChartData, inputBase: DG.InputBase, options: OptionsSection): void {
128
+ const propertyName = inputBase.property.name as string;
129
+ const value = storedValue(propertyName, inputBase.value);
130
+ if (options === CHART_OPTIONS) {
131
+ if (chartData.chartOptions === undefined) return;
132
+ (chartData.chartOptions as any)[propertyName] = value;
133
+ } else {
134
+ if (chartData.series === undefined) return;
135
+ for (const series of chartData.series)
136
+ (series as IFitSeries as any)[propertyName] = value;
137
+ }
138
+ claim(chartData, options, propertyName);
139
+ }
140
+
141
+ export function changeCurvesOptions(gridCell: DG.GridCell, inputBase: DG.InputBase, options: OptionsSection,
142
+ manipulationLevel: ManipulationLevel): void {
143
+ const propertyName = inputBase.property.name as string;
144
+ const affectsStatistics = STATISTIC_AFFECTING_OPTIONS.includes(propertyName);
145
+
146
+ if (manipulationLevel === MANIPULATION_LEVEL.CELL) {
147
+ if (!isNativeFormat(gridCell.cell.column))
148
+ return;
149
+ const value = gridCell.cell.value;
150
+ if (value === '') return;
151
+ let chartData: IFitChartData;
152
+ try {
153
+ chartData = JSON.parse(value ?? '{}') ?? {};
154
+ } catch (e) {
155
+ grok.shell.error(`Curves: this cell holds malformed data, so the option was not applied: ${e}`);
156
+ return;
157
+ }
158
+ changePlotOptions(chartData, inputBase, options);
159
+ // notifying carries this row's index, so only its statistic recalculates - worth it when the
160
+ // option can change one, wasted work when it cannot
161
+ gridCell.cell.column.set(gridCell.cell.rowIndex, JSON.stringify(chartData), affectsStatistics);
162
+ if (!affectsStatistics)
163
+ gridCell.cell.dataFrame.fireValuesChanged();
164
+ gridCell.grid.invalidate();
165
+ return;
166
+ }
167
+
168
+ const chartOptions = manipulationLevel === MANIPULATION_LEVEL.DATAFRAME ?
169
+ getDataFrameChartOptions(gridCell.cell.dataFrame) : getColumnChartOptions(gridCell.cell.column);
170
+ ((chartOptions[options] ??= {}) as any)[propertyName] = storedValue(propertyName, inputBase.value);
171
+ claim(chartOptions, options, propertyName);
172
+
173
+ let columns: DG.Column[];
174
+ if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
175
+ gridCell.cell.dataFrame.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
176
+ columns = gridCell.cell.dataFrame.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE);
177
+ } else {
178
+ gridCell.cell.column.tags[FitConstants.TAG_FIT] = JSON.stringify(chartOptions);
179
+ columns = [gridCell.cell.column];
180
+ }
181
+
182
+ for (const column of columns) {
183
+ if (manipulationLevel === MANIPULATION_LEVEL.DATAFRAME) {
184
+ const columnChartOptions = getColumnChartOptions(column);
185
+ const section = columnChartOptions[options];
186
+ if (section)
187
+ delete (section as any)[propertyName];
188
+ unclaim(columnChartOptions, options, propertyName);
189
+ column.tags[FitConstants.TAG_FIT] = JSON.stringify(columnChartOptions);
190
+ }
191
+ if (!isNativeFormat(column))
192
+ continue;
193
+
194
+ // only the claim is dropped, and silently - a rewrite reads as a data change and would
195
+ // recalculate every dependent statistic column. The notification below is the deliberate one.
196
+ for (let j = 0; j < column.length; j++) {
197
+ const value = column.get(j);
198
+ if (value === '')
199
+ continue;
200
+ let chartData: IFitChartData;
201
+ // a malformed row keeps whatever it has rather than aborting the sweep with the tag already written
202
+ try {
203
+ chartData = (JSON.parse(value) ?? {}) as IFitChartData;
204
+ } catch (_) {
205
+ continue;
206
+ }
207
+ if (unclaim(chartData, options, propertyName))
208
+ column.set(j, JSON.stringify(chartData), false);
209
+ }
210
+ }
211
+
212
+ // the option lives in a tag, so nothing else marks the curve column changed
213
+ if (affectsStatistics) {
214
+ for (const column of columns)
215
+ column.fireValuesChanged();
216
+ }
217
+ // nothing has marked the table modified yet: a tag write raises metadata, not data. Carrying no
218
+ // column keeps the calculated columns' subscription, which filters on one, from firing.
219
+ if (!affectsStatistics)
220
+ gridCell.cell.dataFrame.fireValuesChanged();
221
+ gridCell.grid.invalidate();
222
+ }
@@ -1,5 +1,6 @@
1
1
  import * as DG from 'datagrok-api/dg';
2
2
 
3
+ import {fitFunctions} from '@datagrok-libraries/statistics/src/fit/fit-engine';
3
4
  import {
4
5
  IFitChartData,
5
6
  IFitChartOptions,
@@ -7,12 +8,18 @@ import {
7
8
  IFitSeries,
8
9
  IFitPoint,
9
10
  FIT_FUNCTION_SIGMOID,
11
+ FitFunctionName,
10
12
  } from '@datagrok-libraries/statistics/src/fit/fit-curve';
11
13
 
12
14
 
13
15
  const AXES = {x: 'xAxis', y: 'yAxis'};
14
16
  const EXTREMUMS = {min: 'min', max: 'max'};
15
17
 
18
+ /** XML attributes are strings, so `!!element.getAttribute(name)` is true for "False" as well. */
19
+ function xmlBool(element: Element | undefined, name: string): boolean {
20
+ return element?.getAttribute(name)?.toLowerCase() === 'true';
21
+ }
22
+
16
23
 
17
24
  /** Constructs {@link IFitChartOptions} from grid and settings xml tags.
18
25
  * @param {Element} grid XML grid tag
@@ -28,7 +35,9 @@ function getChartOptions(grid: Element, settings: Element): IFitChartOptions {
28
35
 
29
36
  xAxisName: settings.getAttribute('xLabel')!,
30
37
  yAxisName: settings.getAttribute('yLabel')!,
31
- logX: !!settings.getAttribute('logX')!,
38
+ logX: xmlBool(settings, 'logX'),
39
+ // only when declared, or the key owns it and no Column or Dataframe option can cascade onto it
40
+ ...(settings.getAttribute('logY') !== null ? {logY: xmlBool(settings, 'logY')} : {}),
32
41
  };
33
42
  }
34
43
 
@@ -38,16 +47,18 @@ function getChartOptions(grid: Element, settings: Element): IFitChartOptions {
38
47
  */
39
48
  function getSeriesOptions(series: Element): IFitSeriesOptions {
40
49
  const params = (series.getElementsByTagName('params')[0]?.childNodes[0].nodeValue)?.split(',')!.map(Number)!;
41
- let funcType = series.getElementsByTagName('function')[0]?.getAttribute('type')!;
42
- funcType = !funcType || funcType === 'sigif' ? FIT_FUNCTION_SIGMOID : funcType;
50
+ const declaredType = series.getElementsByTagName('function')[0]?.getAttribute('type');
51
+ // 'sigif' is this format's name for a sigmoid; an unregistered name would render nothing
52
+ const funcType = !declaredType || declaredType === 'sigif' || !(declaredType in fitFunctions) ?
53
+ FIT_FUNCTION_SIGMOID : declaredType;
43
54
  const markerColor = series.getElementsByTagName('settings')[0].getAttribute('markerColor')!;
44
55
  const lineColor = series.getElementsByTagName('settings')[0].getAttribute('color')!;
45
- const drawLine = !!series.getElementsByTagName('settings')[0].getAttribute('drawLine')!;
56
+ const drawLine = xmlBool(series.getElementsByTagName('settings')[0], 'drawLine');
46
57
  const seriesName = series.getAttribute('name')!;
47
58
 
48
59
  const seriesOptions: IFitSeriesOptions = {
49
60
  name: seriesName,
50
- fitFunction: funcType,
61
+ fitFunction: funcType as FitFunctionName,
51
62
  markerType: DG.MARKER_TYPE.CIRCLE,
52
63
  pointColor: markerColor,
53
64
  fitLineColor: lineColor,