diff --git a/src/main/java/org/ohdsi/webapi/service/VocabularyService.java b/src/main/java/org/ohdsi/webapi/service/VocabularyService.java index 93beb43550..7d5d3d293c 100644 --- a/src/main/java/org/ohdsi/webapi/service/VocabularyService.java +++ b/src/main/java/org/ohdsi/webapi/service/VocabularyService.java @@ -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; @@ -1367,22 +1368,18 @@ public Collection compareConceptSetsCsv( public ConceptSetOptimizationResult optimizeConceptSet( @PathVariable("sourceKey") String sourceKey, @RequestBody ConceptSetExpression conceptSetExpression) throws Exception { - // resolve the concept set to get included concepts Collection 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> 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> ancestorMap = new HashMap<>(); for (Map rs : rows) { final Long ancestorConceptId = Long.valueOf(rs.get("ancestor_id").toString()); @@ -1390,17 +1387,14 @@ public ConceptSetOptimizationResult optimizeConceptSet( .add(Long.valueOf(rs.get("descendant_id").toString())); } - // use conceptSetCondenser to optimize concept set - ArrayList 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 concepts = executeIdentifierLookup(source, Arrays.stream(conceptExpressionArray).mapToLong(ce -> ce.conceptId).toArray()); diff --git a/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetCondenser.java b/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetCondenser.java index b5c19ac357..735b8c335e 100644 --- a/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetCondenser.java +++ b/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetCondenser.java @@ -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. diff --git a/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizer.java b/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizer.java new file mode 100644 index 0000000000..9b566f255d --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizer.java @@ -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 candidateAncestorIds(Collection includedConcepts, ConceptSetExpression expression) { + Set 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 includedConcepts, + Map> 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; + } +} diff --git a/src/test/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizerTest.java b/src/test/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizerTest.java new file mode 100644 index 0000000000..5583d9cd11 --- /dev/null +++ b/src/test/java/org/ohdsi/webapi/vocabulary/ConceptSetOptimizerTest.java @@ -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> 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 descendants(long conceptId) { + Set result = new HashSet<>(); + Deque 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 resolve(List items) { + Set included = new HashSet<>(); + Set excluded = new HashSet<>(); + for (long[] item : items) { + Set 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 asItems(ConceptSetExpression expression) { + List 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 asItems(ConceptSetCondenser.ConceptExpression[] condensed) { + List 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 included) { + Map> 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 included = resolve(asItems(expression)); + + Set 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 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 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 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)); + } +}