예제 #1
0
        public int AlphaBeta(Gameboard state, int depth, int alpha, int beta, bool myMove)
        {
            Int64 zHash    = state.GetZobristHash();
            Move  bestMove = null;

            // Check transposition table
            if (transpositionTable.ContainsKey(zHash))
            {
                Transposition transposition = transpositionTable[zHash];

                bestMove = transposition.BestMove;

                if (transposition.Depth >= depth)
                {
                    if (transposition.Lowerbound == transposition.Upperbound)
                    {
                        return(transposition.Lowerbound);
                    }

                    if (transposition.Lowerbound >= beta)
                    {
                        return(transposition.Lowerbound);
                    }
                    if (transposition.Upperbound <= alpha)
                    {
                        return(transposition.Upperbound);
                    }
                    alpha = Math.Max(alpha, transposition.Lowerbound);
                    beta  = Math.Min(beta, transposition.Upperbound);
                }
            }

            GameLogic gameLogic = new GameLogic(state);
            int       score;

            // Evaluate
            if (depth <= 0 || gameLogic.IsFinished())
            {
                score = myMove ? evaluation.Evaluate(state) : -evaluation.Evaluate(state);
            }
            // Search deeper
            else
            {
                score = int.MinValue;
                var possibleMoves = gameLogic.GetPossibleMoves();

                OrderMoves(possibleMoves, state, bestMove);
                // Reset best move
                bestMove = null;

                foreach (Move move in possibleMoves)
                {
                    Gameboard newState = (Gameboard)state.Clone();
                    GameLogic newLogic = new GameLogic(newState);
                    newLogic.ApplyMove(move);

                    // Continue search
                    int value = -AlphaBeta(newState, depth - 1, -beta, -alpha, !myMove);

                    // Adjust alpha and beta
                    if (value > score)
                    {
                        bestMove = move;
                        score    = value;
                    }
                    if (score > alpha)
                    {
                        alpha = score;
                    }
                    if (score >= beta)
                    {
                        break;
                    }
                }
            }


            // Store values in transposition table
            if (score <= alpha)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(alpha, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score > alpha && score < beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score >= beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, beta, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }

            return(score);
        }
