Beispiel #1
0
        public void EnsureIDidNotMessUpTasks()
        {
            var task = new Task("do stuff");
            task.Start();
            task.Stop();

            task.Start();
            task.Stop();

            var description = task.Description;

            // just make sure it doesn't blow up
        }
Beispiel #2
0
        public void RepositoryWorks()
        {
            var taskRepository = new TaskRepository() { Configuration = new CoreConfiguration(".", ".") };

            var task = new Task("do stuff");
            task.Start();
            task.Stop();

            task.Start();
            task.Stop();

            taskRepository.CreateTask(task);

            var loadedTask = taskRepository.FromFileName(task.FileName);
            Assert.Equal(task.Durations.Count, loadedTask.Durations.Count);
            Assert.Equal(task.Name, loadedTask.Name);
        }
Beispiel #3
0
        private void button_electrolesioningStart_Click(object sender, EventArgs e)
        {
            //Change mouse cursor to waiting cursor
            this.Cursor = Cursors.WaitCursor;

            //Grab values from UI
            double voltage = Convert.ToDouble(numericUpDown_electrolesioningVoltage.Value);
            double duration = Convert.ToDouble(numericUpDown_electrolesioningDuration.Value);
            List<Int32> chList = new List<int>(listBox_electrolesioningChannels.SelectedIndices.Count);
            for (int i = 0; i < listBox_electrolesioningChannels.SelectedIndices.Count; ++i)
                chList.Add(listBox_electrolesioningChannels.SelectedIndices[i] + 1); //+1 since indices are 0-based but channels are 1-base

            //Disable buttons, so users don't try running two experiments at once
            button_electrolesioningStart.Enabled = false;
            button_electrolesioningSelectAll.Enabled = false;
            button_electrolesioningSelectNone.Enabled = false;
            button_electrolesioningStart.Refresh();

            //Refresh stim task
            stimDigitalTask.Dispose();
            stimDigitalTask = new Task("stimDigitalTask_Electrolesioning");
            if (Properties.Settings.Default.StimPortBandwidth == 32)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);

            //Refresh pulse task
            stimPulseTask.Dispose();
            stimPulseTask = new Task("stimPulseTask");
            if (Properties.Settings.Default.StimPortBandwidth == 32)
            {
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao2", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual Pulse
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao3", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
            }
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
            {
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts);
                stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts);
            }

            stimPulseWriter = new AnalogMultiChannelWriter(stimPulseTask.Stream);

            stimPulseTask.Timing.ConfigureSampleClock("",
                StimPulse.STIM_SAMPLING_FREQ, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
            stimPulseTask.Timing.SamplesPerChannel = 2;

            stimDigitalTask.Control(TaskAction.Verify);
            stimPulseTask.Control(TaskAction.Verify);

            //For each channel, deliver lesioning pulse
            for (int i = 0; i < chList.Count; ++i)
            {
                int channel = chList[i];
                UInt32 data = StimPulse.channel2MUX((double)channel);

                //Setup digital waveform, open MUX channel
                stimDigitalWriter.WriteSingleSamplePort(true, data);
                stimDigitalTask.WaitUntilDone();
                stimDigitalTask.Stop();

                //Write voltage to channel, wait duration, stop
                stimPulseWriter.WriteMultiSample(true, new double[,] { { 0, 0 }, { 0, 0 }, { voltage, voltage }, { 0, 0 } });
                stimPulseTask.WaitUntilDone();
                stimPulseTask.Stop();
                Thread.Sleep((int)(Math.Round(duration * 1000))); //Convert to ms
                stimPulseWriter.WriteMultiSample(true, new double[,] { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } });
                stimPulseTask.WaitUntilDone();
                stimPulseTask.Stop();

                //Close MUX
                stimDigitalWriter.WriteSingleSamplePort(true, 0);
                stimDigitalTask.WaitUntilDone();
                stimDigitalTask.Stop();
            }

            bool[] fData = new bool[Properties.Settings.Default.StimPortBandwidth];
            stimDigitalWriter.WriteSingleSampleMultiLine(true, fData);
            stimDigitalTask.WaitUntilDone();
            stimDigitalTask.Stop();

            button_electrolesioningSelectAll.Enabled = true;
            button_electrolesioningSelectNone.Enabled = true;
            button_electrolesioningStart.Enabled = true;

            //Now, destroy the objects we made
            updateSettings();
            this.Cursor = Cursors.Default;
        }
Beispiel #4
0
        private void radioButton_stimVoltageControlled_Click(object sender, EventArgs e)
        {
            if (radioButton_stimVoltageControlled.Checked)
            {
                Properties.Settings.Default.StimVoltageControlled = true;
                if (Properties.Settings.Default.UseStimulator)
                {
                    //this line goes high (TTL-wise) when we're doing current-controlled stim, low for voltage-controlled
                    stimIvsVTask = new Task("stimIvsV");
                    stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                        ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                    stimIvsVTask.Control(TaskAction.Verify);
                    stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
                    stimIvsVTask.WaitUntilDone();
                    stimIvsVTask.Stop();
                    stimIvsVTask.Dispose();
                }

                radioButton_impVoltage.Checked = true;
            }
        }
 public void TestStopActualOwner()
 {
     IdentityId actualId = new IdentityId();
     ILoggingService loggingService = SetupLoggerMock(new List<TaskHistoryEvent>());
     Task task = new Task(
                  new TaskId(), TaskStatus.InProgress, string.Empty,
                  string.Empty, Priority.Normal, false,
                  DateTime.UtcNow, new IdentityId().GetIdentity(),
                  DateTime.UtcNow, null, actualId.GetIdentity())
     {
         LoggingService = loggingService
     };
     IPrincipal actualOwner = new ClaimsPrincipal(actualId.GetIdentity());
     Thread.CurrentPrincipal = actualOwner;
     task.Stop();
     Assert.AreEqual(TaskStatus.Reserved, task.Status);
     Assert.AreEqual(actualId.GetIdentity(), task.ActualOwner);
     Assert.IsNotNull(task.History);
     Assert.AreEqual(1, task.History.Count());
     TaskHistoryEvent history = task.History.ElementAt(0);
     Assert.IsNotNull(history);
     Assert.AreEqual(TaskStatus.InProgress, history.OldStatus);
     Assert.AreEqual(TaskStatus.Reserved, history.NewStatus);
     Assert.AreEqual(actualId, history.UserId);
 }
        /// <summary>
        /// Do Cycles of closing and opening the junction, while measuring IVs
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireData(IVSettings settings,BackgroundWorker worker, DoWorkEventArgs e)
        {
            bool isCancelled = false;
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);

            
            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);
            
            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // if we use EM, and we are asked to skip the first cycle (that is done by the stepper motor), 
                // move on to the next cycle.
                //
                if (i == 0 && settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet 
                            && settings.IVSteppingMethodSettings.IsEMSkipFirstCycleEnable)
                {
                    m_stepperMotor.Shutdown();
                    continue;
                }

                //
                // Change the gain power to 5 before reaching contact
                // to ensure full contact current
                //
                m_amplifier.ChangeGain(5);

                //
                // Reach to contact before we start openning the junction
                // If we use EM and we're after the first cycle, use the EM.
                // If user asked to stop than exit
                //
                isCancelled = (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet && i > 0) ?
                               EMTryObtainShortCircuit(settings.IVSteppingMethodSettings.EMShortCircuitDelayTime, settings.IVGeneralSettings.ShortCircuitVoltage, worker, e) :
                               TryObtainShortCircuit(settings.IVGeneralSettings.ShortCircuitVoltage,settings.IVGeneralSettings.UseShortCircuitDelayTime,settings.IVGeneralSettings.ShortCircuitDelayTime,worker, e);
                if (isCancelled)
                {
                    break;
                }

                //
                // Configure the gain to the desired one before strating the measurement.
                // And also this is the time to switch the laser on.
                //
                int gainPower;
                Int32.TryParse(settings.IVGeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);

                //
                // Start openning the junction.
                // If EM is enabled and we're after the first cycle, use the EM.
                //
                if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
                {
                    if (i == 0)
                    {
                        //
                        // we are on the first cycle and wish to open the junction by the stepper motor.
                        //
                        ObtainOpenJunctionByStepperMotor(settings.IVGeneralSettings.TriggerVoltage, worker, e);

                        //
                        // from now on we will be using the electroMagnet, so lets turn the stepper motor off and move to the next cycle
                        //
                        m_stepperMotor.Shutdown();
                        continue;
                    }
                    else
                    {
                        //
                        // we set the votlage to triangle wave and then open the junction by the EM
                        //
                        writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                        IV_EMBeginOpenJunction(settings);
                    }
                }
                else
                {
                    //
                    // we set the voltage to triangle wave and then open the junction by stepper motor
                    //
                    writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                    IV_StepperMotorBeginOpenJunction(settings);
                }

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitJunctionOpenningOperation)
                    {
                        dataAcquired = reader.ReadMultiSample(-1);
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }     
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
Beispiel #7
0
        private void radioButton_stimCurrentControlled_Click(object sender, EventArgs e)
        {
            if (radioButton_stimCurrentControlled.Checked)
            {
                Properties.Settings.Default.StimVoltageControlled = false;

                if (Properties.Settings.Default.UseStimulator)
                {
                    stimIvsVTask = new Task("stimIvsV");
                    //stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port0/line8:15", "",
                    //    ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                        ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                    //stimIvsVTask.Timing.ConfigureSampleClock("100kHztimebase", 100000,
                    //    SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimIvsVTask.Control(TaskAction.Verify);
                    //byte[] b_array = new byte[5] { 255, 255, 255, 255, 255 };
                    //DigitalWaveform wfm = new DigitalWaveform(5, 8, DigitalState.ForceDown);
                    //wfm = NationalInstruments.DigitalWaveform.FromPort(b_array);
                    //stimIvsVWriter.WriteWaveform(true, wfm);
                    stimIvsVWriter.WriteSingleSampleSingleLine(true, true);
                    stimIvsVTask.WaitUntilDone();
                    stimIvsVTask.Stop();
                    stimIvsVTask.Dispose();
                }

                radioButton_impCurrent.Checked = true;
            }
        }
Beispiel #8
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataContinuously(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);
            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;

            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);

            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            } 

            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }
           

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> fullData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < fullData.Capacity; i++)
            {
                fullData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!worker.CancellationPending)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);
                    fullData = AccumulateData(fullData, dataAquired);                    
                    dataAquired = null;                  
                }
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                    m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(fullData));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }


            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
        /// <summary>
        /// Perform IV cycles while standing in place
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireDataWithoutMoving(IVSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);


            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);

            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                m_quitRealTimeOperation = false;

                //
                // we set the votlage to triangle wave and then open the junction by the EM
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitRealTimeOperation)
                    {
                        try
                        {
                            dataAcquired = reader.ReadMultiSample(-1);
                        }
                        catch (DaqException)
                        {
                            continue;
                        }
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException ex)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
Beispiel #10
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataManually(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);

            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
       
            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            
            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            }

            //
            // Turn off the laser before we reach contact
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
                Thread.Sleep(5000);
            }

            //
            // Change the gain power to 5 before reaching contact
            // to ensure full contact current
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                m_amplifier.ChangeGain(5);
            }

            //
            // Reach to contact before we start openning the junction
            // If EM is enabled and we're after the first cycle, use the EM.
            // If user asked to stop than exit
            //
            isCancelled = (settings.ElectromagnetSettings.IsEMEnable) ?
                           EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, 
                                                   settings.GeneralSettings.ShortCircuitVoltage, worker, e) :
                           TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
            if (isCancelled)
            {
                return false;
            }

            //
            // Configure the gain to the desired one before strating the measurement.
            // And also this is the time to switch the laser on.
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                int gainPower;
                Int32.TryParse(settings.GeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);
            }


            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }

            //
            // Start openning the junction.
            // If EM is enabled then use it.
            //
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_stepperMotor.Shutdown();
                EMBeginOpenJunction(settings, worker, e);                
            }
            else
            {
                BeginOpenJunction(settings, worker, e);
            }

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> averagedData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < averagedData.Capacity; i++)
            {
                averagedData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);              

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!m_quitJunctionOpenningOperation)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);

                    //
                    // Get average for the acquired the data and assign to variable
                    //
                    List<double> averageDataValues = GetAverageDataValue(dataAquired);
                    for (int i = 0; i < averageDataValues.Count; i++)
                    {                        
                        averagedData[i].Add(averageDataValues[i]);
                    }
                      
                    dataAquired = null;
 
                    //
                    // Cancel the operatin if user asked for
                    // We do it at the end of the loop to make sure we 
                    // saved all the data we have available.
                    //
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                }                
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(GetAveragedData(averagedData, 5000)));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }
            

            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
