use of de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch in project MetFragRelaunched by ipb-halle.
the class CandidateWriterXLS method writeFile.
@Override
public boolean writeFile(File xlsFile, IList list, Settings settings) throws Exception {
CandidateList candidateList = null;
boolean isScoredCandidate = false;
if (list instanceof ScoredCandidateList || list instanceof SortedScoredCandidateList) {
candidateList = (ScoredCandidateList) list;
isScoredCandidate = true;
}
if (list instanceof CandidateList) {
candidateList = (CandidateList) list;
}
if (candidateList == null || candidateList.getNumberElements() == 0)
return false;
ICandidate candidate = candidateList.getElement(0);
if (settings != null)
candidate.setUseSmiles((Boolean) settings.get(VariableNames.USE_SMILES_NAME));
candidate.initialisePrecursorCandidate();
xlsFile.createNewFile();
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
WritableSheet sheet1 = workbook.createSheet("MetFrag Candidate Result", 0);
WritableFont arial10fontBold = new WritableFont(WritableFont.ARIAL, 10);
arial10fontBold.setBoldStyle(WritableFont.BOLD);
WritableCellFormat arial10formatBold = new WritableCellFormat(arial10fontBold);
WritableFont arial10font = new WritableFont(WritableFont.ARIAL, 10);
arial10font.setBoldStyle(WritableFont.NO_BOLD);
WritableCellFormat arial10format = new WritableCellFormat(arial10font);
sheet1.addCell(new Label(0, 0, VariableNames.IDENTIFIER_NAME, arial10formatBold));
sheet1.addCell(new Label(1, 0, candidate.getIdentifier().replaceAll("\\|[0-9]+", ""), arial10format));
java.util.Hashtable<String, Object> properties = candidate.getProperties();
java.util.Enumeration<?> keys = properties.keys();
int propertyRow = 1;
while (keys.hasMoreElements()) {
String currentKey = (String) keys.nextElement();
sheet1.addCell(new Label(0, propertyRow, currentKey, arial10formatBold));
String value = "";
Object obj = properties.get(currentKey);
if (obj instanceof java.lang.Double)
value = String.valueOf((Double) obj);
else if (obj instanceof java.lang.Integer)
value = String.valueOf((Integer) obj);
else if (obj instanceof java.lang.String)
value = (String) obj;
sheet1.addCell(new Label(1, propertyRow, value, arial10format));
propertyRow++;
}
java.util.List<RenderedImage> molFragmentImages = null;
RenderedImage molImage = this.convertMoleculeToImages(candidate);
File imageFile = File.createTempFile("file", ".png", new File(Constants.OS_TEMP_DIR));
imageFile.deleteOnExit();
int rowHeightImage = 10;
int colWidthImage = 3;
int fragmentColumns = 1;
sheet1.addCell(new Label(0, propertyRow + 1, "Precursor", arial10formatBold));
if (ImageIO.write(molImage, "png", imageFile)) {
WritableImage wi = new WritableImage(0, propertyRow + 2, colWidthImage, rowHeightImage, imageFile);
sheet1.addImage(wi);
}
if (isScoredCandidate) {
molFragmentImages = this.convertMoleculeFragmentsToImages(candidate);
if (molFragmentImages.size() > 0) {
sheet1.addCell(new Label(0, (propertyRow + 4) + rowHeightImage, "Fragments", arial10formatBold));
}
int imagesWritten = 1;
int fragmentRow = 0;
for (int i = 0; i < molFragmentImages.size(); i++) {
File imageFileFragment = File.createTempFile("file" + i, ".png", new File(Constants.OS_TEMP_DIR));
imageFileFragment.deleteOnExit();
if (ImageIO.write(molFragmentImages.get(i), "png", imageFileFragment)) {
int column = (((imagesWritten - 1) % fragmentColumns)) * (colWidthImage + 3);
if ((imagesWritten - 1) % fragmentColumns == 0)
fragmentRow++;
WritableImage wi = new WritableImage(column, (propertyRow + 5) + (rowHeightImage * fragmentRow), colWidthImage, rowHeightImage, imageFileFragment);
sheet1.addImage(wi);
FragmentMassToPeakMatch match = (FragmentMassToPeakMatch) candidate.getMatchList().getElement(imagesWritten - 1);
sheet1.addCell(new Label(column + colWidthImage, (propertyRow + 5) + (rowHeightImage * fragmentRow), "Fragment " + imagesWritten, arial10formatBold));
sheet1.addCell(new Label(column + colWidthImage, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 2, "Formula", arial10formatBold));
sheet1.addCell(new Label(column + colWidthImage + 1, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 2, match.getModifiedFormulaStringOfBestMatchedFragment(candidate.getPrecursorMolecule()), arial10format));
sheet1.addCell(new Label(column + colWidthImage, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 3, "Mass", arial10formatBold));
sheet1.addCell(new Label(column + colWidthImage + 1, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 3, String.valueOf(MathTools.round(match.getBestMatchFragmentMass())), arial10format));
sheet1.addCell(new Label(column + colWidthImage, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 4, "Peak m/z", arial10formatBold));
sheet1.addCell(new Label(column + colWidthImage + 1, (propertyRow + 5) + (rowHeightImage * fragmentRow) + 4, String.valueOf(match.getMatchedPeak().getMass()), arial10format));
imagesWritten++;
}
}
}
workbook.write();
workbook.close();
return true;
}
use of de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch in project MetFragRelaunched by ipb-halle.
the class NewMergedPeakFragmenterScore method calculate.
public void calculate() {
this.matchList = (MatchList) settings.get(VariableNames.MATCH_LIST_NAME);
this.value = Double.valueOf(0);
this.bestFragmentIndeces = new int[this.matchList.getNumberElements()];
this.optimalValues = new double[this.matchList.getNumberElements()];
for (int i = 0; i < this.matchList.getNumberElements(); i++) {
DefaultFragmentToPeakMatch currentMatch = null;
boolean isMatchOfQuerySpectrum = true;
if (this.matchList.getElement(i) instanceof FragmentMassToPeakMatch)
currentMatch = (FragmentMassToPeakMatch) this.matchList.getElement(i);
else
currentMatch = (FragmentFormulaToPeakMatch) this.matchList.getElement(i);
double intensity = 0.0;
try {
intensity = currentMatch.getMatchedPeak().getIntensity();
} catch (RelativeIntensityNotDefinedException e) {
// if the match is not caused by a peak of the query spectrum
isMatchOfQuerySpectrum = false;
intensity = 0.0;
}
MergedTandemMassPeak matchedPeak = (MergedTandemMassPeak) currentMatch.getMatchedPeak();
FragmentList currentFragmentList = currentMatch.getMatchedFragmentList();
double minimumEnergyPerMatch = (double) Integer.MAX_VALUE;
/*
* get all intensities of random spectra of this peak
*/
java.util.ArrayList<Double> intensities = matchedPeak.getIntensities();
java.util.ArrayList<Integer> spectraIDs = matchedPeak.getSpectraIDs();
double peakScore = Math.pow((matchedPeak.getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(intensity, this.BETA);
double[] peakScores = new double[intensities.size()];
for (int k = 0; k < intensities.size(); k++) {
peakScores[k] = Math.pow((matchedPeak.getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(intensities.get(k), this.BETA);
}
for (int ii = 0; ii < currentFragmentList.getNumberElements(); ii++) {
IFragment currentFragment = currentFragmentList.getElement(ii);
/*
* check if current fragment is valid based on the tree depth
*/
// if(currentFragment.getTreeDepth() > this.maximumTreeDepth) continue;
int[] brokenBondIndeces = currentFragment.getBrokenBondIndeces();
double energyOfFragment = 0.0;
for (int bondIndex : brokenBondIndeces) {
energyOfFragment += this.bondEnergies[bondIndex];
}
energyOfFragment += Math.abs(currentMatch.getNumberOfHydrogensDifferToPeakMass(ii)) * this.WEIGHT_HYDROGEN_PENALTY;
/*
* assign optimal bondenergy and store best fragment
*/
if (energyOfFragment < minimumEnergyPerMatch) {
minimumEnergyPerMatch = energyOfFragment;
if (isMatchOfQuerySpectrum)
this.bestFragmentIndeces[i] = ii;
}
}
if (isMatchOfQuerySpectrum) {
currentMatch.initialiseBestMatchedFragment(this.bestFragmentIndeces[i]);
this.value += peakScore / Math.pow(minimumEnergyPerMatch, this.GAMMA);
this.optimalValues[i] = minimumEnergyPerMatch;
}
for (int k = 0; k < spectraIDs.size(); k++) {
this.scoresRandomSpectra[spectraIDs.get(k)] += peakScores[k] / Math.pow(minimumEnergyPerMatch, this.GAMMA);
}
}
int betterEqualScores = 0;
for (int i = 0; i < this.scoresRandomSpectra.length; i++) {
if (this.scoresRandomSpectra[i] >= this.value)
betterEqualScores++;
}
this.scoredCandidate.setProperty("p-value", (double) betterEqualScores / (double) this.scoresRandomSpectra.length);
this.calculationFinished = true;
}
use of de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch in project MetFragRelaunched by ipb-halle.
the class NewFragmenterUniqueFormulaScore method calculate.
public void calculate() {
this.matchList = (MatchList) settings.get(VariableNames.MATCH_LIST_NAME);
this.value = Double.valueOf(0);
java.util.ArrayList<Double> scores = new java.util.ArrayList<Double>();
java.util.ArrayList<Integer> fragmentIds = new java.util.ArrayList<Integer>();
java.util.ArrayList<Integer> fragmentIndeces = new java.util.ArrayList<Integer>();
java.util.ArrayList<IFragment> fragments = new java.util.ArrayList<IFragment>();
java.util.ArrayList<DefaultFragmentToPeakMatch> matches = new java.util.ArrayList<DefaultFragmentToPeakMatch>();
java.util.ArrayList<Byte> hydrogenDifferences = new java.util.ArrayList<Byte>();
for (int i = 0; i < this.matchList.getNumberElements(); i++) {
DefaultFragmentToPeakMatch currentMatch = null;
if (this.matchList.getElement(i) instanceof FragmentMassToPeakMatch)
currentMatch = (FragmentMassToPeakMatch) this.matchList.getElement(i);
else
currentMatch = (FragmentFormulaToPeakMatch) this.matchList.getElement(i);
FragmentList currentFragmentList = currentMatch.getMatchedFragmentList();
double peakScore = 0.0;
try {
peakScore = Math.pow((currentMatch.getMatchedPeak().getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(currentMatch.getMatchedPeak().getIntensity(), this.BETA);
} catch (RelativeIntensityNotDefinedException e) {
e.printStackTrace();
}
for (int ii = 0; ii < currentFragmentList.getNumberElements(); ii++) {
IFragment currentFragment = currentFragmentList.getElement(ii);
// if(currentFragment.getTreeDepth() > this.maximumTreeDepth) continue;
int[] brokenBondIndeces = currentFragment.getBrokenBondIndeces();
double energyOfFragment = 0.0;
for (int bondIndex : brokenBondIndeces) {
energyOfFragment += this.bondEnergies[bondIndex];
}
energyOfFragment += Math.abs(currentMatch.getNumberOfHydrogensDifferToPeakMass(ii)) * this.WEIGHT_HYDROGEN_PENALTY;
double currentScore = peakScore / Math.pow(energyOfFragment, this.GAMMA);
int index = fragmentIds.indexOf(currentFragment.getID());
if (index != -1) {
double lastScore = scores.get(index);
if (lastScore < currentScore) {
scores.remove(index);
fragmentIds.remove(index);
fragments.remove(index);
matches.remove(index);
hydrogenDifferences.remove(index);
fragmentIndeces.remove(index);
index = 0;
while (scores.size() > index && scores.get(index) > currentScore) index++;
scores.add(index, currentScore);
fragmentIds.add(index, currentFragment.getID());
fragments.add(index, currentFragment);
matches.add(index, currentMatch);
hydrogenDifferences.add(index, currentMatch.getNumberOfHydrogensDifferToPeakMass(ii));
fragmentIndeces.add(index, ii);
}
} else {
index = 0;
while (scores.size() > index && scores.get(index) > currentScore) index++;
scores.add(index, currentScore);
fragmentIds.add(index, currentFragment.getID());
fragments.add(index, currentFragment);
matches.add(index, currentMatch);
hydrogenDifferences.add(index, currentMatch.getNumberOfHydrogensDifferToPeakMass(ii));
fragmentIndeces.add(index, ii);
}
}
}
java.util.ArrayList<Integer> validAndBestFragmentMatches = new java.util.ArrayList<Integer>();
for (int i = 0; i < scores.size(); i++) {
boolean validAndBestMatch = true;
for (int k = 0; k < validAndBestFragmentMatches.size(); k++) {
if (fragmentIds.get(validAndBestFragmentMatches.get(k)) == fragmentIds.get(i)) {
validAndBestMatch = false;
}
if (matches.get(validAndBestFragmentMatches.get(k)).getMatchedPeak().getMass() == matches.get(i).getMatchedPeak().getMass()) {
validAndBestMatch = false;
}
}
if (!validAndBestMatch)
continue;
int index = 0;
/*
* insert the valid and best match sorted by mass of the peak
*/
while (index < validAndBestFragmentMatches.size() && matches.get(i).getMatchedPeak().getMass() > matches.get(validAndBestFragmentMatches.get(index)).getMatchedPeak().getMass()) index++;
validAndBestFragmentMatches.add(index, i);
}
MatchList cleanedMatchList = new MatchList();
this.bestFragmentIndeces = new int[validAndBestFragmentMatches.size()];
this.optimalValues = new double[validAndBestFragmentMatches.size()];
for (int i = 0; i < validAndBestFragmentMatches.size(); i++) {
matches.get(validAndBestFragmentMatches.get(i)).initialiseBestMatchedFragment(fragmentIndeces.get(validAndBestFragmentMatches.get(i)));
this.value += scores.get(validAndBestFragmentMatches.get(i));
this.optimalValues[i] = scores.get(validAndBestFragmentMatches.get(i));
cleanedMatchList.addElement(matches.get(validAndBestFragmentMatches.get(i)));
/*
System.out.println(
scores.get(validAndBestFragmentMatches.get(i)) + "\t" +
fragmentIds.get(validAndBestFragmentMatches.get(i)) + "\t" +
matches.get(validAndBestFragmentMatches.get(i)).getMatchedPeak().getMass() + "\t\t" +
fragments.get(validAndBestFragmentMatches.get(i)).getMolecularFormula() + "\t" +
hydrogenDifferences.get(validAndBestFragmentMatches.get(i))
);
*/
}
this.settings.set(VariableNames.MATCH_LIST_NAME, cleanedMatchList);
this.calculationFinished = true;
}
use of de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch in project MetFragRelaunched by ipb-halle.
the class NewFragmenterUniqueFormulaScore method calculateSingleMatch.
public Double[] calculateSingleMatch(IMatch match) {
DefaultFragmentToPeakMatch currentMatch = null;
if (match instanceof FragmentMassToPeakMatch)
currentMatch = (FragmentMassToPeakMatch) match;
else
currentMatch = (FragmentFormulaToPeakMatch) match;
FragmentList currentFragmentList = currentMatch.getMatchedFragmentList();
double minimumEnergyPerMatch = (double) Integer.MAX_VALUE;
double peakScore = 0.0;
try {
peakScore = Math.pow((currentMatch.getMatchedPeak().getMass() / this.measuredPrecursorMass) * 10.0, this.ALPHA) * Math.pow(currentMatch.getMatchedPeak().getIntensity(), this.BETA);
} catch (RelativeIntensityNotDefinedException e) {
e.printStackTrace();
}
for (int ii = 0; ii < currentFragmentList.getNumberElements(); ii++) {
IFragment currentFragment = currentFragmentList.getElement(ii);
/*
* check if current fragment is valid based on the tree depth
*/
// if(currentFragment.getTreeDepth() > this.maximumTreeDepth) continue;
int[] brokenBondIndeces = currentFragment.getBrokenBondIndeces();
double energyOfFragment = 0.0;
for (int bondIndex : brokenBondIndeces) {
energyOfFragment += this.bondEnergies[bondIndex];
}
energyOfFragment += Math.abs(currentMatch.getNumberOfHydrogensDifferToPeakMass(ii)) * this.WEIGHT_HYDROGEN_PENALTY;
/*
* assign optimal bondenergy and store best fragment
*/
if (energyOfFragment < minimumEnergyPerMatch) {
minimumEnergyPerMatch = energyOfFragment;
}
}
this.calculationFinished = true;
return new Double[] { peakScore / Math.pow(minimumEnergyPerMatch, this.GAMMA), minimumEnergyPerMatch };
}
use of de.ipbhalle.metfraglib.match.FragmentMassToPeakMatch in project MetFragRelaunched by ipb-halle.
the class DefaultBitArrayFragment method matchToPeak.
/*
public void initialiseMolecularFormula(IMolecularStructure precursorMolecule) throws AtomTypeNotKnownFromInputListException {
this.molecularFormula = new BitArrayFragmentMolecularFormula((BitArrayPrecursor)precursorMolecule, this.atomsFastBitArray);
}*/
@Override
public byte matchToPeak(IMolecularStructure precursorMolecule, IPeak peak, int precursorIonTypeIndex, boolean isPositive, IMatch[] fragmentPeakMatch) {
if (fragmentPeakMatch == null || fragmentPeakMatch.length != 1)
return -1;
double[] ionisationTypeMassCorrection = new double[] { Constants.getIonisationTypeMassCorrection(precursorIonTypeIndex, isPositive), Constants.getIonisationTypeMassCorrection(0, isPositive) };
byte[] signs = { 1, -1 };
byte[] compareResultValuesToChangeHydrogenCheck = { 1, -1 };
byte numberCompareResultsEqualPlusOne = 0;
byte numberComparisons = 2;
boolean matched = false;
short numberHydrogens = this.getNumberHydrogens();
for (int i = 0; i < ionisationTypeMassCorrection.length; i++) {
int substractHydrogenFromCharge = 0;
if (i == 0 && precursorIonTypeIndex == 1)
substractHydrogenFromCharge = 1;
boolean[] toCheckHydrogenShiftType = { true, true };
double currentFragmentMass = this.getMonoisotopicMass(precursorMolecule) + ionisationTypeMassCorrection[i];
byte compareResult = ((TandemMassPeak) peak).matchesToMass(currentFragmentMass);
if (compareResult == 0 && substractHydrogenFromCharge <= numberHydrogens) {
/*
* if a former fragment has matched already then add the current fragment list to the match object
*/
if (fragmentPeakMatch[0] != null) {
((FragmentMassToPeakMatch) fragmentPeakMatch[0]).addMatchedFragment(this, (byte) 0, currentFragmentMass, i == 0 ? (byte) precursorIonTypeIndex : (byte) 0);
} else /*
* if no former fragment matched before initialise the match object and add the fragment list
*/
{
fragmentPeakMatch[0] = new FragmentMassToPeakMatch(peak);
fragmentPeakMatch[0].setIsPositiveCharge(isPositive);
((FragmentMassToPeakMatch) fragmentPeakMatch[0]).addMatchedFragment(this, (byte) 0, currentFragmentMass, i == 0 ? (byte) precursorIonTypeIndex : (byte) 0);
}
matched = true;
} else if (compareResultValuesToChangeHydrogenCheck[0] == compareResult)
toCheckHydrogenShiftType[0] = false;
else if (compareResultValuesToChangeHydrogenCheck[1] == compareResult)
toCheckHydrogenShiftType[1] = false;
if (compareResult == 1)
numberCompareResultsEqualPlusOne++;
/*
* iteration of hydrogenShift numbers to calculate adapted fragment masses
*/
int maximalHydrogenShift = this.getTreeDepth();
for (byte hydrogenShift = 1; hydrogenShift <= maximalHydrogenShift; hydrogenShift++) {
/*
* check all signs to model hydrogen loss (-1) and hydrogen addition (+1)
*/
for (byte signIndex = 0; signIndex < signs.length; signIndex++) {
if (!toCheckHydrogenShiftType[signIndex]) {
continue;
}
if (numberHydrogens - (signs[signIndex] * hydrogenShift - substractHydrogenFromCharge) < 0) {
continue;
}
/*
* calculate and check adapted fragment mass
*/
double currentFragmentMassIonModeCorrected = currentFragmentMass + signs[signIndex] * hydrogenShift * Constants.HYDROGEN_MASS;
compareResult = ((TandemMassPeak) peak).matchesToMass(currentFragmentMassIonModeCorrected);
numberComparisons++;
/*
* in case fragment matches to peak create match or add the fragment to the match
* if result is 0 then the fragment mass matched to the peak
*/
if (compareResult == 0) {
/*
* if a former fragment has matched already then add the current fragment list to the match object
*/
if (fragmentPeakMatch[0] != null) {
((FragmentMassToPeakMatch) fragmentPeakMatch[0]).addMatchedFragment(this, (byte) (signs[signIndex] * hydrogenShift), currentFragmentMassIonModeCorrected, i == 0 ? (byte) precursorIonTypeIndex : (byte) 0);
} else /*
* if no former fragment matched before initialise the match object and add the fragment list
*/
{
fragmentPeakMatch[0] = new FragmentMassToPeakMatch(peak);
fragmentPeakMatch[0].setIsPositiveCharge(isPositive);
((FragmentMassToPeakMatch) fragmentPeakMatch[0]).addMatchedFragment(this, (byte) (signs[signIndex] * hydrogenShift), currentFragmentMassIonModeCorrected, i == 0 ? (byte) precursorIonTypeIndex : (byte) 0);
}
matched = true;
} else /*
* if hydrogen removed/added from fragment mass and fragment mass smaller/greater than peak mass
* there is no need to check further by removing/adding hydrogens
*/
if (compareResultValuesToChangeHydrogenCheck[signIndex] == compareResult)
toCheckHydrogenShiftType[signIndex] = false;
if (compareResult == 1)
numberCompareResultsEqualPlusOne++;
}
}
}
if (matched == true) {
this.hasMatched = true;
return 0;
} else if (numberCompareResultsEqualPlusOne == numberComparisons)
return 1;
return -1;
}
Aggregations