@datagrok-libraries/utils 0.0.8 → 0.0.9

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/src/spe.ts DELETED
@@ -1,172 +0,0 @@
1
- import {Options, Coordinates, Vectors, DistanceMetric} from './type_declarations';
2
- import {calculateEuclideanDistance, calcDistanceMatrix, fillRandomMatrix, vectorAdd, randomInt} from './operations';
3
-
4
- /**
5
- * Implements stochastic proximity embedding.
6
- *
7
- * @export
8
- * @class SPEBase
9
- * @link doi:10.1016/S1093-3263(03)00155-4
10
- */
11
- export class SPEBase {
12
- protected static dimension = 2;
13
- protected steps: number;
14
- protected cycles: number;
15
- protected cutoff: number;
16
- protected lambda: number;
17
- protected dlambda: number;
18
- protected lambda2: number;
19
- protected dlambda2: number;
20
- protected epsilon: number;
21
- protected distanceFunction: DistanceMetric;
22
- protected distance: Coordinates;
23
-
24
- /**
25
- * Creates an instance of SPEBase.
26
- * @param {Options} [options] Options to pass to the constructor.
27
- * @memberof SPEBase
28
- */
29
- constructor(options?: Options) {
30
- this.steps = options?.steps ?? 0;
31
- this.cycles = options?.cycles ?? 1e6;
32
- // Select a cutoff distance {cutoff} and ...
33
- this.cutoff = options?.cutoff ?? 0;
34
- // ... an initial learning rate {lambda} > 0
35
- this.lambda = options?.lambda ?? 2.0;
36
- this.dlambda = options?.dlambda ?? 0.01;
37
- this.lambda2 = this.lambda/2.;
38
- this.dlambda2 = this.dlambda/2.;
39
- this.epsilon = options?.epsilon ?? 1e-10;
40
- // eslint-disable-next-line brace-style
41
- this.distanceFunction = options?.distance ?? calculateEuclideanDistance;
42
- this.distance = [];
43
- }
44
-
45
- /**
46
- * Initializes distance matrix.
47
- *
48
- * @protected
49
- * @param {Vectors} vectors Input vectors to calculate distance between.
50
- * @memberof SPEBase
51
- */
52
- protected initDistance(vectors: Vectors) {
53
- this.distance = calcDistanceMatrix(vectors, this.distanceFunction);
54
- }
55
-
56
- /**
57
- * Calculates distance between the two vectors given.
58
- *
59
- * @param {Vectors} vectors Set of vectors to calculate distances between.
60
- * @param {number} index1 Index of the first vector of the pair.
61
- * @param {number} index2 Index of the second vector of the pair.
62
- * @return {number} Distance between these two vectors.
63
- */
64
- protected calcDistance(vectors: Vectors, index1: number, index2: number): number {
65
- return this.distance[index1][index2];
66
- }
67
-
68
- /**
69
- * Embeds the vectors given into a two-dimensional space.
70
- *
71
- * @param {Vectors} vectors D-dimensional coordinates.
72
- * @return {Coordinates} SPE coordinates in D space.
73
- */
74
- public embed(vectors: Vectors): Coordinates {
75
- const nItems = vectors.length;
76
- const areaWidth = 40;
77
- // Initialize the D-dimensional coordinates of the N points.
78
- const coordinates = fillRandomMatrix(nItems, SPEBase.dimension, areaWidth);
79
-
80
- let lambda2 = this.lambda2;
81
-
82
- if (this.steps == 0) {
83
- this.steps = vectors.length-1;
84
- }
85
-
86
- this.initDistance(vectors);
87
-
88
- for (let cycle = 0; cycle < this.cycles; ++cycle) {
89
- for (let step = 0; step < this.steps; ++step) {
90
- // Select two points, i and j, at random, ...
91
- const i = randomInt(nItems); let j = randomInt(nItems);
92
- while (i == j) j = randomInt(nItems);
93
-
94
- const rowi = coordinates[i]; const rowj = coordinates[j];
95
-
96
- // ... retrieve (or evaluate) their proximity in the input space, rij and ...
97
- const r = this.calcDistance(vectors, i, j);
98
- // ... compute their Euclidean distance on the D-dimensional map, dij.
99
- const d = calculateEuclideanDistance(rowi, rowj);
100
-
101
- // If rij <= rc, or if rij > rc and dij < rij ...
102
- if ((this.cutoff == 0) || (r <= this.cutoff) || (d < r)) {
103
- const multiplier = lambda2*(r-d)/(d+this.epsilon);
104
- // ... update the coordinates xi and xj.
105
- const diffIJ = vectorAdd(rowi, rowj, -1);
106
- coordinates[i] = vectorAdd(rowi, diffIJ, multiplier);
107
- coordinates[j] = vectorAdd(rowj, diffIJ, -multiplier);
108
- }
109
- }
110
- // Decrease the learning rate {lambda} by a prescribed {dlambda}.
111
- lambda2 -= this.dlambda2;
112
- if (lambda2 <= 0.) {
113
- break;
114
- }
115
- }
116
- return coordinates;
117
- }
118
- }
119
-
120
- /**
121
- * Implements modified stochastic proximity embedding.
122
- *
123
- * @export
124
- * @class PSPEBase
125
- * @link doi:10.1016/S1093-3263(03)00155-4
126
- */
127
- export class PSPEBase extends SPEBase {
128
- /**
129
- * Embeds the vectors given into a two-dimensional space using a modified update rule.
130
- *
131
- * @param {Vectors} vectors D-dimensional coordinates.
132
- * @return {Coordinates} SPE coordinates in D space.
133
- */
134
- public embed(vectors: Vectors): Coordinates {
135
- const nItems = vectors.length;
136
- const areaWidth = 40;
137
- // Initialize the D-dimensional coordinates of the N points.
138
- const coordinates = fillRandomMatrix(nItems, PSPEBase.dimension, areaWidth);
139
- let lambda = this.lambda;
140
-
141
- this.initDistance(vectors);
142
-
143
- for (let cycle = 0; cycle < this.cycles; ++cycle) {
144
- // Select a point, i, at random (pivot).
145
- const i: number = randomInt(nItems);
146
- const rowi = coordinates[i];
147
-
148
- // For every point j != i ...
149
- for (let j = 0; j < nItems; ++j) {
150
- if (i == j) continue;
151
- const rowj = coordinates[j];
152
- // ... retrieve (or evaluate) its proximity to i in the input space, rij ...
153
- const r = this.calcDistance(vectors, i, j);
154
- // ... and compute their Euclidean distance on the D-dimensional map, dij.
155
- const d = calculateEuclideanDistance(rowi, rowj);
156
- // If rij <= rc, or if rij > rc and dij < rij ...
157
- if ((this.cutoff == 0) || (r <= this.cutoff) || (d < r)) {
158
- const multiplier = lambda*(r-d)/(d+this.epsilon);
159
- const diffIJ = vectorAdd(rowi, rowj, -1);
160
- // ... update the coordinates xj.
161
- coordinates[j] = vectorAdd(rowj, diffIJ, -multiplier);
162
- }
163
- }
164
- // Decrease the learning rate {lambda} by a prescribed {dlambda}.
165
- lambda -= this.dlambda;
166
- if (lambda <= 0.) {
167
- break;
168
- }
169
- }
170
- return coordinates;
171
- }
172
- }
@@ -1,54 +0,0 @@
1
- import * as fl from 'fastest-levenshtein';
2
- import {jaroWinkler} from 'jaro-winkler-typescript';
3
-
4
- import {DistanceMetric} from './type_declarations';
5
- import {assert} from './operations';
6
-
7
- /**
8
- * Unified class implementing the different string measures.
9
- *
10
- * @export
11
- * @class Measurer
12
- */
13
- export class Measurer {
14
- protected method: string;
15
- public static receipt: {[name: string]: DistanceMetric} = {
16
- 'Levenshtein': fl.distance,
17
- 'Jaro-Winkler': jaroWinkler,
18
- };
19
-
20
- /**
21
- * Creates an instance of Measurer.
22
- * @param {string} method Method to calculate distance between strings.
23
- * @memberof Measurer
24
- */
25
- constructor(method: string) {
26
- assert(Measurer.availableMeasures.includes(method), 'The ${method} was not found.')
27
- this.method = method;
28
- }
29
-
30
- /**
31
- * Returns custom string distance function specified.
32
- * @return {DistanceMetric} Callback of the measure chosen.
33
- */
34
- public getMeasure(): DistanceMetric {
35
- return Measurer.receipt[this.method];
36
- }
37
-
38
- /**
39
- * Returns available string distance metrics.
40
- *
41
- * @readonly
42
- * @type {string[]}
43
- * @memberof Measurer
44
- */
45
- public static get availableMeasures() : string[] {
46
- let keys = [];
47
-
48
- for (let key in Measurer.receipt) {
49
- keys.push(key);
50
- }
51
- return keys;
52
- }
53
-
54
- }
@@ -1,8 +0,0 @@
1
- export function tryParseJson(s: string) : any {
2
- try {
3
- return JSON.parse(s);
4
- }
5
- catch (_) {
6
- return null;
7
- }
8
- }
@@ -1,67 +0,0 @@
1
- /* Do not change these import lines. Datagrok will import API library in exactly the same manner */
2
- import * as grok from 'datagrok-api/grok';
3
- import * as ui from 'datagrok-api/ui';
4
- import * as DG from "datagrok-api/dg";
5
-
6
- interface Rule {
7
- column: string;
8
- type: string;
9
- pattern: string;
10
- matcher?: any;
11
- }
12
-
13
- interface RuleSet {
14
- name: string;
15
- rules: Rule[];
16
- }
17
-
18
- // @ts-ignore
19
- let ruleSet: RuleSet = {
20
- name: 'SDTM DM rules',
21
- rules: [
22
- {
23
- column: 'age',
24
- type: 'int',
25
- pattern: '18-90'
26
- },
27
- {
28
- column: 'height',
29
- type: 'numerical',
30
- pattern: '18-90'
31
- },
32
- {
33
- column: 'sex',
34
- type: 'string',
35
- pattern: 'in (F, M)'
36
- },
37
- {
38
- column: 'started',
39
- type: 'datetime',
40
- pattern: '> 1/1/1900'
41
- }
42
- ]
43
- };
44
-
45
- /** Returns error message, or null if valid. */
46
- function validateCell(cell: any, ruleset: RuleSet) : string | null {
47
- let name = cell.column.name.toLowerCase();
48
-
49
- for (let rule of ruleset.rules)
50
- if (rule.column == name) {
51
- rule.matcher = rule.matcher ?? DG.ValueMatcher.forColumn(cell.column, rule.pattern);
52
- let error = rule.matcher.validate(cell.value);
53
- if (error !== null)
54
- return error;
55
- }
56
-
57
- return null;
58
- }
59
-
60
- function main() : void {
61
- console.log('foo');
62
- }
63
-
64
- let cell = {column: { name: 'age' }, value: 999 };
65
- validateCell(cell, ruleSet);
66
-
67
- console.log('ddd');
package/src/test-utils.ts DELETED
@@ -1,97 +0,0 @@
1
- import * as path from "path";
2
- import * as os from "os";
3
- import * as fs from "fs";
4
- // @ts-ignore
5
- import * as yaml from 'js-yaml';
6
- const fetch = require('node-fetch');
7
-
8
- export async function getToken(url: string, key: string) {
9
- let response = await fetch(`${url}/users/login/dev/${key}`, {method: 'POST'});
10
- let json = await response.json();
11
- if (json.isSuccess == true)
12
- return json.token;
13
- else
14
- throw 'Unable to login to server. Check your dev key';
15
- }
16
-
17
- export async function getWebUrl(url: string, token: string) {
18
- let response = await fetch(`${url}/admin/plugins/admin/settings`, {headers: {Authorization: token}});
19
- let json = await response.json();
20
- return json.settings.webRoot;
21
- }
22
-
23
- const grokDir = path.join(os.homedir(), '.grok');
24
- const confPath = path.join(grokDir, 'config.yaml');
25
-
26
- function mapURL(conf: Config): Indexable {
27
- let urls: Indexable = {};
28
- for (let server in conf.servers) {
29
- urls[conf['servers'][server]['url']] = conf['servers'][server];
30
- }
31
- return urls;
32
- }
33
-
34
- export function getDevKey(hostKey: string): {url: string, key: string} {
35
- let config = yaml.load(fs.readFileSync(confPath, 'utf8')) as any;
36
- let host = hostKey == '' ? config.default : hostKey;
37
- host = host.trim();
38
- let urls = mapURL(config);
39
- let key = '';
40
- let url = '';
41
- try {
42
- let url = new URL(host).href;
43
- if (url.endsWith('/')) url = url.slice(0, -1);
44
- if (url in urls) key = config['servers'][urls[url]]['key'];
45
- } catch (error) {
46
- if (config['servers'][host] == null)
47
- throw `Unknown server alias. Please add it to ${confPath}`;
48
- url = config['servers'][host]['url'];
49
- key = config['servers'][host]['key'];
50
- }
51
- return {url, key};
52
- }
53
-
54
- export async function getBrowserPage(puppeteer: any): Promise<{browser: any, page: any}> {
55
- let url:string = process.env.HOST ?? '';
56
- let cfg = getDevKey(url);
57
- url = cfg.url;
58
-
59
- let key = cfg.key;
60
- let token = await getToken(url, key);
61
- url = await getWebUrl(url, token);
62
- console.log(`Using web root: ${url}`);
63
-
64
- let browser = await puppeteer.launch({
65
- args: ['--disable-dev-shm-usage', '--disable-features=site-per-process'],
66
- ignoreHTTPSErrors: true,
67
- });
68
-
69
- let page = await browser.newPage();
70
- await page.goto(`${url}/oauth/`);
71
- await page.setCookie({name: 'auth', value: token});
72
- await page.evaluate((token: any) => {
73
- window.localStorage.setItem('auth', token);
74
- }, token);
75
- await page.goto(url);
76
- try {
77
- await page.waitForSelector('.grok-preloader');
78
- console.log('got preloader');
79
- await page.waitForFunction(() => document.querySelector('.grok-preloader') == null, {timeout: 100000});
80
- } catch (error) {
81
- throw error;
82
- }
83
- return {browser, page};
84
- }
85
-
86
-
87
- interface Config {
88
- servers: {
89
- [alias: string]: {
90
- url: string,
91
- key: string
92
- }
93
- },
94
- default: string,
95
- }
96
-
97
- interface Indexable { [key: string]: any }
@@ -1,54 +0,0 @@
1
- /**
2
- * Denotes a vector of floating poit values.
3
- *
4
- * @export
5
- * @class Vector
6
- * @extends {Float32Array}
7
- */
8
- export class Vector extends Float32Array {}
9
-
10
- /**
11
- * Denotes a two-dimensional matrix.
12
- *
13
- * @export
14
- * @class Matrix
15
- * @extends {Array<Vector>}
16
- */
17
- export class Matrix extends Array<Vector> {}
18
-
19
- /**
20
- * Denotes cartesian coordinates.
21
- *
22
- * @export
23
- * @class Coordinates
24
- * @extends {Matrix}
25
- */
26
- export class Coordinates extends Matrix {}
27
-
28
- /**
29
- * Denotes an array of arbitrary-typed vectors.
30
- *
31
- * @export
32
- * @class Vectors
33
- * @extends {Array<any>}
34
- */
35
- export class Vectors extends Array<any> {}
36
-
37
- /**
38
- * Denotes a dictionary containing function options.
39
- *
40
- * @export
41
- * @type Options
42
- */
43
- export type Options = {[name: string]: any};
44
-
45
- /**
46
- * Denotes custom distance metric between the two given vectors.
47
- *
48
- * @export
49
- * @type DistanceMetric
50
- * @param {any} v1 The first vector.
51
- * @param {any} v2 The second vector.
52
- * @return {number} Distance between these two vectors.
53
- */
54
- export type DistanceMetric = (v1: any, v2: any) => (number);