Search in sources :

Example 36 with TIntHashSet

use of gnu.trove.set.hash.TIntHashSet in project BuildCraft by BuildCraft.

the class BuildCraftGui method drawElementForegrounds.

/**
 * @param menuBackgroundRenderer Will be called to draw the background if the current menu returns true from
 *            {@link IMenuElement#shouldFullyOverride()}. This will draw above all of the normal elements.
 *            {@link GL11#GL_DEPTH_TEST} will have been disabled for this.
 */
public void drawElementForegrounds(Runnable menuBackgroundRenderer) {
    for (IGuiElement element : shownElements) {
        if (element != currentMenu) {
            element.drawForeground(lastPartialTicks);
        }
    }
    IMenuElement m = currentMenu;
    if (m != null) {
        if (m.shouldFullyOverride() && menuBackgroundRenderer != null) {
            GlStateManager.disableDepth();
            menuBackgroundRenderer.run();
            GlStateManager.enableDepth();
        }
        m.drawBackground(lastPartialTicks);
        m.drawForeground(lastPartialTicks);
    }
    GuiUtil.drawVerticallyAppending(mouse, getAllTooltips(), this::drawTooltip);
    if (isDebuggingEnabled.evaluate()) {
        int x = 6;
        int y = 18;
        List<String> info = new ArrayList<>();
        TIntHashSet xAxisFilled = new TIntHashSet();
        FontRenderer fr = mc.fontRenderer;
        for (IGuiElement elem : this.getElementsAt(mouse.getX(), mouse.getY())) {
            String name = elem.getDebugInfo(info);
            int sx = (int) elem.getX();
            int sy = (int) elem.getY();
            int ex = sx + (int) elem.getWidth() + 1;
            int ey = sy + (int) elem.getHeight() + 1;
            sx--;
            sy--;
            int colour = (name.hashCode() | 0xFF_00_00_00);
            float[] hsb = Color.RGBtoHSB(colour & 0xFF, (colour >> 8) & 0xFF, (colour >> 16) & 0xFF, null);
            int colourDark = Color.HSBtoRGB(hsb[0], hsb[1], Math.max(hsb[2] - 0.25f, 0)) | 0xFF_00_00_00;
            Gui.drawRect(sx, sy, ex + 1, sy + 1, colour);
            Gui.drawRect(sx, ey, ex + 1, ey + 1, colour);
            Gui.drawRect(sx, sy, sx + 1, ey + 1, colour);
            Gui.drawRect(ex, sy, ex + 1, ey + 1, colour);
            Gui.drawRect(sx - 1, sy - 1, ex + 2, sy, colourDark);
            Gui.drawRect(sx - 1, ey + 1, ex + 2, ey + 2, colourDark);
            Gui.drawRect(sx - 1, sy - 1, sx, ey + 2, colourDark);
            Gui.drawRect(ex + 1, sy - 1, ex + 2, ey + 2, colourDark);
            fr.drawStringWithShadow(name, x, y, -1);
            int w = fr.getStringWidth(name) + 3;
            int mx = ((sx + 3) >> 2) << 2;
            for (int x2 = mx; x2 < ex; x2 += 4) {
                if (xAxisFilled.add(x2)) {
                    mx = x2;
                    break;
                }
            }
            GuiUtil.drawHorizontalLine(x + w, mx, y + 4, colour);
            GuiUtil.drawVerticalLine(mx, y + 4, sy, colour);
            y += fr.FONT_HEIGHT + 2;
            for (String line : info) {
                fr.drawStringWithShadow(line, x + 7, y, -1);
                y += fr.FONT_HEIGHT + 2;
            }
            info.clear();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) FontRenderer(net.minecraft.client.gui.FontRenderer) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Example 37 with TIntHashSet

use of gnu.trove.set.hash.TIntHashSet in project mixcr by milaboratory.

the class FullSeqAssemblerTest method test1.

@Test
public void test1() throws Exception {
    int len = 140;
    PairedRead read1 = new PairedRead(new SingleReadImpl(0, new NSequenceWithQuality(masterSeq1WT.getRangeFromCDR3Begin(-20, len)), "R1"), new SingleReadImpl(0, new NSequenceWithQuality(masterSeq1WT.getRangeFromCDR3Begin(-200, len).getReverseComplement()), "R2"));
    PairedRead read2 = new PairedRead(new SingleReadImpl(1, new NSequenceWithQuality(masterSeq1WT.getRangeFromCDR3Begin(-30, len)), "R1"), new SingleReadImpl(1, new NSequenceWithQuality(masterSeq1WT.getRangeFromCDR3Begin(-150, len).getReverseComplement()), "R2"));
    RunMiXCR.RunMiXCRAnalysis params = new RunMiXCR.RunMiXCRAnalysis(read1, read2);
    // [-200, -60]  [-20, 120]
    // [-150, 110]
    // 
    // [-200, -150], [110, 120] = 60
    // [-60, -20] = 40
    params.alignerParameters = VDJCParametersPresets.getByName("rna-seq");
    params.alignerParameters.setSaveOriginalReads(true);
    params.cloneAssemblerParameters.updateFrom(params.alignerParameters);
    RunMiXCR.AlignResult align = RunMiXCR.align(params);
    // for (VDJCAlignments al : align.alignments) {
    // for (int i = 0; i < al.numberOfTargets(); i++)
    // System.out.println(VDJCAlignmentsFormatter.getTargetAsMultiAlignment(al, i));
    // System.out.println();
    // }
    RunMiXCR.AssembleResult assemble = RunMiXCR.assemble(align);
    CloneFactory cloneFactory = new CloneFactory(align.parameters.cloneAssemblerParameters.getCloneFactoryParameters(), align.parameters.cloneAssemblerParameters.getAssemblingFeatures(), align.usedGenes, align.parameters.alignerParameters.getFeaturesToAlignMap());
    FullSeqAssembler agg = new FullSeqAssembler(cloneFactory, DEFAULT_PARAMETERS, assemble.cloneSet.get(0), align.parameters.alignerParameters);
    PointSequence[] r2s = agg.toPointSequences(align.alignments.get(1));
    TIntHashSet p2 = new TIntHashSet(Arrays.stream(r2s).mapToInt(s -> s.point).toArray());
    Assert.assertEquals(261 - masterSeq1WT.cdr3Part, p2.size());
    PointSequence[] r1s = agg.toPointSequences(align.alignments.get(0));
    TIntHashSet p1 = new TIntHashSet(Arrays.stream(r1s).mapToInt(s -> s.point).toArray());
    Assert.assertEquals(281 - masterSeq1WT.cdr3Part, p1.size());
    FullSeqAssembler.RawVariantsData prep = agg.calculateRawData(() -> CUtils.asOutputPort(align.alignments));
    long uniq1 = StreamSupport.stream(CUtils.it(prep.createPort()).spliterator(), false).mapToInt(l -> l[0]).filter(c -> c == 0xFFFFFFFF).count();
    long uniq2 = StreamSupport.stream(CUtils.it(prep.createPort()).spliterator(), false).mapToInt(l -> l[1]).filter(c -> c == 0xFFFFFFFF).count();
    Assert.assertEquals(40, uniq1);
    Assert.assertEquals(60, uniq2);
    for (Clone clone : new CloneSet(Arrays.asList(agg.callVariants(prep))).getClones()) {
        ActionExportClonesPretty.outputCompact(System.out, clone);
        System.out.println();
        System.out.println(" ================================================ ");
        System.out.println();
    }
}
Also used : java.util(java.util) SequenceRead(com.milaboratory.core.io.sequence.SequenceRead) Well44497b(org.apache.commons.math3.random.Well44497b) SequenceQuality(com.milaboratory.core.sequence.SequenceQuality) Clone(com.milaboratory.mixcr.basictypes.Clone) GeneFeature(io.repseq.core.GeneFeature) CloneFactory(com.milaboratory.mixcr.assembler.CloneFactory) Main(com.milaboratory.mixcr.cli.Main) StreamSupport(java.util.stream.StreamSupport) PairedRead(com.milaboratory.core.io.sequence.PairedRead) RunMiXCR(com.milaboratory.mixcr.util.RunMiXCR) NucleotideSequence(com.milaboratory.core.sequence.NucleotideSequence) VDJCAlignmentsFormatter(com.milaboratory.mixcr.basictypes.VDJCAlignmentsFormatter) CUtils(cc.redberry.pipe.CUtils) Test(org.junit.Test) Collectors(java.util.stream.Collectors) TIntHashSet(gnu.trove.set.hash.TIntHashSet) RandomDataGenerator(org.apache.commons.math3.random.RandomDataGenerator) Well19937c(org.apache.commons.math3.random.Well19937c) CloneSet(com.milaboratory.mixcr.basictypes.CloneSet) SingleReadImpl(com.milaboratory.core.io.sequence.SingleReadImpl) GeneType(io.repseq.core.GeneType) NSequenceWithQuality(com.milaboratory.core.sequence.NSequenceWithQuality) ActionExportClonesPretty(com.milaboratory.mixcr.cli.ActionExportClonesPretty) VDJCParametersPresets(com.milaboratory.mixcr.vdjaligners.VDJCParametersPresets) Assert(org.junit.Assert) SequenceReaderCloseable(com.milaboratory.core.io.sequence.SequenceReaderCloseable) VDJCAlignments(com.milaboratory.mixcr.basictypes.VDJCAlignments) SingleReadImpl(com.milaboratory.core.io.sequence.SingleReadImpl) PairedRead(com.milaboratory.core.io.sequence.PairedRead) TIntHashSet(gnu.trove.set.hash.TIntHashSet) CloneSet(com.milaboratory.mixcr.basictypes.CloneSet) NSequenceWithQuality(com.milaboratory.core.sequence.NSequenceWithQuality) RunMiXCR(com.milaboratory.mixcr.util.RunMiXCR) CloneFactory(com.milaboratory.mixcr.assembler.CloneFactory) Clone(com.milaboratory.mixcr.basictypes.Clone) Test(org.junit.Test)

Example 38 with TIntHashSet

use of gnu.trove.set.hash.TIntHashSet in project OpenTripPlanner by opentripplanner.

the class SkipStop method omitStops.

public TripTimes omitStops(TripTimes tt, int... stopsToSkip) {
    TIntSet skipped = new TIntHashSet(stopsToSkip);
    List<StopTime> newSts = Lists.newArrayList();
    int cumulativeTime = -1;
    for (int i = 0; i < tt.getNumStops(); i++) {
        int hopTime = i != 0 ? tt.getArrivalTime(i) - tt.getDepartureTime(i - 1) : 0;
        int dwellTime = tt.getDepartureTime(i) - tt.getArrivalTime(i);
        // handle the first stop(s) being skipped
        if (cumulativeTime != -1)
            // note that we include hopTime before the check if the stop is included but dwell time after,
            // the assumption being that there is no dwell at a skipped stop.
            cumulativeTime += hopTime;
        if (skipped.contains(i))
            continue;
        // if this stop is now the first stop, get the time
        if (cumulativeTime == -1)
            cumulativeTime = tt.getArrivalTime(i);
        StopTime stopTime = new StopTime();
        stopTime.setArrivalTime(cumulativeTime);
        cumulativeTime += dwellTime;
        stopTime.setDepartureTime(cumulativeTime);
        stopTime.setStopSequence(tt.getStopSequence(i));
        stopTime.setTimepoint(tt.isTimepoint(i) ? 1 : 0);
        newSts.add(stopTime);
    }
    TripTimes newtt = new TripTimes(tt.trip, newSts, new Deduplicator());
    newtt.serviceCode = tt.serviceCode;
    return newtt;
}
Also used : TIntSet(gnu.trove.set.TIntSet) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) Deduplicator(org.opentripplanner.routing.trippattern.Deduplicator) TIntHashSet(gnu.trove.set.hash.TIntHashSet) StopTime(org.onebusaway.gtfs.model.StopTime)

Example 39 with TIntHashSet

use of gnu.trove.set.hash.TIntHashSet in project OpenTripPlanner by opentripplanner.

the class ConvertToFrequency method apply.

public void apply(List<FrequencyEntry> frequencyEntries, List<TripTimes> scheduledTrips, Graph graph, BitSet servicesRunning, RaptorWorkerTimetable.BoardingAssumption assumption) {
    // preserve existing frequency entries
    this.frequencyEntries.addAll(frequencyEntries);
    Set<String> routeIds = new HashSet<>();
    if (routeId != null)
        Stream.of(routeId).forEach(routeIds::add);
    // loop over scheduled trips and figure out what to do with them
    for (TripTimes tt : scheduledTrips) {
        if (routeId == null || routeIds.contains(tt.trip.getRoute().getId().getId())) {
            // put this in the appropriate group for frequency conversion
            String key;
            switch(groupBy) {
                case ROUTE_DIRECTION:
                    key = tt.trip.getRoute().getId().getId() + "_" + tt.trip.getDirectionId();
                    break;
                case ROUTE:
                    key = tt.trip.getRoute().getId().getId();
                    break;
                case PATTERN:
                    key = graph.index.patternForTrip.get(tt.trip).getExemplar().getId().getId();
                    break;
                default:
                    throw new RuntimeException("Unrecognized group by value");
            }
            tripsToConvert.put(key, tt);
        } else {
            // don't touch this trip
            this.scheduledTrips.add(tt);
        }
    }
    // loop over all the groups and create frequency entries
    GROUPS: for (Map.Entry<String, Collection<TripTimes>> e : tripsToConvert.asMap().entrySet()) {
        // get just the running services
        List<TripTimes> group = e.getValue().stream().filter(tt -> servicesRunning.get(tt.serviceCode)).filter(tt -> windowStart < tt.getDepartureTime(0) && tt.getDepartureTime(0) < windowEnd).collect(Collectors.toList());
        if (group.isEmpty())
            continue GROUPS;
        if (group.size() == 1) {
            group.stream().forEach(scheduledTrips::add);
            continue GROUPS;
        }
        // find the dominant pattern
        TObjectIntMap<TripPattern> patternCount = new TObjectIntHashMap<>(5, 0.75f, 0);
        group.forEach(tt -> patternCount.adjustOrPutValue(graph.index.patternForTrip.get(tt.trip), 1, 1));
        int maxCount = 0;
        TripPattern tripPattern = null;
        for (TObjectIntIterator<TripPattern> it = patternCount.iterator(); it.hasNext(); ) {
            it.advance();
            if (it.value() > maxCount) {
                maxCount = it.value();
                tripPattern = it.key();
            }
        }
        // find a stop that is common to all trip patterns. Sort the list so that the same common stop is always returned
        NavigableSet<Stop> stops = new TreeSet<>((s1, s2) -> s1.getId().compareTo(s2.getId()));
        stops.addAll(tripPattern.getStops());
        patternCount.keySet().stream().forEach(p -> stops.retainAll(p.getStops()));
        if (stops.isEmpty()) {
            LOG.warn("Unable to find common stop for key {}, not converting to frequencies", e.getKey());
            scheduledTrips.addAll(e.getValue());
            continue GROUPS;
        }
        Stop stop = stops.stream().findFirst().get();
        // determine the median frequency at this stop
        // use a set to handle duplicated trips
        TIntSet arrivalTimes = new TIntHashSet();
        for (boolean filter : new boolean[] { true, false }) {
            for (TripTimes tt : group) {
                TripPattern tp = graph.index.patternForTrip.get(tt.trip);
                int arrivalTime = tt.getArrivalTime(tp.getStops().indexOf(stop));
                // however, if we apply the filter and end up with no trips at this stop, re-run with the filter disabled
                if (windowStart < arrivalTime && arrivalTime < windowEnd || !filter)
                    arrivalTimes.add(arrivalTime);
            }
            // if we didn't find stops, continue, which will turn off the filter
            if (arrivalTimes.size() > 1)
                break;
        }
        // now convert to elapsed times
        int[] arrivalTimeArray = arrivalTimes.toArray();
        Arrays.sort(arrivalTimeArray);
        int[] headway = new int[arrivalTimeArray.length - 1];
        for (int i = 1; i < arrivalTimeArray.length; i++) {
            headway[i - 1] = arrivalTimeArray[i] - arrivalTimeArray[i - 1];
        }
        Arrays.sort(headway);
        // the headway that we will use
        int aggregateHeadway;
        if (assumption == RaptorWorkerTimetable.BoardingAssumption.WORST_CASE)
            // simple: worst case analysis should use the worst case headway
            aggregateHeadway = Ints.max(headway);
        else {
            // we want the average headway, but we we want the average of the headways weighted
            // by themselves as if there is a two minute headway then a twenty-minute headway,
            // customers are ten times as likely to experience the twenty minute headway
            // (we want the average from the user's perspective, not the vehicle's perspective)
            // This is a weighted average where the weight is the same as the headway so it simplifies
            // to sum (headway^2) / sum(headway)
            aggregateHeadway = IntStream.of(headway).map(h -> h * h).sum() / IntStream.of(headway).sum();
        }
        LOG.info("Headway for route {} ({}) in direction {}: {}min", tripPattern.route.getShortName(), tripPattern.route.getId().getId(), tripPattern.directionId, aggregateHeadway / 60);
        // figure out running/dwell times based on the trips on this pattern
        final TripPattern chosenTp = tripPattern;
        List<TripTimes> candidates = group.stream().filter(tt -> graph.index.patternForTrip.get(tt.trip) == chosenTp).collect(Collectors.toList());
        // transposed from what you'd expect: stops on the rows
        int[][] hopTimes = new int[tripPattern.getStops().size() - 1][candidates.size()];
        int[][] dwellTimes = new int[tripPattern.getStops().size()][candidates.size()];
        int tripIndex = 0;
        for (TripTimes tt : candidates) {
            for (int stopIndex = 0; stopIndex < tripPattern.getStops().size(); stopIndex++) {
                dwellTimes[stopIndex][tripIndex] = tt.getDwellTime(stopIndex);
                if (stopIndex > 0)
                    hopTimes[stopIndex - 1][tripIndex] = tt.getArrivalTime(stopIndex) - tt.getDepartureTime(stopIndex - 1);
            }
            tripIndex++;
        }
        // collapse it down
        int[] meanHopTimes = new int[tripPattern.getStops().size() - 1];
        int hopIndex = 0;
        for (int[] hop : hopTimes) {
            meanHopTimes[hopIndex++] = IntStream.of(hop).sum() / hop.length;
        }
        int[] meanDwellTimes = new int[tripPattern.getStops().size()];
        int dwellIndex = 0;
        for (int[] dwell : dwellTimes) {
            meanDwellTimes[dwellIndex++] = IntStream.of(dwell).sum() / dwell.length;
        }
        // phew! now let's make a frequency entry
        TripTimes tt = new TripTimes(candidates.get(0));
        int cumulative = 0;
        for (int i = 0; i < tt.getNumStops(); i++) {
            tt.updateArrivalTime(i, cumulative);
            cumulative += meanDwellTimes[i];
            tt.updateDepartureTime(i, cumulative);
            if (i + 1 < tt.getNumStops())
                cumulative += meanHopTimes[i];
        }
        FrequencyEntry fe = new FrequencyEntry(windowStart - 60 * 60 * 3, windowEnd + 60 * 60 * 3, aggregateHeadway, false, tt);
        this.frequencyEntries.add(fe);
    }
}
Also used : IntStream(java.util.stream.IntStream) java.util(java.util) Logger(org.slf4j.Logger) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap) LoggerFactory(org.slf4j.LoggerFactory) Multimap(com.google.common.collect.Multimap) Ints(com.google.common.primitives.Ints) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) Collectors(java.util.stream.Collectors) TObjectIntMap(gnu.trove.map.TObjectIntMap) TIntSet(gnu.trove.set.TIntSet) TIntHashSet(gnu.trove.set.hash.TIntHashSet) RaptorWorkerTimetable(org.opentripplanner.profile.RaptorWorkerTimetable) HashMultimap(com.google.common.collect.HashMultimap) TObjectIntIterator(gnu.trove.iterator.TObjectIntIterator) Stop(org.onebusaway.gtfs.model.Stop) Stream(java.util.stream.Stream) Graph(org.opentripplanner.routing.graph.Graph) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TObjectIntMap(gnu.trove.map.TObjectIntMap) Stop(org.onebusaway.gtfs.model.Stop) TIntSet(gnu.trove.set.TIntSet) TObjectIntIterator(gnu.trove.iterator.TObjectIntIterator) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) TIntHashSet(gnu.trove.set.hash.TIntHashSet) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Example 40 with TIntHashSet

