Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary search related bug in MzSpectrum.Extract #710

Open
avcarr2 opened this issue Jun 12, 2023 · 2 comments
Open

Binary search related bug in MzSpectrum.Extract #710

avcarr2 opened this issue Jun 12, 2023 · 2 comments

Comments

@avcarr2
Copy link
Contributor

avcarr2 commented Jun 12, 2023

public IEnumerable<MzPeak> Extract(double minX, double maxX)
{
int ind = Array.BinarySearch(XArray, minX);
if (ind < 0)
{
ind = ~ind;
}
while (ind < Size && XArray[ind] <= maxX)
{
yield return GetPeak(ind);
ind++;
}
}

The linked method has an error commonly associated with performig binary searches on double arrays. The method as written uses a binary search to find the minimum mz value in the MzSpectrum.XArray and does not test to see if the correct, closest value is the index to the right or the left.

To fix this issue, replace lines currently binary search associated code should be replaced with the following:
`
int ind = Array.BinarySearch(XArray, minX);
if (ind < 0)
{
ind = ~ind;
}

        if (ind >= XArray.Length)
        {
            ind = XArray.Length - 1;
        }

        if (ind != 0 && XArray[ind] - minX >
            minX - XArray[ind - 1])
        {
            ind--;
        }`
@avcarr2
Copy link
Contributor Author

avcarr2 commented Jun 12, 2023

@avcarr2
Copy link
Contributor Author

avcarr2 commented Jun 12, 2023

Here, starting index again doesn't correctly determine which index it is closer to. This one is more serious because it has 17 references.

public int NumPeaksWithinRange(double minX, double maxX)
{
int startingIndex = Array.BinarySearch(XArray, minX);
if (startingIndex < 0)
{
startingIndex = ~startingIndex;
}
if (startingIndex >= Size)
{
return 0;
}
int endIndex = Array.BinarySearch(XArray, maxX);
if (endIndex < 0)
{
endIndex = ~endIndex;
}
if (endIndex == 0)
{
return 0;
}
return endIndex - startingIndex;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant