com.google.common.collect.Range Java Examples

The following examples show how to use com.google.common.collect.Range. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KinesisMessageLogReceiverEndpointIntegrationTest.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Test
public void consumeDataFromKinesis() throws ExecutionException, InterruptedException {
    // given
    final ChannelPosition startFrom = findCurrentPosition();
    sendTestMessages(Range.closed(1, 10), "some payload");

    // when
    kinesisMessageLog.consumeUntil(
            startFrom,
            endOfChannel()
    ).get();

    // then
    assertThat(messages, not(empty()));
    assertThat(messages, hasSize(10));
}
 
Example #2
Source File: DateRangeRules.java    From Quicksql with MIT License 6 votes vote down vote up
private Range<Calendar> extractRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  switch (comparison) {
  case EQUALS:
    return Range.closedOpen(round(c, timeUnit, true),
        round(c, timeUnit, false));
  case LESS_THAN:
    return Range.lessThan(round(c, timeUnit, true));
  case LESS_THAN_OR_EQUAL:
    return Range.lessThan(round(c, timeUnit, false));
  case GREATER_THAN:
    return Range.atLeast(round(c, timeUnit, false));
  case GREATER_THAN_OR_EQUAL:
    return Range.atLeast(round(c, timeUnit, true));
  default:
    throw new AssertionError(comparison);
  }
}
 
Example #3
Source File: LipidSearchTask.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
private void searchModifications(PeakListRow rows, double lipidIonMass, LipidIdentity lipid,
    double[] lipidModificationMasses, Range<Double> mzTolModification) {
  for (int j = 0; j < lipidModificationMasses.length; j++) {
    if (mzTolModification.contains(lipidIonMass + (lipidModificationMasses[j]))) {
      // Calc relativ mass deviation
      double relMassDev = ((lipidIonMass + (lipidModificationMasses[j]) - rows.getAverageMZ())
          / (lipidIonMass + lipidModificationMasses[j])) * 1000000;
      // Add row identity
      rows.addPeakIdentity(new SimplePeakIdentity(lipid + " " + lipidModification[j]), false);
      rows.setComment("Ionization: " + ionizationType.getAdduct() + " " + lipidModification[j]
          + ", Δ " + NumberFormat.getInstance().format(relMassDev) + " ppm");
      logger.info("Found modified lipid: " + lipid.getName() + " " + lipidModification[j] + ", Δ "
          + NumberFormat.getInstance().format(relMassDev) + " ppm");
    }
  }
}
 
Example #4
Source File: DateRangeRules.java    From Quicksql with MIT License 6 votes vote down vote up
private Range<Calendar> ceilRange(TimeUnitRange timeUnit, SqlKind comparison,
    Calendar c) {
  final Calendar ceil = ceil(c, timeUnit);
  boolean boundary = ceil.equals(c);
  switch (comparison) {
  case EQUALS:
    return Range.openClosed(boundary ? decrement(ceil, timeUnit) : ceil, ceil);
  case LESS_THAN:
    return Range.atMost(decrement(ceil, timeUnit));
  case LESS_THAN_OR_EQUAL:
    return boundary ? Range.atMost(ceil) : Range.atMost(decrement(ceil, timeUnit));
  case GREATER_THAN:
    return boundary ? Range.greaterThan(ceil) : Range.greaterThan(decrement(ceil, timeUnit));
  case GREATER_THAN_OR_EQUAL:
    return Range.greaterThan(decrement(ceil, timeUnit));
  default:
    throw Util.unexpected(comparison);
  }
}
 
Example #5
Source File: TestTimeRangeUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "computeTimeRanges")
public Object[][] provideComputeTimeRanges() {
  DateTime now = DateTime.now();
  DateTime yesterday = now.minusDays(1);
  List<Object[]> entries = new ArrayList<>();
  entries.add(new Object[] {
      null, yesterday, now, Collections.singletonList(Range.closedOpen(yesterday, now))
  });
  entries.add(new Object[] {
      new TimeGranularity(1, TimeUnit.DAYS), yesterday, now,
      Collections.singletonList(Range.closedOpen(yesterday, now))
  });
  entries.add(new Object[] {
      new TimeGranularity(6, TimeUnit.HOURS), yesterday, now,
      Arrays.asList(Range.closedOpen(yesterday, yesterday.plusHours(6)),
          Range.closedOpen(yesterday.plusHours(6), yesterday.plusHours(12)),
          Range.closedOpen(yesterday.plusHours(12), yesterday.plusHours(18)),
          Range.closedOpen(yesterday.plusHours(18), yesterday.plusHours(24)))
  });
  return entries.toArray(new Object[entries.size()][]);
}
 
Example #6
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return integerRange(value);
    } else if("int8range".equals(type)) {
        return longRange(value);
    } else if("numrange".equals(type)) {
        return bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example #7
Source File: SpectraIdentificationLipidSearchTask.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
private String searchModifications(double searchedMass, double lipidIonMass, LipidIdentity lipid,
    double[] lipidModificationMasses, Range<Double> mzTolModification) {
  String lipidAnnoation = "";
  for (int j = 0; j < lipidModificationMasses.length; j++) {
    if (mzTolModification.contains(lipidIonMass + (lipidModificationMasses[j]))) {
      // Calc relativ mass deviation
      double relMassDev = ((lipidIonMass + (lipidModificationMasses[j]) - searchedMass)
          / (lipidIonMass + lipidModificationMasses[j])) * 1000000;
      // Add row identity
      lipidAnnoation = lipid + " " + ionizationType.getAdduct() + " " + lipidModification[j]
          + ", Δ " + NumberFormat.getInstance().format(relMassDev) + " ppm";
      logger.info("Found modified lipid: " + lipid.getName() + " " + lipidModification[j] + ", Δ "
          + NumberFormat.getInstance().format(relMassDev) + " ppm");
    }
  }
  return lipidAnnoation;
}
 
Example #8
Source File: DoubleRangeEditor.java    From old-mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("null")
@Override
public void setValue(Range<Double> value) {
  if (value == null)
    return;
  String minValue;
  String maxValue;

  if (numberFormat != null) {
    minValue = String.valueOf(numberFormat.format(value.lowerEndpoint()));
    maxValue = String.valueOf(numberFormat.format(value.upperEndpoint()));
  } else {
    minValue = String.valueOf(value.lowerEndpoint());
    maxValue = String.valueOf(value.upperEndpoint());
  }

  minTxtField.setText(minValue);
  maxTxtField.setText(maxValue);
}
 
Example #9
Source File: SensorDatabaseTest.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddScalarReadingLimits() {
  SensorDatabaseImpl db =
      new SensorDatabaseImpl(getContext(), getAppAccount(), TEST_DATABASE_NAME);
  db.addScalarReading("id", "tag", 0, 1, 1.0);
  db.addScalarReading("id", "tag", 0, 2, 2.0);
  db.addScalarReading("id", "tag", 0, 3, 3.0);
  int limit = 2;
  List<ScalarReading> readings =
      ScalarReading.slurp(
          db.getScalarReadings("id", "tag", TimeRange.oldest(Range.closed(0L, 4L)), 0, limit));
  assertEquals(Arrays.asList(new ScalarReading(1, 1.0), new ScalarReading(2, 2.0)), readings);
}
 
Example #10
Source File: RangeRestrictedTypeBuilder.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static <C extends Number & Comparable<C>> List<ValueRange> ensureResolvedRanges(
        final List<ValueRange> unresolved, final Range<C> baseRange) {
    // First check if we need to resolve anything at all
    for (ValueRange c : unresolved) {
        if (c.lowerBound() instanceof UnresolvedNumber || c.upperBound() instanceof UnresolvedNumber) {
            return resolveRanges(unresolved, baseRange);
        }
    }

    // No need, just return the same list
    return unresolved;
}
 
Example #11
Source File: RoadmManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Range<Double> targetPortPowerRange(DeviceId deviceId, PortNumber portNumber) {
    checkNotNull(deviceId);
    checkNotNull(portNumber);
    PowerConfig<Object> powerConfig = getPowerConfig(deviceId);
    if (powerConfig != null) {
        Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL);
        if (range.isPresent()) {
            return range.get();
        }
    }
    return null;
}
 
Example #12
Source File: PeakUtils.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * @param row The row.
 * @return The average retention time range of all features contained in this peak list row across
 *         all raw data files. Empty range (0,0) if the row is null or has no feature assigned to
 *         it.
 */
public @Nonnull static Range<Double> getPeakListRowAvgRtRange(PeakListRow row) {

  if (row == null || row.getBestPeak() == null)
    return Range.closed(0.d, 0.d);

  int size = row.getPeaks().length;
  double[] lower = new double[size];
  double[] upper = new double[size];

  Feature[] f = row.getPeaks();

  for (int i = 0; i < size; i++) {
    if (f[i] == null)
      continue;

    Range<Double> r = f[i].getRawDataPointsRTRange();

    lower[i] = r.lowerEndpoint();
    upper[i] = r.upperEndpoint();
  }

  double avgL = 0, avgU = 0;
  for (int i = 0; i < size; i++) {
    avgL += lower[i];
    avgU += upper[i];
  }
  avgL /= size;
  avgU /= size;

  return Range.closed(avgL, avgU);
}
 
Example #13
Source File: RangeMapExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void google_guava_range_map_example () {

	RangeMap<Integer, String> gradeScale = TreeRangeMap.create();
	gradeScale.put(Range.closed(0, 60), "F");
	gradeScale.put(Range.closed(61, 70), "D");
	gradeScale.put(Range.closed(71, 80), "C");
	gradeScale.put(Range.closed(81, 90), "B");
	gradeScale.put(Range.closed(91, 100), "A");
	
	String grade = gradeScale.get(77);
	
	assertEquals("C", grade);
}
 
Example #14
Source File: StackdriverWriter.java    From java-monitoring-client-library with Apache License 2.0 5 votes vote down vote up
private static TimeInterval encodeTimeInterval(Range<Instant> nativeInterval, Kind metricKind) {

    TimeInterval encodedInterval =
        new TimeInterval().setStartTime(nativeInterval.lowerEndpoint().toString());

    Instant endTimestamp =
        nativeInterval.isEmpty() && metricKind != Kind.GAUGE
            ? nativeInterval.upperEndpoint().plusMillis(1)
            : nativeInterval.upperEndpoint();

    return encodedInterval.setEndTime(endTimestamp.toString());
  }
 
Example #15
Source File: DoubleRangeParameter.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public DoubleRangeParameter(@Nonnull String name, @Nonnull String description,
    @Nonnull String category, @Nullable NumberFormat numberFormat,
    @Nullable ParameterValidator<Range<Double>> validator, @Nullable Range<Double> defaultValue) {
  super(name, description, category, DoubleRangeEditor.class, validator);
  setValue(defaultValue);
  this.numberFormat = numberFormat;
}
 
Example #16
Source File: RoadmManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Range<Double> attenuationRange(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) {
    checkNotNull(deviceId);
    checkNotNull(portNumber);
    checkNotNull(ochSignal);
    PowerConfig<Object> powerConfig = getPowerConfig(deviceId);
    if (powerConfig != null) {
        Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, ochSignal);
        if (range.isPresent()) {
            return range.get();
        }
    }
    return null;
}
 
Example #17
Source File: SlaAlgorithmTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testJobUptimeLiveNonTerminalIgnored() {
  long now = System.currentTimeMillis();
  Set<IScheduledTask> instances = makeUptimeTasks(100, now);
  instances.add(makeTask(ImmutableMap.of(now - 5000, RUNNING, now - 3000, RESTARTING)));
  Number actual = JOB_UPTIME_99.getAlgorithm().calculate(instances, Range.closed(0L, now));
  assertEquals(1.99, actual);
}
 
Example #18
Source File: TeamMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void updatePlayerLimits() {
    int min = 0, max = 0;
    for(Team team : getTeams()) {
        min += team.getMinPlayers();
        max += team.getMaxPlayers();
    }
    getMatch().setPlayerLimits(Range.closed(min, max));
}
 
Example #19
Source File: ScanSelection.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public ScanSelection(Range<Integer> scanNumberRange, Integer baseFilteringInteger,
    Range<Double> scanRTRange, PolarityType polarity, MassSpectrumType spectrumType,
    Integer msLevel, String scanDefinition) {
  this.scanNumberRange = scanNumberRange;
  this.baseFilteringInteger = baseFilteringInteger;
  this.scanRTRange = scanRTRange;
  this.polarity = polarity;
  this.spectrumType = spectrumType;
  this.msLevel = msLevel;
  this.scanDefinition = scanDefinition;
}
 
Example #20
Source File: SnippetFormatter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Generates {@code Replacement}s rewriting {@code source} to {@code replacement}, under the
 * assumption that they differ in whitespace alone.
 */
private static List<Replacement> toReplacements(String source, String replacement) {
    if (!NOT_WHITESPACE.retainFrom(source).equals(NOT_WHITESPACE.retainFrom(replacement))) {
        throw new IllegalArgumentException(
                "source = \"" + source + "\", replacement = \"" + replacement + "\"");
    }
/*
 * In the past we seemed to have problems touching non-whitespace text in the formatter, even
 * just replacing some code with itself.  Retrospective attempts to reproduce this have failed,
 * but this may be an issue for future changes.
 */
    List<Replacement> replacements = new ArrayList<>();
    int i = NOT_WHITESPACE.indexIn(source);
    int j = NOT_WHITESPACE.indexIn(replacement);
    if (i != 0 || j != 0) {
        replacements.add(Replacement.create(Range.closedOpen(0, i), replacement.substring(0, j)));
    }
    while (i != -1 && j != -1) {
        int i2 = NOT_WHITESPACE.indexIn(source, i + 1);
        int j2 = NOT_WHITESPACE.indexIn(replacement, j + 1);
        if (i2 == -1 || j2 == -1) {
            break;
        }
        if ((i2 - i) != (j2 - j)
                || !source.substring(i + 1, i2).equals(replacement.substring(j + 1, j2))) {
            replacements.add(
                    Replacement.create(Range.closedOpen(i + 1, i2), replacement.substring(j + 1, j2)));
        }
        i = i2;
        j = j2;
    }
    return replacements;
}
 
Example #21
Source File: ListDoubleRangeComponent.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public List<Range<Double>> getValue() {
  try {
    return dulab.adap.common.algorithms.String.toRanges(textField.getText());
  } catch (Exception e) {
    return null;
  }
}
 
Example #22
Source File: HMDBGateway.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults,
    ParameterSet parameters) throws IOException {

  Range<Double> toleranceRange = mzTolerance.getToleranceRange(mass);

  String queryAddress = hmdbSeachAddress + "&query_from=" + toleranceRange.lowerEndpoint()
      + "&query_to=" + toleranceRange.upperEndpoint();

  URL queryURL = new URL(queryAddress);

  // Submit the query
  logger.finest("Loading URL " + queryAddress);
  String queryResult = InetUtils.retrieveData(queryURL);

  // Organize the IDs as a TreeSet to keep them sorted
  TreeSet<String> results = new TreeSet<String>();

  // Find IDs in the HTML data
  Pattern pat = Pattern.compile("metabolites/(HMDB[0-9]{5,})");
  Matcher matcher = pat.matcher(queryResult);
  while (matcher.find()) {
    String hmdbID = matcher.group(1);
    results.add(hmdbID);
  }

  // Remove all except first numOfResults IDs. The reason why we first
  // retrieve all results and then remove those above numOfResults is to
  // keep the lowest HDMB IDs - these may be the most interesting ones.
  while (results.size() > numOfResults) {
    String lastItem = results.last();
    results.remove(lastItem);
  }

  return results.toArray(new String[0]);

}
 
Example #23
Source File: CumulusNcluGrammarTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testBondExtraction() {
  CumulusNcluConfiguration vc = parseVendorConfig("cumulus_nclu_bond");
  String bond1Name = "bond1";
  String bond2Name = "bond2";
  String bond3Name = "bond3";
  String bond4Name = "bond4";
  String bond5Name = "bond5";

  String[] expectedSlaves =
      new String[] {"swp1", "swp2", "swp3", "swp4", "swp5", "swp6", "swp7", "swp8"};

  // referenced interfaces should have been created
  assertThat(vc.getInterfaces().keySet(), containsInAnyOrder(expectedSlaves));

  assertThat(
      "Ensure bonds were extracted",
      vc.getBonds().keySet(),
      containsInAnyOrder(bond1Name, bond2Name, bond3Name, bond4Name, bond5Name));

  Bond bond1 = vc.getBonds().get(bond1Name);
  Bond bond2 = vc.getBonds().get(bond2Name);
  Bond bond3 = vc.getBonds().get(bond3Name);

  assertThat("Ensure access VLAN ID was set", bond1.getBridge().getAccess(), equalTo(2));
  assertThat("Ensure CLAG ID was set", bond1.getClagId(), equalTo(1));
  assertThat("Ensure slaves were set", bond1.getSlaves(), containsInAnyOrder(expectedSlaves));
  assertThat(
      "Ensure trunk VLAN IDs were set",
      bond2.getBridge().getVids(),
      equalTo(IntegerSpace.of(Range.closed(3, 5))));
  assertThat(
      "Ensure IP address was extracted",
      bond3.getIpAddresses(),
      contains(ConcreteInterfaceAddress.parse("192.0.2.1/24")));
  assertThat("Ensure VRF was extracted", bond3.getVrf(), equalTo("vrf1"));
}
 
Example #24
Source File: RangeHeader.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param builder
 */
private RangeHeader(final Builder builder) {

  this.field = builder.field;

  if (builder.fromId != null && builder.toId != null) {
    if (builder.fromInclusive && builder.toInclusive) {
      range = Range.closed(builder.fromId, builder.toId);
    } else if (builder.fromInclusive && !builder.toInclusive) {
      range = Range.closedOpen(builder.fromId, builder.toId);
    } else if (!builder.fromInclusive && builder.toInclusive) {
      range = Range.openClosed(builder.fromId, builder.toId);
    } else {
      range = Range.open(builder.fromId, builder.toId);
    }
  } else if (builder.fromId != null && builder.toId == null) {
    if (builder.fromInclusive) {
      range = Range.atLeast(builder.fromId);
    } else {
      range = Range.greaterThan(builder.fromId);
    }
  } else if (builder.fromId == null && builder.toId != null) {
    if (builder.toInclusive) {
      range = Range.atMost(builder.toId);
    } else {
      range = Range.lessThan(builder.toId);
    }
  } else {
    range = Range.all();
  }

  this.max = builder.max;
}
 
Example #25
Source File: DiscretizationUtilTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void boundedRange(){
	Range<Double> open = toRange(Interval.Closure.OPEN_OPEN, -1d, 1d);
	assertFalse(open.contains(-Double.MAX_VALUE));
	assertFalse(open.contains(-1d));
	assertTrue(open.contains(0d));
	assertFalse(open.contains(1d));
	assertFalse(open.contains(Double.MAX_VALUE));

	Range<Double> openClosed = toRange(Interval.Closure.OPEN_CLOSED, -1d, 1d);
	assertFalse(openClosed.contains(-Double.MAX_VALUE));
	assertFalse(openClosed.contains(-1d));
	assertTrue(openClosed.contains(0d));
	assertTrue(openClosed.contains(1d));
	assertFalse(openClosed.contains(Double.MAX_VALUE));

	Range<Double> closedOpen = toRange(Interval.Closure.CLOSED_OPEN, -1d, 1d);
	assertFalse(closedOpen.contains(-Double.MAX_VALUE));
	assertTrue(closedOpen.contains(-1d));
	assertTrue(closedOpen.contains(0d));
	assertFalse(closedOpen.contains(1d));
	assertFalse(closedOpen.contains(Double.MAX_VALUE));

	Range<Double> closed = toRange(Interval.Closure.CLOSED_CLOSED, -1d, 1d);
	assertFalse(closed.contains(-Double.MAX_VALUE));
	assertTrue(closed.contains(-1d));
	assertTrue(closed.contains(0d));
	assertTrue(closed.contains(1d));
	assertFalse(closed.contains(Double.MAX_VALUE));
}
 