use of gnu.trove.set.hash.TIntHashSet in project RFTools by McJty.

the class InvCheckerTileEntity method isEqualForOredict.

private boolean isEqualForOredict(ItemStack s1, ItemStack s2) {
    if (set1 == null) {
        int[] oreIDs1 = OreDictionary.getOreIDs(s1);
        set1 = new TIntHashSet(oreIDs1);
    }
    if (set1.isEmpty()) {
        // The first item is not an ore. In this case we do normal equality of item
        return s1.getItem() == s2.getItem();
    }
    int[] oreIDs2 = OreDictionary.getOreIDs(s2);
    if (oreIDs2.length == 0) {
        // The first is an ore but this isn't. So we cannot match.
        return false;
    }
    TIntSet set2 = new TIntHashSet(oreIDs2);
    set2.retainAll(set1);
    return !set2.isEmpty();
}
Also used : TIntSet(gnu.trove.set.TIntSet) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Aggregations

TIntHashSet (gnu.trove.set.hash.TIntHashSet)49 ArrayList (java.util.ArrayList)16 TIntSet (gnu.trove.set.TIntSet)8 TIntArrayList (gnu.trove.list.array.TIntArrayList)7 TIntProcedure (gnu.trove.procedure.TIntProcedure)7 IJ (ij.IJ)6 PointPair (uk.ac.sussex.gdsc.core.match.PointPair)6 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)6 PeakResultPoint (uk.ac.sussex.gdsc.smlm.results.PeakResultPoint)6 PlugIn (ij.plugin.PlugIn)5 TextWindow (ij.text.TextWindow)5 List (java.util.List)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 ImageJUtils (uk.ac.sussex.gdsc.core.ij.ImageJUtils)5 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)5 TextUtils (uk.ac.sussex.gdsc.core.utils.TextUtils)5 TIntIterator (gnu.trove.iterator.TIntIterator)4 TIntObjectHashMap (gnu.trove.map.hash.TIntObjectHashMap)4 Prefs (ij.Prefs)4 Point (java.awt.Point)4