예제 #2
0
        /// <inheritdoc />
        public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            ConfigureWriter(".mgf");
            using (Writer)
            {
                Log.Info("Processing " + (lastScanNumber - firstScanNumber + 1) + " scans");

                var lastScanProgress = 0;
                for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
                {
                    if (ParseInput.LogFormat == LogFormat.DEFAULT)
                    {
                        var scanProgress = (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100);
                        if (scanProgress % ProgressPercentageStep == 0)
                        {
                            if (scanProgress != lastScanProgress)
                            {
                                Console.Write("" + scanProgress + "% ");
                                lastScanProgress = scanProgress;
                            }
                        }
                    }

                    // Get each scan from the RAW file
                    var scan = Scan.FromFile(rawFile, scanNumber);

                    // Check to see if the RAW file contains label (high-res) data and if it is present
                    // then look for any data that is out of order
                    var time = rawFile.RetentionTimeFromScanNumber(scanNumber);

                    // Get the scan filter for this scan number
                    var scanFilter = rawFile.GetFilterForScanNumber(scanNumber);

                    // Get the scan event for this scan number
                    var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);

                    // precursor reference
                    var spectrumRef = "";

                    //keeping track of precursor scan
                    switch (scanFilter.MSOrder)
                    {
                    case MSOrderType.Ms:

                        // Keep track of scan number for precursor reference
                        _precursorMs1ScanNumber = scanNumber;

                        break;

                    case MSOrderType.Ms2:
                        // Keep track of scan number and isolation m/z for precursor reference
                        var result = Regex.Match(scanEvent.ToString(), FilterStringIsolationMzPattern);
                        if (result.Success)
                        {
                            if (_precursorMs2ScanNumbers.ContainsKey(result.Groups[1].Value))
                            {
                                _precursorMs2ScanNumbers.Remove(result.Groups[1].Value);
                            }

                            _precursorMs2ScanNumbers.Add(result.Groups[1].Value, scanNumber);
                        }

                        spectrumRef = ConstructSpectrumTitle((int)Device.MS, 1, _precursorMs1ScanNumber);
                        break;

                    case MSOrderType.Ms3:
                        var precursorMs2ScanNumber = _precursorMs2ScanNumbers.Keys.FirstOrDefault(
                            isolationMz => scanEvent.ToString().Contains(isolationMz));
                        if (!precursorMs2ScanNumber.IsNullOrEmpty())
                        {
                            spectrumRef = ConstructSpectrumTitle((int)Device.MS, 1, _precursorMs2ScanNumbers[precursorMs2ScanNumber]);
                        }
                        else
                        {
                            throw new InvalidOperationException("Couldn't find a MS2 precursor scan for MS3 scan " + scanEvent);
                        }
                        break;

                    default:
                        break;
                    }


                    // don't include MS1 spectra
                    if (ParseInput.MsLevel.Contains((int)scanFilter.MSOrder))
                    {
                        IReaction reaction = GetReaction(scanEvent, scanNumber);

                        Writer.WriteLine("BEGIN IONS");
                        if
                        (ParseInput.MGFPrecursor)
                        {
                            Writer.WriteLine($"TITLE={ConstructSpectrumTitle((int)Device.MS, 1, scanNumber)} [PRECURSOR={spectrumRef}]");
                        }
                        else
                        {
                            Writer.WriteLine($"TITLE={ConstructSpectrumTitle((int)Device.MS, 1, scanNumber)}");
                        }
                        Writer.WriteLine($"SCANS={scanNumber}");
                        Writer.WriteLine(
                            $"RTINSECONDS={(time * 60).ToString(CultureInfo.InvariantCulture)}");
                        // trailer extra data list
                        var    trailerData    = rawFile.GetTrailerExtraInformation(scanNumber);
                        int?   charge         = null;
                        double?monoisotopicMz = null;
                        double?isolationWidth = null;
                        for (var i = 0; i < trailerData.Length; i++)
                        {
                            if (trailerData.Labels[i] == "Charge State:")
                            {
                                if (Convert.ToInt32(trailerData.Values[i]) > 0)
                                {
                                    charge = Convert.ToInt32(trailerData.Values[i]);
                                }
                            }

                            if (trailerData.Labels[i] == "Monoisotopic M/Z:")
                            {
                                monoisotopicMz = double.Parse(trailerData.Values[i], NumberStyles.Any,
                                                              CultureInfo.CurrentCulture);
                            }

                            if (trailerData.Labels[i] == "MS" + (int)scanFilter.MSOrder + " Isolation Width:")
                            {
                                isolationWidth = double.Parse(trailerData.Values[i], NumberStyles.Any,
                                                              CultureInfo.CurrentCulture);
                            }
                        }

                        if (reaction != null)
                        {
                            var selectedIonMz =
                                CalculateSelectedIonMz(reaction, monoisotopicMz, isolationWidth);

                            Writer.WriteLine("PEPMASS=" +
                                             selectedIonMz.ToString(CultureInfo.InvariantCulture));
                        }

                        // charge
                        if (charge != null)
                        {
                            // Scan polarity
                            var polarity = PositivePolarity;
                            if (scanFilter.Polarity == PolarityType.Negative)
                            {
                                polarity = NegativePolarity;
                            }

                            Writer.WriteLine($"CHARGE={charge}{polarity}");
                        }

                        // write the filter string
                        //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}");

                        if (!ParseInput.NoPeakPicking)
                        {
                            // check if the scan has a centroid stream
                            if (scan.HasCentroidStream)
                            {
                                if (scan.CentroidScan.Length > 0)
                                {
                                    for (var i = 0; i < scan.CentroidScan.Length; i++)
                                    {
                                        Writer.WriteLine(
                                            scan.CentroidScan.Masses[i].ToString("0.0000000",
                                                                                 CultureInfo.InvariantCulture)
                                            + " "
                                            + scan.CentroidScan.Intensities[i].ToString("0.0000000000",
                                                                                        CultureInfo.InvariantCulture));
                                    }
                                }
                            }
                            else // otherwise take segmented (low res) scan data
                            {
                                // if the spectrum is profile perform centroiding
                                var segmentedScan = scanEvent.ScanData == ScanDataType.Profile
                                    ? Scan.ToCentroid(scan).SegmentedScan
                                    : scan.SegmentedScan;

                                for (var i = 0; i < segmentedScan.Positions.Length; i++)
                                {
                                    Writer.WriteLine(
                                        segmentedScan.Positions[i].ToString("0.0000000",
                                                                            CultureInfo.InvariantCulture)
                                        + " "
                                        + segmentedScan.Intensities[i].ToString("0.0000000000",
                                                                                CultureInfo.InvariantCulture));
                                }
                            }
                        }
                        else // use the segmented data as is
                        {
                            for (var i = 0; i < scan.SegmentedScan.Positions.Length; i++)
                            {
                                Writer.WriteLine(
                                    scan.SegmentedScan.Positions[i].ToString("0.0000000",
                                                                             CultureInfo.InvariantCulture)
                                    + " "
                                    + scan.SegmentedScan.Intensities[i].ToString("0.0000000000",
                                                                                 CultureInfo.InvariantCulture));
                            }
                        }

                        Writer.WriteLine("END IONS");

                        Log.Debug("Spectrum written to file -- SCAN " + scanNumber);
                    }
                }

                if (ParseInput.LogFormat == LogFormat.DEFAULT)
                {
                    Console.WriteLine();
                }
            }
        }
예제 #3
0
        public int AlphaBeta(Gameboard state, int depth, int alpha, int beta, bool myMove)
        {
            // DEBUG
            iterationCounter++;

            Int64 zHash    = state.GetZobristHash();
            Move  bestMove = null;

            if (transpositionTable.ContainsKey(zHash))
            {
                Transposition transposition = transpositionTable[zHash];

                bestMove = transposition.BestMove;

                if (transposition.Depth >= depth)
                {
                    if (transposition.Lowerbound == transposition.Upperbound)
                    {
                        return(transposition.Lowerbound);
                    }

                    if (transposition.Lowerbound >= beta)
                    {
                        return(transposition.Lowerbound);
                    }
                    if (transposition.Upperbound <= alpha)
                    {
                        return(transposition.Upperbound);
                    }
                    alpha = Math.Max(alpha, transposition.Lowerbound);
                    beta  = Math.Min(beta, transposition.Upperbound);
                }
            }

            GameLogic gameLogic = new GameLogic(state);
            int       score;

            if (depth <= 0 || gameLogic.IsFinished())
            {
                score = myMove ? evaluation.Evaluate(state) : -evaluation.Evaluate(state);
            }
            else
            {
                score = int.MinValue;
                var possibleMoves = gameLogic.GetPossibleMoves();

                OrderMoves(possibleMoves, state);
                // Reset best move
                bestMove = null;

                // Calculate score for PVS
                {
                    Move pvsMove = possibleMoves[0];

                    Gameboard newState = (Gameboard)state.Clone();
                    GameLogic newLogic = new GameLogic(newState);
                    newLogic.ApplyMove(pvsMove);

                    score = -AlphaBeta(newState, depth - 1, -beta, -alpha, !myMove);

                    bestMove = pvsMove;
                }

                if (score < beta)
                {
                    for (int i = 1; i < possibleMoves.Count; i++)
                    {
                        Move move       = possibleMoves[i];
                        int  lowerbound = Math.Max(alpha, score);
                        int  upperbound = lowerbound + 1;

                        Gameboard newState = (Gameboard)state.Clone();
                        GameLogic newLogic = new GameLogic(newState);
                        newLogic.ApplyMove(move);

                        int value = -AlphaBeta(newState, depth - 1, -upperbound, -lowerbound, !myMove);

                        // Fail high
                        if (value >= upperbound && value < beta)
                        {
                            value = -AlphaBeta(newState, depth - 1, -beta, -value, !myMove);
                        }

                        if (value > score)
                        {
                            bestMove = move;
                            score    = value;
                        }
                        if (score >= beta)
                        {
                            break;
                        }
                    }
                }
            }

            if (score <= alpha)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(alpha, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score > alpha && score < beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score >= beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, beta, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }

            return(score);
        }