Beispiel #11
0
        /// <summary>
        /// Reach to position specified by conductance value and then stop and aqcuire data until asked to stop.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool ReachToPositionByMovingUp(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            double[,] dataAcquired = new double[1000, 1000];
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();


            for (int i = 0; i < settings.GeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // This flag is used to signal us when the user asked to stop the real time data acquisition
                //
                m_quitRealTimeOperation = false;
                m_activeTriggeredTask = GetMultipleChannelsTriggeredTask(settings, null, RunDirection.Break, m_triggerSlope, m_triggerVoltage, worker, e);
                m_activeTriggeredTask.EveryNSamplesReadEventInterval = settings.GeneralSettings.TotalSamples;
                m_activeTriggeredTask.Done += new TaskDoneEventHandler(OnTaskDoneOpenning);
                m_activeTriggeredTask.Control(TaskAction.Verify);
                m_triggerSlope = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Slope;
                m_triggerVoltage = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Level;

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // Create the tasks: One for triggering us to stop and the other for start monitoring the data
                //
                m_realTimeTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
                AnalogMultiChannelReader realTimeReader = new AnalogMultiChannelReader(m_realTimeTask.Stream);

                //
                // Start closing the junction.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, settings.GeneralSettings.ShortCircuitVoltage, worker, e);
                }
                else
                {
                    TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
                }

                //
                // Start openning the junction. ASync operation.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMBeginOpenJunction(settings, worker, e);
                }
                else
                {
                    BeginOpenJunction(settings, worker, e);
                }

                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // Start the triggered task. 
                //
                m_activeTriggeredTask.Start();

                //
                // If the user asked to stop the operation on the external thread then
                // WaitUntilDone will throw an expection. We can ignore that and return.
                //
                try
                {
                    m_activeTriggeredTask.WaitUntilDone();
                }
                catch (DaqException)
                {
                    //
                    // We got here if the user asked to stop the operation
                    //
                    break;
                }

                //
                // We reach this point only after we reached the desired conductance value.
                // As long as the user didn't ask to stop the operation continue recording the data.
                //
                while (!m_quitRealTimeOperation)
                {
                    //
                    // Read operation implicity start the task without the need to call Start() method.
                    //
                    try
                    {
                        dataAcquired = realTimeReader.ReadMultiSample(-1);
                    }
                    catch (DaqException)
                    {
                        continue;
                    }


                    if (dataAcquired.Length == 0)
                    {
                        continue;
                    }
                    //
                    // Assign the aquired data for each channel.
                    //                            
                    AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                    //
                    // calculate the physical data for each channel
                    //
                    GetPhysicalData(physicalChannels);

                    //
                    // Signal UI we have the data
                    //
                    if (DataAquired != null)
                    {
                        DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                    }
                }

                if (DoneReadingData != null)
                {
                    DoneReadingData(this, null);
                }
                m_realTimeTask.Stop();
                m_realTimeTask.Dispose();

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.GeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }
            }

            m_activeTriggeredTask.Dispose();
            m_realTimeTask.Dispose();
            m_triggerSlope = 0;
            m_triggerVoltage = 0;
            return e.Cancel;
        }
Beispiel #12
0
        //call this method after changing stimulation settings, or finishing a stimulation experiment
        //includes code to set dc offsets back to zero
        private void updateStim()
        {
            lock (this)
            {
                bool placedzeros = false;

                if (stimPulseTask != null || stimDigitalTask != null)
                {
                    try
                    {
                        // If we were ruuning a closed loop or open-loop protocol, this will zero the outputs
                        double[,] AnalogBuffer = new double[stimPulseTask.AOChannels.Count, STIMBUFFSIZE]; // buffer for analog channels
                        UInt32[] DigitalBuffer = new UInt32[STIMBUFFSIZE];

                        stimPulseTask.Stop();
                        stimDigitalTask.Stop();

                        stimPulseWriter.WriteMultiSample(true, AnalogBuffer);
                        stimDigitalWriter.WriteMultiSamplePort(true, DigitalBuffer);

                        stimPulseTask.WaitUntilDone(20);
                        stimDigitalTask.WaitUntilDone(20);

                        stimPulseTask.Stop();
                        stimDigitalTask.Stop();
                        placedzeros = true;
                    }
                    catch (Exception ex)
                    {
                        placedzeros = false;
                    }
                }
                if (stimDigitalTask != null)
                {
                    stimDigitalTask.Dispose();
                    stimDigitalTask = null;
                }
                if (stimPulseTask != null)
                {
                    stimPulseTask.Dispose();
                    stimPulseTask = null;
                }

                if (Properties.Settings.Default.UseStimulator)
                {
                    stimPulseTask = new Task("stimPulseTask");
                    stimDigitalTask = new Task("stimDigitalTask");
                    if (Properties.Settings.Default.StimPortBandwidth == 32)
                        stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                            ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                    else if (Properties.Settings.Default.StimPortBandwidth == 8)
                        stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                            ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                    if (Properties.Settings.Default.StimPortBandwidth == 32)
                    {
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao2", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual Pulse
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao3", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
                    }
                    else if (Properties.Settings.Default.StimPortBandwidth == 8)
                    {
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts);
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts);
                    }

                    if (Properties.Settings.Default.UseCineplex)
                    {
                        stimPulseTask.Timing.ReferenceClockSource = videoTask.Timing.ReferenceClockSource;
                        stimPulseTask.Timing.ReferenceClockRate = videoTask.Timing.ReferenceClockRate;
                    }
                    else
                    {
                        stimPulseTask.Timing.ReferenceClockSource = "OnboardClock";
                        //stimPulseTask.Timing.ReferenceClockRate = 10000000.0; //10 MHz timebase
                    }
                    stimDigitalTask.Timing.ConfigureSampleClock("100kHzTimebase", STIM_SAMPLING_FREQ,
                       SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimPulseTask.Timing.ConfigureSampleClock("100kHzTimebase", STIM_SAMPLING_FREQ,
                        SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimDigitalTask.SynchronizeCallbacks = false;
                    stimPulseTask.SynchronizeCallbacks = false;

                    stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
                    stimPulseWriter = new AnalogMultiChannelWriter(stimPulseTask.Stream);

                    stimPulseTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                        "/" + Properties.Settings.Default.StimulatorDevice + "/PFI6", DigitalEdgeStartTriggerEdge.Rising);

                    stimDigitalTask.Control(TaskAction.Verify);
                    stimPulseTask.Control(TaskAction.Verify);

                    //Check to ensure one of the I/V buttons is checked
                    if (!radioButton_impCurrent.Checked && !radioButton_impVoltage.Checked)
                    {
                        radioButton_impCurrent.Checked = true;
                        radioButton_impVoltage.Checked = false;
                        radioButton_stimCurrentControlled.Checked = true;
                        radioButton_stimVoltageControlled.Checked = false;
                    }

                    if (Properties.Settings.Default.UseStimulator)
                    {
                        stimIvsVTask = new Task("stimIvsV");

                        stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                            ChannelLineGrouping.OneChannelForAllLines);
                        stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                        //stimIvsVTask.Timing.ConfigureSampleClock("100kHztimebase", 100000,
                        //    SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                        stimIvsVTask.Control(TaskAction.Verify);
                        //byte[] b_array;
                        //if (radioButton_impCurrent.Checked)
                        //    b_array = new byte[5] { 255, 255, 255, 255, 255 };
                        //else
                        //    b_array = new byte[5] { 0, 0, 0, 0, 0 };
                        //DigitalWaveform wfm = new DigitalWaveform(5, 8, DigitalState.ForceDown);
                        //wfm = NationalInstruments.DigitalWaveform.FromPort(b_array);
                        //stimIvsVWriter.WriteWaveform(true, wfm);
                        if (radioButton_impCurrent.Checked) stimIvsVWriter.WriteSingleSampleSingleLine(true, true);
                        else stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
                        stimIvsVTask.WaitUntilDone();
                        stimIvsVTask.Stop();
                        stimIvsVTask.Dispose();

                        if (!placedzeros)//try again
                        {

                            double[,] AnalogBuffer = new double[stimPulseTask.AOChannels.Count, STIMBUFFSIZE]; // buffer for analog channels
                            UInt32[] DigitalBuffer = new UInt32[STIMBUFFSIZE];

                            stimPulseTask.Stop();
                            stimDigitalTask.Stop();

                            stimPulseWriter.WriteMultiSample(true, AnalogBuffer);
                            stimDigitalWriter.WriteMultiSamplePort(true, DigitalBuffer);

                            //stimPulseTask.Start();

                            //stimDigitalTask.Start();
                            //stimPulseTask.WaitUntilDone();
                            stimPulseTask.Stop();
                            stimDigitalTask.Stop();

                        }
                    }

                    button_stim.Enabled = true;
                    button_stimExpt.Enabled = true;
                    openLoopStart.Enabled = true;
                    radioButton_impCurrent.Enabled = true;
                    radioButton_impVoltage.Enabled = true;
                    radioButton_stimCurrentControlled.Enabled = true;
                    radioButton_stimVoltageControlled.Enabled = true;
                    button_impedanceTest.Enabled = true;
                }
                else
                {
                    button_stim.Enabled = false;
                    button_stimExpt.Enabled = false;
                    openLoopStart.Enabled = false;
                    radioButton_impCurrent.Enabled = false;
                    radioButton_impVoltage.Enabled = false;
                    radioButton_stimCurrentControlled.Enabled = false;
                    radioButton_stimVoltageControlled.Enabled = false;
                    button_impedanceTest.Enabled = false;
                }
            }
            Console.WriteLine("updateStim");
        }
Beispiel #13
0
        // Called when stimulation is stopped
        private void resetStim()
        {
            //Zero out IvsV and dispose
            stimIvsVTask = new Task("stimIvsV");
            stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                ChannelLineGrouping.OneChannelForAllLines);
            stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
            stimIvsVTask.Control(TaskAction.Verify);
            stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
            stimIvsVTask.WaitUntilDone();
            stimIvsVTask.Stop();
            stimIvsVTask.Dispose();

            // Sero out stim digital output and dispose
            if (stimDigitalTask != null)
                stimDigitalTask.Dispose();
            stimDigitalTask = new Task("stimDigitalTask_formClosing");
            if (Properties.Settings.Default.StimPortBandwidth == 32)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
            bool[] fData = new bool[Properties.Settings.Default.StimPortBandwidth];
            stimDigitalWriter.WriteSingleSampleMultiLine(true, fData);
            stimDigitalTask.WaitUntilDone();
            stimDigitalTask.Stop();
            Console.WriteLine("resetStim completed");
        }
        private void button_computeGain_Click(object sender, EventArgs e)
        {
            double startFreq = Convert.ToDouble(numericUpDown_startFreq.Value);
            double stopFreq = Convert.ToDouble(numericUpDown_stopFreq.Value);
            double numPeriods = Convert.ToDouble(numericUpDown_numPeriods.Value);
            double[] freqs = new double[1 + Convert.ToInt32(Math.Floor(Math.Log(stopFreq / startFreq) / Math.Log(Convert.ToDouble(textBox_diagnosticsMult.Text))))]; //This determines the number of frequencies counting by doublings

            radioButton_stimVoltageControlled.Checked = true;
            radioButton_stimVoltageControlled_Click(null, null);

            //Populate freqs vector
            freqs[0] = startFreq;
            for (int i = 1; i < freqs.GetLength(0); ++i)
                freqs[i] = freqs[i - 1] * Convert.ToDouble(textBox_diagnosticsMult.Text);

            spikeSamplingRate = Properties.Settings.Default.RawSampleFrequency;
            buttonStart.Enabled = false;  //So users can't try to get data from the same card
            button_computeGain.Enabled = false;
            button_computeGain.Refresh();
            buttonStart.Refresh();
            spikeTask = new List<Task>(Properties.Settings.Default.AnalogInDevice.Count);
            diagnosticsReaders = new List<AnalogMultiChannelReader>(Properties.Settings.Default.AnalogInDevice.Count);
            for (int i = 0; i < Properties.Settings.Default.AnalogInDevice.Count; ++i)
            {
                spikeTask.Add(new Task("spikeTask_Diagnostics_" + i));
                int numChannelsPerDevice = (numChannels < 32 ? numChannels : 32);
                for (int j = 0; j < numChannelsPerDevice; ++j)
                    spikeTask[i].AIChannels.CreateVoltageChannel(Properties.Settings.Default.AnalogInDevice[0] + "/ai" + j.ToString(), "",
                        AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts);

                //Change gain based on comboBox values (1-100)
                setGain(spikeTask[i], Properties.Settings.Default.A2Dgain);

                //Verify the Task
                spikeTask[i].Control(TaskAction.Verify);

                spikeTask[i].Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples);
                diagnosticsReaders.Add(new AnalogMultiChannelReader(spikeTask[i].Stream));
            }

            spikeTask[0].Timing.ReferenceClockSource = "OnboardClock";
            for (int i = 1; i < spikeTask.Count; ++i)
            {
                spikeTask[i].Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                spikeTask[i].Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
            }
            stimPulseTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
            stimPulseTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;

            stimDigitalTask.Dispose();
            stimDigitalTask = new Task("stimDigitalTask");
            if (Properties.Settings.Default.StimPortBandwidth == 32)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
            stimPulseTask.Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock",
                spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
            stimPulseTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" +
                                Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger",
                                DigitalEdgeStartTriggerEdge.Rising);

            stimDigitalTask.Control(TaskAction.Verify);
            stimPulseTask.Control(TaskAction.Verify);

            switch (Properties.Settings.Default.NumChannels)
            {
                case 0:
                    numChannels = 16;
                    break;
                case 1:
                    numChannels = 32;
                    break;
                case 2:
                    numChannels = 48;
                    break;
                case 3:
                    numChannels = 64;
                    break;
            }
            //gains = new double[numChannels, freqs.GetLength(0)];
            //numChannels = 1;

            gains = new double[numChannels][];
            for (int i = 0; i < numChannels; ++i)
                gains[i] = new double[freqs.GetLength(0)];
            scatterGraph_diagnostics.ClearData();
            scatterGraph_diagnostics.Plots.Clear();

            textBox_diagnosticsResults.Clear();

            if (!checkBox_diagnosticsBulk.Checked)
            {
                //for (int c = 1; c <= numChannels; ++c)
                for (int c = 13; c < 14; ++c)
                {
                    textBox_diagnosticsResults.Text += "Channel " + c.ToString() + "\r\n\tFrequency (Hz)\tGain (dB)\r\n";

                    scatterGraph_diagnostics.Plots.Add(new ScatterPlot());

                    UInt32 data = StimPulse.channel2MUX((double)c); //Get data bits lined up to control MUXes

                    //Setup digital waveform
                    stimDigitalWriter.WriteSingleSamplePort(true, data);
                    stimDigitalTask.WaitUntilDone();
                    stimDigitalTask.Stop();

                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        double numSeconds = 1 / freqs[f];
                        if (numSeconds * numPeriods < 0.1)
                        {
                            numPeriods = Math.Ceiling(0.1 * freqs[f]);
                        }

                        int size = Convert.ToInt32(numSeconds * spikeSamplingRate);
                        SineSignal testWave = new SineSignal(freqs[f], Convert.ToDouble(numericUpDown_diagnosticsVoltage.Value));  //Generate a 100 mV sine wave at 1000 Hz
                        double[] testWaveValues = testWave.Generate(spikeSamplingRate, size);

                        double[,] analogPulse = new double[2, size];

                        for (int i = 0; i < size; ++i)
                            analogPulse[0, i] = testWaveValues[i];

                        for (int i = 0; i < spikeTask.Count; ++i)
                            spikeTask[i].Timing.SamplesPerChannel = (long)(numPeriods * size);

                        stimPulseTask.Timing.SamplesPerChannel = (long)(numPeriods * size); //Do numperiods cycles of sine wave
                        stimPulseWriter.WriteMultiSample(true, analogPulse);

                        double[] stateData = new double[4];
                        stateData[0] = (double)c;
                        stateData[1] = freqs[f];
                        stateData[2] = (double)f;
                        for (int i = diagnosticsReaders.Count - 1; i >= 0; --i)
                        {
                            stateData[3] = (double)i;
                            diagnosticsReaders[i].BeginReadMultiSample((int)(numPeriods * size), analogInCallback_computeGain, (Object)stateData); //Get 5 seconds of "noise"
                        }

                        stimPulseTask.WaitUntilDone();
                        for (int i = 0; i < spikeTask.Count; ++i)
                        {
                            spikeTask[i].WaitUntilDone();
                            spikeTask[i].Stop();
                        }
                        stimPulseTask.Stop();
                    }
                    stimDigitalWriter.WriteSingleSamplePort(true, 0);
                    stimDigitalTask.WaitUntilDone();
                    stimDigitalTask.Stop();
                    //DEBUGGING
                    c = 1;
                    scatterGraph_diagnostics.Plots[c - 1].PlotXY(freqs, gains[c - 1]);
                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        textBox_diagnosticsResults.Text += "\t" + freqs[f].ToString() + "\t" + gains[c - 1][f] + "\r\n";
                    }
                    textBox_diagnosticsResults.Text += "\r\n";
                    scatterGraph_diagnostics.Refresh();

                    //DEBUGGING
                    c = 100;
                }
            }
            else
            {
                for (int f = 0; f < freqs.GetLength(0); ++f)
                {
                    double numSeconds = 1 / freqs[f];
                    if (numSeconds * numPeriods < 0.1)
                    {
                        numPeriods = Math.Ceiling(0.1 * freqs[f]);
                    }

                    int size = Convert.ToInt32(numSeconds * spikeSamplingRate);
                    SineSignal testWave = new SineSignal(freqs[f], Convert.ToDouble(numericUpDown_diagnosticsVoltage.Value));  //Generate a 100 mV sine wave at 1000 Hz
                    double[] testWaveValues = testWave.Generate(spikeSamplingRate, size);

                    double[,] analogPulse = new double[2, size];

                    for (int i = 0; i < size; ++i)
                        analogPulse[0, i] = testWaveValues[i];

                    for (int i = 0; i < spikeTask.Count; ++i)
                        spikeTask[i].Timing.SamplesPerChannel = (long)(numPeriods * size);

                    stimPulseTask.Timing.SamplesPerChannel = (long)(numPeriods * size); //Do numperiods cycles of sine wave
                    stimPulseWriter.WriteMultiSample(true, analogPulse);

                    double[] stateData = new double[4];
                    stateData[0] = -1.0;
                    stateData[1] = freqs[f];
                    stateData[2] = (double)f; //Frequency of interest

                    for (int i = diagnosticsReaders.Count - 1; i >= 0; --i)
                    {
                        stateData[3] = (double)i; //Keeps track of which device called the reader
                        diagnosticsReaders[i].BeginReadMultiSample((int)(numPeriods * size), analogInCallback_computeGain, (Object)stateData); //Get 5 seconds of "noise"
                    }

                    stimPulseTask.WaitUntilDone();
                    for (int i = 0; i < spikeTask.Count; ++i)
                    {
                        spikeTask[i].WaitUntilDone();
                        spikeTask[i].Stop();
                    }
                    stimPulseTask.Stop();
                }
                for (int c = 0; c < numChannels; ++c)
                {
                    scatterGraph_diagnostics.Plots.Add(new ScatterPlot());
                    scatterGraph_diagnostics.Plots[c].PlotXY(freqs, gains[c]);
                    textBox_diagnosticsResults.Text += "Channel " + (c + 1).ToString() + "\r\n\tFrequency (Hz)\tGain (dB)\r\n";
                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        textBox_diagnosticsResults.Text += "\t" + freqs[f].ToString() + "\t" + gains[c][f].ToString() + "\r\n";
                    }
                    textBox_diagnosticsResults.Text += "\r\n";
                }
                scatterGraph_diagnostics.Refresh();
            }
            buttonStart.Enabled = true;
            button_computeGain.Enabled = true;

            //Now, destroy the objects we made
            updateSettings();
            gains = null;
            diagnosticsReaders = null;
        }