Beispiel #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleCurve" /> class.
        /// </summary>
        /// <param name="curve">The Curve.</param>
        /// <exception cref="System.ArgumentNullException">Cannot create an instance of SimpleCurve when curve is null</exception>
        public SimpleCurve(Curve curve, SimpleMeasurement simpleMeasurement)
        {
            if (curve == null)
            {
                throw new ArgumentNullException("Cannot create an instance of SimpleCurve when the specified Curve is null");
            }

            Curve = curve;
            if (!Curve.IsFinished)
            {
                Curve.Finished     += Curve_Finished;
                Curve.NewDataAdded += Curve_NewDataAdded;
            }
            _simpleMeasurement = simpleMeasurement;
        }
        public SimpleMeasurement HackDPV(SimpleMeasurement unHackedMeasurement)
        {
            List <SimpleMeasurement> hackedMeasurements;
            SimpleMeasurement        hackedMeasurement;

            String unHackedMeasurementString;
            String hackedMeasurementString = "";

            List <int>    locations       = new List <int>();
            List <string> stringLocations = new List <string>();

            int startSubstring = 0;

            String file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dpv.pssession");

            SimpleLoadSaveFunctions.SaveMeasurement(unHackedMeasurement, file);

            //Code here for manipulation the file

            using (StreamReader sr = new StreamReader(file))

                unHackedMeasurementString = sr.ReadToEnd();

            locations       = AddLocationsDPV(locations, unHackedMeasurementString);
            stringLocations = AddStringLocationsDPV(stringLocations);

            for (int i = 0; i < locations.Count; i++)
            {
                hackedMeasurementString += unHackedMeasurementString.Substring(startSubstring, locations[i]) + stringLocations[i];
                startSubstring          += locations[i] + stringLocations[i].Length;
            }

            hackedMeasurementString += unHackedMeasurementString.Substring(startSubstring);

            using (StreamWriter writer = File.CreateText(file))

                writer.Write(hackedMeasurementString);

            hackedMeasurements = SimpleLoadSaveFunctions.LoadMeasurements(file);

            hackedMeasurement = hackedMeasurements[0];

            return(hackedMeasurement);
        }
        /// <summary>
        /// Saves a simplemeasurement to a *.pssession file.
        /// </summary>
        /// <param name="simpleMeasurement">The simple measurement.</param>
        /// <param name="filepath">The filepath of the *.pssession file.</param>
        /// <exception cref="System.ArgumentException">File path must be specified</exception>
        /// <exception cref="System.ArgumentNullException">SimpleMeasurement cannot be null</exception>
        /// <exception cref="System.Exception">An error occured while saving, please make sure the file path is correct</exception>
        public static void SaveMeasurement(SimpleMeasurement simpleMeasurement, string filepath)
        {
            if (string.IsNullOrEmpty(filepath))
            {
                throw new ArgumentException("File path must be specified");
            }
            if (simpleMeasurement == null)
            {
                throw new ArgumentNullException("SimpleMeasurement cannot be null");
            }

            SessionManager session = new SessionManager();

            session.AddMeasurement(simpleMeasurement.Measurement);
            session.MethodForEditor = simpleMeasurement.Measurement.Method;

            try { LoadSaveHelperFunctions.SaveSessionFile(filepath, session); }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
                throw new Exception("An error occured while saving, please make sure the file path is correct");
            }
        }
        //Simple connection to the palmsens, currently the only one used
        public async void SimpleConnect(int fileNum, bool RunningPC, bool RunningNC, bool RunningReal, bool RunningDPV)
        {
            bool   RunningBL = true;
            string testRun   = "5";
            //Below sets which option the code will execute
            SimpleMeasurement baseline;
            AssetManager      assetManager = Application.Context.Assets;

            using (StreamReader sr = new StreamReader(assetManager.Open(testRun + "_2525AfterMch" + fileNum + ".pssession")))   //Loads a blank baseline curve to subtract from the scanned/loaded curve
                baseline = SimpleLoadSaveFunctions.LoadMeasurements(sr)[0];

            baselineCurves = baseline.SimpleCurveCollection;

            //Runs a real scan depending on whatever parameters the person has set
            if (RunningReal)
            {
                Context       context      = Application.Context; //Loads the current android context
                IAttributeSet attributeSet = null;
                psCommSimpleAndroid = new PSCommSimpleAndroid(context, attributeSet);
                //Uses a simple comm with the palmsens
                Device[] devices = await psCommSimpleAndroid.GetConnectedDevices();

                try
                {
                    await psCommSimpleAndroid.Connect(devices[0]);   //Connect to the first palmsens found
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }

                psCommSimpleAndroid.MeasurementStarted            += PsCommSimpleAndroid_MeasurementStarted; //Loads the necessary flags
                psCommSimpleAndroid.MeasurementEnded              += PsCommSimpleAndroid_MeasurementEnded;
                psCommSimpleAndroid.SimpleCurveStartReceivingData += PsCommSimpleAndroid_SimpleCurveStartReceivingData;

                Method runScan = await RunScan();                                     //Sets the scan parameters

                activeSimpleMeasurement = await psCommSimpleAndroid.Measure(runScan); //Runs the scan on the potentiostat

                psCommSimpleAndroid.Wait(11000);

                psCommSimpleAndroid.Dispose();

                List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();   //Loads the current database

                //Add in processing stuff here
                SimpleLoadSaveFunctions.SaveMeasurement(activeSimpleMeasurement, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dpv" + allDb.Count + ".pssession"));

                //FileHack instance = new FileHack();

                //activeSimpleMeasurement = instance.HackDPV(activeSimpleMeasurement);

                List <SimpleCurve> simpleCurves = activeSimpleMeasurement.NewSimpleCurve(DataArrayType.Current, DataArrayType.Potential);

                SimpleCurve subtractedCurve = simpleCurves[0].Subtract(baselineCurves[0]);    //Note, replace simpleCurves[1] w/ the standard blank curve

                SimpleCurve movingAverageBaseline = subtractedCurve.MovingAverageBaseline();  //Subtracts the baseline from the subtracted curve

                SimpleCurve baselineCurve = subtractedCurve.Subtract(movingAverageBaseline);

                subtractedCurve.Dispose();   //Disposes of the subtracted curve

                SimpleCurve smoothedCurve = baselineCurve.Smooth(SmoothLevel.VeryHigh);

                smoothedCurve.DetectPeaks(0.1, 0, true, false, false);

                double peakLocation = smoothedCurve.Peaks[smoothedCurve.Peaks.nPeaks - 1].PeakX;
                double peakHeight   = smoothedCurve.Peaks[smoothedCurve.Peaks.nPeaks - 1].PeakValue;

                ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                if (peakLocation <= -0.3 && peakLocation >= -0.4)   //If the peak is between a certain range, the sample is infected, add in a minimum value once one is determined
                {
                    _database.IsInfected = true;
                }
                else
                {
                    _database.IsInfected = false;
                }

                _database.PeakVoltage = peakHeight;
                await App.Database.SaveScanAsync(_database);   //Saves the current database

                subtractedCurve.Dispose();
                baselineCurve.Dispose();   //Disposes of the baseline curve
                smoothedCurve.Dispose();
            }

            //Runs a differential pulse voltammetric scan for testing
            else if (RunningDPV)
            {
                using (StreamReader sr = new StreamReader(assetManager.Open("blank.pssession")))   //Loads a blank curve as a baseline to be subtracted
                    baseline = SimpleLoadSaveFunctions.LoadMeasurements(sr)[0];

                Context       context      = Application.Context;                     //Loads the current android context
                IAttributeSet attributeSet = null;
                psCommSimpleAndroid = new PSCommSimpleAndroid(context, attributeSet); //Initializes the palmsens comm
                Device[] devices = await psCommSimpleAndroid.GetConnectedDevices();

                try
                {
                    await psCommSimpleAndroid.Connect(devices[0]);   //Connects to the first palmsens found
                }
                catch (Exception ex)
                {
                    psCommSimpleAndroid.Dispose();
                    Crashes.TrackError(ex);
                    return;
                }

                psCommSimpleAndroid.MeasurementStarted            += PsCommSimpleAndroid_MeasurementStarted; //Loads the necessary flags
                psCommSimpleAndroid.MeasurementEnded              += PsCommSimpleAndroid_MeasurementEnded;
                psCommSimpleAndroid.SimpleCurveStartReceivingData += PsCommSimpleAndroid_SimpleCurveStartReceivingData;

                Method runScan = await RunScan();                                     //Sets the scan parameters

                activeSimpleMeasurement = await psCommSimpleAndroid.Measure(runScan); //Runs the scan on the potentiostat

                Thread.Sleep(50000);

                psCommSimpleAndroid.Dispose();                                          //Disposes of the comm when it is done being used

                List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync(); //Loads the current database

                //Add in processing stuff here
                SimpleLoadSaveFunctions.SaveMeasurement(activeSimpleMeasurement, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dpv" + allDb.Count + ".pssession"));

                //FileHack instance = new FileHack();

                //activeSimpleMeasurement = instance.HackDPV(activeSimpleMeasurement);

                List <SimpleCurve> simpleCurves = activeSimpleMeasurement.NewSimpleCurve(DataArrayType.Current, DataArrayType.Potential);

                //SimpleCurve subtractedCurve = simpleCurves[0].Subtract(baselineCurves[0]);    //Note, replace simpleCurves[1] w/ the standard blank curve

                SimpleCurve movingAverageBaseline = simpleCurves[0].MovingAverageBaseline();   //Subtracts the baseline from the subtracted curve

                SimpleCurve baselineCurve = simpleCurves[0].Subtract(movingAverageBaseline);

                //subtractedCurve.Dispose();   //Disposes of the subtracted curve

                SimpleCurve smoothedCurve = baselineCurve.Smooth(SmoothLevel.VeryHigh);

                smoothedCurve.DetectPeaks(0.1, 0, true, false, false);

                PeakList peakList = smoothedCurve.Peaks; //Detects the peaks on the subtracted curve

                baselineCurve.Dispose();                 //Disposes of the baseline curve
                smoothedCurve.Dispose();

                Peak   mainPeak     = peakList[peakList.nPeaks - 1]; //Note, the proper peak is the last peak, not the first peak
                double peakLocation = mainPeak.PeakX;
                double peakHeight   = mainPeak.PeakValue;

                ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                if (peakLocation <= -0.3 && peakLocation >= -0.4)   //If the peak is between a certain range, the sample is infected, add in a minimum value once one is determined
                {
                    _database.IsInfected = true;
                }
                else
                {
                    _database.IsInfected = false;
                }

                _database.PeakVoltage = peakHeight;
                await App.Database.SaveScanAsync(_database); //Saves the current database
            }
            else if (RunningNC || RunningPC || RunningBL)    //If a test scan is being run
            {
                if (RunningBL)                               //If a simple baseline test is run with no subtraction or curve manipulation
                {
                    SimpleMeasurement baselineMeasurement;
                    using (StreamReader sr = new StreamReader(assetManager.Open(testRun + "_baselineOnly" + fileNum + ".pssession")))
                        baselineMeasurement = SimpleLoadSaveFunctions.LoadMeasurements(sr)[0];

                    List <SimpleCurve> avgBaselineCurves = baselineMeasurement.SimpleCurveCollection;

                    SimpleCurve avgBaselineCurve = avgBaselineCurves[0];

                    avgBaselineCurve.DetectPeaks(0.05, 0, true, false);   //Detect peaks only if they are wider than 0.05 V

                    PeakList avgBaselinePeakList = avgBaselineCurve.Peaks;

                    if (avgBaselinePeakList.nPeaks != 0)                                            //If it detects a peak run below code
                    {
                        Peak avgBaselinePeak = avgBaselinePeakList[avgBaselinePeakList.nPeaks - 1]; //Use the last peak detected which should be the wanted peak

                        double avgBaselinePeakLocation = avgBaselinePeak.PeakX;
                        double avgBaselinePeakValue    = avgBaselinePeak.PeakValue;

                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        if (avgBaselinePeakLocation <= -0.3 && avgBaselinePeakLocation >= -0.4)   //If a peak is between a certain range, the sample is infected, add in a minimal value once determined
                        {
                            _database.IsInfected = true;
                        }
                        else
                        {
                            _database.IsInfected = false;
                        }

                        _database.PeakVoltage = avgBaselinePeakValue;
                        await App.Database.SaveScanAsync(_database);
                    }
                    else   //If no peak is detected
                    {
                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        _database.IsInfected  = false;
                        _database.PeakVoltage = 0.0;
                        _database.VoltamType  = "Failed PC";
                        await App.Database.SaveScanAsync(_database);
                    }
                }
                else if (RunningPC)   //If a postitive control test is being run with known values
                {
                    SimpleMeasurement positiveControl;
                    using (StreamReader sr = new StreamReader(assetManager.Open(testRun + "_2525AfterTarget" + fileNum + ".pssession")))
                        positiveControl = SimpleLoadSaveFunctions.LoadMeasurements(sr)[0];

                    List <SimpleCurve> positiveCurves = positiveControl.SimpleCurveCollection;

                    SimpleCurve baselineCurve;

                    SimpleCurve subtractedCurve = positiveCurves[0].Subtract(baselineCurves[0]);

                    baselineCurve = subtractedCurve.MovingAverageBaseline();

                    subtractedCurve.Dispose();

                    baselineCurve.DetectPeaks(0.05, 0, true, false);   //Detect all peaks with width greater than 0.05 V

                    PeakList positivePeakList = baselineCurve.Peaks;

                    baselineCurve.Dispose();

                    if (positivePeakList.nPeaks != 0)   //If a peak is detected, execute the code below
                    {
                        Peak positivePeak = positivePeakList[positivePeakList.nPeaks - 1];

                        double positivePeakLocation = positivePeak.PeakX;
                        double positivePeakValue    = positivePeak.PeakValue;

                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        if (positivePeakLocation <= -0.3 && positivePeakLocation >= -0.4)   //If a peak is between a certain range, the sample is infected, add in minimum value once determined
                        {
                            _database.IsInfected = true;
                        }
                        else
                        {
                            _database.IsInfected = false;
                        }

                        _database.PeakVoltage = positivePeakValue;
                        await App.Database.SaveScanAsync(_database);
                    }
                    else   //If no peak is detected, execute the code below
                    {
                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        _database.IsInfected  = false;
                        _database.PeakVoltage = 0.0;
                        _database.VoltamType  = "Failed PC";
                        await App.Database.SaveScanAsync(_database);
                    }
                }
                else if (RunningNC)   //If a negative control test is being run
                {
                    SimpleMeasurement negativeControl;
                    using (StreamReader sr = new StreamReader(assetManager.Open(testRun + "_2525AfterMch" + fileNum + ".pssession")))
                        negativeControl = SimpleLoadSaveFunctions.LoadMeasurements(sr)[0];

                    List <SimpleCurve> negativeCurves = negativeControl.SimpleCurveCollection;

                    SimpleCurve baselineCurve;

                    SimpleCurve subtractedCurve = negativeCurves[0].Subtract(baselineCurves[0]);

                    baselineCurve = subtractedCurve.MovingAverageBaseline();

                    subtractedCurve.Dispose();

                    baselineCurve.DetectPeaks(0.05, 0, true, false);   //Detect all peaks with a width greater than 0.05 V

                    PeakList negativePeakList = baselineCurve.Peaks;

                    baselineCurve.Dispose();

                    if (negativePeakList.nPeaks != 0)   //If a peak is detected, execute the code below
                    {
                        Peak   negativePeak         = negativePeakList[negativePeakList.nPeaks - 1];
                        double negativePeakLocation = negativePeak.PeakX;
                        double negativePeakValue    = negativePeak.PeakValue;

                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        if (negativePeakLocation <= -0.3 && negativePeakLocation >= -0.4)   //If a peak is in a certain range, the sample is infected, add a minimum value once determined
                        {
                            _database.IsInfected = true;
                        }
                        else
                        {
                            _database.IsInfected = false;
                        }

                        _database.PeakVoltage = negativePeakValue;
                        await App.Database.SaveScanAsync(_database);
                    }
                    else   //If a peak is not detected
                    {
                        List <ScanDatabase> allDb = await App.Database.GetScanDatabasesAsync();

                        ScanDatabase _database = await App.Database.GetScanAsync(allDb.Count);

                        _database.IsInfected  = false;
                        _database.PeakVoltage = 0.0;
                        _database.VoltamType  = "Failed NC";
                        await App.Database.SaveScanAsync(_database);
                    }
                }
            }
        }