예제 #4
0
파일: Program.cs 프로젝트: Ykobe/metaCode
            //Console.ReadKey();
        }

        public static void getentityData(string resFilePath, string rawFile, string headerInfo, string paraIndex)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(rawFile);
            plus.SelectInstrument(Device.MS, 1);

            ArrayList indexOfpara = new ArrayList();
            string[] selectIndex = paraIndex.Split(',');

            foreach (string ele in selectIndex)
            {
                int index = Int32.Parse(ele);
                indexOfpara.Add(index);
            }

            //string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(resFilePath, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);

            headerInfo = "RT," + headerInfo;
            headerInfo = "#," + headerInfo;
            writer.WriteLine(headerInfo);

            int offset = 0;
            int maxoffset = plus.GetStatusLogEntriesCount();
            while (offset < maxoffset)
            {
                string temp = "";
                IStatusLogEntry statusLogEntry = plus.GetStatusLogEntry(offset);
                temp += offset.ToString() + ",";
                temp += statusLogEntry.Time.ToString() + ",";

                foreach (int ele in indexOfpara)
                {
                    temp += Convert.ToString(statusLogEntry.Values[ele]) + ",";
                }

                writer.WriteLine(temp.Substring(0, temp.Length - 1));
                offset += 1;
            }

            writer.Close();
        }

        public static void showheaderInfo(string filePath)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);
            plus.SelectInstrument(Device.MS, 1);
            HeaderItem[] statuslogheaderinformation = plus.GetStatusLogHeaderInformation();
            int index = 0;

            Console.OutputEncoding = Encoding.UTF8;

            while (index < statuslogheaderinformation.Length)
            {
                Console.WriteLine(statuslogheaderinformation[index].Label);
                //headerInfo[index] = statuslogheaderinformation[index].Label;
                //writer.WriteLine(statuslogheaderinformation[index].Label);
                index += 1;
            }
            //writer.Close();

            //while (true)
            //{
            //if (index >= statuslogheaderinformation.Length)
            //{
            //    Console.WriteLine(plus.RunHeaderEx.FirstSpectrum.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.LastSpectrum.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.StartTime.ToString("F2"));
            //    Console.WriteLine(plus.RunHeaderEx.EndTime.ToString("F2"));
            //    Console.WriteLine(plus.RunHeaderEx.LowMass.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.HighMass.ToString());
            //    break;
            //}
            //    Console.WriteLine(statuslogheaderinformation[index].Label);
            //    writer.WriteLine(statuslogheaderinformation[index].Label);
            //    index++;
            //}

            //writer.Close();

        }
        public static void getTuneInfo(string filePath)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);
            plus.SelectInstrument(Device.MS, 1);
            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".txt";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            writer.WriteLine("*********************InstrumentMethod(0)***************************");
            writer.WriteLine(plus.GetInstrumentMethod(0));

            writer.WriteLine("*********************InstrumentMethod(1)****************************");
            writer.WriteLine(plus.GetInstrumentMethod(1));

            HeaderItem[] tuneDataHeaderInfo = plus.GetTuneDataHeaderInformation();

            writer.WriteLine("*********************Tune DATA ****************************");
            int tuneCnt = plus.GetTuneDataCount();

            for (int i = 0; i < tuneDataHeaderInfo.Length; ++i)
            {
                writer.WriteLine(tuneDataHeaderInfo[i].Label);
            }
            writer.Close();
        }

        public static void getMSdataFromScanNum(int startNum, int endNum, string filePath, double lowMS = 0.00, double highMS = 0.00)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);

            //////////////////////////////////
            plus.SelectInstrument(Device.MS, 1);
            /////////////////////////////////
            
            const string FilterStringIsolationMzPattern = @"ms2 (.*?)@";
            int precursorMs1ScanNumber = 0;
            double precursorMS= 0.00;
            IReaction reaction = null;
            var value = "";

            var firstScanNumber = plus.RunHeaderEx.FirstSpectrum;
            var lastScanNumber = plus.RunHeaderEx.LastSpectrum;

            startNum = firstScanNumber;
            endNum = lastScanNumber;

            //int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum;

            LimitedSizeDictionary<string, int> precursorMs2ScanNumbers = new LimitedSizeDictionary<string, int>(40);

            plus.SelectInstrument(Device.MS, 1);
            if(highMS - 0.00 <= 0.01)
            {
                highMS = plus.RunHeaderEx.HighMass;
            }

            double maxMs = plus.RunHeaderEx.HighMass;
            double minMs = plus.RunHeaderEx.LowMass;

            lowMS = minMs;
            highMS = maxMs;

            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            
            writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter,MSLevel,collisionEnergy, precursorNum,precursorMS");
            while (startNum <= endNum)
            {
                var levelInfo = "";
                var spectrumRef = "";
                Scan scan = Scan.FromFile(plus, startNum);
                IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum);

                IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum);

                switch (scanFilter.MSOrder)
                {
                    case MSOrderType.Ms:
                        // Keep track of scan number for precursor reference
                        precursorMs1ScanNumber = startNum;
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + "" + "," + "" + "," + "";
                        break;
                    case MSOrderType.Ms2:

                        // Keep track of scan number and isolation m/z for precursor reference                   
                        var result = Regex.Match(scanEvent.ToString(), FilterStringIsolationMzPattern);
                        if (result.Success)
                        {
                            if (precursorMs2ScanNumbers.ContainsKey(result.Groups[1].Value))
                            {
                                precursorMs2ScanNumbers.Remove(result.Groups[1].Value);
                            }

                            precursorMs2ScanNumbers.Add(result.Groups[1].Value, startNum);
                        }
                        spectrumRef = precursorMs1ScanNumber.ToString();
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        precursorMS = reaction.PrecursorMass;
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value + "," + spectrumRef.ToString() + "," +  precursorMS.ToString()  ;
                        break;
                    case MSOrderType.Ms3:
                        var precursorMs2ScanNumber = precursorMs2ScanNumbers.Keys.FirstOrDefault(isolationMz => scanEvent.ToString().Contains(isolationMz));
                        spectrumRef = precursorMs2ScanNumbers[precursorMs2ScanNumber].ToString();
                        if (!precursorMs2ScanNumber.IsNullOrEmpty())
                        {
                            reaction = scanEvent.GetReaction(1);
                        }
                        else
                        {
                            throw new InvalidOperationException("Couldn't find a MS2 precursor scan for MS3 scan " + scanEvent);
                        }
                        precursorMS = reaction.PrecursorMass;
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value +  "," + spectrumRef.ToString() + "," + precursorMS.ToString();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                //var scanStatistics = plus.GetScanStatsForScanNumber(startNum);
                //// Get the segmented (low res and profile) scan data
                //var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics);
                //double[] masses = segmentedScan.Positions;
                //double[] intensitis = segmentedScan.Intensities;

                //Console.WriteLine(masses.Length);
                //Console.WriteLine(intensitis.Length);

                int cnt = 0;

                if (scanFilter.MSOrder == MSOrderType.Ms)
                {
                    while (cnt < scan.PreferredMasses.Length)
                    {
                        if (lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS)
                        {
                            double rt = plus.RetentionTimeFromScanNumber(startNum);
                            double msval = scan.PreferredMasses[cnt];
                            double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt];
                            double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt];
                            double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt];

                            //msval.ToString("f4");Return a number to a given precision,carry bit
                            //msval.ToString("n4");Return a number to a given precision,not carry bit

                            //writer.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}", startNum.ToString(), rt.ToString(),
                            //    msval.ToString("n4"), resolution.ToString(), intensity.ToString(), noise.ToString(),
                            //    scanFilter.ToString(), levelInfo);

                            writer.WriteLine("{0},{1},{2},{3}", startNum.ToString(), rt.ToString(), msval.ToString(), intensity.ToString());
                        }
                        cnt += 1;
                    }
                }
                writer.Flush();
                startNum += 1;
            }
            writer.Close();

        }

        public static void getMSdataFromRT(double startRT, int endRT, string filePath, double lowMS = 0.00, double highMS = 0.00)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);

            plus.SelectInstrument(Device.MS, 1);
            if (highMS - 0.00 <= 0.01)
            {
                highMS = plus.RunHeaderEx.HighMass;
            }
            int startNum = plus.ScanNumberFromRetentionTime(startRT);
            int endNum = plus.ScanNumberFromRetentionTime(endRT);
            int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum;

            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter");
            while (startNum <= endNum)
            {
                Scan scan = Scan.FromFile(plus, startNum);
                string filter = plus.GetFilterForScanNumber(startNum).ToString();
                int cnt = 0;
                while (cnt < scan.PreferredMasses.Length)
                {
                    if (lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS)
                    {
                        double rt = plus.RetentionTimeFromScanNumber(startNum);
                        double msval = scan.PreferredMasses[cnt];
                        double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt];
                        double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt];
                        double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt];
                        //writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", startNum.ToString(), rt.ToString(), msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(), filter.ToString());
