Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 13 additions & 19 deletions src/main/java/org/ohdsi/webapi/service/VocabularyService.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.ohdsi.webapi.vocabulary.ConceptRelationship;
import org.ohdsi.webapi.vocabulary.ConceptSearch;
import org.ohdsi.webapi.vocabulary.ConceptSetCondenser;
import org.ohdsi.webapi.vocabulary.ConceptSetOptimizer;
import org.ohdsi.webapi.vocabulary.DescendentOfAncestorSearch;
import org.ohdsi.webapi.vocabulary.Domain;
import org.ohdsi.webapi.vocabulary.RecommendedConcept;
Expand Down Expand Up @@ -1367,40 +1368,33 @@ public Collection<ConceptSetComparison> compareConceptSetsCsv(
public ConceptSetOptimizationResult optimizeConceptSet(
@PathVariable("sourceKey") String sourceKey,
@RequestBody ConceptSetExpression conceptSetExpression) throws Exception {
// resolve the concept set to get included concepts
Collection<Long> includedConcepts = this.resolveConceptSetExpression(sourceKey, conceptSetExpression);
long[] includedConceptsArray = includedConcepts.stream().mapToLong(Long::longValue).toArray();

// perform vocabulary search to find ancestor/descendant concepts for the included concepts

Source source = getSourceRepository().findBySourceKey(sourceKey);
String tableQualifier = source.getTableQualifier(SourceDaimon.DaimonType.Vocabulary);
String ancestorSql = ResourceHelper.GetResourceAsString("/resources/vocabulary/sql/calculateAncestors.sql");
String allConceptsList = includedConcepts.stream().map(Object::toString).collect(Collectors.joining(", "));

String allConceptsList = ConceptSetOptimizer.candidateAncestorIds(includedConcepts, conceptSetExpression).stream()
.map(Object::toString).collect(Collectors.joining(", "));

ancestorSql = SqlRender.renderSql(ancestorSql, new String[]{"ancestors", "CDM_schema"}, new String[]{allConceptsList, tableQualifier});
ancestorSql = SqlTranslate.translateSql(ancestorSql, source.getSourceDialect());
List<Map<String, Object>> rows = getSourceJdbcTemplate(source).queryForList(ancestorSql);

// the candidate concepts are all ancestors from the query, and we add any
// descendants in the result to the collection of CandidateConcepts

Map<Long, Collection<Long>> ancestorMap = new HashMap<>();
for (Map rs : rows) {
final Long ancestorConceptId = Long.valueOf(rs.get("ancestor_id").toString());
ancestorMap.computeIfAbsent(ancestorConceptId,k -> new ArrayList<>())
.add(Long.valueOf(rs.get("descendant_id").toString()));
}

// use conceptSetCondenser to optimize concept set
ArrayList<ConceptSetCondenser.CandidateConcept> candidateConcepts = new ArrayList<>();
for (Long candidateConcept : ancestorMap.keySet()){
long[] candidateDescendants = ancestorMap.get(candidateConcept).stream().mapToLong(Long::longValue).toArray();
candidateConcepts.add(new ConceptSetCondenser.CandidateConcept(candidateConcept, candidateDescendants));
ConceptSetCondenser.ConceptExpression[] conceptExpressionArray = ConceptSetOptimizer.condense(includedConcepts, ancestorMap);
if (!ConceptSetOptimizer.isImprovement(conceptExpressionArray, conceptSetExpression)) {
ConceptSetOptimizationResult unchanged = new ConceptSetOptimizationResult();
unchanged.optimizedConceptSet.items = conceptSetExpression.items;
unchanged.removedConceptSet.items = new ConceptSetExpression.ConceptSetItem[0];
return unchanged;
}
ConceptSetCondenser.CandidateConcept[] candidateConceptsArray = candidateConcepts.toArray(new ConceptSetCondenser.CandidateConcept[0]);
ConceptSetCondenser condenser = new ConceptSetCondenser(includedConceptsArray, candidateConceptsArray);
condenser.condense();
ConceptSetCondenser.ConceptExpression[] conceptExpressionArray = condenser.getConceptSetExpression();


// convert condensed concept set to a ConceptSetExpression
// 1. get lookup of Concept objects from the conceptExpression[] and make a map
Collection<Concept> concepts = executeIdentifierLookup(source, Arrays.stream(conceptExpressionArray).mapToLong(ce -> ce.conceptId).toArray());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ public void condense() {
bruteForceSearch();
}

/**
* @return true if condense() found an expression. It can fail to when the
* search hits the step limit before reaching any valid solution.
*/
public boolean hasSolution() {
return optimalSolution != null && optimalLength <= candidateConcepts.size();
}

/**
* Get the optimal concept set expression. Will throw an exception if
* condense() hasn't been called first.
Expand Down
82 changes: 82 additions & 0 deletions src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/** *****************************************************************************
* Copyright 2025 Observational Health Data Sciences and Informatics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************** */
package org.ohdsi.webapi.vocabulary;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.ohdsi.circe.vocabulary.ConceptSetExpression;

public final class ConceptSetOptimizer {

private ConceptSetOptimizer() {
}

/**
* The concepts whose descendants must be looked up to build condenser
* candidates: every resolved concept plus every concept named in the
* expression. Excluded items are not part of the resolved set, but without
* them as candidates the condenser cannot express "X with descendants
* minus Y with descendants".
*/
public static Set<Long> candidateAncestorIds(Collection<Long> includedConcepts, ConceptSetExpression expression) {
Set<Long> ids = new LinkedHashSet<>(includedConcepts);
if (expression != null && expression.items != null) {
for (ConceptSetExpression.ConceptSetItem item : expression.items) {
if (item != null && item.concept != null && item.concept.conceptId != null) {
ids.add(item.concept.conceptId);
}
}
}
return ids;
}

/**
* Runs the condenser.
*
* @param includedConcepts the resolved concept set
* @param descendantsByAncestor for each id from
* {@link #candidateAncestorIds}, its full descendant set (including itself)
* @return the condensed expression, or null when no solution was found
*/
public static ConceptSetCondenser.ConceptExpression[] condense(Collection<Long> includedConcepts,
Map<Long, ? extends Collection<Long>> descendantsByAncestor) {
long[] included = includedConcepts.stream().mapToLong(Long::longValue).toArray();
ConceptSetCondenser.CandidateConcept[] candidates = descendantsByAncestor.entrySet().stream()
.map(e -> new ConceptSetCondenser.CandidateConcept(e.getKey(),
e.getValue().stream().mapToLong(Long::longValue).toArray()))
.toArray(ConceptSetCondenser.CandidateConcept[]::new);
ConceptSetCondenser condenser = new ConceptSetCondenser(included, candidates);
condenser.condense();
if (!condenser.hasSolution()) {
return null;
}
return condenser.getConceptSetExpression();
}

/**
* @return true when the condensed expression should replace the original,
* i.e. it exists and has strictly fewer items.
*/
public static boolean isImprovement(ConceptSetCondenser.ConceptExpression[] condensed, ConceptSetExpression original) {
if (condensed == null) {
return false;
}
int originalLength = original == null || original.items == null ? 0 : original.items.length;
return condensed.length < originalLength;
}
}
199 changes: 199 additions & 0 deletions src/test/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package org.ohdsi.webapi.vocabulary;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.ohdsi.circe.vocabulary.Concept;
import org.ohdsi.circe.vocabulary.ConceptSetExpression;

public class ConceptSetOptimizerTest {

private static final long ROOT = 1;

private Map<Long, List<Long>> children;

@Before
public void buildHierarchy() {
children = new HashMap<>();
for (long a = 10; a < 22; a++) {
edge(ROOT, a);
for (long b = 0; b < 6; b++) {
edge(a, a * 10 + b);
}
}
edge(190, 1900);
edge(190, 1901);
edge(120, 1200);
edge(1200, 1201);
edge(1200, 1202);
edge(1201, 1203);
// shared child under 13 and 14, so excluding 13 with descendants also removes it from 14
edge(13, 1300);
edge(14, 1300);
edge(150, 1500);
edge(170, 1700);
}

private void edge(long parent, long child) {
children.computeIfAbsent(parent, k -> new ArrayList<>()).add(child);
}

private Set<Long> descendants(long conceptId) {
Set<Long> result = new HashSet<>();
Deque<Long> queue = new ArrayDeque<>();
queue.add(conceptId);
while (!queue.isEmpty()) {
long id = queue.poll();
if (result.add(id)) {
queue.addAll(children.getOrDefault(id, new ArrayList<>()));
}
}
return result;
}

private Set<Long> resolve(List<long[]> items) {
Set<Long> included = new HashSet<>();
Set<Long> excluded = new HashSet<>();
for (long[] item : items) {
Set<Long> ids = item[2] == 1 ? descendants(item[0]) : new HashSet<>(Arrays.asList(item[0]));
(item[1] == 1 ? excluded : included).addAll(ids);
}
included.removeAll(excluded);
return included;
}

private static ConceptSetExpression expression(long[]... items) {
ConceptSetExpression expression = new ConceptSetExpression();
expression.items = Arrays.stream(items).map(item -> {
ConceptSetExpression.ConceptSetItem csi = new ConceptSetExpression.ConceptSetItem();
csi.concept = new Concept();
csi.concept.conceptId = item[0];
csi.isExcluded = item[1] == 1;
csi.includeDescendants = item[2] == 1;
return csi;
}).toArray(ConceptSetExpression.ConceptSetItem[]::new);
return expression;
}

private static List<long[]> asItems(ConceptSetExpression expression) {
List<long[]> items = new ArrayList<>();
for (ConceptSetExpression.ConceptSetItem csi : expression.items) {
items.add(new long[]{csi.concept.conceptId, csi.isExcluded ? 1 : 0, csi.includeDescendants ? 1 : 0});
}
return items;
}

private static List<long[]> asItems(ConceptSetCondenser.ConceptExpression[] condensed) {
List<long[]> items = new ArrayList<>();
for (ConceptSetCondenser.ConceptExpression ce : condensed) {
items.add(new long[]{ce.conceptId, ce.exclude ? 1 : 0, ce.descendants ? 1 : 0});
}
return items;
}

private ConceptSetCondenser.ConceptExpression[] optimize(ConceptSetExpression expression, Set<Long> included) {
Map<Long, Set<Long>> descendantsByAncestor = new HashMap<>();
for (Long id : ConceptSetOptimizer.candidateAncestorIds(included, expression)) {
descendantsByAncestor.put(id, descendants(id));
}
return ConceptSetOptimizer.condense(included, descendantsByAncestor);
}

private ConceptSetExpression issue539Expression() {
return expression(
new long[]{ROOT, 0, 1},
new long[]{11, 1, 1},
new long[]{190, 1, 1},
new long[]{120, 1, 1},
new long[]{13, 1, 1},
new long[]{150, 1, 1},
new long[]{160, 1, 0},
new long[]{170, 1, 0});
}

@Test
public void candidatesIncludeExcludedExpressionItems() {
ConceptSetExpression expression = issue539Expression();
Set<Long> included = resolve(asItems(expression));

Set<Long> candidates = ConceptSetOptimizer.candidateAncestorIds(included, expression);

assertTrue(candidates.containsAll(included));
for (long excluded : new long[]{11, 190, 120, 13, 150, 160, 170}) {
assertFalse(included.contains(excluded));
assertTrue(candidates.contains(excluded));
}
}

@Test
public void keepsExclusionsAndResolvesToTheSameConcepts() {
ConceptSetExpression expression = issue539Expression();
Set<Long> included = resolve(asItems(expression));

ConceptSetCondenser.ConceptExpression[] condensed = optimize(expression, included);

assertNotNull(condensed);
// the issue's expression is already minimal: the condenser keeps its 7 exclusions instead of
// listing the remaining branches, so it finds 8 items again, and the endpoint keeps the original
assertEquals(expression.items.length, condensed.length);
assertEquals(7, Arrays.stream(condensed).filter(ce -> ce.exclude).count());
assertEquals(included, resolve(asItems(condensed)));
assertFalse(ConceptSetOptimizer.isImprovement(condensed, expression));
}

@Test
public void removesRedundantItemsWhileKeepingExclusions() {
ConceptSetExpression expression = expression(
new long[]{ROOT, 0, 1},
new long[]{15, 0, 1},
new long[]{151, 0, 0},
new long[]{11, 1, 1},
new long[]{111, 1, 1},
new long[]{170, 1, 0});
Set<Long> included = resolve(asItems(expression));

ConceptSetCondenser.ConceptExpression[] condensed = optimize(expression, included);

assertTrue(ConceptSetOptimizer.isImprovement(condensed, expression));
assertEquals(3, condensed.length);
assertEquals(included, resolve(asItems(condensed)));
}

@Test
public void guardRejectsResultThatIsNotShorter() {
ConceptSetExpression expression = expression(
new long[]{ROOT, 0, 1},
new long[]{11, 1, 1});
Set<Long> included = resolve(asItems(expression));

ConceptSetCondenser.ConceptExpression[] condensed = optimize(expression, included);

assertEquals(included, resolve(asItems(condensed)));
assertFalse(ConceptSetOptimizer.isImprovement(condensed, expression));
assertFalse(ConceptSetOptimizer.isImprovement(null, expression));
}

@Test
public void guardRejectsLongerResult() {
ConceptSetExpression expression = expression(new long[]{ROOT, 0, 1});
ConceptSetCondenser.ConceptExpression[] longer = optimize(
expression(new long[]{ROOT, 0, 1}, new long[]{11, 1, 1}, new long[]{12, 1, 1}),
resolve(asItems(expression(new long[]{ROOT, 0, 1}, new long[]{11, 1, 1}, new long[]{12, 1, 1}))));

assertTrue(longer.length > expression.items.length);
assertFalse(ConceptSetOptimizer.isImprovement(longer, expression));
}
}
Loading