@aehrc/ecl-core 1.8.0 → 1.9.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.
- package/README.md +59 -5
- package/dist/derive/compress-expression.d.ts +2 -0
- package/dist/derive/compress-expression.d.ts.map +1 -1
- package/dist/derive/derive-ecl.d.ts +62 -3
- package/dist/derive/derive-ecl.d.ts.map +1 -1
- package/dist/derive/refinements.d.ts +1 -1
- package/dist/derive/refinements.d.ts.map +1 -1
- package/dist/derive/set-queries.d.ts +72 -1
- package/dist/derive/set-queries.d.ts.map +1 -1
- package/dist/derive/taxonomy-graph.d.ts +58 -0
- package/dist/derive/taxonomy-graph.d.ts.map +1 -1
- package/dist/index.cjs +1086 -140
- package/dist/index.mjs +1086 -140
- package/dist/terminology/fhir-service.d.ts +49 -0
- package/dist/terminology/fhir-service.d.ts.map +1 -1
- package/dist/terminology/types.d.ts +26 -0
- package/dist/terminology/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -43265,23 +43265,53 @@ var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/e
|
|
|
43265
43265
|
* extension form; undefined when the server sent no parent property at all.
|
|
43266
43266
|
*/
|
|
43267
43267
|
function parentCodes(item) {
|
|
43268
|
+
return propertyCodes(item, "parent");
|
|
43269
|
+
}
|
|
43270
|
+
/** One boolean property of an expansion entry, from R5 `property` or its R4 extension form; undefined when absent. */
|
|
43271
|
+
function propertyBoolean(item, code) {
|
|
43272
|
+
const direct = item.property?.find((p) => p.code === code && typeof p.valueBoolean === "boolean");
|
|
43273
|
+
if (direct) return direct.valueBoolean;
|
|
43274
|
+
for (const ext of item.extension ?? []) {
|
|
43275
|
+
if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
|
|
43276
|
+
const parts = ext.extension ?? [];
|
|
43277
|
+
if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
|
|
43278
|
+
const value = parts.find((x) => x.url === "value")?.valueBoolean;
|
|
43279
|
+
if (typeof value === "boolean") return value;
|
|
43280
|
+
}
|
|
43281
|
+
}
|
|
43282
|
+
/** The codes of one coded property of an expansion entry, or undefined when the entry has none. */
|
|
43283
|
+
function propertyCodes(item, code) {
|
|
43268
43284
|
const codes = [];
|
|
43269
43285
|
let seen = false;
|
|
43270
43286
|
for (const p of item.property ?? []) {
|
|
43271
|
-
if (p.code !==
|
|
43287
|
+
if (p.code !== code) continue;
|
|
43272
43288
|
seen = true;
|
|
43273
43289
|
if (p.valueCode) codes.push(p.valueCode);
|
|
43274
43290
|
}
|
|
43275
43291
|
for (const ext of item.extension ?? []) {
|
|
43276
43292
|
if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
|
|
43277
43293
|
const parts = ext.extension ?? [];
|
|
43278
|
-
if (parts.find((x) => x.url === "code")?.valueCode !==
|
|
43294
|
+
if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
|
|
43279
43295
|
seen = true;
|
|
43280
43296
|
const value = parts.find((x) => x.url === "value")?.valueCode;
|
|
43281
43297
|
if (value) codes.push(value);
|
|
43282
43298
|
}
|
|
43283
43299
|
return seen ? codes : void 0;
|
|
43284
43300
|
}
|
|
43301
|
+
var conceptListCache = /* @__PURE__ */ new WeakMap();
|
|
43302
|
+
/**
|
|
43303
|
+
* `[{"code": ...}, ...]` for a compose's `concept`. Cached for the life of the
|
|
43304
|
+
* list only when the array is frozen, so the text cannot go stale: derive
|
|
43305
|
+
* freezes its member list, which it sends with every comparison, and any other
|
|
43306
|
+
* caller's array is built afresh each time.
|
|
43307
|
+
*/
|
|
43308
|
+
function conceptListJson(codes) {
|
|
43309
|
+
const cached = conceptListCache.get(codes);
|
|
43310
|
+
if (cached !== void 0) return cached;
|
|
43311
|
+
const json = "[" + codes.map((code) => "{\"code\":" + JSON.stringify(code) + "}").join(",") + "]";
|
|
43312
|
+
if (Object.isFrozen(codes)) conceptListCache.set(codes, json);
|
|
43313
|
+
return json;
|
|
43314
|
+
}
|
|
43285
43315
|
var DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
|
|
43286
43316
|
/** True when running in a browser environment. */
|
|
43287
43317
|
var IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
|
|
@@ -43313,8 +43343,33 @@ var ConcurrencyQueue = class {
|
|
|
43313
43343
|
};
|
|
43314
43344
|
var RETRY_BASE_DELAY_MS = 500;
|
|
43315
43345
|
var RETRY_MAX_DELAY_MS = 1e4;
|
|
43316
|
-
var RETRY_MAX_ATTEMPTS = 3;
|
|
43317
43346
|
var RETRY_JITTER_MS = 200;
|
|
43347
|
+
/** Default for {@link FhirTerminologyServiceOptions.rateLimitWaitMs}. */
|
|
43348
|
+
var DEFAULT_RATE_LIMIT_WAIT_MS = 6e4;
|
|
43349
|
+
/**
|
|
43350
|
+
* Milliseconds until the server says requests may resume, from `Retry-After`
|
|
43351
|
+
* (seconds or an HTTP date) or `x-ratelimit-reset` (seconds from now, or an
|
|
43352
|
+
* epoch time in seconds), whichever is later; 0 when it says neither.
|
|
43353
|
+
*/
|
|
43354
|
+
/** `x-ratelimit-remaining`, when the server sends it. */
|
|
43355
|
+
function remainingRequests(headers) {
|
|
43356
|
+
const value = headers.get("x-ratelimit-remaining")?.trim();
|
|
43357
|
+
if (!value) return void 0;
|
|
43358
|
+
const n = Number(value);
|
|
43359
|
+
return Number.isFinite(n) && n >= 0 ? n : void 0;
|
|
43360
|
+
}
|
|
43361
|
+
function serverResetMs(headers, now) {
|
|
43362
|
+
let ms = 0;
|
|
43363
|
+
const retryAfter = headers.get("Retry-After")?.trim();
|
|
43364
|
+
if (retryAfter) {
|
|
43365
|
+
const seconds = Number(retryAfter);
|
|
43366
|
+
const at = Number.isFinite(seconds) ? now + seconds * 1e3 : Date.parse(retryAfter);
|
|
43367
|
+
if (Number.isFinite(at)) ms = Math.max(ms, at - now);
|
|
43368
|
+
}
|
|
43369
|
+
const reset = Number(headers.get("x-ratelimit-reset"));
|
|
43370
|
+
if (Number.isFinite(reset) && reset > 0) ms = Math.max(ms, reset > 1e9 ? reset * 1e3 - now : reset * 1e3);
|
|
43371
|
+
return Math.max(0, ms);
|
|
43372
|
+
}
|
|
43318
43373
|
/**
|
|
43319
43374
|
* Characters that carry structural meaning inside the *canonical* implicit ValueSet URL
|
|
43320
43375
|
* (`http://snomed.info/sct?fhir_vs=ecl/<expression>`) and must therefore be percent-encoded
|
|
@@ -43391,10 +43446,26 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43391
43446
|
*/
|
|
43392
43447
|
bulkExpandUnsupported = false;
|
|
43393
43448
|
queue;
|
|
43449
|
+
rateLimitWaitMs;
|
|
43450
|
+
/** No request is sent before this time: the server said its rate limit is spent until then. */
|
|
43451
|
+
pausedUntil = 0;
|
|
43452
|
+
/**
|
|
43453
|
+
* Requests held by the rate limit, oldest first (a retry goes back to the
|
|
43454
|
+
* front). When a pause ends they do not all go at once, which would meet
|
|
43455
|
+
* one success and a storm of 429s: one goes first (the probe), and its
|
|
43456
|
+
* response says how many more the server has room for.
|
|
43457
|
+
*/
|
|
43458
|
+
held = [];
|
|
43459
|
+
/** A probe is in flight: the others wait for its answer. */
|
|
43460
|
+
probing = false;
|
|
43461
|
+
/** Requests sent and not yet answered, so `x-ratelimit-remaining` is not spent twice. */
|
|
43462
|
+
unanswered = 0;
|
|
43463
|
+
wakeTimer;
|
|
43394
43464
|
constructor(options = {}) {
|
|
43395
43465
|
const maxConcurrency = options.maxConcurrency ?? 25;
|
|
43396
43466
|
if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
|
|
43397
43467
|
this.queue = new ConcurrencyQueue(maxConcurrency);
|
|
43468
|
+
this.rateLimitWaitMs = options.rateLimitWaitMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
|
|
43398
43469
|
this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
|
|
43399
43470
|
this.timeout = options.timeout ?? 2e3;
|
|
43400
43471
|
this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
|
|
@@ -43572,18 +43643,74 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43572
43643
|
* status that is not an "unknown code" response.
|
|
43573
43644
|
*/
|
|
43574
43645
|
async fetchWithRetry(url, timeoutMs, init) {
|
|
43575
|
-
|
|
43576
|
-
|
|
43577
|
-
|
|
43578
|
-
|
|
43579
|
-
|
|
43580
|
-
|
|
43581
|
-
|
|
43646
|
+
const started = Date.now();
|
|
43647
|
+
for (let attempt = 1;; attempt++) {
|
|
43648
|
+
const probe = await this.waitForRateLimit(attempt > 1);
|
|
43649
|
+
this.unanswered++;
|
|
43650
|
+
let response;
|
|
43651
|
+
try {
|
|
43652
|
+
response = await this.fetchWithTimeout(url, timeoutMs, init);
|
|
43653
|
+
} catch (error) {
|
|
43654
|
+
this.release(probe, 0);
|
|
43655
|
+
throw error;
|
|
43656
|
+
}
|
|
43657
|
+
const now = Date.now();
|
|
43658
|
+
const resetMs = serverResetMs(response.headers, now);
|
|
43659
|
+
const remaining = remainingRequests(response.headers);
|
|
43660
|
+
if (response.status !== 429) {
|
|
43661
|
+
if (remaining === 0 && resetMs > 0) this.pauseUntil(now + resetMs);
|
|
43662
|
+
this.release(probe, remaining ?? Infinity);
|
|
43663
|
+
return response;
|
|
43664
|
+
}
|
|
43665
|
+
const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1), RETRY_MAX_DELAY_MS);
|
|
43582
43666
|
const jitter = Math.random() * RETRY_JITTER_MS;
|
|
43583
|
-
const waitMs =
|
|
43584
|
-
|
|
43667
|
+
const waitMs = (resetMs > 0 ? resetMs : backoff) + jitter;
|
|
43668
|
+
this.pauseUntil(now + waitMs);
|
|
43669
|
+
this.release(probe, 0);
|
|
43670
|
+
if (now + waitMs - started > this.rateLimitWaitMs) throw new Error(`FHIR request rate-limited after ${attempt} attempts over ${Math.round((now - started) / 1e3)} s`);
|
|
43585
43671
|
}
|
|
43586
|
-
|
|
43672
|
+
}
|
|
43673
|
+
pauseUntil(time) {
|
|
43674
|
+
this.pausedUntil = Math.max(this.pausedUntil, time);
|
|
43675
|
+
this.schedule();
|
|
43676
|
+
}
|
|
43677
|
+
/**
|
|
43678
|
+
* Go now, or wait in line while the rate limit is spent or other requests
|
|
43679
|
+
* are held; true when this request is the probe. A retry waits at the front.
|
|
43680
|
+
*/
|
|
43681
|
+
waitForRateLimit(retry) {
|
|
43682
|
+
if (!retry && !this.probing && this.held.length === 0 && Date.now() >= this.pausedUntil) return Promise.resolve(false);
|
|
43683
|
+
return new Promise((resolve) => {
|
|
43684
|
+
if (retry) this.held.unshift(resolve);
|
|
43685
|
+
else this.held.push(resolve);
|
|
43686
|
+
this.schedule();
|
|
43687
|
+
});
|
|
43688
|
+
}
|
|
43689
|
+
/** When the pause ends, send the oldest held request alone, as the probe. */
|
|
43690
|
+
schedule() {
|
|
43691
|
+
if (this.wakeTimer !== void 0 || this.probing || this.held.length === 0) return;
|
|
43692
|
+
this.wakeTimer = setTimeout(() => {
|
|
43693
|
+
this.wakeTimer = void 0;
|
|
43694
|
+
if (Date.now() < this.pausedUntil) {
|
|
43695
|
+
this.schedule();
|
|
43696
|
+
return;
|
|
43697
|
+
}
|
|
43698
|
+
const next = this.held.shift();
|
|
43699
|
+
if (!next) return;
|
|
43700
|
+
this.probing = true;
|
|
43701
|
+
next(true);
|
|
43702
|
+
}, Math.max(0, this.pausedUntil - Date.now()));
|
|
43703
|
+
}
|
|
43704
|
+
/**
|
|
43705
|
+
* A request's answer: if it was the probe, the next may go; while no pause
|
|
43706
|
+
* is set, let as many held requests go as the server has room for
|
|
43707
|
+
* (`remaining`), oldest first, and probe again for the rest.
|
|
43708
|
+
*/
|
|
43709
|
+
release(probe, room) {
|
|
43710
|
+
this.unanswered--;
|
|
43711
|
+
if (probe) this.probing = false;
|
|
43712
|
+
if (Date.now() >= this.pausedUntil) for (let n = room - this.unanswered; n > 0 && this.held.length > 0; n--) this.held.shift()?.(false);
|
|
43713
|
+
this.schedule();
|
|
43587
43714
|
}
|
|
43588
43715
|
fetchQueued(url, timeoutMs, init) {
|
|
43589
43716
|
return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
|
|
@@ -43943,6 +44070,53 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43943
44070
|
const data = await response.json();
|
|
43944
44071
|
return FhirTerminologyService.relationshipsOf(data.parameter ?? []);
|
|
43945
44072
|
}
|
|
44073
|
+
/**
|
|
44074
|
+
* Many `$lookup`s in one FHIR batch Bundle, so a sample of relationships
|
|
44075
|
+
* costs one request against the rate limit rather than one per concept.
|
|
44076
|
+
*/
|
|
44077
|
+
async getDefiningRelationshipsMany(conceptIds) {
|
|
44078
|
+
const version = this.snomedVersion ? `&version=${encodeURIComponent(this.snomedVersion)}` : "";
|
|
44079
|
+
const body = {
|
|
44080
|
+
resourceType: "Bundle",
|
|
44081
|
+
type: "batch",
|
|
44082
|
+
entry: conceptIds.map((id) => ({ request: {
|
|
44083
|
+
method: "GET",
|
|
44084
|
+
url: `CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(id)}&property=*${version}`
|
|
44085
|
+
} }))
|
|
44086
|
+
};
|
|
44087
|
+
const operation = `batch $lookup of the relationships of ${conceptIds.length} concepts`;
|
|
44088
|
+
const url = this.baseUrl;
|
|
44089
|
+
const response = await this.request(url, this.timeout * Math.max(1, conceptIds.length), operation, {
|
|
44090
|
+
method: "POST",
|
|
44091
|
+
headers: {
|
|
44092
|
+
"Content-Type": "application/fhir+json",
|
|
44093
|
+
Accept: "application/fhir+json"
|
|
44094
|
+
},
|
|
44095
|
+
body: JSON.stringify(body)
|
|
44096
|
+
});
|
|
44097
|
+
if (!response.ok) {
|
|
44098
|
+
const { detail } = await FhirTerminologyService.readErrorBody(response);
|
|
44099
|
+
throw toHttpError({
|
|
44100
|
+
status: response.status,
|
|
44101
|
+
statusText: response.statusText,
|
|
44102
|
+
url,
|
|
44103
|
+
operation,
|
|
44104
|
+
detail
|
|
44105
|
+
});
|
|
44106
|
+
}
|
|
44107
|
+
const data = await response.json();
|
|
44108
|
+
return conceptIds.map((id, i) => FhirTerminologyService.batchRelationships(id, data.entry?.[i]));
|
|
44109
|
+
}
|
|
44110
|
+
/** One batch entry's relationships: null for an unknown code, an Error for any other failure. */
|
|
44111
|
+
static batchRelationships(id, entry) {
|
|
44112
|
+
const status = Number.parseInt(entry?.response?.status ?? "", 10);
|
|
44113
|
+
const resource = entry?.resource;
|
|
44114
|
+
let answer;
|
|
44115
|
+
if (status >= 200 && status < 300 && resource?.resourceType === "Parameters") answer = FhirTerminologyService.relationshipsOf(resource.parameter ?? []);
|
|
44116
|
+
else if (FhirTerminologyService.isUnknownCodeResponse(status, resource?.resourceType === "OperationOutcome" ? resource : null)) answer = null;
|
|
44117
|
+
else answer = /* @__PURE__ */ new Error(`$lookup of ${id} in a batch answered ${entry?.response?.status ?? "nothing"}`);
|
|
44118
|
+
return answer;
|
|
44119
|
+
}
|
|
43946
44120
|
/** The relationships in a `$lookup` response's `property` parameters; role groups are numbered from 1. */
|
|
43947
44121
|
static relationshipsOf(parameters) {
|
|
43948
44122
|
const partValue = (parts, name) => FhirTerminologyService.eclValue(parts?.find((p) => p.name === name));
|
|
@@ -43990,24 +44164,22 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43990
44164
|
* @throws {TerminologyHttpError} when the server answered with an error status.
|
|
43991
44165
|
*/
|
|
43992
44166
|
async expandCompose(compose, options = {}) {
|
|
43993
|
-
const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false } = options;
|
|
43994
|
-
const
|
|
44167
|
+
const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false, children = false, activity = false } = options;
|
|
44168
|
+
const system = {
|
|
43995
44169
|
system: "http://snomed.info/sct",
|
|
43996
|
-
...this.snomedVersion ? { version: this.snomedVersion } : {}
|
|
43997
|
-
|
|
44170
|
+
...this.snomedVersion ? { version: this.snomedVersion } : {}
|
|
44171
|
+
};
|
|
44172
|
+
const toInclude = (clause) => "ecl" in clause ? JSON.stringify({
|
|
44173
|
+
...system,
|
|
44174
|
+
filter: [{
|
|
43998
44175
|
property: "constraint",
|
|
43999
44176
|
op: "=",
|
|
44000
44177
|
value: clause.ecl
|
|
44001
|
-
}]
|
|
44002
|
-
})
|
|
44003
|
-
const
|
|
44004
|
-
|
|
44005
|
-
|
|
44006
|
-
include: compose.include.map(toInclude),
|
|
44007
|
-
...compose.exclude?.length ? { exclude: compose.exclude.map(toInclude) } : {}
|
|
44008
|
-
}
|
|
44009
|
-
};
|
|
44010
|
-
const property = parents ? "&property=parent" : "";
|
|
44178
|
+
}]
|
|
44179
|
+
}) : `${JSON.stringify(system).slice(0, -1)},"concept":${conceptListJson(clause.concepts)}}`;
|
|
44180
|
+
const exclude = compose.exclude?.length ? `,"exclude":[${compose.exclude.map(toInclude).join(",")}]` : "";
|
|
44181
|
+
const body = `{"resourceType":"ValueSet","compose":{"include":[${compose.include.map(toInclude).join(",")}]${exclude}}}`;
|
|
44182
|
+
const property = (parents ? "&property=parent" : "") + (children ? "&property=child" : "") + (activity ? "&property=inactive" : "");
|
|
44011
44183
|
const url = `${this.baseUrl}/ValueSet/$expand?count=${count}&offset=${offset}&activeOnly=${activeOnly}${property}`;
|
|
44012
44184
|
const operation = "POST ValueSet/$expand of an inline compose";
|
|
44013
44185
|
const response = await this.request(url, timeoutMs, operation, {
|
|
@@ -44016,7 +44188,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44016
44188
|
"Content-Type": "application/fhir+json",
|
|
44017
44189
|
Accept: "application/fhir+json"
|
|
44018
44190
|
},
|
|
44019
|
-
body
|
|
44191
|
+
body
|
|
44020
44192
|
});
|
|
44021
44193
|
if (!response.ok) {
|
|
44022
44194
|
const { detail } = await FhirTerminologyService.readErrorBody(response);
|
|
@@ -44034,6 +44206,13 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44034
44206
|
const found = parentCodes(item);
|
|
44035
44207
|
if (found) result.concepts[i].parents = found;
|
|
44036
44208
|
});
|
|
44209
|
+
if (activity) (data.expansion?.contains ?? []).forEach((item, i) => {
|
|
44210
|
+
const stated = item.inactive === true ? true : propertyBoolean(item, "inactive");
|
|
44211
|
+
if (stated !== void 0) result.concepts[i].inactive = stated;
|
|
44212
|
+
});
|
|
44213
|
+
if (children) (data.expansion?.contains ?? []).forEach((item, i) => {
|
|
44214
|
+
result.concepts[i].children = propertyCodes(item, "child") ?? [];
|
|
44215
|
+
});
|
|
44037
44216
|
return result;
|
|
44038
44217
|
}
|
|
44039
44218
|
/**
|
|
@@ -44069,7 +44248,8 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44069
44248
|
const total = typeof expansion.total === "number" ? expansion.total : 0;
|
|
44070
44249
|
const concepts = (expansion.contains ?? []).map((item) => ({
|
|
44071
44250
|
code: item.code ?? "",
|
|
44072
|
-
display: item.display ?? ""
|
|
44251
|
+
display: item.display ?? "",
|
|
44252
|
+
...item.inactive === true ? { inactive: true } : {}
|
|
44073
44253
|
}));
|
|
44074
44254
|
return {
|
|
44075
44255
|
total,
|
|
@@ -48456,6 +48636,12 @@ function compareExpressions(a, b) {
|
|
|
48456
48636
|
var SNOMED_ROOT = "138875005";
|
|
48457
48637
|
/** Ontoserver returns at most this many concepts per page, whatever `count` asks for. */
|
|
48458
48638
|
var PAGE_SIZE = 5e4;
|
|
48639
|
+
/**
|
|
48640
|
+
* Codes per request when looking concepts up by code. The server's cost grows
|
|
48641
|
+
* with the codes in a request, and is paid again for every page of it, so a
|
|
48642
|
+
* long list costs least as many small requests rather than one paged one.
|
|
48643
|
+
*/
|
|
48644
|
+
var LOOKUP_CHUNK = 1e4;
|
|
48459
48645
|
/** Numeric order for SCTIDs, so output does not depend on input or server order. */
|
|
48460
48646
|
function byId(a, b) {
|
|
48461
48647
|
return a.length - b.length || compareText(a, b);
|
|
@@ -48480,15 +48666,92 @@ function countClauses(ecl) {
|
|
|
48480
48666
|
return ecl.match(/\b\d{6,18}\b/g)?.length ?? 0;
|
|
48481
48667
|
}
|
|
48482
48668
|
/**
|
|
48669
|
+
* `terminology`, counting the requests that fail because of the server: it
|
|
48670
|
+
* could not be reached, timed out, was rate-limited or answered 5xx. A 4xx
|
|
48671
|
+
* other than 429 is about the request, not the server, and is not counted.
|
|
48672
|
+
* Derive drops what a failed request was for and goes on, so this count is
|
|
48673
|
+
* what tells a degraded result from a complete one.
|
|
48674
|
+
*/
|
|
48675
|
+
var UNCOUNTED = Symbol("uncounted");
|
|
48676
|
+
/**
|
|
48677
|
+
* The service behind a {@link countingFailures} wrapper (or `terminology`
|
|
48678
|
+
* itself), for a request whose failure the caller recovers from by other
|
|
48679
|
+
* requests, which are counted: a failure there loses nothing, so it must not
|
|
48680
|
+
* mark the result incomplete.
|
|
48681
|
+
*/
|
|
48682
|
+
function uncounted(terminology) {
|
|
48683
|
+
return terminology[UNCOUNTED] ?? terminology;
|
|
48684
|
+
}
|
|
48685
|
+
function countingFailures(terminology) {
|
|
48686
|
+
let count = 0;
|
|
48687
|
+
const counted = (error) => {
|
|
48688
|
+
if (!(isTerminologyHttpError(error) && error.status >= 400 && error.status < 500 && error.status !== 429)) count++;
|
|
48689
|
+
throw error;
|
|
48690
|
+
};
|
|
48691
|
+
return {
|
|
48692
|
+
service: new Proxy(terminology, { get(target, prop, receiver) {
|
|
48693
|
+
if (prop === UNCOUNTED) return uncounted(target);
|
|
48694
|
+
const value = Reflect.get(target, prop, receiver);
|
|
48695
|
+
if (typeof value !== "function") return value;
|
|
48696
|
+
return (...args) => {
|
|
48697
|
+
const out = value.apply(target, args);
|
|
48698
|
+
return out instanceof Promise ? out.catch(counted) : out;
|
|
48699
|
+
};
|
|
48700
|
+
} }),
|
|
48701
|
+
failures: () => count
|
|
48702
|
+
};
|
|
48703
|
+
}
|
|
48704
|
+
/**
|
|
48483
48705
|
* Set queries against the server. At most {@link MAX_IN_FLIGHT} run at once:
|
|
48484
48706
|
* many carry the whole member list, and the service may not queue them itself.
|
|
48485
48707
|
*/
|
|
48486
48708
|
var SetQueries = class {
|
|
48487
48709
|
expandCompose;
|
|
48710
|
+
parallelPages;
|
|
48488
48711
|
inFlight = 0;
|
|
48489
48712
|
waiting = [];
|
|
48490
|
-
constructor(expandCompose) {
|
|
48713
|
+
constructor(expandCompose, parallelPages = false) {
|
|
48491
48714
|
this.expandCompose = expandCompose;
|
|
48715
|
+
this.parallelPages = parallelPages;
|
|
48716
|
+
}
|
|
48717
|
+
/**
|
|
48718
|
+
* The rest of an expansion whose first `first.length` concepts have been
|
|
48719
|
+
* read, up to `until`, in order. Pages step by the first page's length, which
|
|
48720
|
+
* is the server's page cap when it returned fewer than asked (Ontoserver
|
|
48721
|
+
* caps at 50,000; other servers lower). With `parallelPages` those pages are
|
|
48722
|
+
* asked for at once. Whatever is still missing after that (a server whose
|
|
48723
|
+
* pages shrink) is read one page after another, advancing by what each page
|
|
48724
|
+
* actually held, so a smaller cap never silently drops concepts.
|
|
48725
|
+
*/
|
|
48726
|
+
async rest(compose, first, until, options) {
|
|
48727
|
+
const concepts = [...first];
|
|
48728
|
+
const step = first.length;
|
|
48729
|
+
if (step === 0) return concepts;
|
|
48730
|
+
const page = async (offset, count) => (await this.expand(compose, {
|
|
48731
|
+
...options,
|
|
48732
|
+
count,
|
|
48733
|
+
offset
|
|
48734
|
+
})).concepts;
|
|
48735
|
+
if (this.parallelPages) await this.pagesAtOnce(concepts, step, until, page);
|
|
48736
|
+
while (concepts.length < until) {
|
|
48737
|
+
const p = await page(concepts.length, Math.min(PAGE_SIZE, until - concepts.length));
|
|
48738
|
+
if (p.length === 0) break;
|
|
48739
|
+
for (const c of p) concepts.push(c);
|
|
48740
|
+
}
|
|
48741
|
+
return concepts;
|
|
48742
|
+
}
|
|
48743
|
+
/**
|
|
48744
|
+
* Append the pages from `step` to `until`, `step` apart, asked for at once.
|
|
48745
|
+
* Only the run of full pages is kept: after a short one the offsets no longer line up.
|
|
48746
|
+
*/
|
|
48747
|
+
async pagesAtOnce(concepts, step, until, page) {
|
|
48748
|
+
const offsets = [];
|
|
48749
|
+
for (let o = step; o < until; o += step) offsets.push(o);
|
|
48750
|
+
const pages = await Promise.all(offsets.map((o) => page(o, Math.min(step, until - o))));
|
|
48751
|
+
for (const p of pages) {
|
|
48752
|
+
for (const c of p) concepts.push(c);
|
|
48753
|
+
if (p.length < step) return;
|
|
48754
|
+
}
|
|
48492
48755
|
}
|
|
48493
48756
|
async expand(...args) {
|
|
48494
48757
|
if (this.inFlight >= 8) await new Promise((resolve) => this.waiting.push(resolve));
|
|
@@ -48523,20 +48786,65 @@ var SetQueries = class {
|
|
|
48523
48786
|
}
|
|
48524
48787
|
/** Up to `max` concepts of the set with their terms, in the server's order, plus the set's exact total. */
|
|
48525
48788
|
async concepts(compose, max, activeOnly = true) {
|
|
48526
|
-
const
|
|
48527
|
-
|
|
48528
|
-
|
|
48529
|
-
|
|
48530
|
-
|
|
48531
|
-
|
|
48532
|
-
|
|
48789
|
+
const first = await this.expand(compose, {
|
|
48790
|
+
count: Math.min(PAGE_SIZE, max),
|
|
48791
|
+
offset: 0,
|
|
48792
|
+
activeOnly
|
|
48793
|
+
});
|
|
48794
|
+
const total = first.total;
|
|
48795
|
+
return {
|
|
48796
|
+
concepts: await this.rest(compose, first.concepts, Math.min(max, total), { activeOnly }),
|
|
48797
|
+
total
|
|
48798
|
+
};
|
|
48799
|
+
}
|
|
48800
|
+
/**
|
|
48801
|
+
* The concepts of `codes` the server knows, in chunks of {@link LOOKUP_CHUNK}
|
|
48802
|
+
* run concurrently, with their terms and, as asked, parents and children.
|
|
48803
|
+
* With `activeOnly: false` inactive ones come back flagged `inactive`.
|
|
48804
|
+
*/
|
|
48805
|
+
async lookup(codes, options = {}) {
|
|
48806
|
+
return (await this.lookupEach(codes, options, (concepts) => concepts)).flat();
|
|
48807
|
+
}
|
|
48808
|
+
/**
|
|
48809
|
+
* {@link lookup}, with each chunk's answer passed through `each` as it
|
|
48810
|
+
* arrives, so a caller that keeps less than the server sends need not hold
|
|
48811
|
+
* every answer at once. The results are in chunk order.
|
|
48812
|
+
*/
|
|
48813
|
+
async lookupEach(codes, options, each) {
|
|
48814
|
+
const chunks = [];
|
|
48815
|
+
for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) chunks.push(codes.slice(i, i + LOOKUP_CHUNK));
|
|
48816
|
+
return Promise.all(chunks.map(async (chunk) => {
|
|
48817
|
+
const compose = { include: [{ concepts: chunk }] };
|
|
48818
|
+
const expandOptions = {
|
|
48819
|
+
activeOnly: options.activeOnly ?? true,
|
|
48820
|
+
...options
|
|
48821
|
+
};
|
|
48822
|
+
const page = await this.expand(compose, {
|
|
48823
|
+
...expandOptions,
|
|
48824
|
+
count: chunk.length,
|
|
48825
|
+
offset: 0
|
|
48533
48826
|
});
|
|
48534
|
-
total
|
|
48535
|
-
|
|
48536
|
-
|
|
48537
|
-
|
|
48538
|
-
|
|
48539
|
-
|
|
48827
|
+
if (page.concepts.length >= page.total) return each(page.concepts);
|
|
48828
|
+
return each(await this.rest(compose, page.concepts, page.total, expandOptions));
|
|
48829
|
+
}));
|
|
48830
|
+
}
|
|
48831
|
+
/**
|
|
48832
|
+
* Up to `max` concepts of a set known to have at most `max`, such as a list
|
|
48833
|
+
* of codes: with `parallelPages` every page is asked for at once, since the
|
|
48834
|
+
* offsets do not depend on the first page's total.
|
|
48835
|
+
*/
|
|
48836
|
+
async conceptsUpTo(compose, max, activeOnly = true) {
|
|
48837
|
+
if (!this.parallelPages || max <= PAGE_SIZE) return this.concepts(compose, max, activeOnly);
|
|
48838
|
+
const offsets = [];
|
|
48839
|
+
for (let o = 0; o < max; o += PAGE_SIZE) offsets.push(o);
|
|
48840
|
+
const pages = await Promise.all(offsets.map((offset) => this.expand(compose, {
|
|
48841
|
+
count: Math.min(PAGE_SIZE, max - offset),
|
|
48842
|
+
offset,
|
|
48843
|
+
activeOnly
|
|
48844
|
+
})));
|
|
48845
|
+
const total = pages[0].total;
|
|
48846
|
+
const concepts = pages.flatMap((p) => p.concepts);
|
|
48847
|
+
if (concepts.length < Math.min(max, total)) return this.concepts(compose, max, activeOnly);
|
|
48540
48848
|
return {
|
|
48541
48849
|
concepts,
|
|
48542
48850
|
total
|
|
@@ -48548,20 +48856,17 @@ var SetQueries = class {
|
|
|
48548
48856
|
*/
|
|
48549
48857
|
async graph(compose, max) {
|
|
48550
48858
|
const graph = /* @__PURE__ */ new Map();
|
|
48551
|
-
|
|
48552
|
-
|
|
48553
|
-
|
|
48554
|
-
|
|
48555
|
-
|
|
48556
|
-
|
|
48557
|
-
|
|
48558
|
-
|
|
48559
|
-
|
|
48560
|
-
graph.set(c.code, c.parents ?? []);
|
|
48561
|
-
}
|
|
48562
|
-
offset += r.concepts.length;
|
|
48563
|
-
if (r.concepts.length === 0 || offset >= r.total) return graph;
|
|
48859
|
+
const first = await this.expand(compose, {
|
|
48860
|
+
count: PAGE_SIZE,
|
|
48861
|
+
offset: 0,
|
|
48862
|
+
parents: true
|
|
48863
|
+
});
|
|
48864
|
+
if (first.total > max) return "too-large";
|
|
48865
|
+
for (const c of await this.rest(compose, first.concepts, first.total, { parents: true })) {
|
|
48866
|
+
if (!c.parents && c.code !== "138875005") return "no-parents";
|
|
48867
|
+
graph.set(c.code, c.parents ?? []);
|
|
48564
48868
|
}
|
|
48869
|
+
return graph;
|
|
48565
48870
|
}
|
|
48566
48871
|
countEcl(ecl) {
|
|
48567
48872
|
return this.count({ include: [{ ecl }] });
|
|
@@ -49059,122 +49364,439 @@ function chooseInclusions(candidates, inList, maxClauses) {
|
|
|
49059
49364
|
// src/derive/taxonomy-graph.ts
|
|
49060
49365
|
async function loadTaxonomyGraph(members, q, options) {
|
|
49061
49366
|
const max = options.maxConcepts;
|
|
49062
|
-
const memberList =
|
|
49367
|
+
const memberList = options.memberCodes ? {
|
|
49368
|
+
codes: options.memberCodes,
|
|
49369
|
+
total: options.memberCodes.length
|
|
49370
|
+
} : await q.codes({ include: [members.clause] }, max + 1);
|
|
49063
49371
|
if (memberList.total > max) return { unavailable: "the set" };
|
|
49372
|
+
if (options.walk) {
|
|
49373
|
+
const walked = await walkedGraph(memberList.codes, q, options);
|
|
49374
|
+
if (walked) return walked;
|
|
49375
|
+
}
|
|
49376
|
+
const around = await eclSubgraph(members, q, options);
|
|
49377
|
+
if ("unavailable" in around) return around;
|
|
49378
|
+
const ids = new Ids();
|
|
49379
|
+
return await withDescendants(new LoadedGraph(new Set(memberList.codes), numbered(ids, around.up), numbered(ids, around.childGraph), ids), options, async (load) => {
|
|
49380
|
+
if (load.length === 0) return /* @__PURE__ */ new Map();
|
|
49381
|
+
const below = await q.graph({ include: [{ ecl: `<< ${orGroup(load)}` }] }, max);
|
|
49382
|
+
return typeof below === "string" ? below : numbered(ids, below);
|
|
49383
|
+
}) ?? { unavailable: "the descendants of the candidate groupers" };
|
|
49384
|
+
}
|
|
49385
|
+
/** `>> set` with each concept's parents, and the children of those concepts, by ECL queries that carry the set. */
|
|
49386
|
+
async function eclSubgraph(members, q, options) {
|
|
49387
|
+
const max = options.maxConcepts;
|
|
49064
49388
|
const up = await q.graph({ include: [{ ecl: `>> ${members.ecl}` }] }, max);
|
|
49065
49389
|
if (typeof up === "string") return refused(up, "the set with its ancestors");
|
|
49066
49390
|
const childGraph = await q.graph({ include: [{ ecl: `<! (>> ${members.ecl})` }] }, max);
|
|
49067
49391
|
if (typeof childGraph === "string") return refused(childGraph, "the children of those ancestors");
|
|
49068
|
-
|
|
49392
|
+
return {
|
|
49393
|
+
up,
|
|
49394
|
+
childGraph
|
|
49395
|
+
};
|
|
49396
|
+
}
|
|
49397
|
+
function numbered(ids, graph) {
|
|
49398
|
+
const out = /* @__PURE__ */ new Map();
|
|
49399
|
+
for (const [id, parents] of graph) out.set(ids.at(id), parents.map((p) => ids.at(p)));
|
|
49400
|
+
return out;
|
|
49401
|
+
}
|
|
49402
|
+
/**
|
|
49403
|
+
* The graph with the descendants loaded of the concepts `descend` picks (and
|
|
49404
|
+
* the roots), or of those `fallbackDescend` picks when those are too many
|
|
49405
|
+
* (the graph is then partial); a refusal when even those are too many, and
|
|
49406
|
+
* null when `fetch` cannot say.
|
|
49407
|
+
*/
|
|
49408
|
+
async function withDescendants(graph, options, fetch) {
|
|
49069
49409
|
const roots = new Set(graph.roots());
|
|
49070
|
-
|
|
49410
|
+
const loadFor = (pick) => graph.ancestors().filter((id) => graph.children(id).length > 0 && pick(id));
|
|
49411
|
+
let down = await fetch(loadFor((id) => options.descend(id, graph) || roots.has(id)));
|
|
49071
49412
|
if (down === "too-large" && options.fallbackDescend) {
|
|
49072
49413
|
const fallback = options.fallbackDescend;
|
|
49073
|
-
down = await
|
|
49414
|
+
down = await fetch(loadFor((id) => fallback(id, graph)));
|
|
49074
49415
|
graph.partial = true;
|
|
49075
49416
|
}
|
|
49417
|
+
if (down === null) return null;
|
|
49076
49418
|
if (typeof down === "string") return refused(down, "the descendants of the candidate groupers");
|
|
49077
49419
|
graph.addBelow(down);
|
|
49078
49420
|
return graph;
|
|
49079
49421
|
}
|
|
49080
|
-
/**
|
|
49081
|
-
|
|
49082
|
-
|
|
49083
|
-
|
|
49084
|
-
|
|
49422
|
+
/** Concept ids, each numbered once, shared by a walk and the graph built from it. */
|
|
49423
|
+
var Ids = class {
|
|
49424
|
+
list = [];
|
|
49425
|
+
index = /* @__PURE__ */ new Map();
|
|
49426
|
+
get(id) {
|
|
49427
|
+
return this.index.get(id);
|
|
49428
|
+
}
|
|
49429
|
+
/** The number of `id`, given one if it has none. */
|
|
49430
|
+
at(id) {
|
|
49431
|
+
let i = this.index.get(id);
|
|
49432
|
+
if (i === void 0) {
|
|
49433
|
+
i = this.list.length;
|
|
49434
|
+
this.list.push(id);
|
|
49435
|
+
this.index.set(id, i);
|
|
49436
|
+
}
|
|
49437
|
+
return i;
|
|
49438
|
+
}
|
|
49439
|
+
};
|
|
49440
|
+
/**
|
|
49441
|
+
* Concepts looked up with their parents and children, by number. Resolving a
|
|
49442
|
+
* list can start one, converting each chunk as it arrives, so the server's
|
|
49443
|
+
* answers are not all held at once (see {@link TaxonomyGraphOptions.seed}).
|
|
49444
|
+
*/
|
|
49445
|
+
var Walk = class {
|
|
49446
|
+
ids = new Ids();
|
|
49447
|
+
nodes = /* @__PURE__ */ new Map();
|
|
49448
|
+
/** The nodes for `concepts`, not yet added; null when one came back without the parents or children asked for. */
|
|
49449
|
+
nodesFor(concepts) {
|
|
49450
|
+
const at = (id) => this.ids.at(id);
|
|
49451
|
+
const out = [];
|
|
49452
|
+
for (const c of concepts) {
|
|
49453
|
+
if (!c.children || !c.parents && c.code !== "138875005") return null;
|
|
49454
|
+
out.push([at(c.code), {
|
|
49455
|
+
parents: (c.parents ?? []).map(at),
|
|
49456
|
+
children: c.children.map(at),
|
|
49457
|
+
display: c.display
|
|
49458
|
+
}]);
|
|
49459
|
+
}
|
|
49460
|
+
return out;
|
|
49461
|
+
}
|
|
49462
|
+
add(nodes) {
|
|
49463
|
+
for (const [i, n] of nodes) this.nodes.set(i, n);
|
|
49464
|
+
}
|
|
49465
|
+
/** True when every one of `codes` has been looked up. */
|
|
49466
|
+
has(codes) {
|
|
49467
|
+
for (const c of codes) {
|
|
49468
|
+
const i = this.ids.get(c);
|
|
49469
|
+
if (i === void 0 || !this.nodes.has(i)) return false;
|
|
49470
|
+
}
|
|
49471
|
+
return true;
|
|
49472
|
+
}
|
|
49473
|
+
};
|
|
49474
|
+
/** Record looked-up concepts; false when one came back without the parents or children asked for. */
|
|
49475
|
+
function record(walk, concepts) {
|
|
49476
|
+
const nodes = walk.nodesFor(concepts);
|
|
49477
|
+
if (nodes) walk.add(nodes);
|
|
49478
|
+
return nodes !== null;
|
|
49479
|
+
}
|
|
49480
|
+
/**
|
|
49481
|
+
* The graph built by walking (see {@link TaxonomyGraphOptions.walk}), or null
|
|
49482
|
+
* when the server does not return children, or a refusal when it is too large.
|
|
49483
|
+
*/
|
|
49484
|
+
async function walkedGraph(memberCodes, q, options) {
|
|
49485
|
+
const max = options.maxConcepts;
|
|
49486
|
+
const members = new Set(memberCodes);
|
|
49487
|
+
const seeded = options.seed?.has(members) ? options.seed : void 0;
|
|
49488
|
+
const walk = seeded ?? new Walk();
|
|
49489
|
+
if (!seeded && !record(walk, await q.lookup(memberCodes, {
|
|
49490
|
+
parents: true,
|
|
49491
|
+
children: true
|
|
49492
|
+
}))) return null;
|
|
49493
|
+
const climbed = await walkUp(memberCodes, walk, q, max);
|
|
49494
|
+
if (climbed !== "done") return climbed;
|
|
49495
|
+
const { ids, nodes } = walk;
|
|
49496
|
+
const up = /* @__PURE__ */ new Map();
|
|
49497
|
+
const childGraph = /* @__PURE__ */ new Map();
|
|
49498
|
+
for (const [i, n] of nodes) {
|
|
49499
|
+
up.set(i, n.parents);
|
|
49500
|
+
for (const c of n.children) {
|
|
49501
|
+
if (nodes.has(c)) continue;
|
|
49502
|
+
const parents = childGraph.get(c);
|
|
49503
|
+
if (parents) parents.push(i);
|
|
49504
|
+
else childGraph.set(c, [i]);
|
|
49505
|
+
}
|
|
49506
|
+
}
|
|
49507
|
+
const graph = new LoadedGraph(members, up, childGraph, ids);
|
|
49508
|
+
const loaded = await withDescendants(graph, options, (load) => walkDown(load, walk, q, max));
|
|
49509
|
+
if (!loaded || "unavailable" in loaded) return loaded;
|
|
49510
|
+
graph.loadBelow = async (load) => {
|
|
49511
|
+
const more = await walkDown(load, walk, options.belowQueries ?? q, max);
|
|
49512
|
+
if (more === "too-large" || more === null) return false;
|
|
49513
|
+
graph.addBelow(more);
|
|
49514
|
+
return true;
|
|
49515
|
+
};
|
|
49516
|
+
graph.term = (id) => {
|
|
49517
|
+
const i = ids.get(id);
|
|
49518
|
+
return i === void 0 ? void 0 : nodes.get(i)?.display;
|
|
49519
|
+
};
|
|
49520
|
+
return graph;
|
|
49521
|
+
}
|
|
49522
|
+
/**
|
|
49523
|
+
* Add the ancestors of `start` to the walk, a level at a time: `'done'`, a
|
|
49524
|
+
* refusal when they are too many, or null when the server ignored
|
|
49525
|
+
* `property=child` (then no parent lists its child).
|
|
49526
|
+
*/
|
|
49527
|
+
async function walkUp(start, walk, q, max) {
|
|
49528
|
+
const { ids, nodes } = walk;
|
|
49529
|
+
let frontier = newParents(start.map((c) => ids.at(c)), nodes);
|
|
49530
|
+
while (frontier.length > 0) {
|
|
49531
|
+
if (nodes.size + frontier.length > max) return { unavailable: "the set with its ancestors" };
|
|
49532
|
+
const found = await q.lookup(frontier.map((i) => ids.list[i]), {
|
|
49533
|
+
parents: true,
|
|
49534
|
+
children: true
|
|
49535
|
+
});
|
|
49536
|
+
if (!record(walk, found)) return null;
|
|
49537
|
+
frontier = newParents(found.map((c) => ids.at(c.code)), nodes);
|
|
49538
|
+
}
|
|
49539
|
+
for (const [i, n] of nodes) if (n.parents.some((p) => !nodes.get(p)?.children.includes(i))) return null;
|
|
49540
|
+
return "done";
|
|
49541
|
+
}
|
|
49542
|
+
function newParents(codes, nodes) {
|
|
49543
|
+
const out = /* @__PURE__ */ new Set();
|
|
49544
|
+
for (const c of codes) for (const p of nodes.get(c)?.parents ?? []) if (!nodes.has(p)) out.add(p);
|
|
49545
|
+
return [...out];
|
|
49546
|
+
}
|
|
49547
|
+
/**
|
|
49548
|
+
* `<< load` with each concept's parents, walked down level by level. Concepts
|
|
49549
|
+
* already in the walk are not looked up, and those looked up are added to it,
|
|
49550
|
+
* so a later walk does not look them up again.
|
|
49551
|
+
*/
|
|
49552
|
+
async function walkDown(load, walk, q, max) {
|
|
49553
|
+
const { ids, nodes } = walk;
|
|
49554
|
+
const result = /* @__PURE__ */ new Map();
|
|
49555
|
+
let level = [...new Set(load.map((c) => ids.at(c)))];
|
|
49556
|
+
while (level.length > 0) {
|
|
49557
|
+
const missing = level.filter((c) => !nodes.has(c));
|
|
49558
|
+
if (missing.length > 0 && !record(walk, await q.lookup(missing.map((i) => ids.list[i]), {
|
|
49559
|
+
parents: true,
|
|
49560
|
+
children: true
|
|
49561
|
+
}))) return null;
|
|
49562
|
+
level = descendOneLevel(level, nodes, result);
|
|
49563
|
+
if (result.size + level.length > max) return "too-large";
|
|
49564
|
+
}
|
|
49565
|
+
return result;
|
|
49566
|
+
}
|
|
49567
|
+
/** Record `level` in `result` and return its children not yet there. */
|
|
49568
|
+
function descendOneLevel(level, nodes, result) {
|
|
49569
|
+
const next = /* @__PURE__ */ new Set();
|
|
49570
|
+
for (const c of level) {
|
|
49571
|
+
const n = nodes.get(c);
|
|
49572
|
+
if (!n) continue;
|
|
49573
|
+
result.set(c, n.parents);
|
|
49574
|
+
for (const child of n.children) if (!result.has(child)) next.add(child);
|
|
49575
|
+
}
|
|
49576
|
+
return [...next];
|
|
49085
49577
|
}
|
|
49086
49578
|
function refused(reason, what) {
|
|
49087
49579
|
return { unavailable: reason === "no-parents" ? "parents" : what };
|
|
49088
49580
|
}
|
|
49581
|
+
/**
|
|
49582
|
+
* The graph, with each concept numbered once and its parents and children held
|
|
49583
|
+
* as lists of numbers, so a graph of a few hundred thousand concepts keeps one
|
|
49584
|
+
* copy of each edge in each direction (it held four, with strings, before).
|
|
49585
|
+
*/
|
|
49089
49586
|
var LoadedGraph = class {
|
|
49090
49587
|
members;
|
|
49091
|
-
|
|
49588
|
+
ids;
|
|
49092
49589
|
partial = false;
|
|
49093
|
-
|
|
49094
|
-
|
|
49095
|
-
|
|
49590
|
+
loadBelow;
|
|
49591
|
+
term;
|
|
49592
|
+
/** Parents by number; a list may be the caller's (see SHARED) until the graph adds to it. */
|
|
49593
|
+
parentIdx = [];
|
|
49594
|
+
/** Children, in the order each child was first given parents (as `childrenOf` built them). */
|
|
49595
|
+
childIdx = [];
|
|
49596
|
+
/** When each concept was first given parents; -1 for a concept only seen as a parent. */
|
|
49597
|
+
rank = (/* @__PURE__ */ new Int32Array(1024)).fill(-1);
|
|
49598
|
+
nextRank = 0;
|
|
49599
|
+
/** How many of a concept's parents came from `up`, which come first. */
|
|
49600
|
+
upLength = /* @__PURE__ */ new Int32Array(1024);
|
|
49601
|
+
/** Bits: IN_UP, BELOW and SHARED (below the class). */
|
|
49602
|
+
flags = /* @__PURE__ */ new Uint8Array(1024);
|
|
49603
|
+
counts = /* @__PURE__ */ new Int32Array(1024);
|
|
49096
49604
|
cache = /* @__PURE__ */ new Map();
|
|
49097
|
-
counts = /* @__PURE__ */ new Map();
|
|
49098
49605
|
rootIds = [];
|
|
49099
|
-
constructor(members, up, childGraph) {
|
|
49606
|
+
constructor(members, up, childGraph, ids) {
|
|
49100
49607
|
this.members = members;
|
|
49101
|
-
this.
|
|
49608
|
+
this.ids = ids;
|
|
49102
49609
|
this.merge(up);
|
|
49610
|
+
for (const i of up.keys()) {
|
|
49611
|
+
this.flags[i] |= IN_UP;
|
|
49612
|
+
this.upLength[i] = this.parentIdx[i]?.length ?? 0;
|
|
49613
|
+
}
|
|
49103
49614
|
this.merge(childGraph);
|
|
49104
|
-
this.childMap = childrenOf(this.parentMap);
|
|
49105
49615
|
this.countMembers();
|
|
49106
49616
|
}
|
|
49107
49617
|
/** Add `<< candidates`, so their descendants are complete. */
|
|
49108
49618
|
addBelow(down) {
|
|
49109
49619
|
this.merge(down);
|
|
49110
|
-
for (const
|
|
49111
|
-
this.childMap = childrenOf(this.parentMap);
|
|
49620
|
+
for (const i of down.keys()) this.flags[i] |= BELOW;
|
|
49112
49621
|
this.cache.clear();
|
|
49113
49622
|
}
|
|
49623
|
+
/** The number of `id`, given one if it has none, with room for it here. */
|
|
49624
|
+
at(id) {
|
|
49625
|
+
const i = this.ids.at(id);
|
|
49626
|
+
this.room(i);
|
|
49627
|
+
return i;
|
|
49628
|
+
}
|
|
49629
|
+
/** Room for concept `i`, and for every concept numbered before it. */
|
|
49630
|
+
room(i) {
|
|
49631
|
+
while (this.parentIdx.length <= i) {
|
|
49632
|
+
this.parentIdx.push(void 0);
|
|
49633
|
+
this.childIdx.push(void 0);
|
|
49634
|
+
}
|
|
49635
|
+
while (i >= this.rank.length) this.grow();
|
|
49636
|
+
}
|
|
49637
|
+
/** The number of `id` when the graph has it. */
|
|
49638
|
+
known(id) {
|
|
49639
|
+
const i = this.ids.get(id);
|
|
49640
|
+
return i !== void 0 && i < this.parentIdx.length ? i : void 0;
|
|
49641
|
+
}
|
|
49642
|
+
grow() {
|
|
49643
|
+
const size = this.rank.length * 2;
|
|
49644
|
+
const rank = new Int32Array(size).fill(-1);
|
|
49645
|
+
rank.set(this.rank);
|
|
49646
|
+
this.rank = rank;
|
|
49647
|
+
this.upLength = withSize(this.upLength, size);
|
|
49648
|
+
this.counts = withSize(this.counts, size);
|
|
49649
|
+
const flags = new Uint8Array(size);
|
|
49650
|
+
flags.set(this.flags);
|
|
49651
|
+
this.flags = flags;
|
|
49652
|
+
}
|
|
49114
49653
|
merge(graph) {
|
|
49115
|
-
for (const [
|
|
49116
|
-
|
|
49117
|
-
for (const p of parents)
|
|
49118
|
-
this.
|
|
49654
|
+
for (const [i, parents] of graph) {
|
|
49655
|
+
this.room(i);
|
|
49656
|
+
for (const p of parents) this.room(p);
|
|
49657
|
+
if (this.rank[i] < 0) this.rank[i] = this.nextRank++;
|
|
49658
|
+
if (!this.parentIdx[i] && new Set(parents).size === parents.length) {
|
|
49659
|
+
this.parentIdx[i] = parents;
|
|
49660
|
+
this.flags[i] |= SHARED;
|
|
49661
|
+
for (const p of parents) this.addChild(p, i);
|
|
49662
|
+
} else for (const p of parents) this.addParent(i, p);
|
|
49663
|
+
}
|
|
49664
|
+
}
|
|
49665
|
+
addParent(i, p) {
|
|
49666
|
+
let known = this.parentIdx[i];
|
|
49667
|
+
if (known?.includes(p)) return;
|
|
49668
|
+
if (!known || (this.flags[i] & SHARED) !== 0) {
|
|
49669
|
+
known = known ? [...known] : [];
|
|
49670
|
+
this.parentIdx[i] = known;
|
|
49671
|
+
this.flags[i] &= ~SHARED;
|
|
49672
|
+
}
|
|
49673
|
+
known.push(p);
|
|
49674
|
+
this.addChild(p, i);
|
|
49675
|
+
}
|
|
49676
|
+
/** Put `child` among `parent`'s children, keeping them in rank order. */
|
|
49677
|
+
addChild(parent, child) {
|
|
49678
|
+
const list = this.childIdx[parent];
|
|
49679
|
+
if (!list) {
|
|
49680
|
+
this.childIdx[parent] = [child];
|
|
49681
|
+
return;
|
|
49119
49682
|
}
|
|
49683
|
+
const r = this.rank[child];
|
|
49684
|
+
let at = list.length;
|
|
49685
|
+
while (at > 0 && this.rank[list[at - 1]] > r) at--;
|
|
49686
|
+
if (at === list.length) list.push(child);
|
|
49687
|
+
else list.splice(at, 0, child);
|
|
49120
49688
|
}
|
|
49121
49689
|
countMembers() {
|
|
49122
49690
|
const nonRoots = /* @__PURE__ */ new Set();
|
|
49123
|
-
for (const m of this.members)
|
|
49124
|
-
|
|
49125
|
-
|
|
49691
|
+
for (const m of this.members) this.at(m);
|
|
49692
|
+
const seen = new Uint8Array(this.parentIdx.length);
|
|
49693
|
+
const touched = [];
|
|
49694
|
+
for (const m of this.members) {
|
|
49695
|
+
const start = this.at(m);
|
|
49696
|
+
this.upFrom(start, seen, touched);
|
|
49697
|
+
for (const a of touched) {
|
|
49698
|
+
this.counts[a]++;
|
|
49699
|
+
seen[a] = 0;
|
|
49700
|
+
if (a !== start && this.members.has(this.ids.list[a])) nonRoots.add(m);
|
|
49701
|
+
}
|
|
49702
|
+
touched.length = 0;
|
|
49126
49703
|
}
|
|
49127
49704
|
this.rootIds.push(...[...this.members].filter((m) => !nonRoots.has(m)).sort(byId));
|
|
49128
49705
|
}
|
|
49706
|
+
/** `start` and everything reachable from it along `up`'s parents, into `touched`, marked in `seen`. */
|
|
49707
|
+
upFrom(start, seen, touched) {
|
|
49708
|
+
seen[start] = 1;
|
|
49709
|
+
touched.push(start);
|
|
49710
|
+
for (const next of touched) {
|
|
49711
|
+
const parents = this.parentIdx[next] ?? [];
|
|
49712
|
+
const fromUp = this.upLength[next];
|
|
49713
|
+
for (const p of fromUp === parents.length ? parents : parents.slice(0, fromUp)) {
|
|
49714
|
+
if (seen[p]) continue;
|
|
49715
|
+
seen[p] = 1;
|
|
49716
|
+
touched.push(p);
|
|
49717
|
+
}
|
|
49718
|
+
}
|
|
49719
|
+
}
|
|
49720
|
+
names(list) {
|
|
49721
|
+
const out = [];
|
|
49722
|
+
if (list) for (const i of list) out.push(this.ids.list[i]);
|
|
49723
|
+
return out;
|
|
49724
|
+
}
|
|
49129
49725
|
aboveMember(id) {
|
|
49130
|
-
|
|
49726
|
+
const i = this.known(id);
|
|
49727
|
+
return i !== void 0 && (this.flags[i] & IN_UP) !== 0;
|
|
49131
49728
|
}
|
|
49132
49729
|
children(id) {
|
|
49133
|
-
|
|
49730
|
+
const i = this.known(id);
|
|
49731
|
+
return i === void 0 ? [] : this.names(this.childIdx[i]);
|
|
49134
49732
|
}
|
|
49135
49733
|
parents(id) {
|
|
49136
|
-
|
|
49734
|
+
const i = this.known(id);
|
|
49735
|
+
return i === void 0 ? [] : this.names(this.parentIdx[i]);
|
|
49137
49736
|
}
|
|
49138
49737
|
descendants(id) {
|
|
49139
|
-
|
|
49738
|
+
const i = this.known(id);
|
|
49739
|
+
if (i === void 0) return [id];
|
|
49740
|
+
let list = this.cache.get(i);
|
|
49140
49741
|
if (!list) {
|
|
49141
|
-
list =
|
|
49142
|
-
this.cache.set(
|
|
49742
|
+
list = this.reachableDown(i);
|
|
49743
|
+
if (list.length >= CACHED_DESCENDANTS) this.cache.set(i, list);
|
|
49143
49744
|
}
|
|
49144
|
-
return list;
|
|
49745
|
+
return this.names(list);
|
|
49746
|
+
}
|
|
49747
|
+
/** `start` and everything below it, in the order a depth-first walk first meets them. */
|
|
49748
|
+
reachableDown(start) {
|
|
49749
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
49750
|
+
const stack = [start];
|
|
49751
|
+
for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of this.childIdx[next] ?? []) {
|
|
49752
|
+
if (seen.has(x)) continue;
|
|
49753
|
+
seen.add(x);
|
|
49754
|
+
stack.push(x);
|
|
49755
|
+
}
|
|
49756
|
+
return Int32Array.from(seen);
|
|
49145
49757
|
}
|
|
49146
49758
|
hasDescendants(id) {
|
|
49147
|
-
|
|
49759
|
+
const i = this.known(id);
|
|
49760
|
+
if (i === void 0) return false;
|
|
49761
|
+
return (this.flags[i] & BELOW) !== 0 || (this.flags[i] & IN_UP) !== 0 && !this.childIdx[i]?.length;
|
|
49148
49762
|
}
|
|
49149
49763
|
truePos(id) {
|
|
49150
|
-
|
|
49764
|
+
const i = this.known(id);
|
|
49765
|
+
return i === void 0 ? 0 : this.counts[i];
|
|
49766
|
+
}
|
|
49767
|
+
membersBelow(id) {
|
|
49768
|
+
const start = this.known(id);
|
|
49769
|
+
if (start === void 0) return this.members.has(id) ? [id] : [];
|
|
49770
|
+
const found = [];
|
|
49771
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
49772
|
+
const stack = [start];
|
|
49773
|
+
for (let next = stack.pop(); next !== void 0; next = stack.pop()) {
|
|
49774
|
+
if (this.members.has(this.ids.list[next])) found.push(this.ids.list[next]);
|
|
49775
|
+
for (const c of this.childIdx[next] ?? []) {
|
|
49776
|
+
if (seen.has(c) || (this.flags[c] & IN_UP) === 0) continue;
|
|
49777
|
+
seen.add(c);
|
|
49778
|
+
stack.push(c);
|
|
49779
|
+
}
|
|
49780
|
+
}
|
|
49781
|
+
return found.sort(byId);
|
|
49151
49782
|
}
|
|
49152
49783
|
roots() {
|
|
49153
49784
|
return this.rootIds;
|
|
49154
49785
|
}
|
|
49155
49786
|
ancestors() {
|
|
49156
|
-
return
|
|
49787
|
+
return this.ids.list.filter((id, i) => i < this.parentIdx.length && (this.flags[i] & IN_UP) !== 0 && id !== "138875005").sort(byId);
|
|
49157
49788
|
}
|
|
49158
49789
|
};
|
|
49159
|
-
|
|
49160
|
-
|
|
49161
|
-
|
|
49162
|
-
|
|
49163
|
-
|
|
49164
|
-
|
|
49165
|
-
|
|
49166
|
-
|
|
49167
|
-
|
|
49168
|
-
|
|
49169
|
-
function reachable(start, edges) {
|
|
49170
|
-
const seen = /* @__PURE__ */ new Set([start]);
|
|
49171
|
-
const stack = [start];
|
|
49172
|
-
for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of edges.get(next) ?? []) {
|
|
49173
|
-
if (seen.has(x)) continue;
|
|
49174
|
-
seen.add(x);
|
|
49175
|
-
stack.push(x);
|
|
49176
|
-
}
|
|
49177
|
-
return seen;
|
|
49790
|
+
/** The fewest descendants worth caching. */
|
|
49791
|
+
var CACHED_DESCENDANTS = 64;
|
|
49792
|
+
var IN_UP = 1;
|
|
49793
|
+
var BELOW = 2;
|
|
49794
|
+
/** The concept's parent list is the caller's, so it is copied before the graph adds to it. */
|
|
49795
|
+
var SHARED = 4;
|
|
49796
|
+
function withSize(a, size) {
|
|
49797
|
+
const out = new Int32Array(size);
|
|
49798
|
+
out.set(a);
|
|
49799
|
+
return out;
|
|
49178
49800
|
}
|
|
49179
49801
|
// src/derive/refinements.ts
|
|
49180
49802
|
/** Members whose relationships are read to profile the attributes the set shares. */
|
|
@@ -49215,19 +49837,39 @@ async function readRelationships(sample, getRelationships, notes) {
|
|
|
49215
49837
|
return sampled;
|
|
49216
49838
|
}
|
|
49217
49839
|
/**
|
|
49840
|
+
* The sample's relationships in one batch request; null (read one by one)
|
|
49841
|
+
* when the batch fails. Entries the batch could not answer are read one by
|
|
49842
|
+
* one. `many` is not counted as a failure (see `uncounted`): only the one-by-one
|
|
49843
|
+
* reads, which lose what they cannot read, are.
|
|
49844
|
+
*/
|
|
49845
|
+
async function readMany(sample, many, getRelationships, notes) {
|
|
49846
|
+
let answers;
|
|
49847
|
+
try {
|
|
49848
|
+
answers = await many(sample);
|
|
49849
|
+
} catch {
|
|
49850
|
+
return null;
|
|
49851
|
+
}
|
|
49852
|
+
const answered = answers.filter((a) => !(a instanceof Error));
|
|
49853
|
+
const retry = sample.filter((_, i) => answers[i] instanceof Error);
|
|
49854
|
+
if (retry.length > 0) answered.push(...await readRelationships(retry, getRelationships, notes));
|
|
49855
|
+
return answered;
|
|
49856
|
+
}
|
|
49857
|
+
/**
|
|
49218
49858
|
* Refinement candidates for the set, likeliest first. `roots` are the set's
|
|
49219
49859
|
* roots (all of them when `roots.total` fits); `givenFoci` come from the input
|
|
49220
49860
|
* or the caller, and the most specific concept above every member is added
|
|
49221
49861
|
* unless `fixedFocus` says the caller chose the focus.
|
|
49222
49862
|
*/
|
|
49223
|
-
async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes) {
|
|
49863
|
+
async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes, batch = false) {
|
|
49224
49864
|
const getRelationships = terminology.getDefiningRelationships?.bind(terminology);
|
|
49225
49865
|
if (!getRelationships) {
|
|
49226
49866
|
notes.push("Refinement candidates need a terminology service with getDefiningRelationships.");
|
|
49227
49867
|
return [];
|
|
49228
49868
|
}
|
|
49229
49869
|
const sample = (await q.codes({ include: [members.clause] }, REFINEMENT_SAMPLE)).codes;
|
|
49230
|
-
const
|
|
49870
|
+
const quiet = uncounted(terminology);
|
|
49871
|
+
const many = batch ? quiet.getDefiningRelationshipsMany?.bind(quiet) : void 0;
|
|
49872
|
+
const sampled = (many && await readMany(sample, many, getRelationships, notes)) ?? await readRelationships(sample, getRelationships, notes);
|
|
49231
49873
|
const profiles = profileAttributes(sampled);
|
|
49232
49874
|
if (profiles.length === 0) {
|
|
49233
49875
|
notes.push("No attribute is shared by most members, so no refinement candidates were built.");
|
|
@@ -49472,7 +50114,13 @@ var DEFAULTS = {
|
|
|
49472
50114
|
greedyGrouping: true,
|
|
49473
50115
|
useGraph: true,
|
|
49474
50116
|
maxGraphConcepts: 2e5,
|
|
49475
|
-
critique: false
|
|
50117
|
+
critique: false,
|
|
50118
|
+
restrictTo: "auto",
|
|
50119
|
+
parallelPages: true,
|
|
50120
|
+
localScoring: false,
|
|
50121
|
+
scopedExclusions: true,
|
|
50122
|
+
walkGraph: true,
|
|
50123
|
+
batchLookups: true
|
|
49476
50124
|
};
|
|
49477
50125
|
var CRITIQUE_DEFAULTS = {
|
|
49478
50126
|
maxClauses: 35,
|
|
@@ -49507,6 +50155,13 @@ var MAX_SUBTRACTED = 2;
|
|
|
49507
50155
|
*/
|
|
49508
50156
|
async function deriveEcl(input, terminology, options = {}) {
|
|
49509
50157
|
if (!terminology.expandCompose) throw new Error("deriveEcl needs a terminology service that supports expandCompose (POST ValueSet/$expand)");
|
|
50158
|
+
const { service, failures } = countingFailures(terminology);
|
|
50159
|
+
const result = await derive(input, service, options);
|
|
50160
|
+
result.failures = failures();
|
|
50161
|
+
return result;
|
|
50162
|
+
}
|
|
50163
|
+
async function derive(input, terminology, options) {
|
|
50164
|
+
if (!terminology.expandCompose) throw new Error("unreachable: checked by deriveEcl");
|
|
49510
50165
|
const opts = {
|
|
49511
50166
|
...DEFAULTS,
|
|
49512
50167
|
...options
|
|
@@ -49515,21 +50170,28 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49515
50170
|
const q = new SetQueries((compose, o) => expandCompose(compose, {
|
|
49516
50171
|
timeoutMs: opts.queryTimeoutMs,
|
|
49517
50172
|
...o
|
|
49518
|
-
}));
|
|
50173
|
+
}), opts.parallelPages);
|
|
50174
|
+
const quiet = uncounted(terminology);
|
|
50175
|
+
const quietExpand = quiet.expandCompose?.bind(quiet) ?? expandCompose;
|
|
50176
|
+
const belowQueries = new SetQueries((compose, o) => quietExpand(compose, {
|
|
50177
|
+
timeoutMs: opts.queryTimeoutMs,
|
|
50178
|
+
...o
|
|
50179
|
+
}), opts.parallelPages);
|
|
49519
50180
|
const notes = [];
|
|
49520
|
-
const { report, members } = await resolveInput(input, q, terminology, notes);
|
|
50181
|
+
const { report, members } = await resolveInput(input, q, terminology, notes, opts.walkGraph);
|
|
49521
50182
|
const result = {
|
|
49522
50183
|
input: report,
|
|
49523
50184
|
hierarchies: [],
|
|
49524
50185
|
roots: 0,
|
|
49525
50186
|
candidates: [],
|
|
49526
|
-
notes
|
|
50187
|
+
notes,
|
|
50188
|
+
failures: 0
|
|
49527
50189
|
};
|
|
49528
50190
|
if (!members) {
|
|
49529
50191
|
if (notes.length === 0) notes.push("The input has no active concepts the server knows, so there is nothing to derive.");
|
|
49530
50192
|
return result;
|
|
49531
50193
|
}
|
|
49532
|
-
const graph = opts.useGraph ? await loadGraph(members, q, opts, notes) : null;
|
|
50194
|
+
const graph = opts.useGraph ? await loadGraph(members, q, opts, notes, belowQueries) : null;
|
|
49533
50195
|
const critique = critiqueOptions(opts.critique);
|
|
49534
50196
|
let hierarchies = [];
|
|
49535
50197
|
if (opts.hierarchySummary || critique) hierarchies = graph ? await graphHierarchies(graph, terminology) : await hierarchyDistribution(members, q);
|
|
@@ -49543,8 +50205,12 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49543
50205
|
}, opts.maxRoots + 1);
|
|
49544
50206
|
result.roots = rootQuery.total;
|
|
49545
50207
|
const scorer = new Scorer(members, q, opts, notes);
|
|
49546
|
-
|
|
49547
|
-
|
|
50208
|
+
const countedLocally = /* @__PURE__ */ new Set();
|
|
50209
|
+
if (graph) {
|
|
50210
|
+
const worth = worthCounting(graphCandidates(graph, opts, notes), inputCost(input, members), opts, notes);
|
|
50211
|
+
await scorer.score(countOnGraph(worth, graph, opts, countedLocally));
|
|
50212
|
+
await scorer.score(await restrictedCovers(graph, members, q, opts, notes));
|
|
50213
|
+
} else await scorer.score(await hierarchyCandidates(rootQuery.codes, result.roots, members, q, opts, notes));
|
|
49548
50214
|
if (wantRefinements(opts.refinements, result.roots, scorer.scored)) await scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes);
|
|
49549
50215
|
await scorer.score([inputItself(input, members)]);
|
|
49550
50216
|
if (critique) result.critique = await buildCritique(critique, {
|
|
@@ -49555,9 +50221,11 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49555
50221
|
hierarchies,
|
|
49556
50222
|
scored: scorer.scored
|
|
49557
50223
|
}, q, terminology, opts);
|
|
49558
|
-
scorer.scored.
|
|
49559
|
-
|
|
49560
|
-
const
|
|
50224
|
+
const useful = scorer.scored.filter((s) => s.covered > 0);
|
|
50225
|
+
useful.sort((a, b) => byRank(rankOf(a), rankOf(b)));
|
|
50226
|
+
const top = useful.slice(0, opts.maxCandidates);
|
|
50227
|
+
await checkLocalCounts(top, countedLocally, members, q, opts, notes);
|
|
50228
|
+
const terms = opts.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, notes);
|
|
49561
50229
|
result.candidates = top.map((s) => ({
|
|
49562
50230
|
expression: decorate(s.ecl, terms),
|
|
49563
50231
|
...s
|
|
@@ -49568,7 +50236,7 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49568
50236
|
async function scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes) {
|
|
49569
50237
|
let given = "ecl" in input ? refsetFoci(input.ecl) : [];
|
|
49570
50238
|
if (opts.refinementFocus) given = [asFocus(opts.refinementFocus)];
|
|
49571
|
-
const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes)).map(({ focus, clauses }) => ({
|
|
50239
|
+
const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes, opts.batchLookups)).map(({ focus, clauses }) => ({
|
|
49572
50240
|
ecl: refinementText(focus, clauses),
|
|
49573
50241
|
construction: {
|
|
49574
50242
|
kind: "refinement",
|
|
@@ -49599,7 +50267,7 @@ async function subtractions(scored, members, terminology, opts) {
|
|
|
49599
50267
|
critique: false,
|
|
49600
50268
|
omitTerms: true,
|
|
49601
50269
|
maxCandidates: 3
|
|
49602
|
-
})).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0);
|
|
50270
|
+
})).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0 && x.additions.count < c.additions.count);
|
|
49603
50271
|
if (d) built.push({
|
|
49604
50272
|
ecl: `(${c.ecl}) MINUS (${d.ecl})`,
|
|
49605
50273
|
construction: {
|
|
@@ -49619,6 +50287,7 @@ async function subtractions(scored, members, terminology, opts) {
|
|
|
49619
50287
|
function wantRefinements(mode, roots, scored) {
|
|
49620
50288
|
if (mode === "always") return true;
|
|
49621
50289
|
if (mode === "never") return false;
|
|
50290
|
+
if (scored.some((c) => c.exact && c.construction.kind === "restricted-cover")) return false;
|
|
49622
50291
|
if (roots > REFINEMENT_ROOTS) return true;
|
|
49623
50292
|
return roots > 3 && !scored.some((c) => c.exact && c.clauses <= 3);
|
|
49624
50293
|
}
|
|
@@ -49671,9 +50340,9 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
|
|
|
49671
50340
|
return [];
|
|
49672
50341
|
}
|
|
49673
50342
|
const local = nearMissCandidates(graph, limits.nearMissShare, limits.nearMissMinSize).slice(0, limits.maxNearMisses * NEAR_MISS_CANDIDATES_PER_REPORTED);
|
|
49674
|
-
const counted = await Promise.allSettled(local.map((n) => q.sample({
|
|
50343
|
+
const counted = await nearMissesOnGraph(local, graph, opts.sampleSize) ?? await Promise.allSettled(local.map((n) => q.sample({
|
|
49675
50344
|
include: [{ ecl: `<< ${n.conceptId}` }],
|
|
49676
|
-
exclude: [members.clause]
|
|
50345
|
+
exclude: [opts.scopedExclusions ? { concepts: graph.membersBelow(n.conceptId) } : members.clause]
|
|
49677
50346
|
}, opts.sampleSize)));
|
|
49678
50347
|
const confirmed = [];
|
|
49679
50348
|
counted.forEach((r, i) => {
|
|
@@ -49700,6 +50369,34 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
|
|
|
49700
50369
|
return found;
|
|
49701
50370
|
}
|
|
49702
50371
|
/**
|
|
50372
|
+
* What each near-miss candidate adds, counted on a walked graph
|
|
50373
|
+
* after walking down below the candidates whose descendants are not loaded;
|
|
50374
|
+
* null when the graph cannot (not walked, or too many), and the server counts.
|
|
50375
|
+
*/
|
|
50376
|
+
async function nearMissesOnGraph(local, graph, sampleSize) {
|
|
50377
|
+
if (!graph.loadBelow || local.length === 0) return null;
|
|
50378
|
+
const need = local.map((n) => n.conceptId).filter((id) => !graph.hasDescendants(id));
|
|
50379
|
+
try {
|
|
50380
|
+
if (need.length > 0 && !await graph.loadBelow(need)) return null;
|
|
50381
|
+
} catch {
|
|
50382
|
+
return null;
|
|
50383
|
+
}
|
|
50384
|
+
return local.map((n) => {
|
|
50385
|
+
const missing = graph.descendants(n.conceptId).filter((x) => !graph.members.has(x)).sort(byId);
|
|
50386
|
+
const sample = missing.slice(0, sampleSize).map((code) => ({
|
|
50387
|
+
code,
|
|
50388
|
+
display: graph.term?.(code) ?? ""
|
|
50389
|
+
}));
|
|
50390
|
+
return {
|
|
50391
|
+
status: "fulfilled",
|
|
50392
|
+
value: {
|
|
50393
|
+
count: missing.length,
|
|
50394
|
+
sample
|
|
50395
|
+
}
|
|
50396
|
+
};
|
|
50397
|
+
});
|
|
50398
|
+
}
|
|
50399
|
+
/**
|
|
49703
50400
|
* Members that share a preferred term (CHK13): one listing of the members with
|
|
49704
50401
|
* their terms, plus a lookup of the FSNs that tell each group apart.
|
|
49705
50402
|
*/
|
|
@@ -49712,7 +50409,7 @@ async function sharedTerms(max, members, q, terminology, opts, notes) {
|
|
|
49712
50409
|
}
|
|
49713
50410
|
let groups;
|
|
49714
50411
|
try {
|
|
49715
|
-
groups = findDuplicateTerms((await q.concepts({ include: [members.clause] }, members.size)).concepts);
|
|
50412
|
+
groups = findDuplicateTerms(members.concepts ?? (await q.concepts({ include: [members.clause] }, members.size)).concepts);
|
|
49716
50413
|
} catch (error) {
|
|
49717
50414
|
notes.push(`Shared terms were not checked: ${errorMessage(error)}.`);
|
|
49718
50415
|
return [];
|
|
@@ -49786,7 +50483,7 @@ function formKey(ecl) {
|
|
|
49786
50483
|
return ecl;
|
|
49787
50484
|
}
|
|
49788
50485
|
}
|
|
49789
|
-
async function resolveInput(input, q, terminology, notes) {
|
|
50486
|
+
async function resolveInput(input, q, terminology, notes, lookUp = false) {
|
|
49790
50487
|
if ("refsetId" in input) return resolveRefset(input.refsetId.trim(), q, terminology, notes);
|
|
49791
50488
|
if ("ecl" in input) {
|
|
49792
50489
|
const ecl = `(${stripTermsAndComments(input.ecl)})`;
|
|
@@ -49824,8 +50521,19 @@ async function resolveInput(input, q, terminology, notes) {
|
|
|
49824
50521
|
members: null
|
|
49825
50522
|
};
|
|
49826
50523
|
const listed = { include: [{ concepts: wellFormed }] };
|
|
49827
|
-
|
|
49828
|
-
|
|
50524
|
+
let activeConcepts;
|
|
50525
|
+
let knownConcepts;
|
|
50526
|
+
let walk;
|
|
50527
|
+
let walkable = true;
|
|
50528
|
+
const looked = lookUp ? await lookUpList(wellFormed, q) : null;
|
|
50529
|
+
if (looked) {
|
|
50530
|
+
knownConcepts = { concepts: looked.concepts };
|
|
50531
|
+
activeConcepts = { concepts: looked.concepts.filter((c) => !c.inactive) };
|
|
50532
|
+
walk = looked.walk;
|
|
50533
|
+
walkable = looked.walkable;
|
|
50534
|
+
} else [activeConcepts, knownConcepts] = await Promise.all([q.conceptsUpTo(listed, wellFormed.length, true), q.conceptsUpTo(listed, wellFormed.length, false)]);
|
|
50535
|
+
const active = activeConcepts.concepts.map((c) => c.code).sort(byId);
|
|
50536
|
+
const known = new Set(knownConcepts.concepts.map((c) => c.code));
|
|
49829
50537
|
const activeSet = new Set(active);
|
|
49830
50538
|
report.inactive = wellFormed.filter((id) => known.has(id) && !activeSet.has(id));
|
|
49831
50539
|
report.unknown = wellFormed.filter((id) => !known.has(id));
|
|
@@ -49834,15 +50542,73 @@ async function resolveInput(input, q, terminology, notes) {
|
|
|
49834
50542
|
report,
|
|
49835
50543
|
members: null
|
|
49836
50544
|
};
|
|
50545
|
+
Object.freeze(active);
|
|
49837
50546
|
return {
|
|
49838
50547
|
report,
|
|
49839
50548
|
members: {
|
|
49840
50549
|
clause: { concepts: active },
|
|
49841
50550
|
ecl: orGroup(active),
|
|
49842
|
-
size: active.length
|
|
50551
|
+
size: active.length,
|
|
50552
|
+
concepts: activeConcepts.concepts,
|
|
50553
|
+
...walk ? { walk } : {},
|
|
50554
|
+
...walkable ? {} : { walkUnsupported: true }
|
|
49843
50555
|
}
|
|
49844
50556
|
};
|
|
49845
50557
|
}
|
|
50558
|
+
/**
|
|
50559
|
+
* One chunked lookup of a list, for activity, terms, parents and children (for
|
|
50560
|
+
* walkGraph). Each chunk is cut down as it arrives: the terms kept, the active
|
|
50561
|
+
* concepts' parents and children numbered into a walk (none when the server
|
|
50562
|
+
* left them out).
|
|
50563
|
+
*/
|
|
50564
|
+
/**
|
|
50565
|
+
* The list looked up once, with each concept's activity, parents and children:
|
|
50566
|
+
* its concepts, and the walk they seed (absent, with `walkable` false, when
|
|
50567
|
+
* the server gave no parents or children). Activity is asked for explicitly
|
|
50568
|
+
* (`property=inactive`), so a server that states it (Ontoserver) answers with
|
|
50569
|
+
* nothing more. On one that does not, a list with no concept flagged inactive
|
|
50570
|
+
* is checked with one count per chunk; null when that count disagrees: the
|
|
50571
|
+
* server does not flag inactive concepts, so the caller must ask twice and
|
|
50572
|
+
* difference the answers.
|
|
50573
|
+
*/
|
|
50574
|
+
async function lookUpList(codes, q) {
|
|
50575
|
+
const seed = new Walk();
|
|
50576
|
+
const chunks = await q.lookupEach(codes, {
|
|
50577
|
+
activeOnly: false,
|
|
50578
|
+
parents: true,
|
|
50579
|
+
children: true,
|
|
50580
|
+
activity: true
|
|
50581
|
+
}, (concepts) => ({
|
|
50582
|
+
terms: concepts.map(({ code, display, inactive }) => inactive ? {
|
|
50583
|
+
code,
|
|
50584
|
+
display,
|
|
50585
|
+
inactive
|
|
50586
|
+
} : {
|
|
50587
|
+
code,
|
|
50588
|
+
display
|
|
50589
|
+
}),
|
|
50590
|
+
nodes: seed.nodesFor(concepts.filter((c) => !c.inactive)),
|
|
50591
|
+
stated: concepts.every((c) => c.inactive !== void 0)
|
|
50592
|
+
}));
|
|
50593
|
+
const concepts = chunks.flatMap((c) => c.terms);
|
|
50594
|
+
if (chunks.some((c) => !c.stated) && !concepts.some((c) => c.inactive) && await activeCount(codes, q) !== concepts.length) return null;
|
|
50595
|
+
if (chunks.some((c) => c.nodes === null)) return {
|
|
50596
|
+
concepts,
|
|
50597
|
+
walkable: false
|
|
50598
|
+
};
|
|
50599
|
+
for (const c of chunks) if (c.nodes) seed.add(c.nodes);
|
|
50600
|
+
return {
|
|
50601
|
+
concepts,
|
|
50602
|
+
walk: seed,
|
|
50603
|
+
walkable: true
|
|
50604
|
+
};
|
|
50605
|
+
}
|
|
50606
|
+
/** How many of `codes` are active, one count per lookup chunk. */
|
|
50607
|
+
async function activeCount(codes, q) {
|
|
50608
|
+
const counts = [];
|
|
50609
|
+
for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) counts.push(q.count({ include: [{ concepts: codes.slice(i, i + LOOKUP_CHUNK) }] }));
|
|
50610
|
+
return (await Promise.all(counts)).reduce((a, b) => a + b, 0);
|
|
50611
|
+
}
|
|
49846
50612
|
async function resolveRefset(refsetId, q, terminology, notes) {
|
|
49847
50613
|
const report = {
|
|
49848
50614
|
given: 1,
|
|
@@ -49859,7 +50625,16 @@ async function resolveRefset(refsetId, q, terminology, notes) {
|
|
|
49859
50625
|
const ecl = `(^ ${refsetId})`;
|
|
49860
50626
|
report.members = await q.countEcl(ecl);
|
|
49861
50627
|
if (report.members === 0) {
|
|
49862
|
-
|
|
50628
|
+
let info;
|
|
50629
|
+
try {
|
|
50630
|
+
info = await terminology.getConceptInfo(refsetId);
|
|
50631
|
+
} catch (error) {
|
|
50632
|
+
notes.push(`${refsetId} has no active members; could not look it up to say why: ${errorMessage(error)}.`);
|
|
50633
|
+
return {
|
|
50634
|
+
report,
|
|
50635
|
+
members: null
|
|
50636
|
+
};
|
|
50637
|
+
}
|
|
49863
50638
|
if (info === null) report.unknown.push(refsetId);
|
|
49864
50639
|
else if (info.active) notes.push(`${refsetId} |${info.pt}| has no active members, or is not a reference set.`);
|
|
49865
50640
|
else report.inactive.push(refsetId);
|
|
@@ -49899,14 +50674,19 @@ async function graphHierarchies(g, terminology) {
|
|
|
49899
50674
|
})).sort((a, b) => b.count - a.count || byId(a.conceptId, b.conceptId));
|
|
49900
50675
|
}
|
|
49901
50676
|
/** The IS-A subgraph around the set, or null (with a note) when the per-query path must be used. */
|
|
49902
|
-
async function loadGraph(members, q, opts, notes) {
|
|
50677
|
+
async function loadGraph(members, q, opts, notes, belowQueries) {
|
|
49903
50678
|
let why;
|
|
49904
50679
|
try {
|
|
49905
50680
|
const graph = await loadTaxonomyGraph(members, q, {
|
|
49906
50681
|
maxConcepts: opts.maxGraphConcepts,
|
|
49907
50682
|
descend: (id, g) => coverDescend(id, g) || refactorDescend(id, g),
|
|
49908
|
-
fallbackDescend: refactorDescend
|
|
50683
|
+
fallbackDescend: refactorDescend,
|
|
50684
|
+
walk: opts.walkGraph && !members.walkUnsupported,
|
|
50685
|
+
...members.walk ? { seed: members.walk } : {},
|
|
50686
|
+
belowQueries,
|
|
50687
|
+
..."concepts" in members.clause ? { memberCodes: members.clause.concepts } : {}
|
|
49909
50688
|
});
|
|
50689
|
+
delete members.walk;
|
|
49910
50690
|
if (!("unavailable" in graph)) {
|
|
49911
50691
|
if (graph.partial) notes.push(`The IS-A subgraph is partial: below the set's roots and every candidate grouper it has more than ${opts.maxGraphConcepts} concepts (maxGraphConcepts), so descendants were loaded only for greedy grouping's candidates, and hierarchy forms that need others were left out.`);
|
|
49912
50692
|
return graph;
|
|
@@ -49971,7 +50751,8 @@ function graphCandidates(g, opts, notes) {
|
|
|
49971
50751
|
if (local) candidates.push({
|
|
49972
50752
|
ecl,
|
|
49973
50753
|
construction,
|
|
49974
|
-
local
|
|
50754
|
+
local,
|
|
50755
|
+
form
|
|
49975
50756
|
});
|
|
49976
50757
|
}
|
|
49977
50758
|
return candidates.sort((a, b) => byRank({
|
|
@@ -49984,6 +50765,70 @@ function graphCandidates(g, opts, notes) {
|
|
|
49984
50765
|
...b.local
|
|
49985
50766
|
}));
|
|
49986
50767
|
}
|
|
50768
|
+
/** AMT's level reference sets, likeliest first for a list of products: MPUU, MP, TPUU, TP, MPP, TPP, CTPP. */
|
|
50769
|
+
var AMT_LEVEL_REFSETS = [
|
|
50770
|
+
"929360071000036103",
|
|
50771
|
+
"929360061000036106",
|
|
50772
|
+
"929360031000036100",
|
|
50773
|
+
"929360021000036102",
|
|
50774
|
+
"929360081000036101",
|
|
50775
|
+
"929360041000036105",
|
|
50776
|
+
"929360051000036108"
|
|
50777
|
+
];
|
|
50778
|
+
var MEDICINAL_PRODUCT = "763158003";
|
|
50779
|
+
/**
|
|
50780
|
+
* The cover exact within `restrictTo` (see {@link DeriveOptions.restrictTo}).
|
|
50781
|
+
* A concept of `>> set` may stand as `<< x` when nothing of `restrictTo` below
|
|
50782
|
+
* it is a non-member: one query finds the concepts of `>> set` that are above
|
|
50783
|
+
* such a non-member. The highest of the rest, with each member that is itself
|
|
50784
|
+
* above a non-member, cover the set exactly once ANDed with `restrictTo`.
|
|
50785
|
+
*/
|
|
50786
|
+
async function restrictedCovers(g, members, q, opts, notes) {
|
|
50787
|
+
if (g.partial) return [];
|
|
50788
|
+
const restrictTo = opts.restrictTo === "auto" ? await amtLevel(g, members, q) : opts.restrictTo.trim();
|
|
50789
|
+
if (!restrictTo) return [];
|
|
50790
|
+
const within = /^\^ ?\d+$/.test(restrictTo) ? restrictTo : `(${restrictTo})`;
|
|
50791
|
+
let blocked;
|
|
50792
|
+
try {
|
|
50793
|
+
blocked = await q.codes({ include: [{ ecl: `(>> ${members.ecl}) AND (>> (${within} MINUS ${members.ecl}))` }] }, opts.maxGraphConcepts);
|
|
50794
|
+
} catch (error) {
|
|
50795
|
+
notes.push(`No cover within ${restrictTo}: ${errorMessage(error)}.`);
|
|
50796
|
+
return [];
|
|
50797
|
+
}
|
|
50798
|
+
const above = new Set(blocked.codes);
|
|
50799
|
+
const free = (id) => id !== "138875005" && !above.has(id);
|
|
50800
|
+
const includes = [];
|
|
50801
|
+
for (const x of /* @__PURE__ */ new Set([...g.ancestors(), ...g.members])) if (free(x)) {
|
|
50802
|
+
if (!g.parents(x).some(free)) includes.push({
|
|
50803
|
+
conceptId: x,
|
|
50804
|
+
operator: "<<"
|
|
50805
|
+
});
|
|
50806
|
+
} else if (g.members.has(x)) includes.push({
|
|
50807
|
+
conceptId: x,
|
|
50808
|
+
operator: "="
|
|
50809
|
+
});
|
|
50810
|
+
if (includes.length + 1 >= members.size) return [];
|
|
50811
|
+
includes.sort((a, b) => byId(a.conceptId, b.conceptId));
|
|
50812
|
+
return [{
|
|
50813
|
+
ecl: `${orGroup(includes.map((c) => c.operator === "=" ? c.conceptId : `<< ${c.conceptId}`))} AND ${within}`,
|
|
50814
|
+
construction: {
|
|
50815
|
+
kind: "restricted-cover",
|
|
50816
|
+
restrictTo,
|
|
50817
|
+
includes
|
|
50818
|
+
}
|
|
50819
|
+
}];
|
|
50820
|
+
}
|
|
50821
|
+
/** `^ R` for the AMT level reference set R holding every member, when all of them are medicinal products; else ''. */
|
|
50822
|
+
async function amtLevel(g, members, q) {
|
|
50823
|
+
if (g.truePos(MEDICINAL_PRODUCT) !== members.size) return "";
|
|
50824
|
+
for (const refset of AMT_LEVEL_REFSETS) try {
|
|
50825
|
+
if (await q.count({
|
|
50826
|
+
include: [members.clause],
|
|
50827
|
+
exclude: [{ ecl: `^ ${refset}` }]
|
|
50828
|
+
}) === 0) return `^ ${refset}`;
|
|
50829
|
+
} catch {}
|
|
50830
|
+
return "";
|
|
50831
|
+
}
|
|
49987
50832
|
/**
|
|
49988
50833
|
* The lowest non-member concepts with every member below them, at most 3. Their
|
|
49989
50834
|
* descendants may not be loaded: under `within` they are still worth counting
|
|
@@ -50394,6 +51239,82 @@ function exactScore(size) {
|
|
|
50394
51239
|
clauses: 0
|
|
50395
51240
|
};
|
|
50396
51241
|
}
|
|
51242
|
+
/**
|
|
51243
|
+
* localScoring: the candidates with their counts taken from the
|
|
51244
|
+
* graph, when it is complete and nothing restricts what additions count;
|
|
51245
|
+
* `countedLocally` collects those so counted.
|
|
51246
|
+
*/
|
|
51247
|
+
function countOnGraph(candidates, graph, opts, countedLocally) {
|
|
51248
|
+
if (!opts.localScoring || graph.partial || opts.within) return candidates;
|
|
51249
|
+
return candidates.map((b) => {
|
|
51250
|
+
const known = b.form ? graphScore(b.form, graph, opts.sampleSize) : null;
|
|
51251
|
+
if (!known) return b;
|
|
51252
|
+
countedLocally.add(b.ecl);
|
|
51253
|
+
return {
|
|
51254
|
+
...b,
|
|
51255
|
+
known: {
|
|
51256
|
+
...known,
|
|
51257
|
+
clauses: countClauses(b.ecl)
|
|
51258
|
+
}
|
|
51259
|
+
};
|
|
51260
|
+
});
|
|
51261
|
+
}
|
|
51262
|
+
/** Additions and misses of a form counted on the graph, with sample codes (no terms yet). */
|
|
51263
|
+
function graphScore(form, g, sampleSize) {
|
|
51264
|
+
const selected = evaluate(form, g);
|
|
51265
|
+
if (!selected) return null;
|
|
51266
|
+
const additions = [...selected].filter((x) => !g.members.has(x)).sort(byId);
|
|
51267
|
+
const misses = [...g.members].filter((m) => !selected.has(m)).sort(byId);
|
|
51268
|
+
const sample = (ids) => ids.slice(0, sampleSize).map((code) => ({
|
|
51269
|
+
code,
|
|
51270
|
+
display: ""
|
|
51271
|
+
}));
|
|
51272
|
+
return {
|
|
51273
|
+
covered: g.members.size - misses.length,
|
|
51274
|
+
additions: {
|
|
51275
|
+
count: additions.length,
|
|
51276
|
+
sample: sample(additions)
|
|
51277
|
+
},
|
|
51278
|
+
misses: {
|
|
51279
|
+
count: misses.length,
|
|
51280
|
+
sample: sample(misses)
|
|
51281
|
+
},
|
|
51282
|
+
exact: additions.length === 0 && misses.length === 0
|
|
51283
|
+
};
|
|
51284
|
+
}
|
|
51285
|
+
/**
|
|
51286
|
+
* The best candidate, when counted on the graph, is counted again
|
|
51287
|
+
* on the server (the server's counts replace the graph's), and the samples of
|
|
51288
|
+
* the others counted on the graph get their terms in one lookup.
|
|
51289
|
+
*/
|
|
51290
|
+
async function checkLocalCounts(top, countedLocally, members, q, opts, notes) {
|
|
51291
|
+
if (countedLocally.size === 0) return;
|
|
51292
|
+
const best = top.length > 0 ? top[0] : void 0;
|
|
51293
|
+
if (best && countedLocally.has(best.ecl)) try {
|
|
51294
|
+
if (await q.countEcl(best.ecl) === best.covered + best.additions.count) {
|
|
51295
|
+
await fillTerms(top, countedLocally, q);
|
|
51296
|
+
return;
|
|
51297
|
+
}
|
|
51298
|
+
const server = await compare(best.ecl, members, q, opts.sampleSize, opts.within);
|
|
51299
|
+
if (server.additions.count !== best.additions.count || server.misses.count !== best.misses.count) notes.push(`Graph counts for ${best.ecl.slice(0, 120)} differed from the server's (+${best.additions.count} -${best.misses.count} on the graph, +${server.additions.count} -${server.misses.count} on the server).`);
|
|
51300
|
+
Object.assign(best, server);
|
|
51301
|
+
} catch (error) {
|
|
51302
|
+
notes.push(`Could not check ${best.ecl.slice(0, 120)} on the server: ${errorMessage(error)}`);
|
|
51303
|
+
}
|
|
51304
|
+
await fillTerms(top, countedLocally, q);
|
|
51305
|
+
}
|
|
51306
|
+
/** Terms for the samples of the candidates counted on the graph, in one lookup. */
|
|
51307
|
+
async function fillTerms(top, countedLocally, q) {
|
|
51308
|
+
const codes = /* @__PURE__ */ new Set();
|
|
51309
|
+
for (const s of top) {
|
|
51310
|
+
if (!countedLocally.has(s.ecl)) continue;
|
|
51311
|
+
for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) codes.add(c.code);
|
|
51312
|
+
}
|
|
51313
|
+
if (codes.size === 0) return;
|
|
51314
|
+
const found = await q.concepts({ include: [{ concepts: [...codes] }] }, codes.size, false);
|
|
51315
|
+
const terms = new Map(found.concepts.map((c) => [c.code, c.display]));
|
|
51316
|
+
for (const s of top) for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) c.display = terms.get(c.code) ?? "";
|
|
51317
|
+
}
|
|
50397
51318
|
/** Additions and misses of `ecl` against the set, counted and sampled by the server. */
|
|
50398
51319
|
async function compare(ecl, members, q, sampleSize, within) {
|
|
50399
51320
|
const counted = within ? `(${ecl}) AND (${within})` : ecl;
|
|
@@ -50412,7 +51333,13 @@ async function compare(ecl, members, q, sampleSize, within) {
|
|
|
50412
51333
|
clauses: countClauses(ecl)
|
|
50413
51334
|
};
|
|
50414
51335
|
}
|
|
50415
|
-
|
|
51336
|
+
/**
|
|
51337
|
+
* Preferred terms for the ids in the candidates worth decorating. Terms are
|
|
51338
|
+
* decoration: when the lookup fails, the candidates go out with bare ids and,
|
|
51339
|
+
* given `notes`, a note says why (the failure itself is counted by the caller's
|
|
51340
|
+
* service), rather than losing a finished result.
|
|
51341
|
+
*/
|
|
51342
|
+
async function displayTerms(candidates, terminology, notes) {
|
|
50416
51343
|
const ids = /* @__PURE__ */ new Set();
|
|
50417
51344
|
for (const c of candidates) {
|
|
50418
51345
|
if (c.clauses > MAX_DECORATED_CLAUSES) continue;
|
|
@@ -50420,7 +51347,13 @@ async function displayTerms(candidates, terminology) {
|
|
|
50420
51347
|
}
|
|
50421
51348
|
const terms = /* @__PURE__ */ new Map();
|
|
50422
51349
|
if (ids.size === 0) return terms;
|
|
50423
|
-
|
|
51350
|
+
let infos;
|
|
51351
|
+
try {
|
|
51352
|
+
infos = await terminology.validateConcepts([...ids].sort(byId));
|
|
51353
|
+
} catch (error) {
|
|
51354
|
+
notes?.push(`Display terms could not be looked up: ${errorMessage(error)}.`);
|
|
51355
|
+
return terms;
|
|
51356
|
+
}
|
|
50424
51357
|
for (const [id, info] of infos) if (info?.pt) terms.set(id, info.pt);
|
|
50425
51358
|
return terms;
|
|
50426
51359
|
}
|
|
@@ -50500,6 +51433,7 @@ function bareSub(s) {
|
|
|
50500
51433
|
function formatDeriveReport(result) {
|
|
50501
51434
|
const lines = [];
|
|
50502
51435
|
const { input } = result;
|
|
51436
|
+
if (result.failures > 0) lines.push(incompleteLine(result.failures));
|
|
50503
51437
|
const duplicates = input.duplicates ? ` (${plural(input.duplicates, "duplicate")} ignored)` : "";
|
|
50504
51438
|
lines.push(`Members: ${input.members} of ${input.given} distinct ids${duplicates}`);
|
|
50505
51439
|
const leftOut = [
|
|
@@ -50558,6 +51492,10 @@ function reviewLines(c, inactiveListedAbove) {
|
|
|
50558
51492
|
}
|
|
50559
51493
|
return lines.length > 0 ? lines : ["Nothing flagged."];
|
|
50560
51494
|
}
|
|
51495
|
+
/** The first line of a report whose result lost candidates or checks to server failures. */
|
|
51496
|
+
function incompleteLine(failures) {
|
|
51497
|
+
return `Incomplete: ${failures} server ${failures === 1 ? "query" : "queries"} failed, so candidates or checks that needed them are missing and a better form may exist (see Notes). Run it again when the server recovers.`;
|
|
51498
|
+
}
|
|
50561
51499
|
function errorMessage(error) {
|
|
50562
51500
|
return error instanceof Error ? error.message : String(error);
|
|
50563
51501
|
}
|
|
@@ -50572,6 +51510,12 @@ function plural(n, noun) {
|
|
|
50572
51510
|
* Needs a terminology service with `expandCompose`.
|
|
50573
51511
|
*/
|
|
50574
51512
|
async function compressExpression(ecl, terminology, options = {}) {
|
|
51513
|
+
const { service, failures } = countingFailures(terminology);
|
|
51514
|
+
const result = await compress(ecl, service, options);
|
|
51515
|
+
result.failures = failures();
|
|
51516
|
+
return result;
|
|
51517
|
+
}
|
|
51518
|
+
async function compress(ecl, terminology, options) {
|
|
50575
51519
|
const original = stripTermsAndComments(ecl);
|
|
50576
51520
|
const parsed = parseECL(original);
|
|
50577
51521
|
const result = {
|
|
@@ -50579,7 +51523,8 @@ async function compressExpression(ecl, terminology, options = {}) {
|
|
|
50579
51523
|
group: null,
|
|
50580
51524
|
candidates: [],
|
|
50581
51525
|
notes: [],
|
|
50582
|
-
errors: []
|
|
51526
|
+
errors: [],
|
|
51527
|
+
failures: 0
|
|
50583
51528
|
};
|
|
50584
51529
|
if (!parsed.ast || parsed.errors.length > 0) {
|
|
50585
51530
|
result.errors = parsed.errors.map((e) => e.message);
|
|
@@ -50628,7 +51573,7 @@ async function compressExpression(ecl, terminology, options = {}) {
|
|
|
50628
51573
|
built.sort((a, b) => cost(a) - cost(b) || Number(b.exact) - Number(a.exact) || SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source] || a.ecl.length - b.ecl.length);
|
|
50629
51574
|
const top = built.slice(0, options.maxCandidates ?? 8);
|
|
50630
51575
|
for (const c of built) if (c.source !== "derived" && !top.includes(c)) top.push(c);
|
|
50631
|
-
const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology);
|
|
51576
|
+
const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, result.notes);
|
|
50632
51577
|
result.candidates = top.map((c) => ({
|
|
50633
51578
|
expression: decorate(c.ecl, terms),
|
|
50634
51579
|
...c,
|
|
@@ -50753,6 +51698,7 @@ function orInside(sub, text) {
|
|
|
50753
51698
|
function formatCompressReport(result) {
|
|
50754
51699
|
if (result.errors.length > 0) return `Not compressed: ${result.errors.join("; ")}`;
|
|
50755
51700
|
const lines = [`Original selects ${result.members} concepts.`];
|
|
51701
|
+
if (result.failures > 0) lines.unshift(incompleteLine(result.failures));
|
|
50756
51702
|
if (result.group && result.group.start > 0) lines.push(`Compressed group: ${result.group.text}`);
|
|
50757
51703
|
for (const note of result.notes) lines.push(`Note: ${note}`);
|
|
50758
51704
|
result.candidates.forEach((c, i) => {
|