|
| 1 | +package org.baderlab.csplugins.enrichmentmap.view.heatmap.table; |
| 2 | + |
| 3 | +import java.util.Map; |
| 4 | +import java.util.Optional; |
| 5 | +import java.util.concurrent.ExecutionException; |
| 6 | + |
| 7 | +import javax.annotation.Nullable; |
| 8 | + |
| 9 | +import org.apache.commons.lang3.tuple.Pair; |
| 10 | +import org.baderlab.csplugins.enrichmentmap.model.EMDataSet; |
| 11 | +import org.baderlab.csplugins.enrichmentmap.model.GeneExpression; |
| 12 | +import org.baderlab.csplugins.enrichmentmap.model.GeneExpressionMatrix; |
| 13 | +import org.baderlab.csplugins.enrichmentmap.view.heatmap.HeatMapParams.Transform; |
| 14 | + |
| 15 | +import com.google.common.cache.Cache; |
| 16 | +import com.google.common.cache.CacheBuilder; |
| 17 | + |
| 18 | +public class ExpressionCache { |
| 19 | + |
| 20 | + private final Cache<Pair<Integer,EMDataSet>, Optional<float[]>> cache; |
| 21 | + private final Transform transform; |
| 22 | + |
| 23 | + public ExpressionCache(Transform transform) { |
| 24 | + this.transform = transform; |
| 25 | + this.cache = CacheBuilder.newBuilder().maximumSize(20).build(); |
| 26 | + } |
| 27 | + |
| 28 | + public Optional<float[]> getExpressions(EMDataSet dataset, int geneID) { |
| 29 | + try { |
| 30 | + return cache.get(Pair.of(geneID, dataset), |
| 31 | + () -> Optional.ofNullable(getExpression(dataset, geneID, transform)) |
| 32 | + ); |
| 33 | + } catch (ExecutionException e) { |
| 34 | + return Optional.empty(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public float getExpression(EMDataSet dataset, int geneID, int expressionIndex) { |
| 39 | + Optional<float[]> vals = getExpressions(dataset, geneID); |
| 40 | + if(vals.isPresent()) { |
| 41 | + return vals.get()[expressionIndex]; |
| 42 | + } else { |
| 43 | + return Float.NaN; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | + public static GeneExpression getGeneExpression(EMDataSet dataset, int geneID) { |
| 49 | + GeneExpressionMatrix matrix = dataset.getExpressionSets(); |
| 50 | + Map<Integer,GeneExpression> expressions = matrix.getExpressionMatrix(); |
| 51 | + GeneExpression row = expressions.get(geneID); |
| 52 | + return row; |
| 53 | + } |
| 54 | + |
| 55 | + private static @Nullable float[] getExpression(EMDataSet dataset, int geneID, Transform transform) { |
| 56 | + GeneExpression expression = getGeneExpression(dataset, geneID); |
| 57 | + if(expression != null) { |
| 58 | + switch(transform) { |
| 59 | + case ROW_NORMALIZE: return expression.rowNormalize(); |
| 60 | + case LOG_TRANSFORM: return expression.rowLogTransform(); |
| 61 | + case AS_IS: return expression.getExpression(); |
| 62 | + } |
| 63 | + } |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments