ExitCodes main_(int, const char**)
  {
    // parsing parameters
    String in(getStringOption_("in"));
    String feature_in(getStringOption_("feature_in"));
    String out(getStringOption_("out"));
    double precursor_mass_tolerance(getDoubleOption_("precursor_mass_tolerance"));

    // reading input
    FileHandler fh;
    FileTypes::Type in_type = fh.getType(in);

    PeakMap exp;
    fh.loadExperiment(in, exp, in_type, log_type_, false, false);
    exp.sortSpectra();

    FeatureMap feature_map;
    if (feature_in != "")
    {
      FeatureXMLFile().load(feature_in, feature_map);
    }

    // calculations
    FeatureFinderAlgorithmIsotopeWavelet iso_ff;
    Param ff_param(iso_ff.getParameters());
    ff_param.setValue("max_charge", getIntOption_("max_charge"));
    ff_param.setValue("intensity_threshold", getDoubleOption_("intensity_threshold"));
    iso_ff.setParameters(ff_param);

    FeatureFinder ff;
    ff.setLogType(ProgressLogger::NONE);

    PeakMap exp2 = exp;
    exp2.clear(false);
    for (PeakMap::ConstIterator it = exp.begin(); it != exp.end(); ++it)
    {
      if (it->size() != 0)
      {
        exp2.addSpectrum(*it);
      }
    }

    exp = exp2;
    exp.updateRanges();

    // TODO check MS2 and MS1 counts
    ProgressLogger progresslogger;
    progresslogger.setLogType(log_type_);
    progresslogger.startProgress(0, exp.size(), "Correcting precursor masses");
    for (PeakMap::Iterator it = exp.begin(); it != exp.end(); ++it)
    {
      progresslogger.setProgress(exp.end() - it);
      if (it->getMSLevel() != 2)
      {
        continue;
      }
      // find first MS1 scan of the MS/MS scan
      PeakMap::Iterator ms1_it = it;
      while (ms1_it != exp.begin() && ms1_it->getMSLevel() != 1)
      {
        --ms1_it;
      }
      if (ms1_it == exp.begin() && ms1_it->getMSLevel() != 1)
      {
        writeLog_("Did not find a MS1 scan to the MS/MS scan at RT=" + String(it->getRT()));
        continue;
      }
      if (ms1_it->size() == 0)
      {
        writeDebug_("No peaks in scan at RT=" + String(ms1_it->getRT()) + String(", skipping"), 1);
        continue;
      }

      PeakMap::Iterator ms2_it = ms1_it;
      ++ms2_it;

      while (ms2_it != exp.end() && ms2_it->getMSLevel() == 2)
      {
        // first: error checks
        if (ms2_it->getPrecursors().empty())
        {
          writeDebug_("Warning: found no precursors of spectrum RT=" + String(ms2_it->getRT()) + ", skipping it.", 1);
          ++ms2_it;
          continue;
        }
        else if (ms2_it->getPrecursors().size() > 1)
        {
          writeLog_("Warning: found more than one precursor of spectrum RT=" + String(ms2_it->getRT()) + ", using first one.");
        }

        Precursor prec = *ms2_it->getPrecursors().begin();
        double prec_pos = prec.getMZ();

        PeakMap new_exp;
        // now excise small region from the MS1 spec for the feature finder (isotope pattern must be covered...)
        PeakSpectrum zoom_spec;
        for (PeakSpectrum::ConstIterator pit = ms1_it->begin(); pit != ms1_it->end(); ++pit)
        {
          if (pit->getMZ() > prec_pos - 3 && pit->getMZ() < prec_pos + 3)
          {
            zoom_spec.push_back(*pit);
          }
        }
        new_exp.addSpectrum(zoom_spec);
        new_exp.updateRanges();
        FeatureMap features, seeds;
        ff.run("isotope_wavelet", new_exp, features, ff_param, seeds);
        if (features.empty())
        {
          writeDebug_("No features found for scan RT=" + String(ms1_it->getRT()), 1);
          ++ms2_it;
          continue;
        }

        double max_int(numeric_limits<double>::min());
        double min_dist(numeric_limits<double>::max());
        Size max_int_feat_idx(0);

        for (Size i = 0; i != features.size(); ++i)
        {
          if (fabs(features[i].getMZ() - prec_pos) < precursor_mass_tolerance &&
              features[i].getIntensity() > max_int)
          {
            max_int_feat_idx = i;
            max_int = features[i].getIntensity();
            min_dist = fabs(features[i].getMZ() - prec_pos);
          }
        }


        writeDebug_(" max_int=" + String(max_int) + " mz=" + String(features[max_int_feat_idx].getMZ()) + " charge=" + String(features[max_int_feat_idx].getCharge()), 5);
        if (min_dist < precursor_mass_tolerance)
        {
          prec.setMZ(features[max_int_feat_idx].getMZ());
          prec.setCharge(features[max_int_feat_idx].getCharge());
          vector<Precursor> precs;
          precs.push_back(prec);
          ms2_it->setPrecursors(precs);
          writeDebug_("Correcting precursor mass of spectrum RT=" + String(ms2_it->getRT()) + " from " + String(prec_pos) + " to " + String(prec.getMZ()) + " (z=" + String(prec.getCharge()) + ")", 1);
        }

        ++ms2_it;
      }
      it = --ms2_it;
    }
    progresslogger.endProgress();

    // writing output
    fh.storeExperiment(out, exp, log_type_);

    return EXECUTION_OK;
  }
Example #2
0
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

Precursor* ptr = 0;
Precursor* nullPointer = 0;
START_SECTION((Precursor()))
	ptr = new Precursor();
	TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION

START_SECTION((~Precursor()))
	delete ptr;
END_SECTION

START_SECTION((double getActivationEnergy() const))
  Precursor tmp;
  TEST_EQUAL(tmp.getActivationEnergy(),0);
END_SECTION

START_SECTION((void setActivationEnergy(double activation_energy)))
  Precursor tmp;
  tmp.setActivationEnergy(47.11);
  TEST_REAL_SIMILAR(tmp.getActivationEnergy(),47.11);
END_SECTION

START_SECTION((const set<ActivationMethod>& getActivationMethods() const))
  Precursor tmp;
  TEST_EQUAL(tmp.getActivationMethods().size(),0);
END_SECTION

PWIZ_API_DECL SpectrumPtr SpectrumList_ABI::spectrum(size_t index, DetailLevel detailLevel, const pwiz::util::IntegerSet& msLevelsToCentroid) const
{
    boost::lock_guard<boost::mutex> lock(readMutex);  // lock_guard will unlock mutex when out of scope or when exception thrown (during destruction)
    boost::call_once(indexInitialized_.flag, boost::bind(&SpectrumList_ABI::createIndex, this));
    if (index >= size_)
        throw runtime_error("[SpectrumList_ABI::spectrum()] Bad index: " + lexical_cast<string>(index));


    // allocate a new Spectrum
    IndexEntry& ie = index_[index];
    SpectrumPtr result = SpectrumPtr(new Spectrum);
    if (!result.get())
        throw std::runtime_error("[SpectrumList_ABI::spectrum()] Allocation error.");

    result->index = index;
    result->id = ie.id;

    //Console::WriteLine("spce: {0}.{1}.{2}.{3}", ie.sample, ie.period, ie.cycle, ie.experiment);

    result->scanList.set(MS_no_combination);
    result->scanList.scans.push_back(Scan());
    Scan& scan = result->scanList.scans[0];

    ExperimentPtr msExperiment = ie.experiment;

    // Synchronize access to cached spectrum for multi-threaded use
    pwiz::vendor_api::ABI::SpectrumPtr spectrum;
    {
        boost::mutex::scoped_lock spectrum_lock(spectrum_mutex);

        if (spectrumLastIndex_ != index)
        {
            spectrumLastIndex_ = index;
            spectrumLast_ = wifffile_->getSpectrum(msExperiment, ie.cycle);
        }
        spectrum = spectrumLast_;
    }

    double scanTime = spectrum->getStartTime();
    if (scanTime > 0)
        scan.set(MS_scan_start_time, scanTime, UO_minute);
    scan.set(MS_preset_scan_configuration, msExperiment->getExperimentNumber());

    ExperimentType experimentType = msExperiment->getExperimentType();
    int msLevel = spectrum->getMSLevel();
    result->set(MS_ms_level, msLevel);
    result->set(translateAsSpectrumType(experimentType));
    result->set(translate(msExperiment->getPolarity()));

    // CONSIDER: Can anything below here be added to instant?
    if (detailLevel == DetailLevel_InstantMetadata)
        return result;

	// Revert to previous behavior for getting binary data or not.
	bool getBinaryData = (detailLevel == DetailLevel_FullData);

    double startMz, stopMz;
    msExperiment->getAcquisitionMassRange(startMz, stopMz);
    scan.scanWindows.push_back(ScanWindow(startMz, stopMz, MS_m_z));

    // decide whether to use Points or Peaks to populate data arrays
    bool doCentroid = msLevelsToCentroid.contains(msLevel);

    bool continuousData = spectrum->getDataIsContinuous();
    if (continuousData && !doCentroid)
        result->set(MS_profile_spectrum);
    else
    {
        result->set(MS_centroid_spectrum);
        doCentroid = continuousData;
    }

    /*if (experimentType == MRM)
    {
        MRMTransitions^ transitions = msExperiment->MRMTransitions;
        double q1mz = transitions[ie.transition]->Q1Mass;//ie.transition->first;
        double q3mz = transitions[ie.transition]->Q3Mass;
        double intensity = points[ie.transition]->Y;
        result->defaultArrayLength = 1;//ie.transition->second.size();

        Precursor precursor;
        SelectedIon selectedIon;

        selectedIon.set(MS_selected_ion_m_z, q1mz, MS_m_z);

        precursor.activation.set(MS_CID); // assume CID

        precursor.selectedIons.push_back(selectedIon);
        result->precursors.push_back(precursor);

        if (getBinaryData)
        {
            mzArray.resize(result->defaultArrayLength, q3mz);
            intensityArray.resize(result->defaultArrayLength, intensity);
        }
    }
    else*/
    {
        if (spectrum->getHasPrecursorInfo())
        {
            double selectedMz, intensity;
            int charge;
            spectrum->getPrecursorInfo(selectedMz, intensity, charge);

            Precursor precursor;
            SelectedIon selectedIon;

            selectedIon.set(MS_selected_ion_m_z, selectedMz, MS_m_z);
            if (charge > 0)
                selectedIon.set(MS_charge_state, charge);

            precursor.activation.set(MS_beam_type_collision_induced_dissociation); // assume beam-type CID since all ABI instruments that write WIFFs are either QqTOF or QqLIT

            precursor.selectedIons.push_back(selectedIon);

            // fix isolation width
            if (spectrum->getHasIsolationInfo())
            {
                double centerMz, lowerLimit, upperLimit;
                spectrum->getIsolationInfo(centerMz, lowerLimit, upperLimit);

                precursor.set(MS_isolation_window_target_m_z, centerMz, MS_m_z);
                precursor.set(MS_isolation_window_upper_offset, upperLimit);
                precursor.set(MS_isolation_window_lower_offset, lowerLimit);
            }


            result->precursors.push_back(precursor);
        }

        //virtual bool getHasIsolationInfo() const;
        //virtual void getIsolationInfo(double& centerMz, double& lowerLimit, double& upperLimit) const;


        //result->set(MS_lowest_observed_m_z, spectrum->getMinX(), MS_m_z);
        //result->set(MS_highest_observed_m_z, spectrum->getMaxX(), MS_m_z);
        result->set(MS_base_peak_intensity, spectrum->getBasePeakY(), MS_number_of_detector_counts);
        result->set(MS_base_peak_m_z, spectrum->getBasePeakX(), MS_m_z);
        result->set(MS_total_ion_current, spectrum->getSumY(), MS_number_of_detector_counts);

        if (getBinaryData)
        {
            result->setMZIntensityArrays(std::vector<double>(), std::vector<double>(), MS_number_of_detector_counts);
            BinaryDataArrayPtr mzArray = result->getMZArray();
            BinaryDataArrayPtr intensityArray = result->getIntensityArray();

            spectrum->getData(doCentroid, mzArray->data, intensityArray->data);
            if (doCentroid)
                result->set(MS_profile_spectrum); // let SpectrumList_PeakPicker know this was a profile spectrum
        }

        result->defaultArrayLength = spectrum->getDataSize(doCentroid);
    }

    return result;
}
 bool IsobaricChannelExtractor::isValidPrecursor_(const Precursor& precursor) const
 {
   return (precursor.getIntensity() == 0.0 && keep_unannotated_precursor_) || !(precursor.getIntensity() < min_precursor_intensity_);
 }
int Narrator::script(int st, PRNG &prng)
{
    static ChaosParticles chaosA(flow, runner.config["chaosParticles"]);
    static ChaosParticles chaosB(flow, runner.config["chaosParticles"]);
    static OrderParticles orderParticles(flow, runner.config["orderParticles"]);
    static Precursor precursor(flow, runner.config["precursor"]);
    static RingsEffect ringsA(flow, runner.config["ringsA"]);
    static RingsEffect ringsB(flow, runner.config["ringsB"]);
    static RingsEffect ringsC(flow, runner.config["ringsC"]);
    static PartnerDance partnerDance(flow, runner.config["partnerDance"]);
    static CameraFlowDebugEffect flowDebugEffect(flow, runner.config["flowDebugEffect"]);
    static Forest forest(flow, runner.config["forest"]);
    static DarknessEffect darkness;

    rapidjson::Value& config = runner.config["narrator"];
    Sampler s(prng.uniform32());

    switch (st) {

        //////////////////////////////////////////////////////////////////////////////////////////////
        // Special states

        case 1: {
            // Darkness only ("off")
            crossfade(&darkness, 1);
            delayForever();
        }

        case 2: {
            // Precursor only (sleep mode)            
            precursor.reseed(prng.uniform32());
            crossfade(&precursor, 1);
            delayForever();
        }

        case 3: {
            // Debugging the computer vision system
            crossfade(&flowDebugEffect, 1);
            delayForever();
        }

        //////////////////////////////////////////////////////////////////////////////////////////////
        // Opening sequence

        case 0: {
            // Darkness until opening

            crossfade(&darkness, 1);
            delayUntilDate(config["opening"]["date"]);
            return config["opening"]["nextState"].GetInt();
        }

        //////////////////////////////////////////////////////////////////////////////////////////////
        // Cyclic states

        default: {
            endCycle();
            return 10;
        }

        case 10: {
            // Order trying to form out of the tiniest sparks; runs for an unpredictable time, fails.
            precursor.reseed(prng.uniform32());
            crossfade(&precursor, s.value(config["precursorCrossfade"]));

            // Bootstrap
            delay(s.value(config["precursorBootstrap"]));

            // Wait for darkness
            while (!precursor.isDone) {
                doFrame();
            }
            return 20;
        }

        case 20: {
            // Bang. Explosive energy, hints of self-organization

            ChaosParticles *pChaosA = &chaosA;
            ChaosParticles *pChaosB = &chaosB;
            
            int bangCount = s.value(config["bangCount"]);
            for (int i = 0; i < bangCount; i++) {
                pChaosA->reseed(prng.circularVector() * s.value(config["bangSeedRadius"]), prng.uniform32());
                crossfade(pChaosA, s.value(config["bangCrossfadeDuration"]));
                delay((1 << i) * s.value(config["bangDelayBasis"]));
                std::swap(pChaosA, pChaosB);
            }

            attention(s, config["bangAttention"]);

            return 30;
        }

        case 30: {
            // Textures of light, exploring something formless. Slow crossfade in
            ringsA.reseed(prng.uniform32());
            crossfade(&ringsA, s.value(config["ringsA-Crossfade"]));
            attention(s, config["ringsA-Attention"]);
            return 40;
        }

        case 40: {
            // Add energy, explore another layer.
            ringsB.reseed(prng.uniform32());
            crossfade(&ringsB, s.value(config["ringsB-Crossfade"]));
            attention(s, config["ringsB-Attention"]);
            return 50;
        }

        case 50: {
            // Biology happens, order emerges. Cellular look, emergent order.

            orderParticles.reseed(prng.uniform32());
            orderParticles.symmetry = 10;
            crossfade(&orderParticles, s.value(config["orderCrossfade"]));
            while (orderParticles.symmetry > 4) {
                attention(s, config["orderStepAttention"]);
                orderParticles.symmetry--;
            }
            attention(s, config["orderStepAttention"]);
            return 60;
        }

        case 60: {
            // Two partners, populations of particles.
            // Spiralling inwards. Depression. Beauty on the edge of destruction,
            // pressing forward until nothing remains.

            partnerDance.reseed(prng.uniform32());
            crossfade(&partnerDance, s.value(config["partnerCrossfade"]));
            attention(s, config["partnerAttention"]);
            return 70;
        }

        case 70: {
            // Sinking deeper. Interlude before a change.

            ringsC.reseed(prng.uniform32());
            crossfade(&ringsC, s.value(config["ringsC-Crossfade"]));
            attention(s, config["ringsC-Attention"]);
            return 80;
        }

        case 80: {
            // Continuous renewal and regrowth. Destruction happens unintentionally,
            // regrowth is quick and generative. The only way to lose is to stagnate.

            forest.reseed(prng.uniform32());
            crossfade(&forest, s.value(config["forestCrossfade"]));
            attention(s, config["forestAttention"]);
            return 90;
        }
    }
}
  void ChromatogramExtractor::return_chromatogram(std::vector< OpenSwath::ChromatogramPtr > & chromatograms,
    std::vector< ChromatogramExtractor::ExtractionCoordinates > & coordinates,
    OpenMS::TargetedExperiment & transition_exp_used, SpectrumSettings settings,
    std::vector<OpenMS::MSChromatogram<> > & output_chromatograms, bool ms1) const
  {
    typedef std::map<String, const ReactionMonitoringTransition* > TransitionMapType;
    TransitionMapType trans_map;
    for (Size i = 0; i < transition_exp_used.getTransitions().size(); i++)
    {
      trans_map[transition_exp_used.getTransitions()[i].getNativeID()] = &transition_exp_used.getTransitions()[i];
    }

    for (Size i = 0; i < chromatograms.size(); i++)
    { 
      const OpenSwath::ChromatogramPtr & chromptr = chromatograms[i];
      const ChromatogramExtractor::ExtractionCoordinates & coord = coordinates[i];

      TargetedExperiment::Peptide pep;
      OpenMS::ReactionMonitoringTransition transition;
      OpenMS::MSChromatogram<> chrom;

      // copy data
      OpenSwathDataAccessHelper::convertToOpenMSChromatogram(chrom, chromptr);
      chrom.setNativeID(coord.id);

      // Create precursor and set
      // 1) the target m/z
      // 2) the isolation window (upper/lower)
      // 3) the peptide sequence
      Precursor prec;
      if (ms1) 
      {
        pep = transition_exp_used.getPeptideByRef(coord.id); 
        prec.setMZ(coord.mz);
        chrom.setChromatogramType(ChromatogramSettings::BASEPEAK_CHROMATOGRAM);
      }
      else 
      {
        transition = (*trans_map[coord.id]);
        pep = transition_exp_used.getPeptideByRef(transition.getPeptideRef()); 

        prec.setMZ(transition.getPrecursorMZ());
        if (settings.getPrecursors().size() > 0)
        {
          prec.setIsolationWindowLowerOffset(settings.getPrecursors()[0].getIsolationWindowLowerOffset());
          prec.setIsolationWindowUpperOffset(settings.getPrecursors()[0].getIsolationWindowUpperOffset());
        }

        // Create product and set its m/z
        Product prod;
        prod.setMZ(transition.getProductMZ());
        chrom.setProduct(prod);
        chrom.setChromatogramType(ChromatogramSettings::SELECTED_REACTION_MONITORING_CHROMATOGRAM);
      }
      prec.setMetaValue("peptide_sequence", pep.sequence);
      chrom.setPrecursor(prec);

      // Set the rest of the meta-data
      chrom.setInstrumentSettings(settings.getInstrumentSettings());
      chrom.setAcquisitionInfo(settings.getAcquisitionInfo());
      chrom.setSourceFile(settings.getSourceFile());

      for (Size i = 0; i < settings.getDataProcessing().size(); ++i)
      {
        DataProcessing dp = settings.getDataProcessing()[i];
        dp.setMetaValue("performed_on_spectra", "true");
        chrom.getDataProcessing().push_back(dp);
      }
      output_chromatograms.push_back(chrom);
    }
  }