Exemplo n.º 1
0
 public SignalData(SignalTypes type, IEnumerable<double> samples, double samplingSpeed, PhaseData phaseData)
 {
     SignalType = type;
     SignalSamples = samples;
     SampleSpeed = samplingSpeed;
     PhaseShiftData = phaseData;
 }
        public ERROR_CODES RunExperiment(IExperimentData experimentToRun)
        {
            //alot of constants here that later on need to be parametrized
            ERROR_CODES status = ERROR_CODES.AA_OK;
            PhaseData phaseData = null;
            double scopeSampleRate = 0;
            bool[] demodulatorToRead = new bool[LockinAmplifier.NumberOfDemodulators];
            for (int i = 0; i < LockinAmplifier.NumberOfDemodulators; i++)
            {
                demodulatorToRead[i] = true;
            }

            try
            {
                status |= SignalGenerator.UpdateOutputState(true);
                status |= SignalGenerator.UploadArbitrarySignalData(experimentToRun.SignalGeneratorData.ArbitrarySignalData, false);
                //LaserModulation.SignalFixer.Classes.Saver.SaveArrayToFile("C:\\Pts\\bad1.txt", experimentToRun.SignalGeneratorData.ArbitrarySignalData.ToArray());
                System.Threading.Thread.Sleep(500);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            if (status != ERROR_CODES.AA_OK)
            {
                status = status;
            }
            status = ERROR_CODES.NOT_CONNECTED_TO_ZI_SERVER;
            System.Threading.Thread.Sleep(1000);
            IEnumerable<double> signalData;

            double tmpAmplitude = 0;
            try
            {
                signalData = null;
                foreach (SignalTypes signalType in Enum.GetValues(typeof(SignalTypes)))
                {

                    ScopeInputChannel scopeInChl = experimentToRun.GetScopeChannelByDataType(signalType);
                    if (signalType == SignalTypes.PhotodiodeOutput)
                    {
                        try
                        {
                            status = Scope.ReadScopeData(scopeInChl, experimentToRun.ScopeData.PointsToSave, experimentToRun.ScopeData.SampleMode, 512, out signalData);
                            if (status != ERROR_CODES.AA_OK)
                            {
                                status = status;
                            }
                        }
                        catch (Exception ex)
                        {

                            string ds = ex.Message;
                        }
                    }
                    else
                    {
                        signalData = new double[0];
                    }

                    if (status != ERROR_CODES.AA_OK)
                    {
                        status = status;
                    }
                    switch (signalType)
                    {
                        case SignalTypes.PhotodiodeOutput:
                            double[] expectedOutput = new double[scopeCycleSize];
                            double[] normalizeSignalData = SignalDigitizer.NormalizeSignal(signalData.ToArray(), new DigitzerParameters(DigitizingMethods.Absolute, 0, 0, 0, false), out tmpAmplitude).ToArray();
                            expectedOutput = FunctionGenerator.PositivieNormalizeCosine(scopeCycleSize);

                            try
                            {
                                phaseData = PhaseAnalyzer.FindBinPhaseByShift(normalizeSignalData, expectedOutput, scopeCycleSize, -30, 30, 0, false);

                            }
                            catch (Exception ex)
                            {

                                string s = ex.Message;
                            }
                            break;
                        case SignalTypes.SignalGeneratorOutput:
                            phaseData = new PhaseData(0,0,0);
                            if (!workWithLockinScope)
                            {
                                double[] normalizeSignalGeneratorOutput = SignalDigitizer.NormalizeSignal(signalData.ToArray(), new DigitzerParameters(DigitizingMethods.Absolute, 0, 0, 0, false), out tmpAmplitude).ToArray();
                                double[] normalizeExpectedSignalGeneratoroutput = SignalDigitizer.NormalizeSignal(experimentToRun.SignalGeneratorData.ArbitrarySignalData.ToArray(), new DigitzerParameters(DigitizingMethods.Absolute, 0, 0, 0, false), out tmpAmplitude).ToArray();
                                phaseData = PhaseAnalyzer.FindBinPhaseByShift(normalizeSignalGeneratorOutput, normalizeExpectedSignalGeneratoroutput, scopeCycleSize, -30, 30, 0, false);
                            }
                            break;
                        case SignalTypes.SignalGeneratorSync:
                            phaseData = null;
                            break;
                    }
                    try
                    {
                        SignalData tmp = new SignalData(signalType, signalData.ToArray(), scopeSampleRate, phaseData);
                        experimentToRun.ScopeData.SavedData.Add(scopeInChl, tmp);
                    }
                    catch (Exception ex)
                    {
                        String s = ex.Message;
                    }
                }

            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            //add here lockin code.
            IDemodulatorDataPacket[] lockinData = null;
            try
            {
                LockinAmplifier.GetPolledData(demodulatorToRead, 1000, out lockinData);
                experimentToRun.DemodulatorsData = lockinData;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }

            try
            {
                double r1 = experimentToRun.DemodulatorsData[0].R.Mean;
                double std1 = experimentToRun.DemodulatorsData[0].R.StandardDeviation;

                double r2 = experimentToRun.DemodulatorsData[1].R.Mean;
                double std2 = experimentToRun.DemodulatorsData[1].R.StandardDeviation;
                //MatlabFigure dbg = new MatlabFigure();
                //dbg.AddPlot("R2", experimentToRun.DemodulatorsData[1].RSamples, false);
                //dbg.Show();
            }

            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return status;
        }
        public ERROR_CODES TestScopeError()
        {
            ERROR_CODES status = ERROR_CODES.AA_OK;
            if (!workWithLockinScope)
            {
                double dbg1 = 0, dbg2 = 0, dbg3 = 0;
                try
                {
                    int iterationsCount = 100;
                    double scopeSampleRate;
                    double pi = Math.PI;

                    double testFrequencyHz = SignalGenerator.OutputFrequency;
                    Scope.GetSampleRate(out scopeSampleRate);

                    int binsInPeriod = Convert.ToInt32(scopeSampleRate / testFrequencyHz);
                    int periodsInScopeData = Convert.ToInt32(scopeSamplesToRead / binsInPeriod);

                    double[] refSineSignal = new double[binsInPeriod];
                    for (int i = 0; i < binsInPeriod; i++)
                    {
                        refSineSignal[i] = 0.5 * (Math.Sin(2 * pi * i / binsInPeriod) + 1);
                    }
                    MatlabFigure tmp = new MatlabFigure("ref", refSineSignal);
                    tmp.Show();

                    double[] normalizeBuffer, scopeData;
                    double[] data = new double[0];
                    double signalAmp;

                    PhaseData[] phaseData = new PhaseData[iterationsCount];
                    double[] phaseValue = new double[iterationsCount];
                    double[][] iterationData = new double[binsInPeriod][];
                    double[][] errorData = new double[binsInPeriod][];
                    int rowsCount = iterationsCount * periodsInScopeData;
                    for (int i = 0; i < binsInPeriod; i++)
                    {
                        iterationData[i] = new double[rowsCount];
                        errorData[i] = new double[rowsCount];
                    }
                    bool showDebugWindow = false;
                    Scope.SetupScopeRead(ScopeInputChannel.Chl2, scopeSamplesToRead, ScopeSampleMode.Average, 512);
                    for (int iterationIndex = 0; iterationIndex < iterationsCount; iterationIndex++)
                    {
                        //showDebugWindow = ((iterationIndex % 10) == 0) ? true : false;
                        dbg1 = iterationIndex;
                        Scope.ReadChannel(out scopeData);
                        normalizeBuffer = SignalDigitizer.NormalizeSignal(scopeData, new DigitzerParameters(DigitizingMethods.AverageMinMax, 0.005, 0.005, 1, false), out signalAmp).ToArray();
                        phaseData[iterationIndex] = PhaseAnalyzer.FindBinPhaseByShift(normalizeBuffer, refSineSignal, binsInPeriod, -500, 500, 0, showDebugWindow);
                        data = data.Concat(scopeData).ToArray();
                        phaseValue[iterationIndex] = phaseData[iterationIndex].PhaseInBins;
                        //slice up the scope data the single periods data
                        for (int j = 0; j < binsInPeriod; j++)
                        {
                            dbg2 = j;
                            for (int k = 0; k < periodsInScopeData; k++)
                            {
                                dbg3 = k;
                                int periodIndex = k + (periodsInScopeData * iterationIndex);
                                int zeroPhaseIndex = j + k * binsInPeriod + phaseData[iterationIndex].PhaseInBins;
                                if (zeroPhaseIndex >= scopeSamplesToRead)
                                {
                                    zeroPhaseIndex = zeroPhaseIndex - scopeSamplesToRead;
                                }
                                iterationData[j][periodIndex] = scopeData[zeroPhaseIndex];
                                errorData[j][periodIndex] = Math.Abs(normalizeBuffer[zeroPhaseIndex] - refSineSignal[j]) * signalAmp;
                            }
                        }
                    }
                    MatlabFigure debugSignal = new MatlabFigure(string.Format("Scope date over {0} iterations.", iterationsCount), data);
                    debugSignal.Show();
                    MatlabFigure debugPhase = new MatlabFigure(string.Format("Scope phase date over {0} iterations.", iterationsCount), phaseValue);
                    debugPhase.Show();
                    int totalPeriods = iterationsCount * periodsInScopeData;
                    double[] stdDevivations = new double[binsInPeriod];
                    IStatisticalData[] valueVariation = new StatisticalData[binsInPeriod];
                    IStatisticalData[] errorVariation = new StatisticalData[binsInPeriod];
                    for (int i = 0; i < binsInPeriod; i++)
                    {
                        valueVariation[i] = new StatisticalData(iterationData[i]);
                        stdDevivations[i] = valueVariation[i].StandardDeviation;
                        errorVariation[i] = new StatisticalData(errorData[i]);
                    }
                    IStatisticalData secondMoment = new StatisticalData(stdDevivations);
                    MatlabFigure debugValues = new MatlabFigure();
                    debugValues.AddPlot("Values fluctuation.", valueVariation, false);
                    debugValues.Show();
                    MatlabFigure debugStdDeviations = new MatlabFigure("std deviations", stdDevivations);
                    debugStdDeviations.Show();
                    MatlabFigure debugErrorVariations = new MatlabFigure();
                    debugErrorVariations.AddPlot("Error variations", errorVariation, false);
                    debugErrorVariations.Show();
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                    double z = dbg1;
                    z = dbg2; z = dbg3;

                }
            }
            return status;
        }
Exemplo n.º 4
0
        /// <summary>Find the phase shift between an input signal and the zero-phase expected signal.
        /// The phase shift is found by shifting the reference signal and finding the shift where the difference between 
        /// the input and the reference is at minimum.</summary>
        /// <param name="inputSignal"> Input signal whos phase we want to find</param>
        /// <param name="zeroPhasedSignal"> Zero phase reference signal.</param>
        /// <param name="binsInPeriod"> The expected preiod of the input signal in bins.</param>
        /// <param name="startShift"> The intitial shift to check.</param>
        /// <param name=endShift"> The final shift to check.</param>
        /// <remarks>The function assume that the zero phase signal start @ a global minimum!
        /// Positive shift value shift the shifted signal right  (negative value shift to the left).</remarks>
        public static PhaseData FindBinPhaseByShift(IEnumerable<double> inputSignal, IEnumerable<double> zeroPhasedSignal, int binsInPeriod, int startShift, int endShift, bool showDebugWindow)
        {
            try
            {
                double tmpMin = inputSignal.Min();
                double[] tmpSignal = inputSignal.SkipWhile(x => x != tmpMin).ToArray();
                int skippedBins = inputSignal.Count() - tmpSignal.Count();
                if (skippedBins > (inputSignal.Count() - binsInPeriod))
                {
                    //skippedBins = skippedBins - binsInPeriod;
                }

                double differenceSum, minDifferenceSum;
                int minDifferencePhase = 0;
                int phaseShiftIndex = 0;
                double[] sig = inputSignal.ToArray();
                double[] refSig = zeroPhasedSignal.ToArray();

                minDifferenceSum = double.PositiveInfinity;
                int shift;
                int i;
                try
                {
                    for (shift = startShift; shift <= endShift; shift++)
                    {
                        differenceSum = 0;
                        for (i = 0; i < binsInPeriod; i++)
                        {
                            phaseShiftIndex = skippedBins + shift + i;
                            phaseShiftIndex = phaseShiftIndex % inputSignal.Count();
                            phaseShiftIndex = (phaseShiftIndex < 0) ? phaseShiftIndex + binsInPeriod : phaseShiftIndex;
                            phaseShiftIndex = (phaseShiftIndex >= binsInPeriod) ? phaseShiftIndex - binsInPeriod : phaseShiftIndex;
                            differenceSum += Math.Abs(sig[phaseShiftIndex] - refSig[i]);
                        }
                        if (differenceSum < minDifferenceSum)
                        {
                            minDifferencePhase = shift;
                            minDifferenceSum = differenceSum;
                        }
                    }

                }
                catch (Exception ex)
                {

                    string s = ex.Message;
                }
                PhaseData phaseData = new PhaseData((skippedBins + minDifferencePhase), binsInPeriod, minDifferenceSum / binsInPeriod);

                int totalPhase = skippedBins + minDifferencePhase;
                if (totalPhase < 0)
                {
                    totalPhase += inputSignal.Count();
                }
                double[] shiftedSig = new double[binsInPeriod];
                for (i = 0; i < binsInPeriod; i++)
                {
                    int phaseIdx = (i + totalPhase) % sig.Length;
                    phaseIdx = (phaseIdx > sig.Length) ? phaseIdx - sig.Length : phaseIdx;
                    phaseIdx = (phaseIdx < 0) ? phaseIdx + sig.Length : phaseIdx;
                    if (phaseIdx >= sig.Length)
                    {
                        phaseIdx = phaseIdx - sig.Length;
                    }
                    shiftedSig[i] = sig[phaseIdx];
                }
                if (showDebugWindow)
                {
                    SharedCode.DebugHelper.MatlabFigure tmp = new SharedCode.DebugHelper.MatlabFigure("ref", zeroPhasedSignal.ToArray());
                    tmp.AddPlot("phased", shiftedSig, true);
                    tmp.Show();
                }
                return phaseData;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                throw new Exception("Find phase fail - " + ex.Message);
            }
        }