Example #26
Source File: AdvaTerminalDevicePowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Getting target value of output power.
 * @param port port
 * @param component the component
 * @return target output power range
 */
@Override
public Optional<Range<Double>> getTargetPowerRange(PortNumber port, Object component) {
    double targetMin = -30;
    double targetMax = 1;
    return Optional.of(Range.open(targetMin, targetMax));
}
 
Example #27
Source File: KinesisMessageLogReceiverEndpointIntegrationTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Test
public void runInSeparateThreads() throws ExecutionException, InterruptedException {
    // when
    final ChannelPosition startFrom = findCurrentPosition();
    sendTestMessages(Range.closed(1, 10), "some payload");

    // then
    kinesisMessageLog
            .consumeUntil(startFrom, endOfChannel())
            .get();

    assertThat(threads, hasSize(2));
}
 
Example #28
Source File: ScanDataSet.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This function finds highest data point intensity in given m/z range. It is important for
 * normalizing isotope patterns.
 */
public double getHighestIntensity(Range<Double> mzRange) {

  double maxIntensity = 0;
  for (DataPoint dp : dataPoints) {
    if ((mzRange.contains(dp.getMZ())) && (dp.getIntensity() > maxIntensity))
      maxIntensity = dp.getIntensity();
  }

  return maxIntensity;
}
 
Example #29
Source File: BaselineCorrectorSetupDialog.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This function sets all the information into the plot chart
 */
@Override
protected void loadPreview(TICPlot ticPlot, RawDataFile dataFile, Range<Double> rtRange,
    Range<Double> mzRange) {

  boolean ready = true;
  // Abort previous preview task.
  if (previewTask != null && previewTask.getStatus() == TaskStatus.PROCESSING) {
    ready = false;
    previewTask.kill();
    try {
      previewThread.join();
      ready = true;
    } catch (InterruptedException e) {
      ready = false;
    }
  }

  // Start processing new preview task.
  if (ready && (previewTask == null || previewTask.getStatus() != TaskStatus.PROCESSING)) {

    baselineCorrector.initProgress(dataFile);
    previewTask = new PreviewTask(this, ticPlot, dataFile, rtRange, mzRange);
    previewThread = new Thread(previewTask);
    LOG.info("Launch preview task.");
    previewThread.start();
  }
}
 
Example #30
Source File: BaselineCorrector.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs TIC (sum) chromatograms - one for each m/z bin.
 * 
 * @param origDataFile dataFile of concern.
 * @param level the MS level.
 * @param numBins number of m/z bins.
 * @return the chromatograms as double[number of bins][number of scans].
 */
private double[][] buildTICChromatograms(final RawDataFile origDataFile, final int level,
    final int numBins) {

  // Get scan numbers from original file.
  final int[] scanNumbers = origDataFile.getScanNumbers(level);
  final int numScans = scanNumbers.length;

  // Determine MZ range.
  final Range<Double> mzRange = origDataFile.getDataMZRange();

  // Create chromatograms.
  final double[][] chromatograms = new double[numBins][numScans];

  for (int scanIndex = 0; !isAborted(origDataFile) && scanIndex < numScans; scanIndex++) {

    // Get original scan.
    final Scan scan = origDataFile.getScan(scanNumbers[scanIndex]);

    // Process data points.
    for (final DataPoint dataPoint : scan.getDataPoints()) {

      chromatograms[RangeUtils.binNumber(mzRange, numBins, dataPoint.getMZ())][scanIndex] +=
          dataPoint.getIntensity();
    }
    progressMap.get(origDataFile)[0]++;
  }

  return chromatograms;
}