コード例 #1
0
    def test_one_sample(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        # Select a random loopback channel pair on the device.
        loopback_channel_pairs = self._get_analog_loopback_channels(
            x_series_device)
        loopback_channel_pair = random.choice(loopback_channel_pairs)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task:
            write_task.ao_channels.add_ao_voltage_chan(
                loopback_channel_pair.output_channel, max_val=10, min_val=-10)

            read_task.ai_channels.add_ai_voltage_chan(
                loopback_channel_pair.input_channel, max_val=10, min_val=-10)

            writer = AnalogSingleChannelWriter(write_task.out_stream)
            reader = AnalogSingleChannelReader(read_task.in_stream)

            # Generate random values to test.
            values_to_test = [random.uniform(-10, 10) for _ in range(10)]

            values_read = []
            for value_to_test in values_to_test:
                writer.write_one_sample(value_to_test)
                time.sleep(0.001)

                value_read = reader.read_one_sample()
                assert isinstance(value_read, float)
                values_read.append(value_read)

            numpy.testing.assert_allclose(
                values_read, values_to_test, rtol=0.05, atol=0.005)
コード例 #2
0
    def test_many_sample(self, x_series_device, seed):
        # Reset the pseudorandom number generator with seed.
        random.seed(seed)

        number_of_samples = random.randint(20, 100)
        sample_rate = random.uniform(1000, 5000)

        # Select a random loopback channel pair on the device.
        loopback_channel_pairs = self._get_analog_loopback_channels(
            x_series_device)
        loopback_channel_pair = random.choice(loopback_channel_pairs)

        with nidaqmx.Task() as write_task, nidaqmx.Task() as read_task, \
                nidaqmx.Task() as sample_clk_task:

            # Use a counter output pulse train task as the sample clock source
            # for both the AI and AO tasks.
            sample_clk_task.co_channels.add_co_pulse_chan_freq(
                '{0}/ctr0'.format(x_series_device.name), freq=sample_rate)
            sample_clk_task.timing.cfg_implicit_timing(
                samps_per_chan=number_of_samples)

            samp_clk_terminal = '/{0}/Ctr0InternalOutput'.format(
                x_series_device.name)

            write_task.ao_channels.add_ao_voltage_chan(
                loopback_channel_pair.output_channel, max_val=10, min_val=-10)
            write_task.timing.cfg_samp_clk_timing(
                sample_rate, source=samp_clk_terminal, active_edge=Edge.RISING,
                samps_per_chan=number_of_samples)

            read_task.ai_channels.add_ai_voltage_chan(
                loopback_channel_pair.input_channel, max_val=10, min_val=-10)
            read_task.timing.cfg_samp_clk_timing(
                sample_rate, source=samp_clk_terminal,
                active_edge=Edge.FALLING, samps_per_chan=number_of_samples)

            writer = AnalogSingleChannelWriter(write_task.out_stream)
            reader = AnalogSingleChannelReader(read_task.in_stream)

            # Generate random values to test.
            values_to_test = numpy.array(
                [random.uniform(-10, 10) for _ in range(number_of_samples)],
                dtype=numpy.float64)
            writer.write_many_sample(values_to_test)

            # Start the read and write tasks before starting the sample clock
            # source task.
            read_task.start()
            write_task.start()
            sample_clk_task.start()

            values_read = numpy.zeros(number_of_samples, dtype=numpy.float64)
            reader.read_many_sample(
                values_read, number_of_samples_per_channel=number_of_samples,
                timeout=2)

            numpy.testing.assert_allclose(
                values_read, values_to_test, rtol=0.05, atol=0.005)
コード例 #3
0
    def run(self):
        """
        Starts writing a waveform continuously while reading 
        the buffer periodically
        """

        #DAQ
        with nidaqmx.Task() as slave_Task3, nidaqmx.Task() as master_Task:
            #slave_Task3 = nidaqmx.Task()
            slave_Task3.ao_channels.add_ao_voltage_chan("/Dev1/ao0:1")
            master_Task.ai_channels.add_ai_voltage_chan("/Dev1/ai0")

            slave_Task3.timing.cfg_samp_clk_timing(
                rate=self.sampleRate,
                source='ai/SampleClock',
                sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS)

            # Analoginput
            master_Task.timing.cfg_samp_clk_timing(
                rate=self.sampleRate,
                sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS,
                samps_per_chan=self.readNumber)

            reader = AnalogSingleChannelReader(master_Task.in_stream)
            writer = AnalogMultiChannelWriter(slave_Task3.out_stream)

            reader.auto_start = False
            writer.auto_start = False

            writer.write_many_sample(self.wave)
            """Reading data from the buffer in a loop. 
            The idea is to let the task read more than could be loaded in the buffer for each iteration.
            This way the task will have to wait slightly longer for incoming samples. And leaves the buffer
            entirely clean. This way we always know the correct numpy size and are always left with an empty
            buffer (and the buffer will not slowly fill up)."""
            output = np.zeros(self.readNumber)
            slave_Task3.start(
            )  #Will wait for the readtask to start so it can use its clock
            master_Task.start()
            while not self.isInterruptionRequested():
                reader.read_many_sample(
                    data=output, number_of_samples_per_channel=self.readNumber)

                #Emiting the data just received as a signal

                Dataholder_average = np.mean(output.reshape(
                    self.averagenumber, -1),
                                             axis=0)

                self.data_PMT = np.reshape(
                    Dataholder_average,
                    (self.ypixelnumber, self.ScanArrayXnum))

                if self.ypixelnumber == 500:
                    self.data_PMT = self.data_PMT[:, 50:550] * -1
                elif self.ypixelnumber == 256:
                    self.data_PMT = self.data_PMT[:, 70:326] * -1

                self.measurement.emit(self.data_PMT)
コード例 #4
0
def read_single_data(port='Dev1/ai0', sample_rate=100):
    from nidaqmx.stream_readers import AnalogSingleChannelReader
    from nidaqmx._task_modules.in_stream import InStream
    data_list = []
    config_task = config_for_task(name_task='Task read I signal', frequency=sample_rate, port=port)
    instream_analog_task = AnalogSingleChannelReader(InStream(config_task))
    data_read = instream_analog_task.read_one_sample(timeout=10)
    data_list.append(data_read)
    config_task.close()
    return data_list
コード例 #5
0
    def __init__(self, *args, read_task, write_task_z, write_task_xy):
        super().__init__(*args)
        self.read_task = read_task
        self.write_task_xy = write_task_xy
        self.write_task_z = write_task_z

        self.z_writer = AnalogMultiChannelWriter(write_task_z.out_stream)
        self.xy_writer = AnalogMultiChannelWriter(write_task_xy.out_stream)
        self.z_reader = AnalogSingleChannelReader(read_task.in_stream)

        self.xy_array = np.zeros((2, self.n_samples))
        self.z_array = np.zeros((4, self.n_samples))

        self.read_array = np.zeros(self.n_samples)

        self.setup_tasks()
def configureDAQ(Nsamples):
    try:
        #Create and configure an analog input voltage task
        NsampsPerDAQread = 2 * Nsamples
        readTask = nidaqmx.Task()
        channel = readTask.ai_channels.add_ai_voltage_chan(DAQ_APDInput)

        #Configure sample clock
        readTask.timing.cfg_samp_clk_timing(DAQ_MaxSamplingRate, DAQ_SampleClk,
                                            Edge.RISING,
                                            AcquisitionType.CONTINUOUS,
                                            NsampsPerDAQread)

        #Configure convert clock
        readTask.timing.ai_conv_src = DAQ_SampleClk
        readTask.timing.ai_conv_active_edge = Edge.RISING

        #Configure start trigger
        readStartTrig = readTask.triggers.start_trigger
        readStartTrig.cfg_dig_edge_start_trig(DAQ_StartTrig, Edge.RISING)

        #Create a reader from stream reading
        reader = AnalogSingleChannelReader(readTask.in_stream)

    except Exception as excpt:
        print(
            'Error configuring DAQ. Please check your DAQ is connected and powered. Exception details:',
            type(excpt).__name__, '.', excpt)
        closeDAQTask(task)
        sys.exit()

    return readTask, reader
コード例 #7
0
 def readPXIDataTask(self):
     with nidaqmx.Task() as task:
         chan0 = task.ai_channels.add_ai_voltage_chan(
             self.__settings.readChannels(),
             terminal_config=TerminalConfiguration.DIFFERENTIAL,
             min_val=float(self.__settings.readMinVal()),
             max_val=float(self.__settings.readMaxVal()),
             units=VoltageUnits.VOLTS)
         chan0.ai_coupling = coupling[self.__couplingCob.currentText()]
         task.timing.cfg_samp_clk_timing(
             self.__settings.readSampleFreq(),
             source="",
             active_edge=edge[self.__settings.readActiveEdge()],
             sample_mode=acquisitiontype[self.__settings.readSampleMode()],
             samps_per_chan=self.__settings.readSamplesPerChan())
         # TODO 保存数据并显示
         # TODO 管理员权限测试
         data = np.ndarray((1, self.__settings.readSamplesPerFile()),
                           dtype=np.float64)
         AnalogSingleChannelReader(task.in_stream).read_many_sample(
             data,
             self.__settings.readSamplesPerFile(),
             timeout=nidaqmx.constants.WAIT_INFINITELY)
         # TODO 绘图
         self.signalReadPXIData.emit(
             np.arange(self.__settings.readSamplesPerFile()), data)
         np.savetxt("%s" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    data)
コード例 #8
0
 def add_test_ai_chan(self, channel):
     if channel not in self.ai_chan:
         test_task = nidaqmx.Task()
         channel_name = self.name + '/ai' + str(channel)
         test_task.ai_channels.add_ai_voltage_chan(
             channel_name, terminal_config=TerminalConfiguration.RSE)
         reader = AnalogSingleChannelReader(test_task.in_stream)
         return reader
コード例 #9
0
    def __init__(self, parent):
        from nidaqmx.stream_readers import AnalogSingleChannelReader
        from nidaqmx._task_modules.in_stream import InStream
        super(DisplayHrRr, self).__init__(parent)
        ui_path = str(pathlib.Path(__file__).parent) + "\\display.ui"
        self.ui = uic.loadUi(ui_path, self)

        info = read_config_file()
        configed_task = Task('Task read I signal')
        configed_task.ai_channels.add_ai_voltage_chan(info['port'])
        configed_task.timing.cfg_samp_clk_timing(
            rate=100,
            source=u'',
            active_edge=Edge.RISING,
            sample_mode=AcquisitionType.FINITE,
            samps_per_chan=1500)

        self.data_raw = np.zeros(shape=(1500, ))
        self.instream_analog_task = AnalogSingleChannelReader(
            InStream(configed_task))

        # init
        self.progress.setValue(0)
        self.init_state_button()

        self.button_auto.clicked.connect(self.button_auto_event)
        self.button_manual.clicked.connect(self.button_manual_event)
        self.button_refresh.clicked.connect(self.refresh)

        # click predict
        self.combobox_mode.addItems(["Tự động", "Thủ công"])
        self.manual_mode = False
        self.combobox_mode.currentIndexChanged.connect(self.update_mode)

        # event button
        self.button_predict.clicked.connect(self.predict)

        #thread read data temp
        import threading
        import src.utils.read_data_temp as rdt
        thread_read_data = threading.Thread(target=rdt.read_data_temp,
                                            daemon=True)
        thread_read_data.start()
コード例 #10
0
    def makeSinglePic(self, writeTask, readTask):
        #Check if the measurement is possible and execute
        if self.checkMeasurement():
            self.writeTask.timing.cfg_samp_clk_timing(
                rate=self.sampleRate,
                sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
                samps_per_chan=self.outputData.size)
            self.readTask.timing.cfg_samp_clk_timing(
                rate=self.sampleRate,
                sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
                samps_per_chan=self.inputData.size)

            reader = AnalogSingleChannelReader(self.readTask.in_stream)
            writer = AnalogMultiChannelWriter(self.writeTask.out_stream)

            estT = self.outputData.size / self.sampleRate
            writer.write_many_sample(self.outputData)

            self.writeTask.start()
            reader.read_many_sample(self.inputData, timeout=estT + 5)

            return self.inputData
コード例 #11
0
 def __init__(self):
     """Assumes first device by default."""
     self.system = nidaqmx.system.System.local()
     self.task = nidaqmx.Task()
     self.sampleSize = 100
     self.buffer = numpy.zeros(self.sampleSize)
     self.reader = ASCR(self.task.in_stream)
     if len(self.system.devices) > 0:
         self.device = self.system.devices[0]
     else:
         raise RuntimeError("NIDAQmx device not found during init." \
         + " Please make sure a NI device is connected.")
     self.devAddr = self.device.name + '/ai0'
コード例 #12
0
def calibrate(sRate, aiChan, aoChan, xValues):
    writingRate = sRate
    readingRate = writingRate
    outputData = xValues
    inputData = np.zeros(outputData.size + 1)

    with nidaqmx.Task() as writeTask, nidaqmx.Task() as readTask:
        writeTask.ao_channels.add_ao_voltage_chan(aoChan)
        readTask.ai_channels.add_ai_voltage_chan(aiChan)

        #In the USB6001 DAQ there seems to be no SampleClock, therefore we cannot sync the signals without an external trigger/clock
        #sample_clock = '/Dev2/ai/SampleClock'

        writeTask.timing.cfg_samp_clk_timing(
            rate=writingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS,
            samps_per_chan=outputData.size)
        readTask.timing.cfg_samp_clk_timing(
            rate=readingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
            samps_per_chan=inputData.size)
        #writeTask.triggers.start_trigger.cfg_dig_edge_start_trig(trigger_source = '/Dev2/ai/StartTrigger') #Setting the trigger on the analog input
        #readTask.triggers.start_trigger.cfg_dig_edge_start_trig(trigger_source = '/Dev2/ao/StartTrigger')

        reader = AnalogSingleChannelReader(readTask.in_stream)
        writer = AnalogSingleChannelWriter(writeTask.out_stream)

        writer.write_many_sample(outputData)
        writeTask.start()
        reader.read_many_sample(inputData,
                                timeout=outputData.size / readingRate + 4)

    #The ai/StartTrigger 'takes' one sample from writing so the actual writing starts one sample later, therefore the inputData starts one sample later
    inputData = inputData[1::]

    return outputData, inputData
コード例 #13
0
def read_data_continously(port='Dev1/ai0', sample_rate=100, time_in_seconds=30, name_file=''):
    """
    :param sample_rate: in Hz
    :param time_to_seconds: in seconds
    :param file_path: path to excel file
    :return: log data to a file
    """
    import datetime
    from nidaqmx.stream_readers import AnalogSingleChannelReader
    from nidaqmx._task_modules.in_stream import InStream
    import src.utils.file_utils as file_utils
    start_time = datetime.datetime.now().timestamp()
    data_list = []
    config_task = config_for_task(name_task='Task read I signal', frequency=sample_rate, port=port)
    instream_analog_task = AnalogSingleChannelReader(InStream(config_task))
    while True:
        data_read = instream_analog_task.read_one_sample(timeout=10)
        data_list.append(data_read)
        end_time = datetime.datetime.now().timestamp()
        if (end_time - start_time) >= time_in_seconds:
            break

    config_task.close()
    file_utils.write_to_csv_file(data=data_list, name_file=name_file)
コード例 #14
0
    def __init__(self, parent, frame_rate, sample_rate, spectrogram_settings,
                 address):

        self.sample_rate = int(sample_rate)
        self.parent = parent
        self.parse_settings(spectrogram_settings)

        AcquisitionObject.__init__(self, parent, self.run_rate,
                                   (int(self.sample_rate // self.run_rate), 1),
                                   address)

        # TODO: verify that we are not violating the task state model: https://zone.ni.com/reference/en-XX/help/370466AH-01/mxcncpts/taskstatemodel/
        # specifically, if we change logging mode, do we need to re-commit the task??

        # set up the audio task
        self.audio_task = nidaqmx.Task()
        self.audio_task.ai_channels.add_ai_voltage_chan(AUDIO_INPUT_CHANNEL)
        # self.audio.ai_channels[AUDIO_INPUT_CHANNEL].ai_gain = int(AUDIO_INPUT_GAIN) #TODO: (how) does this work?
        self.audio_task.timing.cfg_samp_clk_timing(
            self.sample_rate,
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS)
        self.audio_task.in_stream.input_buf_size = self.sample_rate * PC_BUFFER_TIME_IN_SECONDS
        self.audio_task.control(nidaqmx.constants.TaskMode.TASK_COMMIT)
        self._audio_reader = AnalogReader(self.audio_task.in_stream)

        # set up the trigger task
        self.trigger_freq = frame_rate

        self.trigger_task = nidaqmx.Task()
        self.trigger_task.co_channels.add_co_pulse_chan_freq(
            TRIGGER_OUTPUT_CHANNEL,
            freq=self.trigger_freq,
            duty_cycle=DUTY_CYCLE)
        self.trigger_task.triggers.start_trigger.cfg_dig_edge_start_trig(
            f"/{AUDIO_INPUT_CHANNEL[:-1]}/StartTrigger"
        )  # start the video trigger with the audio channel
        self.trigger_task.timing.cfg_implicit_timing(
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS
        )  # configure the trigger to repeat until the task is stopped
        self.trigger_task.control(nidaqmx.constants.TaskMode.TASK_COMMIT)

        self._log_mode = [False, False]  # [isLogging, isDisplaying]
コード例 #15
0
        plt.plot(a0[1:-1]-a1[0:-2])
        plt.plot(a0)
        dt_sample = 1/(2*3*frec_de_rampa) * np.mean(np.abs(diferencias))
        return dt_sample*1e6

#fig, (ax1, ax2) = plt.subplots(1, 2, num = 'rampa y difs')
#ax1.plot(a0)
#ax2.plot(np.diff(a))

#np.save('D:\\Intrumentacion_fersammar\\20181017\\rampa_a_500hz_2_canales.npy', a)

#%%
data_values = np.zeros(100)
with nidaqmx.Task() as read_task:
     read_task.ai_channels.add_ai_voltage_chan('Dev1/ai0',terminal_config = nidaqmx.constants.TerminalConfiguration.RSE)
     reader = AnalogSingleChannelReader(read_task.in_stream)
     print(read_task.in_stream.input_buf_size)
     value_read = reader.read_many_sample(data_values, 100)
     

#%% 
def measure_sample_time_1_channel(frec_de_rampa, frecuencia_de_muestreo, fs=44100):
    """
    esto es para medir tiempo entre puntos medidos adyacentes de un solo canal
    Esta funcion devuelve el tiempo de adquisicon en un canal en us
    fs: Frecuencia de muestreo de la placa de audio para la funcion play_sawtooth
    """
    duracion = 1024/frecuencia_de_muestreo+2
    play_sawtooth(frec_de_rampa, duracion, fs=44100, wait=False)
    time.sleep(1)
    with nidaqmx.Task() as read_task:
コード例 #16
0
    def start(self):
        # settings for scanning index
        position_index=[]
        row_start = self.UI_row_start_stagescan #position index start number
        row_end = self.UI_row_end_stagescan #end number
        
        column_start = self.UI_column_start_stagescan
        column_end = self.UI_column_end_stagescan
        
        step = self.UI_step_stagescan #length of each step, 1500 for -5~5V FOV
        
        #Settings for A/D output
        Daq_sample_rate = self.UI_Daq_sample_rate_stagescan
        
        #Scanning settings
        Value_voltXMin = self.UI_voltXMin_stagescan
        Value_voltXMax = self.UI_voltXMax_stagescan
        Value_voltYMin = self.UI_voltYMin_stagescan
        Value_voltYMax = self.UI_voltYMax_stagescan
        Value_xPixels = self.UI_Value_xPixels_stagescan
        Value_yPixels = self.UI_Value_yPixels_stagescan
        averagenum =self.UI_Value_averagenum_stagescan
        #Generate galvo samples
        samples_1, samples_2= wavegenerator.waveRecPic(sampleRate = Daq_sample_rate, imAngle = 0, voltXMin = Value_voltXMin, voltXMax = Value_voltXMax, 
                         voltYMin = Value_voltYMin, voltYMax = Value_voltYMax, xPixels = Value_xPixels, yPixels = Value_yPixels, 
                         sawtooth = True)
        #ScanArrayX = wavegenerator.xValuesSingleSawtooth(sampleRate = Daq_sample_rate, voltXMin = Value_voltXMin, voltXMax = Value_voltXMax, xPixels = Value_xPixels, sawtooth = True)
        Totalscansamples = len(samples_1)*averagenum # Calculate number of samples to feed to scanner, by default it's one frame 
        ScanArrayXnum = int (len(samples_1)/Value_yPixels) # number of samples of each individual line of x scanning
        Galvo_samples = np.vstack((samples_1,samples_2)) #
        
            
            
        #generate dig samples
        One_Dig_samples = np.append(np.ones(25000,dtype=bool), np.zeros(25000,dtype=bool))
        Dig_repeat_times = int(Totalscansamples/len(One_Dig_samples))
        Dig_samples = []
        for i in range(Dig_repeat_times):
            Dig_samples = np.append(Dig_samples, One_Dig_samples)
            
        Dataholder = np.zeros(Totalscansamples)
        
        
        
        with nidaqmx.Task() as slave_Task3, nidaqmx.Task() as master_Task, nidaqmx.Task() as slave_Task2:
            #slave_Task3 = nidaqmx.Task()
            slave_Task3.ao_channels.add_ao_voltage_chan("/Dev1/ao0:1")
            master_Task.ai_channels.add_ai_voltage_chan("/Dev1/ai0")
            slave_Task2.do_channels.add_do_chan("/Dev1/port0/line25")
            
            #slave_Task3.ao_channels.add_ao_voltage_chan("/Dev1/ao1")
            # MultiAnalogchannels
            slave_Task3.timing.cfg_samp_clk_timing(Daq_sample_rate, source='ai/SampleClock', sample_mode= AcquisitionType.FINITE, samps_per_chan=Totalscansamples)
            slave_Task3.triggers.sync_type.SLAVE = True
            
            # Analoginput
            master_Task.timing.cfg_samp_clk_timing(Daq_sample_rate, sample_mode= AcquisitionType.FINITE, samps_per_chan=Totalscansamples)
            master_Task.triggers.sync_type.MASTER = True
            
            # Digital output
            slave_Task2.timing.cfg_samp_clk_timing(Daq_sample_rate, source='ai/SampleClock', sample_mode= AcquisitionType.FINITE, samps_per_chan=Totalscansamples)
            slave_Task2.triggers.sync_type.SLAVE = True
            
            AnalogWriter = nidaqmx.stream_writers.AnalogMultiChannelWriter(slave_Task3.out_stream, auto_start= False)
            AnalogWriter.auto_start = False
            DigitalWriter = nidaqmx.stream_writers.DigitalSingleChannelWriter(slave_Task2.out_stream, auto_start= False)
            DigitalWriter.auto_start = False
            reader = AnalogSingleChannelReader(master_Task.in_stream)
                
            time.sleep(2)
            
            RepeatNum = 0
            Data_dict_0 = {}
            loopnum = 0        
            for i in range(row_start, row_end, step):
                position_index.append(i)
                for j in range(column_start, column_end, step):
                    position_index.append(j)
                    print ('-----------------------------------')
                    print (position_index)
                    
                    #stage movement
                    self.ludlStage.moveAbs(i,j)
                    time.sleep(1)
                    
                    AnalogWriter .write_many_sample(Galvo_samples, timeout=16.0)
                    DigitalWriter.write_one_sample_one_line(Dig_samples, timeout=16.0)
                    
                    slave_Task3.start()
                    slave_Task2.start()
                    reader.read_many_sample(Dataholder, number_of_samples_per_channel =  Totalscansamples, timeout=16.0)
                    Dataholder_average = np.mean(Dataholder.reshape(averagenum, -1), axis=0)
                    data1 = np.reshape(Dataholder_average, (Value_yPixels, ScanArrayXnum))
                    
                    slave_Task3.wait_until_done()
                    slave_Task2.wait_until_done()
                    master_Task.wait_until_done()
                    
                    Pic_name =str(i)+str(j)
                    print('Picture index name:'+str(RepeatNum)+'|'+str(i)+'|'+str(j))
                    Data_dict_0[Pic_name] = data1[:,:Value_yPixels]*-1
                    Localimg = Image.fromarray(Data_dict_0[Pic_name]) #generate an image object
                    Localimg.save(str(RepeatNum)+Pic_name+'out_1st.tif') #save as tif
                    
                    plt.figure(loopnum)
                    plt.imshow(Data_dict_0[Pic_name], cmap = plt.cm.gray)
                    plt.show()
                    
                    
                    slave_Task3.stop()
                    master_Task.stop()
                    slave_Task2.stop()
                    
                    time.sleep(1)
                   
                    self.ludlStage.getPos()
                    loopnum = loopnum+1
                    
                    
                    del position_index[-1]
                    print ('---------------^^^^---------------')
                position_index=[]
            print ('Finish round 1')
            
            time.sleep(1) 
            
            self.ludlStage.moveAbs(row_start,column_start) #move to the start as preparation
            time.sleep(2)
            input("Press Enter to continue...")
            
            Data_dict_1 = {} #dictionary for images
            All_cell_properties_dict = {}
            All_cell_properties = []
            cp_end_index = -1
            cp_index_dict = {} #dictionary for each cell properties
            
            RepeatNum = 1
            loopnum = 0        
            for i in range(row_start, row_end, step):
                position_index.append(i)
                for j in range(column_start, column_end, step):
                    position_index.append(j)
                    print ('----(´・ω・`)---------vvv-Start-vvv-------(´・ω・`)--------')
                    print (position_index)
                    
                    #stage movement
                    self.ludlStage.moveAbs(i,j)
                    time.sleep(1)
                    
                    AnalogWriter .write_many_sample(Galvo_samples, timeout=16.0)
                    DigitalWriter.write_one_sample_one_line(Dig_samples, timeout=16.0)
                    
                    slave_Task3.start()
                    slave_Task2.start()
                    reader.read_many_sample(Dataholder, number_of_samples_per_channel =  Totalscansamples, timeout=16.0)
                    Dataholder_average = np.mean(Dataholder.reshape(averagenum, -1), axis=0)
                    data1 = np.reshape(Dataholder_average, (Value_yPixels, ScanArrayXnum))
                    
                    slave_Task3.wait_until_done()
                    slave_Task2.wait_until_done()
                    master_Task.wait_until_done()
                    
                    Pic_name = str(i)+str(j)
                    print('Picture index name:'+str(RepeatNum)+'|'+str(i)+'|'+str(j))
                    Data_dict_1[Pic_name] = data1[:,:Value_yPixels]*-1
                    Localimg = Image.fromarray(Data_dict_1[Pic_name]) #generate an image object
                    Localimg.save(str(RepeatNum)+Pic_name+'out.tif') #save as tif
                    plt.figure(loopnum)
                    plt.imshow(Data_dict_1[Pic_name], cmap = plt.cm.gray)
                    plt.show()
                    time.sleep(1)
                    # Image processing
                    #kkk = Data_dict_1[Pic_name]/Data_dict_0[Pic_name]
                    S = ImageAnalysis(Data_dict_0[Pic_name], Data_dict_1[Pic_name])
                    v1, v2, bw, thres = S.applyMask()
                    #R = S.ratio(v1, v2)
                    L, cp, coutourmask, coutourimg, sing = S.get_intensity_properties(100, bw, v2, thres, v2, i, j, 7)
                    S.showlabel(100, bw, v2, thres, i, j, cp)
                    #print (L)
                    print (cp)
                    All_cell_properties_dict[loopnum] = cp
                    if loopnum == 0:
                        All_cell_properties = All_cell_properties_dict[0]
                    if loopnum != 0:
                        All_cell_properties = np.append(All_cell_properties, All_cell_properties_dict[loopnum], axis=0)
                    
                    cp_end_index = cp_end_index + len(cp)
                    cp_start_index = cp_end_index - len(cp) +1
                    cp_index_dict[Pic_name] = [cp_start_index, cp_end_index] #get the location of individual cp index & put in dictionary, as they are stored in sequence.
                    
                    time.sleep(2)
                    
                    slave_Task3.stop()
                    master_Task.stop()
                    slave_Task2.stop()
                    
                    time.sleep(1)
                   
                    self.ludlStage.getPos()
                    loopnum = loopnum+1
                    
                    
                    del position_index[-1]
                    print ('-----(⊙⊙!)-----^^^^END^^^------结束-----')
                position_index=[]
            
            print ('End of round 2')
            #print(All_cell_properties)
            
            time.sleep(2)
            #Sorting and trace back
            original_dtype = np.dtype(All_cell_properties.dtype.descr + [('Original_sequence', '<i4')])
            original_cp = np.zeros(All_cell_properties.shape, dtype=original_dtype)
            original_cp['Row index'] = All_cell_properties['Row index']
            original_cp['Column index'] = All_cell_properties['Column index']
            original_cp['Mean intensity'] = All_cell_properties['Mean intensity']
            original_cp['Circularity'] = All_cell_properties['Circularity']
            original_cp['Mean intensity in contour'] = All_cell_properties['Mean intensity in contour']
            original_cp['Original_sequence'] = list(range(0, len(All_cell_properties)))
            
            #print (original_cp['Mean intensity in contour'])
            #print('*********************sorted************************')
            #sort
            sortedcp = np.flip(np.sort(original_cp, order='Mean intensity in contour'), 0)
            selected_num = 10 #determine how many we want
            #unsorted_cp = All_cell_properties[:selected_num]
            #targetcp = sortedcp[:selected_num]
            
            rank_dtype = np.dtype(sortedcp.dtype.descr + [('Ranking', '<i4')])
            ranked_cp = np.zeros(sortedcp.shape, dtype=rank_dtype)
            ranked_cp['Row index'] = sortedcp['Row index']
            ranked_cp['Column index'] = sortedcp['Column index']
            ranked_cp['Mean intensity'] = sortedcp['Mean intensity']
            ranked_cp['Circularity'] = sortedcp['Circularity']
            ranked_cp['Mean intensity in contour'] = sortedcp['Mean intensity in contour']
            ranked_cp['Original_sequence'] = sortedcp['Original_sequence']
            ranked_cp['Ranking'] = list(range(0, len(All_cell_properties)))
            
            withranking_cp = np.sort(ranked_cp, order='Original_sequence')
            
            #print (ranked_cp)
            #print('***********************Original sequence with ranking**************************')
            
            # All the cells are ranked, now we find the desired group and their position indexs, call the images and show labels of
            # these who meet the requirements, omitting bad ones.
            
            #get the index
            cell_properties_selected_hits = ranked_cp[0:selected_num]
            cell_properties_selected_hits_index_sorted = np.sort(cell_properties_selected_hits, order=['Row index', 'Column index'])
            index_samples = np.vstack((cell_properties_selected_hits_index_sorted['Row index'],cell_properties_selected_hits_index_sorted['Column index']))
            
            merged_index_samples = index_samples[:,0]

            #consider these after 1st one
            for i in range(1, len(index_samples[0])):
                #print(index_samples[:,i][0] - index_samples[:,i-1][0])    
                if index_samples[:,i][0] != index_samples[:,i-1][0] or index_samples[:,i][1] != index_samples[:,i-1][1]: 
                    merged_index_samples = np.append(merged_index_samples, index_samples[:,i], axis=0)
            merged_index_samples = merged_index_samples.reshape(-1, 2) # 1st column=i, 2nd column=j
            
            # then we move back to each of this positions and show the labels
            input("Press Enter to continue...")
            print(merged_index_samples)
            print(withranking_cp)

            for i in range(len(merged_index_samples)):
                print ('-----------------------------------')
                    
                #stage movement
                self.ludlStage.moveAbs(merged_index_samples[i,:].tolist()[0],merged_index_samples[i,:].tolist()[1])
                time.sleep(1)
                    
                Pic_name_trace = str(merged_index_samples[i,:].tolist()[0])+str(merged_index_samples[i,:].tolist()[1])
                    
                S = ImageAnalysis(Data_dict_0[Pic_name_trace], Data_dict_1[Pic_name_trace]) #The same as ImageAnalysis(Data_dict_0[Pic_name], Data_dict_1[Pic_name]), call the same image with same dictionary index.
                v1, v2, bw, thres = S.applyMask()
                S.showlabel_with_rank(100, bw, v2, cp_index_dict[Pic_name_trace][0], cp_index_dict[Pic_name_trace][1], withranking_cp, 'Mean intensity in contour', 10)
                print ( ' i: '+ str(merged_index_samples[i,:].tolist()[0]) + ' j: '+ str(merged_index_samples[i,:].tolist()[1]))
                print ('-----------------------------------')
                input("Press Enter to continue...")
コード例 #17
0
import numpy as np
import src.utils.file_utils as file_utils
data_raw = np.zeros(shape=(6000, ))

if __name__ == "__main__":

    configed_task = task.Task('Task read I signal')
    configed_task.ai_channels.add_ai_voltage_chan('Dev1/ai0')
    configed_task.timing.cfg_samp_clk_timing(
        rate=100,
        source=u'',
        active_edge=Edge.RISING,
        sample_mode=AcquisitionType.FINITE,
        samps_per_chan=6000)

    instream_analog_task = AnalogSingleChannelReader(InStream(configed_task))
    instream_analog_task.read_many_sample(data=data_raw,
                                          number_of_samples_per_channel=6000,
                                          timeout=100)
    file_path = 'E:\\python_project\\hoang\data\\data_test.csv'
    file_utils.write_to_csv_file(data_raw, file_path)

    import matplotlib.pyplot as plt
    import numpy as np
    peaks = btwf.find_hr(data_raw)
    peaks2 = btwf.find_rr(data_raw)
    HR = btwf.butter_bandpass_filter(data_raw)
    RR = btwf.butter_lowpass_filter(data_raw)
    t = np.arange(0, 60, 0.01)
    plt.figure(2)
    plt.title('HR signal')
コード例 #18
0
class NIBoards(AbstractScanInterface):
    def __init__(self, *args, read_task, write_task_z, write_task_xy):
        super().__init__(*args)
        self.read_task = read_task
        self.write_task_xy = write_task_xy
        self.write_task_z = write_task_z

        self.z_writer = AnalogMultiChannelWriter(write_task_z.out_stream)
        self.xy_writer = AnalogMultiChannelWriter(write_task_xy.out_stream)
        self.z_reader = AnalogSingleChannelReader(read_task.in_stream)

        self.xy_array = np.zeros((2, self.n_samples))
        self.z_array = np.zeros((4, self.n_samples))

        self.read_array = np.zeros(self.n_samples)

        self.setup_tasks()

    def setup_tasks(self):
        # Configure the channels

        # read channel is only the piezo position on board 1
        self.read_task.ai_channels.add_ai_voltage_chan(
            self.conf["z_board"]["read"]["channel"],
            min_val=self.conf["z_board"]["read"]["min_val"],
            max_val=self.conf["z_board"]["read"]["max_val"],
        )

        # write channels are on board 1: piezo and z galvos
        self.write_task_z.ao_channels.add_ao_voltage_chan(
            self.conf["z_board"]["write"]["channel"],
            min_val=self.conf["z_board"]["write"]["min_val"],
            max_val=self.conf["z_board"]["write"]["max_val"],
        )

        # on board 2: lateral galvos
        self.write_task_xy.ao_channels.add_ao_voltage_chan(
            self.conf["xy_board"]["write"]["channel"],
            min_val=self.conf["xy_board"]["write"]["min_val"],
            max_val=self.conf["xy_board"]["write"]["max_val"],
        )

        # Set the timing of both to the onboard clock so that they are synchronised
        self.read_task.timing.cfg_samp_clk_timing(
            rate=self.sample_rate,
            source="OnboardClock",
            active_edge=Edge.RISING,
            sample_mode=AcquisitionType.CONTINUOUS,
            samps_per_chan=self.n_samples,
        )
        self.write_task_z.timing.cfg_samp_clk_timing(
            rate=self.sample_rate,
            source="OnboardClock",
            active_edge=Edge.RISING,
            sample_mode=AcquisitionType.CONTINUOUS,
            samps_per_chan=self.n_samples,
        )

        self.write_task_xy.timing.cfg_samp_clk_timing(
            rate=self.sample_rate,
            source="OnboardClock",
            active_edge=Edge.RISING,
            sample_mode=AcquisitionType.CONTINUOUS,
            samps_per_chan=self.n_samples,
        )

        # This is necessary to synchronise reading and writing
        self.read_task.triggers.start_trigger.cfg_dig_edge_start_trig(
            self.conf["z_board"]["sync"]["channel"], Edge.RISING)

    def start(self):
        self.read_task.start()
        self.write_task_xy.start()
        self.write_task_z.start()

    def write(self):
        self.z_writer.write_many_sample(self.z_array)
        self.xy_writer.write_many_sample(self.xy_array)

    def read(self):
        self.z_reader.read_many_sample(
            self.read_array,
            number_of_samples_per_channel=self.n_samples,
            timeout=1,
        )
        self.read_array[:] = self.read_array

    @property
    def z_piezo(self):
        return self.read_array / self.conf["piezo"]["scale"]

    @z_piezo.setter
    def z_piezo(self, waveform):
        self.z_array[0, :] = waveform * self.conf["piezo"]["scale"]

    @property
    def z_lateral(self):
        return self.z_array[1, :]

    @property
    def z_frontal(self):
        return self.z_array[2, :]

    @z_lateral.setter
    def z_lateral(self, waveform):
        self.z_array[1, :] = waveform

    @z_frontal.setter
    def z_frontal(self, waveform):
        self.z_array[2, :] = waveform

    @property
    def camera_trigger(self):
        return self.z_array[3, :]

    @camera_trigger.setter
    def camera_trigger(self, waveform):
        self.z_array[3, :] = waveform

    @property
    def xy_frontal(self):
        return self.xy_array[1, :]

    @xy_frontal.setter
    def xy_frontal(self, waveform):
        self.xy_array[1, :] = waveform

    @property
    def xy_lateral(self):
        return self.xy_array[0, :]

    @xy_lateral.setter
    def xy_lateral(self, waveform):
        self.xy_array[0, :] = waveform
コード例 #19
0
class Nidaq(AcquisitionObject):
    # def __init__(self, frame_rate, audio_settings):
    # Nidaq(status['frame_rate'].current, status['sample frequency'].current,
    #  status['read rate'].current, status['spectrogram'].current)
    def __init__(self, parent, frame_rate, sample_rate, spectrogram_settings,
                 address):

        self.sample_rate = int(sample_rate)
        self.parent = parent
        self.parse_settings(spectrogram_settings)

        AcquisitionObject.__init__(self, parent, self.run_rate,
                                   (int(self.sample_rate // self.run_rate), 1),
                                   address)

        # TODO: verify that we are not violating the task state model: https://zone.ni.com/reference/en-XX/help/370466AH-01/mxcncpts/taskstatemodel/
        # specifically, if we change logging mode, do we need to re-commit the task??

        # set up the audio task
        self.audio_task = nidaqmx.Task()
        self.audio_task.ai_channels.add_ai_voltage_chan(AUDIO_INPUT_CHANNEL)
        # self.audio.ai_channels[AUDIO_INPUT_CHANNEL].ai_gain = int(AUDIO_INPUT_GAIN) #TODO: (how) does this work?
        self.audio_task.timing.cfg_samp_clk_timing(
            self.sample_rate,
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS)
        self.audio_task.in_stream.input_buf_size = self.sample_rate * PC_BUFFER_TIME_IN_SECONDS
        self.audio_task.control(nidaqmx.constants.TaskMode.TASK_COMMIT)
        self._audio_reader = AnalogReader(self.audio_task.in_stream)

        # set up the trigger task
        self.trigger_freq = frame_rate

        self.trigger_task = nidaqmx.Task()
        self.trigger_task.co_channels.add_co_pulse_chan_freq(
            TRIGGER_OUTPUT_CHANNEL,
            freq=self.trigger_freq,
            duty_cycle=DUTY_CYCLE)
        self.trigger_task.triggers.start_trigger.cfg_dig_edge_start_trig(
            f"/{AUDIO_INPUT_CHANNEL[:-1]}/StartTrigger"
        )  # start the video trigger with the audio channel
        self.trigger_task.timing.cfg_implicit_timing(
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS
        )  # configure the trigger to repeat until the task is stopped
        self.trigger_task.control(nidaqmx.constants.TaskMode.TASK_COMMIT)

        self._log_mode = [False, False]  # [isLogging, isDisplaying]
        # self._filepath = ''

    def parse_settings(self, spectrogram_settings):
        self._nfft = int(spectrogram_settings['frequency resolution'].current)
        self._window = int(spectrogram_settings['pixel duration'].current *
                           self.sample_rate)
        self._overlap = int(
            spectrogram_settings['pixel fractional overlap'].current *
            self._window)
        self.run_rate = spectrogram_settings['read rate'].current

        _, _, spectrogram = signal.spectrogram(np.zeros(
            (int(self.sample_rate // self.run_rate), )),
                                               self.sample_rate,
                                               nperseg=self._window,
                                               noverlap=self._overlap)
        self._nx = spectrogram.shape[1]
        # self._nx = int(np.round(np.floor(self.sample_rate-self._overlap) /
        #                         (self._window-self._overlap) / self.run_rate))
        self._xq = np.linspace(0, 1, num=self._nx)
        self._yq = np.linspace(0,
                               int(self.sample_rate / 2),
                               num=int(self._window / 2 + 1))
        if spectrogram_settings['log scaling'].current:
            self._zq = np.logspace(
                int(np.log10(
                    spectrogram_settings['minimum frequency'].current)),
                int(np.log10(
                    spectrogram_settings['maximum frequency'].current)),
                num=int(spectrogram_settings['frequency resolution'].current))
        else:
            self._zq = np.linspace(
                int(spectrogram_settings['minimum frequency'].current),
                int(spectrogram_settings['maximum frequency'].current),
                num=int(spectrogram_settings['frequency resolution'].current))

        self._freq_correct = spectrogram_settings['noise correction'].current
        self.print(f'_nx is {self._nx} and _nfft is {self._nfft}')

    def open_file(self, filePath):
        self._log_mode[0] = True
        # NOTE: whatever we return here becomes self.file
        # return os.path.join(filePath, 'nidaq.tdms')
        self.print(f'Saving nidaq data to {filePath}')
        return filePath

    def prepare_display(self):
        self._log_mode[1] = True

    def prepare_run(self):
        if self._log_mode[0]:
            if self._log_mode[1]:
                log_mode = nidaqmx.constants.LoggingMode.LOG_AND_READ
            else:
                log_mode = nidaqmx.constants.LoggingMode.LOG
        else:
            log_mode = nidaqmx.constants.LoggingMode.OFF

        self.audio_task.in_stream.configure_logging(
            self.file,
            logging_mode=log_mode,
            operation=nidaqmx.constants.LoggingOperation.CREATE_OR_REPLACE
        )  # see nptdms

        self.trigger_task.start()
        self.audio_task.start()
        self.print('trigger on')
        self.print('audio on')

    def prepare_processing(self, options):
        # in the future if we use deepsqueak for real-time annotation, we would set up for that here
        pass

    def capture(self, data):
        while True:
            self._audio_reader.read_many_sample(
                data[:, 0], number_of_samples_per_channel=self.data_size[0])
            yield data

    def predisplay(self, data):
        '''
    Calculate the spectrogram of the data and send to connected browsers.
    There are many ways to approach this, in particular by using wavelets or by using
    overlapping FFTs. For now just trying non-overlapping FFTs ~ the simplest approach.
    '''
        _, _, spectrogram = signal.spectrogram(data[:, 0],
                                               self.sample_rate,
                                               nperseg=self._window,
                                               noverlap=self._overlap)

        # print(self._xq.shape, self._yq.shape, spectrogram.shape, self._zq.shape)
        interpSpect = interpolate.RectBivariateSpline(
            self._yq, self._xq, spectrogram
        )(
            self._zq, self._xq
        )  # TODO: try linear instead of spline, univariate instead of bivariate

        if self._freq_correct:
            interpSpect *= self._zq[:, np.newaxis]
            # corrects for 1/f noise by multiplying with f

        thisMin = np.amin(interpSpect, axis=(0, 1))
        interpSpect -= thisMin

        thisMax = np.amax(interpSpect, axis=(0, 1))
        if thisMax != 0:
            interpSpect /= thisMax  # normalized to [0,1]

        # interpSpect = mpl.cm.viridis(interpSpect) * 255  # colormap
        interpSpect = interpSpect * 255  # TODO: decide how to handle colormapping?
        return interpSpect

    def end_run(self):
        self.audio_task.stop()
        self.trigger_task.stop()
        '''
    if self.filepath:
      audio, _ = read_audio(self.filepath)
      wavfile.write(self.filepath[:-4]+'wav', self.sample_rate, audio)
      self.print('save nidaq mic')
    '''
        self.print("done end run for nidaq")

    def end_display(self):
        self._log_mode[1] = True

    def close_file(self, fileObj):
        self._log_mode[0] = False
        self._filepath = ''

    def end_processing(self, process):
        # in the future we would teardown deepsqueak here
        pass
コード例 #20
0
class DisplayHrRr(QtWidgets.QWidget):
    def __init__(self, parent):
        from nidaqmx.stream_readers import AnalogSingleChannelReader
        from nidaqmx._task_modules.in_stream import InStream
        super(DisplayHrRr, self).__init__(parent)
        ui_path = str(pathlib.Path(__file__).parent) + "\\display.ui"
        self.ui = uic.loadUi(ui_path, self)

        info = read_config_file()
        configed_task = Task('Task read I signal')
        configed_task.ai_channels.add_ai_voltage_chan(info['port'])
        configed_task.timing.cfg_samp_clk_timing(
            rate=100,
            source=u'',
            active_edge=Edge.RISING,
            sample_mode=AcquisitionType.FINITE,
            samps_per_chan=1500)

        self.data_raw = np.zeros(shape=(1500, ))
        self.instream_analog_task = AnalogSingleChannelReader(
            InStream(configed_task))

        # init
        self.progress.setValue(0)
        self.init_state_button()

        self.button_auto.clicked.connect(self.button_auto_event)
        self.button_manual.clicked.connect(self.button_manual_event)
        self.button_refresh.clicked.connect(self.refresh)

        # click predict
        self.combobox_mode.addItems(["Tự động", "Thủ công"])
        self.manual_mode = False
        self.combobox_mode.currentIndexChanged.connect(self.update_mode)

        # event button
        self.button_predict.clicked.connect(self.predict)

        #thread read data temp
        import threading
        import src.utils.read_data_temp as rdt
        thread_read_data = threading.Thread(target=rdt.read_data_temp,
                                            daemon=True)
        thread_read_data.start()

    # ==================event button ================
    def init_state_button(self):
        self.button_auto.setEnabled(True)
        self.button_manual.setEnabled(False)

    def function_append_data(self):
        self.instream_analog_task.read_many_sample(
            data=self.data_raw,
            number_of_samples_per_channel=1500,
            timeout=100)
        self.button_auto.setEnabled(True)
        self.button_auto.setText("Tiến hành đo tự động")
        self.combobox_mode.setEnabled(True)

        # calculate
        data_raw_hr_rr = self.data_raw
        import src.utils.butterworth_filter as btwf

        hr = len(btwf.find_hr(data_raw_hr_rr)) * 4
        rr = len(btwf.find_rr(data_raw_hr_rr)) * 4

        self.label_hr.setText('Nhịp tim: ' + str(hr) + ' bpm')
        self.label_rr.setText('Nhịp thở: ' + str(rr) + ' bpm')

        parent_path = str(
            pathlib.Path(__file__).parent.parent.parent) + "\\data\\temp"
        file_path = parent_path + '\\temp.txt'
        with open(file_path, 'r') as file_temp:
            temp = file_temp.readline(5)
            file_temp.close()

        info = {'name': 'Default', 'hr': hr, 'rr': rr, 'temp': temp}
        file_utils.write_person_data(info)

        import matplotlib.pyplot as plt
        import numpy as np
        peaks = btwf.find_hr(self.data_raw)
        peaks2 = btwf.find_rr(self.data_raw)
        HR = btwf.butter_bandpass_filter(self.data_raw)
        RR = btwf.butter_lowpass_filter(self.data_raw)
        t = np.arange(0, 15, 0.01)
        plt.figure(2)
        plt.title('HR signal')
        plt.xlabel('Times')
        plt.ylabel('Voltage')
        plt.plot(t, HR)
        plt.plot(t[peaks], HR[peaks], 'x')
        # tín hiệu nhịp thở
        plt.figure(3)
        plt.title('RR signal')
        plt.xlabel('Times')
        plt.ylabel('Voltage')
        plt.plot(t, RR)
        plt.plot(t[peaks2], RR[peaks2], 'x')
        plt.show()

    def timer_count(self):
        timer_amount = 15  # s
        val_pro = 0
        import time
        while timer_amount > 0:
            time.sleep(1)
            val_pro += 6.67
            if val_pro >= 100:
                val_pro = 100
            timer_amount -= 1
            self.progress.setValue(int(val_pro))

    def button_auto_event(self):
        self.button_auto.setEnabled(False)
        self.button_auto.setText("Đang xử lý dữ liệu...")
        self.combobox_mode.setEnabled(False)
        self.label_hr.setText('Nhịp tim: đang xử lý dữ liệu')
        self.label_rr.setText('Nhịp thở: đang xử lý dữ liệu')

        if self.data_raw.size > 0:
            self.data_raw = np.zeros(shape=(1500, ))

        # create thread and run
        import threading
        thread_append = threading.Thread(target=self.function_append_data,
                                         daemon=True)
        thread_append.start()

        thread_timer = threading.Thread(target=self.timer_count, daemon=True)
        thread_timer.start()

    def button_manual_event(self):
        self.w = ManualFill()
        self.w.show()

    def update_mode(self):
        print(self.combobox_mode.currentIndex())
        if self.combobox_mode.currentIndex() == 0:
            self.manual_mode = False
            self.button_auto.setEnabled(True)
            self.button_manual.setEnabled(False)
        else:
            self.manual_mode = True
            self.button_auto.setEnabled(False)
            self.button_manual.setEnabled(True)

    def refresh(self):
        parent_path = str(
            pathlib.Path(__file__).parent.parent.parent) + "\\data\\temp"
        file_path = parent_path + '\\temp.txt'
        with open(file_path, 'r') as file_temp:
            temp = file_temp.readline(5)
            file_temp.close()
        print(temp)
        self.label_temp.setText('Nhiệt độ: {}'.format(temp))

    def predict(self):
        info = read_person_data()
        assert info != None
        name = info['name']
        hr = int(info['hr'])
        rr = int(info['rr'])
        temp = float(info['temp'])
        data = [[hr, rr, temp]]

        import pathlib
        import pickle
        path_folder_model = str(
            pathlib.Path(__file__).parent.parent) + '\\trained_model'
        model_file_path = path_folder_model + '\\SVM.sav'
        with open(model_file_path, 'rb') as model_file:
            loaded_model = pickle.load(model_file)
            result = loaded_model.predict(data)
            print(result[0])
            model_file.close()

            if result == 1.0:
                self.label_result.setText(
                    "KẾT QUẢ: Bệnh nhân {name} bình thường".format(name=name))
            else:
                self.label_result.setText(
                    "KẾT QUẢ: Bệnh nhân {name} có khả năng bị sốt xuất huyết".
                    format(name=name))
コード例 #21
0
def sawtooth(ai_chan, ao_chan_x, ao_chan_y, sRate, imAngle, outputX, outputY,
             xPixels, yPixels, exPixels):
    """
    Notes:
        Variables:
            ai_chan = string specifying the analog input channel
            ao_chan_x, ao_chan_y = string, specifying the analog output channel for x and y
    
    """
    print("Measurement started")
    writingRate = sRate
    readingRate = writingRate

    #radAngle = math.pi/180*imAngle
    #exPixelsX = int(math.cos(radAngle)*exPixels) #Amount of excess pixels in X
    #exPixelsY = int(math.sin(radAngle)*exPixels) #Amount of excess pixels in Y

    totalxPixels = exPixels + xPixels
    totalyPixels = yPixels

    print("total x pixels", totalxPixels, "xpixels", xPixels, "exPixels",
          exPixels)
    inputData = np.zeros(
        outputX.size +
        1)  #Need the extra one because of the sample shift due to the trigger
    outputData = np.array([outputX, outputY])
    outputChannels = ao_chan_x + ", " + ao_chan_y
    with nidaqmx.Task() as writeTask, nidaqmx.Task() as readTask:
        writeTask.ao_channels.add_ao_voltage_chan(outputChannels)
        readTask.ai_channels.add_ai_voltage_chan(ai_chan)

        #In the USB6001 DAQ there seems to be no SampleClock, therefore we cannot sync the signals without an external trigger/clock
        #sample_clock = '/Dev2/ai/SampleClock'

        writeTask.timing.cfg_samp_clk_timing(
            rate=writingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
            samps_per_chan=outputX.size)
        readTask.timing.cfg_samp_clk_timing(
            rate=readingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
            samps_per_chan=inputData.size)
        writeTask.triggers.start_trigger.cfg_dig_edge_start_trig(
            trigger_source='/Dev2/ai/StartTrigger'
        )  #Setting the trigger on the analog input

        reader = AnalogSingleChannelReader(readTask.in_stream)
        writer = AnalogMultiChannelWriter(writeTask.out_stream)

        estT = outputX.size / writingRate
        writer.write_many_sample(outputData)

        writeTask.start()
        reader.read_many_sample(inputData, timeout=estT + 5)

        writeTask.wait_until_done(timeout=estT + 5)
        readTask.wait_until_done(timeout=estT + 5)
        print("Done with data")

    #----------------------------Creating the Image----------------------------
    print("Creating the image")
    #Creating the array for the image
    imArray = inputData[1::].reshape(
        (totalyPixels,
         totalxPixels))  #Not taking into account the first sample

    #Plotting the image
    plt.imshow(imArray, cmap=plt.cm.gray)
    plt.show()
コード例 #22
0
def triangle(ai_chan, ao_chan_x, ao_chan_y, sRate, imAngle, outputX, outputY,
             xPixels, yPixels, exPixels):
    print("Measurement started")
    writingRate = sRate
    readingRate = writingRate

    radAngle = math.pi / 180 * imAngle
    exPixelsX = int(math.cos(radAngle) *
                    exPixels)  #Amount of excess pixels in X
    exPixelsY = int(math.sin(radAngle) *
                    exPixels)  #Amount of excess pixels in Y

    totalxPixels = 2 * exPixelsX + xPixels  #2 times excess pixels because we overshoot on two sides
    totalyPixels = 2 * exPixelsY + yPixels

    inputData = np.zeros(
        outputX.size +
        1)  #Need the extra one because of the sample shift due to the trigger
    outputData = np.array([outputX, outputY])
    outputChannels = ao_chan_x + ", " + ao_chan_y
    with nidaqmx.Task() as writeTask, nidaqmx.Task() as readTask:
        writeTask.ao_channels.add_ao_voltage_chan(outputChannels)
        readTask.ai_channels.add_ai_voltage_chan(ai_chan)

        #In the USB6001 DAQ there seems to be no SampleClock, therefore we cannot sync the signals without an external trigger/clock
        #sample_clock = '/Dev2/ai/SampleClock'

        writeTask.timing.cfg_samp_clk_timing(
            rate=writingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
            samps_per_chan=outputX.size)
        readTask.timing.cfg_samp_clk_timing(
            rate=readingRate,
            sample_mode=nidaqmx.constants.AcquisitionType.FINITE,
            samps_per_chan=inputData.size)
        writeTask.triggers.start_trigger.cfg_dig_edge_start_trig(
            trigger_source='/Dev2/ai/StartTrigger'
        )  #Setting the trigger on the analog input

        reader = AnalogSingleChannelReader(readTask.in_stream)
        writer = AnalogMultiChannelWriter(writeTask.out_stream)

        estT = outputX.size / writingRate
        writer.write_many_sample(outputData)
        writeTask.start()
        reader.read_many_sample(inputData, timeout=estT + 5)

        writeTask.wait_until_done(timeout=estT + 5)
        readTask.wait_until_done(timeout=estT + 5)

    #----------------------------Creating the Image----------------------------
    #Creating the array for the image
    imArray = np.zeros(
        (totalyPixels,
         totalxPixels))  #Not taking into account the first sample

    #Resolving the sample shift
    inputData = inputData[1::]

    #Now we have to loop over the positions because the reshape function does not work
    forward = True
    xPix = exPixelsX  #Defines the x position
    yPix = 0  #Defines the y position

    #Doing the first iteration in case we start at x=0
    imArray[yPix, xPix] = inputData[0]
    xPix += 1

    #Going through all the other values
    i = 1
    while i < inputData.size:
        imArray[yPix, xPix] = inputData[i]

        #Moving one y position up when reaching one end of the image
        if xPix == (totalxPixels - 1):
            xPix = totalxPixels - exPixelsX - 1
            yPix += 1
            #Going to the next value manually
            i += 1
            if i == inputData.size:
                break  #Making sure i does not exceed the input data array
            imArray[yPix, xPix] = inputData[i]
            forward = not forward
        elif xPix == 0:
            xPix = exPixelsX
            yPix += 1
            #Going to the next value manually
            i += 1
            if i == inputData.size:
                break  #Making sure i does not exceed the input data array
            imArray[yPix, xPix] = inputData[i]
            forward = not forward

        if forward == True:
            xPix += 1  #Moving one up if moving forward over the x pixels
        else:
            xPix -= 1  #Moving one down if moving backward over the x pixels

        i += 1  #Going to the next value of the input data

    #Plotting the image
    plt.imshow(imArray, cmap=plt.cm.gray)
    plt.show()
コード例 #23
0
                                     min_val=-2.0,
                                     max_val=2.0,
                                     units=VoltageUnits.VOLTS)

task.timing.cfg_samp_clk_timing(sample_rate,
                                active_edge=Edge.RISING,
                                sample_mode=AcquisitionType.CONTINUOUS,
                                samps_per_chan=number_sample)

# getting and handling data
print("Start Reading...")
print("Start Wraping Task Into Instream...")
in_stream = InStream(task)
arr_np_data = np.empty(shape=(number_sample, ), dtype=np.float64)

analogSingleChannel = AnalogSingleChannelReader(in_stream)
time.sleep(3)
pass_time = time.time()
analogSingleChannel.read_many_sample(
    data=arr_np_data, number_of_samples_per_channel=number_sample, timeout=40)
end_time = time.time()

print("time: {}".format(end_time - pass_time))
print("Closing Stream...")
task.close()
print("closed Stream...")


def butterwordth():
    pass
コード例 #24
0
class DAQ:
    """Convenience Wrapper to make it easy to record data from NIDAQ."""
    def __init__(self):
        """Assumes first device by default."""
        self.system = nidaqmx.system.System.local()
        self.task = nidaqmx.Task()
        self.sampleSize = 100
        self.buffer = numpy.zeros(self.sampleSize)
        self.reader = ASCR(self.task.in_stream)
        if len(self.system.devices) > 0:
            self.device = self.system.devices[0]
        else:
            raise RuntimeError("NIDAQmx device not found during init." \
            + " Please make sure a NI device is connected.")
        self.devAddr = self.device.name + '/ai0'

    def __repr__(self):
        drv = self.system.driver_version
        return "<DAQ Wrapper class - NIDAQmx Driver ver: " +\
            f"{drv.major_version}.{drv.minor_version}.{drv.update_version}>"

    def printChans(self):
        """Returns a list of available device identifiers."""
        print(self.device.name + " | " + self._enumChans())

    def _enumChans(self):
        """Returns prettied device detail string."""
        out = ''
        # Analog and counter channels bc they're similiar first:
        for chanType in ['ai', 'ao', 'ci', 'co', 'di', 'do']:
            if chanType in ['di', 'do']:
                count = len(getattr(self.device, chanType + '_lines')) - 1
            else:
                count = len(getattr(self.device,
                                    chanType + '_physical_chans')) - 1
            if count == 0:
                out += f'/{chanType}0 '
            elif count == -1:
                out += f'/{chanType}N '
            else:
                out += f'/{chanType}0:{count} '
        return out

    def _callback(self, taskHandle, everyNSamplesEventType, numberSamples,
                  callbackData):
        # pylint: disable=unused-argument
        """Reads data from NI when enough samples are buffered."""
        self.reader.read_many_sample(self.buffer,
                                     numberSamples,
                                     timeout=NIconstants.WAIT_INFINITELY)
        print(self.buffer.tolist())
        return 0

    def _setupCallback(self, rate: int = 100):
        """Sets up a callback to read data whenever a buffer gets filled."""
        self.task.ai_channels.add_ai_voltage_chan(self.devAddr)
        self.task.timing.cfg_samp_clk_timing(
            rate=rate,
            sample_mode=NIconstants.AcquisitionType.CONTINUOUS,
            samps_per_chan=self.sampleSize)
        self.task.register_every_n_samples_acquired_into_buffer_event(
            self.sampleSize, self._callback)

    def _getSamples(self, sampleSize: int = 128, devAddr: str = "Dev1/ai0"):
        """Naive and synchronous. Internal func returns numpy array."""
        sampleArray = numpy.zeros(sampleSize)
        # And "Dev1/ai4" on my test bench
        with self.task as task:
            port = devAddr[(devAddr.find('/') + 1):]  # everything after the /
            if 'ai' in port:
                task.ai_channels.add_ai_voltage_chan(devAddr)
            elif 'di' in port:
                task.di_channels.add_di_chan(devAddr)
            else:
                print('sampleStream(devAddr) type is unsupported oh no')
            self.reader.read_many_sample(sampleArray, sampleSize)
        return sampleArray

    def sampleStream(self, sampleSize: int = 128, devAddr: str = "Dev1/ai0"):
        """Naive and synchronous.
        Return an iterator that gets (a set of) samples every time it's queried."""
        class IterSamples:
            """Iterator of samples."""
            def __init__(self, daq: DAQ, sampleSize: int, devAddr: str):
                self.daq = daq
                self.sampleSize = sampleSize
                self.devAddr = devAddr
                self.index = 0  # Really just how many times it's queried

            def __iter__(self):
                return self

            def __next__(self):
                self.index += 1
                # pylint: disable=protected-access
                return self.daq._getSamples(sampleSize=self.sampleSize,
                                            devAddr=self.devAddr).tolist()

        return IterSamples(daq=self, sampleSize=sampleSize, devAddr=devAddr)
コード例 #25
0
    def run(self):
        """
        Starts writing a waveform continuously while reading 
        the buffer periodically
        """

        with nidaqmx.Task() as slave_Task, nidaqmx.Task() as master_Task:

            slave_Task.ao_channels.add_ao_voltage_chan("/Dev1/ao0:1")
            master_Task.ai_channels.add_ai_voltage_chan("/Dev1/ai0")

            if self.flag_continuous == False:
                # Timing of analog output channels
                slave_Task.timing.cfg_samp_clk_timing(
                    rate=self.Daq_sample_rate,
                    source='ai/SampleClock',
                    sample_mode=AcquisitionType.FINITE,
                    samps_per_chan=self.Totalscansamples)

                # Timing of recording channels
                master_Task.timing.cfg_samp_clk_timing(
                    rate=self.Daq_sample_rate,
                    sample_mode=AcquisitionType.FINITE,
                    samps_per_chan=self.Totalscansamples)
            else:
                # Timing of analog output channels
                slave_Task.timing.cfg_samp_clk_timing(
                    rate=self.Daq_sample_rate,
                    source='ai/SampleClock',
                    sample_mode=AcquisitionType.CONTINUOUS)

                # Timing of recording channels
                master_Task.timing.cfg_samp_clk_timing(
                    rate=self.Daq_sample_rate,
                    sample_mode=AcquisitionType.CONTINUOUS,
                    samps_per_chan=self.Totalscansamples)

            reader = AnalogSingleChannelReader(master_Task.in_stream)
            writer = AnalogMultiChannelWriter(slave_Task.out_stream)

            reader.auto_start = False
            writer.auto_start = False

            writer.write_many_sample(self.Galvo_samples)
            """Reading data from the buffer in a loop. 
            The idea is to let the task read more than could be loaded in the buffer for each iteration.
            This way the task will have to wait slightly longer for incoming samples. And leaves the buffer
            entirely clean. This way we always know the correct numpy size and are always left with an empty
            buffer (and the buffer will not slowly fill up)."""
            output = np.zeros(self.Totalscansamples)
            slave_Task.start(
            )  #Will wait for the readtask to start so it can use its clock
            master_Task.start()

            # while not self.isInterruptionRequested():
            reader.read_many_sample(
                data=output,
                number_of_samples_per_channel=self.Totalscansamples)

            Dataholder_average = np.mean(output.reshape(self.averagenum, -1),
                                         axis=0)

            if self.flag_return_image == True:
                # Calculate the mean of average frames.
                self.data_PMT = np.reshape(
                    Dataholder_average,
                    (self.pixel_number, self.total_X_sample_number))

                # Cut off the flying back part.
                if self.pixel_number == 500:
                    self.image_PMT = self.data_PMT[:, 50:550] * -1
                elif self.pixel_number == 256:
                    self.image_PMT = self.data_PMT[:, 70:326] * -1

                return self.image_PMT