def SetBField(self):
     try:
         xyz.fine_field_cart(self.xValue, self.yValue, self.zValue, self.handle)
         print("Magnetic Field Set")
     except Error as err:
         xyz.closePorts(self.handle) # close the ports before raising the error.
         raise err
예제 #2
0
try:
	while True:
		# querry the labjack
		t1 = time.time()
		sumSignal, leftMinusRight = xyz.ljm.eReadNames(handle, 2, ['AIN0', 'AIN1'])
		# run the control loop
		output = pid(setpoint, leftMinusRight)
		outputYField += output*1e-6

		print('output = %s' % output)
		# set the field
		xyz.fine_field_cart(xyz.xCoil.coilField, outputYField, xyz.zCoil.largeCoilField, handle)

		# save the (now) old leftMinusRight value for the next loop
		lastLeft = leftMinusRight
		dt = time.time() - t1 # keep track of the timestep for consistancy sake.
		print('time step = %s' % dt)
		if sumSignal < 3:
			raise exception('sum signal LOW!')

except Exception as e:
    # helpful to close the ports on except when debugging the code!
    xyz.closePorts(handle)
    print('closed all the ports')
    print(e) # print the exception
    raise

# work in the optical zero space so we are always adusting perpenductular to the optical zero.

# each limit will need to be an equation for a line and the max and min values will need to be changesd based on the lineear range of that line.
예제 #3
0
def StreamCollection(max_requests=60, scanrate=1000, bKick=True, minSum=-1.0):
    #time will take about max_requests/2 in seconds

    MAX_REQUESTS = max_requests  # The number of eStreamRead calls that will be performed.
    FIRST_AIN_CHANNEL = 0  #AIN0
    NUMBER_OF_AINS = 3  # AIN0: L-R, AIN1: Sum, AIN2: T-B

    rawData = []

    # open the all ports and get the labjack handle
    handle = xyz.openPorts()

    info = ljm.getHandleInfo(handle)
    print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
        "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
        (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))

    # Stream Configuration
    aScanListNames = [
        "AIN%i" % i
        for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS)
    ]  #Scan list names
    print("\nScan List = " + " ".join(aScanListNames))
    numAddresses = len(aScanListNames)
    aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0]
    global scanRate
    scanRate = scanrate

    scansPerRead = int(scanRate / 2)

    try:
        # Configure the analog inputs' negative channel, range, settling time and
        # resolution.
        # Note when streaming, negative channels and ranges can be configured for
        # individual analog inputs, but the stream has only one settling time and
        # resolution.
        aNames = [
            "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [ljm.constants.GND, 10.0, 0,
                   0]  #single-ended, +/-10V, 0 (default),
        #0 (default)
        ljm.eWriteNames(handle, len(aNames), aNames, aValues)

        eventNumber = 0  # keeps track of the event we make a new one each time the user resets the pendulum and hits enter
        input('start?')
        while True:

            if bKick:
                # kick the pendulum to drive it so we can take period data.
                print('Kicking')
                xr, yr, zr = kickUpAndWait(
                    0, 4.5e-6, 0,
                    10)  # kick the field and save the current values.
                #xr,yr,zr = kickUpAndWait(0, 2e-6, 0, 10) # seems like we maight want a bit less kick

            # Configure and start stream
            scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses,
                                        aScanList, scanRate)
            print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

            print("\nPerforming %i stream reads." % MAX_REQUESTS)

            if bKick:
                kickDown(xr, yr,
                         zr)  # put the currents back to where they were
                print('Done Kicking!')

            # then do the stream.
            start = datetime.now()
            totScans = 0
            totSkip = 0  # Total skipped samples

            i = 1  # counter for number of stream requests

            while i <= MAX_REQUESTS:
                ret = ljm.eStreamRead(handle)

                data = ret[0]
                scans = len(data) / numAddresses
                totScans += scans

                # Count the skipped samples which are indicated by -9999 values. Missed
                # samples occur after a device's stream buffer overflows and are
                # reported after auto-recover mode ends.
                curSkip = data.count(-9999.0)
                totSkip += curSkip

                print("\neStreamRead %i" % i)
                ainStr = ""
                for j in range(0, numAddresses):
                    ainStr += "%s = %0.5f " % (aScanListNames[j], data[j])
                print("  1st scan out of %i: %s" % (scans, ainStr))
                print("  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = " \
                      "%i" % (curSkip/numAddresses, ret[1], ret[2]))

                newDataChunk = np.reshape(
                    data, (-1, NUMBER_OF_AINS)
                )  # reshape the data to have each row be a different reading

                if i != 1:  # if we are not on the first run.
                    rawData = np.vstack((rawData, newDataChunk))
                else:
                    rawData = newDataChunk  # this should only run on the first time.
                    #print('FIRST RUN THROUGH')

                #print(rawData,'\n')

                i += 1

            end = datetime.now()

            print("\nTotal scans = %i" % (totScans))
            tt = (end - start).seconds + float(
                (end - start).microseconds) / 1000000
            print("Time taken = %f seconds" % (tt))
            print("LJM Scan Rate = %f scans/second" % (scanRate))
            print("Timed Scan Rate = %f scans/second" % (totScans / tt))
            print("Timed Sample Rate = %f samples/second" %
                  (totScans * numAddresses / tt))
            print("Skipped scans = %0.0f" % (totSkip / numAddresses))

            print("\nStop Stream")
            ljm.eStreamStop(handle)

            print('current querry!')
            # update the powersupply field readings so we can reference them later
            xyz.xCoil.getLargeCoilField()
            xyz.yCoil.getLargeCoilField()
            print('done with current querry!')

            # format data to include field values
            rawDataWithFieldValues = []
            print(rawData)
            first = True
            for j, row in enumerate(
                    rawData
            ):  # setp throuh and append the field values to each datapoint
                if row[1] >= minSum:
                    timestamp = j * (1.0 / scanRate)
                    rowWithFieldValues = np.append(
                        row,
                        np.array([
                            xyz.xCoil.largeCoilField, xyz.yCoil.largeCoilField,
                            timestamp, eventNumber
                        ]))  # for now we aren't using the adustment coils
                    if first:
                        first = False
                        rawDataWithFieldValues = rowWithFieldValues

                    else:  # not on the first loop
                        rawDataWithFieldValues = np.vstack(
                            (rawDataWithFieldValues, rowWithFieldValues))
            print(np.shape(rawDataWithFieldValues))

            # and add it to our master data array
            if eventNumber != 0:
                #print(np.shape(allTheData))
                #print('--------')
                #print(np.shape(rawDataWithFieldValues))
                allTheData = np.vstack((allTheData, rawDataWithFieldValues))
                #print(np.shape(allTheData))
            else:
                allTheData = rawDataWithFieldValues

            print(allTheData)
            print(np.shape(allTheData))

            input(
                "finished with eventNumber %s. Press enter to start a new data run."
                % eventNumber)
            eventNumber += 1  # increment the event number

    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
        #xyz.closePorts(handle)

    except KeyboardInterrupt:  # usefull to have a KeyboardInterrupt when your're debugging

        # save the data to a DataFrame
        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)

    except Exception as e:
        # helpful to close the ports on except when debugging the code.
        # it prevents the devices from thinking they are still conected and refusing the new connecton
        # on the next open ports call.

        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)
        print('closed all the ports\n')

        print(e)  # print the exception
        raise