예제 #5
0
        public int AlphaBeta(Gameboard state, int depth, int alpha, int beta, bool myMove)
        {
            // DEBUG
            iterationCounter++;

            Int64 zHash = state.GetZobristHash();

            Move bestMove = null;

            if (transpositionTable.ContainsKey(zHash))
            {
                Transposition transposition = transpositionTable[zHash];

                bestMove = transposition.BestMove;

                if (transposition.Depth >= depth)
                {
                    if (transposition.Lowerbound == transposition.Upperbound)
                    {
                        return(transposition.Lowerbound);
                    }

                    if (transposition.Lowerbound >= beta)
                    {
                        return(transposition.Lowerbound);
                    }
                    if (transposition.Upperbound <= alpha)
                    {
                        return(transposition.Upperbound);
                    }
                    alpha = Math.Max(alpha, transposition.Lowerbound);
                    beta  = Math.Min(beta, transposition.Upperbound);
                }
            }

            GameLogic gameLogic = new GameLogic(state);
            int       score;

            if (depth <= 0 || gameLogic.IsFinished())
            {
                score = myMove ? evaluation.Evaluate(state) : -evaluation.Evaluate(state);
            }
            else
            {
                score = int.MinValue;
                var possibleMoves = gameLogic.GetPossibleMoves();

                OrderMoves(possibleMoves, state);
                // Reset best move
                bestMove = null;

                // Multi-Cut
                {
                    Move move = possibleMoves[0];

                    Gameboard newState = (Gameboard)state.Clone();
                    GameLogic newLogic = new GameLogic(newState);
                    newLogic.ApplyMove(move);

                    int c = 0;
                    int m = 0;

                    while (newState != null && m < 10)
                    {
                        int value = -AlphaBeta(newState, depth - 1 - 2, GameLogic.LOSS_VALUE, GameLogic.WIN_VALUE, false);

                        if (value >= beta)
                        {
                            c++;
                            if (c > 3)
                            {
                                return(beta);
                            }
                        }

                        m++;

                        if (m < possibleMoves.Count)
                        {
                            move = possibleMoves[m];

                            newState = (Gameboard)state.Clone();
                            newLogic = new GameLogic(newState);
                            newLogic.ApplyMove(move);
                        }
                        else
                        {
                            newState = null;
                        }
                    }
                }

                foreach (Move move in possibleMoves)
                {
                    Gameboard newState = (Gameboard)state.Clone();
                    GameLogic newLogic = new GameLogic(newState);
                    newLogic.ApplyMove(move);

                    int value = -AlphaBeta(newState, depth - 1, -beta, -alpha, !myMove);
                    if (value > score)
                    {
                        bestMove = move;
                        score    = value;
                    }
                    if (score > alpha)
                    {
                        alpha = score;
                    }
                    if (score >= beta)
                    {
                        break;
                    }
                }
            }

            if (score <= alpha)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(alpha, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score > alpha && score < beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, score, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Upperbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }
            else if (score >= beta)
            {
                if (!transpositionTable.ContainsKey(zHash))
                {
                    Transposition transposition = new Transposition(score, beta, depth, bestMove);
                    transpositionTable.Add(state.GetZobristHash(), transposition);
                }
                else
                {
                    Transposition transposition = transpositionTable[zHash];
                    transposition.Lowerbound = score;
                    transposition.Depth      = depth;
                    transposition.BestMove   = bestMove;
                }
            }

            return(score);
        }