def init_device(self, set_clock=None): ''' Initalizes device by setting the functionality of each channel (all set to ARB channel here). Not recommand to call it directly Input: None Output: None ''' logging.debug(__name__ + ' : Initializing device...') self._CDriver = Lecroy_1104() if set_clock == None: leftClockDec = Decimal(self._leftClock) rightClockDec = Decimal(self._rightClock) else: self._leftClock = set_clock self._rightClock = set_clock leftClockDec = Decimal(set_clock) rightClockDec = Decimal(set_clock) exClockDec = Decimal(self._exClock) source = ClockSource.Internal if (self._clockSource.upper() == "INTERNAL"): source = ClockSource.Internal elif (self._clockSource.upper() == "EXTERNAL"): source = ClockSource.External aterr = self._CDriver.SetSamplingFrequency(leftClockDec, rightClockDec, source, exClockDec) self._device = self._CDriver.GetDevice() if (self._device == None): logging.error(__name__ + ' : Initialization failed.') print "Initialization failed."
def testDecimalIndexer(self): """Test Decimal indexers.""" object = Test.DecimalIndexerTest() from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") self.assertTrue(object[max_d] == None) object[max_d] = "max" self.assertTrue(object[max_d] == "max") object[min_d] = "min" self.assertTrue(object[min_d] == "min") def test(): object = Test.DecimalIndexerTest() object["wrong"] self.assertRaises(TypeError, test) def test(): object = Test.DecimalIndexerTest() object["wrong"] = "wrong" self.assertRaises(TypeError, test)
def move_axis(self, pos, axis, relative=False): """Move one axis (currently in volts)""" chan = self.select_axis(self.channels, axis) if relative: # emulate relative moves pos += Decimal.ToDouble(chan.GetOutputVoltage()) chan.SetOutputVoltage(Decimal(pos))
def calibrate_pos(self): '''Creates a calibration that translates position to voltage. The controller takes as input a value that is the percentage of the maximum posible voltage. It usefull to be able to use as input a number in um. Hence, a simple calibration procedure is used. The stage moves to 10 and 70 percent of the maximum voltage and the reader value is recorded. Assuming a linear relationship, percentage = a*position + b the slope a and the constant b are calculated and used to translate position to percentage voltage. This function should be called imediately after set_closed_loop. ''' y1 = 10 y2 = 70 time.sleep(1) if self.is_closed_loop(): self.device.SetPercentageTravel(Decimal(y1)) time.sleep(4) x1 = self.reader.get_pos() time.sleep(0.01) self.device.SetPercentageTravel(Decimal(y2)) time.sleep(4) x2 = self.reader.get_pos() time.sleep(0.01) self.a = (y2 - y1) / (x2 - x1) self.b = -self.a * x1 + y1 # eg go to 1um y = self.a * 1.0 + self.b self.device.SetPercentageTravel(Decimal(y))
def initialize(self): # Create the device self.device = TCubePiezo.CreateDevice(self.serialNo) if self.device is None: print('Piezo Controller is a null object') else: print('Piezo Controller, ' + str(self.serialNo) + ', has been created') # Connect and enable the device self.connect_enable(self.device, self.serialNo) # Initialize the DeviceUnitConverter object required for real world # unit parameters. self.device.GetPiezoConfiguration(self.serialNo) # Create an instance of device setting. # Change the settings using this object and then use set # settings to load them into the device. self.mysettings = self.device.PiezoDeviceSettings # Eg. # self.mysettings.HubInputSource.set_HubMode(2) # self.device.SetSettings(mysettings, False) # False means to not write it in the memory for default on startup # Change the Jog steps self.mysettings.OutputVoltageRange.set_MaxOutputVoltage(Decimal(75)) self.mysettings.Control.set_VoltageStepSize(Decimal(1)) self.mysettings.Control.set_PercentageStepSize(Decimal(1)) self.device.SetSettings(self.mysettings, False) # False for not persistent settings if self.serial_reader is not 'Empty': self.reader = StrainReader(self.serial_reader)
def test_decimal_array(): """Test Decimal arrays.""" ob = Test.DecimalArrayTest() items = ob.items from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") assert len(items) == 5 assert items[0] == Decimal(0) assert items[4] == Decimal(4) items[0] = max_d assert items[0] == max_d items[0] = min_d assert items[0] == min_d items[-4] = max_d assert items[-4] == max_d items[-1] = min_d assert items[-1] == min_d with pytest.raises(TypeError): ob = Test.DecimalArrayTest() _ = ob.items["wrong"] with pytest.raises(TypeError): ob = Test.DecimalArrayTest() ob[0] = "wrong"
def __init__(self, pandasSeries): t = str(pandasSeries.name)[:10].split("-") self.Date = DateTime(int(t[0]), int(t[1]), int(t[2])) self.Open = Decimal(float(pandasSeries["Open"])) self.High = Decimal(float(pandasSeries["High"])) self.Low = Decimal(float(pandasSeries["Low"])) self.Close = Decimal(float(pandasSeries["Close"])) self.Volume = Decimal(float(pandasSeries["Volume"]))
def InitiateMotor(serialNumber, pollingRate=250, DeviceSettingsName='Z812'): ''' Function for initalizing contact with a thorlabs k-cube controller object. Parameters ---------- serialNumber : String Serial number of device to be connected. Written on the back of the pollingRate : int, optional Polling rate of device in ms. The default is 250. DeviceSettingsName : string, optional Indicates which type of motor is connectd to the controller. The default is 'Z812'. Returns ------- motor : k-cube controller k-cube controller which can be used to control a thorlabs motor. ''' DeviceManagerCLI.BuildDeviceList() DeviceManagerCLI.GetDeviceListSize() motor = KCubeDCServo.CreateKCubeDCServo(serialNumber) for attempts in range(3): try: motor.Connect(serialNumber) except: print("Connection attempt", attempts, "failed") if attempts < 2: print("Will wait 2 seconds and try again") sleep(2) else: print("Cannot connect to device.\n Please ensure that the" +\ " device is connected to your computer and not in"+\ " use by any other program!") return None motor.WaitForSettingsInitialized(5000) # configure the stage motorSettings = motor.LoadMotorConfiguration(serialNumber) motorSettings.DeviceSettingsName = DeviceSettingsName # update the RealToDeviceUnit converter motorSettings.UpdateCurrentConfiguration() # push the settings down to the device MotorDeviceSettings = motor.MotorDeviceSettings motor.SetSettings(MotorDeviceSettings, True, False) # Start polling the device motor.StartPolling(pollingRate) motor.EnableDevice() # Jogging parameters set to minimum motor.SetJogVelocityParams(Decimal(0.01), Decimal(0.01)) return motor
def move_relative(self, distance, cb=None): if not self.is_busy(): f = cb is None if f: e = threading.Event() cb = lambda x: e.set() direction = MotorDirection.Forward if distance >= 0 else MotorDirection.Backward self.device.SetVelocityParams(Decimal(2.6), Decimal(4)) self.device.MoveRelative(direction, Decimal(abs(distance)), Action[UInt64](cb)) if f: e.wait()
def MoveMotorPixels(motor, distance, mmToPixel=16140): # TODO - check if the mmToPixel value is valid for the basler camera. ''' Moves motor a specified number of pixels. Parameters ---------- motor : TYPE - thorlabs motor Motor to be moved distance : TYPE number Distance to move the motor mmToPixel : TYPE number for converting from mm(motor units) to pixels, optional The default is 16140, valid for our 100x objective and setup. Returns ------- bool True if move was successfull, false otherwise. ''' motor.SetJogStepSize(Decimal(float(distance / mmToPixel))) try: motor.MoveJog(1, timeoutVal) # Jog in forward direction except: print("Trying to move motor to NOK position") return False return True
def MoveMotor(motor, distance): ''' Helper function for moving a motor. Parameters ---------- motor : thorlabs motor Motor to be moved. distance : float Distance to move the motor. Returns ------- bool True if the move was a success, otherwise false. ''' if distance > 0.1 or distance < -0.1: print("Trying to move too far") return False # For unknown reason python thinks one first must convert to float but # only when running from console... motor.SetJogStepSize(Decimal(float(distance))) try: motor.MoveJog(1, timeoutVal) # Jog in forward direction except: print("Trying to move motor to NOK position") return False return True
def force_move(self, pos): self.is_moving = True try: self.stage.MoveTo(Decimal(pos), self.isDone()) except BaseException as e: self.is_moving = False print("An error has occurred. Can't move to position") raise e
def test_decimal_conversion(): """Test decimal conversion.""" from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") assert Decimal.ToInt64(Decimal(10)) == 10 ob = ConversionTest() assert ob.DecimalField == Decimal(0) ob.DecimalField = Decimal(10) assert ob.DecimalField == Decimal(10) ob.DecimalField = Decimal.One assert ob.DecimalField == Decimal.One ob.DecimalField = Decimal.Zero assert ob.DecimalField == Decimal.Zero ob.DecimalField = max_d assert ob.DecimalField == max_d ob.DecimalField = min_d assert ob.DecimalField == min_d with pytest.raises(TypeError): ConversionTest().DecimalField = None with pytest.raises(TypeError): ConversionTest().DecimalField = "spam" with pytest.raises(TypeError): ConversionTest().DecimalField = 1
def set_velocity(self, V): V = V / 1000 try: velocity_parameters = self._kCubeDCServoMotor.GetVelocityParams() velocity_parameters.MaxVelocity = Decimal(float(V)) self._kCubeDCServoMotor.SetVelocityParams(velocity_parameters) except Thorlabs.MotionControl.DeviceManagerCLI.DeviceException as exc: logError() print("Can't set velocity {}".format(V))
def _Py_Decimal(self, value): ''' Casting a python double to System.Decimal results in the Decimal having only integer values, likely due to an improper selection of the overloaded Decimal function. Casting it first to System.Double, which always maintains precision, then from Double to Decimal, where the proper overloaded function is clear, bypasses this issue :param value: a python double :return: the input as a System.Decimal ''' return Decimal(Double(value))
def move_to(self, position, *args): try: user_input = int(position) except ValueError: print("Please Enter a digit and not a " + str(type(position))) return else: print("Moving to position " + str(position) + " degrees.") self.device.MoveTo(Decimal(position), 60000) self.device.StopPolling() print("Final Position: " + str(self.device.Position))
def move_to(self, position, cb=None): if not self.is_busy(): f = cb is None if f: e = threading.Event() cb = lambda x: e.set() self.device.MoveTo(Decimal(position), Action[UInt64](cb)) if f: e.wait()
def _move_to(self, pos, timeout=0): try: pos = pos / 1000 # Move the device to position 0. We specify 0 as the wait timeout # as we don't care how long it takes. self._kCubeDCServoMotor.MoveTo(Decimal(float(pos)), timeout) except Thorlabs.MotionControl.DeviceManagerCLI.DeviceMovingException: print("Ignored, Already moving") except BaseException as e: print("Unable to move to position\n", e) raise
def get_super_trend(history, lookbackPeriod, multiplier): _list = Indicator.GetSuperTrend[Qoute](_convert_df_to_csharp_list(history), lookbackPeriod, CsDecimal.Parse(str(multiplier))) _dict = { _convert_csharp_datetime(i.Date): (float(str(i.SuperTrend)) if i.SuperTrend else None) for i in _list } return _dict
def get_std_dev_channels(history, lookbackPeriod, standardDeviations): _list = Indicator.GetStdDevChannels[Qoute]( _convert_df_to_csharp_list(history), lookbackPeriod, CsDecimal.Parse(str(standardDeviations))) _dict = { _convert_csharp_datetime(i.Date): (float(str(i.Centerline)) if i.Centerline else None) for i in _list } return _dict
def get_bollinger_bands_lower(history, lookbackPeriod, standardDeviations): _list = Indicator.GetBollingerBands[Qoute]( _convert_df_to_csharp_list(history), lookbackPeriod, CsDecimal.Parse(str(standardDeviations))) _dict = { _convert_csharp_datetime(i.Date): (float(str(i.LowerBand)) if i.LowerBand else None) for i in _list } return _dict
def __set_axis_position(self, axis, pos): # define """ Internal method setting the position in um if the channel is in Closed Loop mode """ if axis in ("x", "y", "z"): print("\t- moving %s axis piezo to %f um -->" % (axis, pos), end="") channel = self.__get_chan(axis) channel.SetPosition(Decimal(pos)) print(" done") else: print("\t- axis invalid)")
def createInvoice(actionContext): # make sure that input set contains at least one object if (Enumerable.Count[EntityObject](actionContext.InputSet) > 0): # find next free invoice number lastInvoiceNumber = 0 lastInvoice = actionContext.DataContext.SelectSingleWithParams({ "Query": "From I In Invoice Where :Year(I.InvoiceDate) = @YearParam And :Month(I.InvoiceDate) = @MonthParam Order By I.InvoiceNumberMonthly Desc Select New With { I.InvoiceNumberMonthly }", "@YearParam": Decimal(actionContext.Parameter.InvoiceDate.Year), "@MonthParam": Decimal(actionContext.Parameter.InvoiceDate.Month) }) if (lastInvoice <> None): lastInvoiceNumber = lastInvoice.InvoiceNumberMonthly # create invoice newInvoice = actionContext.DataContext.CreateInvoice() newInvoice.InvoiceDate = actionContext.Parameter.InvoiceDate newInvoice.InvoiceNumberMonthly = lastInvoiceNumber + 1 newInvoice.InvoiceText = actionContext.Parameter.InvoiceText newInvoice.Customer = actionContext.Parameter.Customer actionContext.DataContext.SaveObject(newInvoice)
def test_decimal_indexer(): """Test Decimal indexers.""" ob = Test.DecimalIndexerTest() from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") assert ob[max_d] is None ob[max_d] = "max_" assert ob[max_d] == "max_" ob[min_d] = "min_" assert ob[min_d] == "min_" with pytest.raises(TypeError): ob = Test.DecimalIndexerTest() ob["wrong"] with pytest.raises(TypeError): ob = Test.DecimalIndexerTest() ob["wrong"] = "wrong"
def test_decimal_conversion(): """Test decimal conversion.""" from System import Decimal assert Decimal.ToInt64(Decimal(10)) == 10 ob = ConversionTest() assert ob.DecimalField == Decimal(0) ob.DecimalField = Decimal(10) assert ob.DecimalField == Decimal(10) ob.DecimalField = Decimal.One assert ob.DecimalField == Decimal.One ob.DecimalField = Decimal.Zero assert ob.DecimalField == Decimal.Zero with pytest.raises(TypeError): ConversionTest().DecimalField = None with pytest.raises(TypeError): ConversionTest().DecimalField = "spam"
def testDecimalArray(self): """Test Decimal arrays.""" object = Test.DecimalArrayTest() items = object.items from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") self.assertTrue(len(items) == 5) self.assertTrue(items[0] == Decimal(0)) self.assertTrue(items[4] == Decimal(4)) items[0] = max_d self.assertTrue(items[0] == max_d) items[0] = min_d self.assertTrue(items[0] == min_d) items[-4] = max_d self.assertTrue(items[-4] == max_d) items[-1] = min_d self.assertTrue(items[-1] == min_d) def test(): object = Test.DecimalArrayTest() v = object.items["wrong"] self.assertRaises(TypeError, test) def test(): object = Test.DecimalArrayTest() object[0] = "wrong" self.assertRaises(TypeError, test)
def jog(self,jog,min=50,max=250,max_wait=0): new_pos = float(str(self.device.Position)) + jog print(new_pos) if new_pos >= min and new_pos <= max: try: # device.Stop(10) # if jog > 0: # device.MoveContinuous(Thorlabs.MotionControl.GenericMotorCLI.MotorDirection.Forward) # else: # device.MoveContinuous(Thorlabs.MotionControl.GenericMotorCLI.MotorDirection.Backward) self.device.SetMoveRelativeDistance(Decimal(jog)) self.device.MoveRelative(max_wait) #except Thorlabs.MotionControl.DeviceManagerCLI.DeviceMovingException as ex: except Thorlabs.MotionControl.DeviceManagerCLI.MoveTimeoutException as ex: print('Jog time exceeded wait time!')
def _open_connection(self): _SN = HW_conf.kinesis_cube_serial # Instructs the DeviceManager to build and maintain the list of # devices connected. DeviceManagerCLI.BuildDeviceList() kCubeDCServoMotor = KCubeDCServo.CreateKCubeDCServo(_SN) # Establish a connection with the device. try_connect(lambda: kCubeDCServoMotor.Connect(_SN), DeviceNotReadyException) # Wait for the device settings to initialize. We ask the device to # throw an exception if this takes more than 5000ms (5s) to complete. kCubeDCServoMotor.WaitForSettingsInitialized(5000) # Initialize the DeviceUnitConverter object required for real world # unit parameters. kCubeDCServoMotor.GetMotorConfiguration(_SN) # This starts polling the device at intervals of 250ms (0.25s). kCubeDCServoMotor.StartPolling(20) # We are now able to enable the device for commands. kCubeDCServoMotor.EnableDevice() if not (kCubeDCServoMotor.IsActuatorDefined): raise HardwareError("Actuator not defined") print("Zstage Connected") velocity_parameters = kCubeDCServoMotor.GetVelocityParams() velocity_parameters.MaxVelocity = Decimal(1) kCubeDCServoMotor.SetVelocityParams(velocity_parameters) if not kCubeDCServoMotor.Status.IsHomed: kCubeDCServoMotor.Home(0) return kCubeDCServoMotor
def MoveMotorToPixel(motor, targetPixel, currentPixel, maxPixel=1280, mmToPixel=16140): ''' Parameters ---------- motor : TYPE DESCRIPTION. targetPixel : TYPE DESCRIPTION. currentPixel : TYPE DESCRIPTION. maxPixel : TYPE, optional DESCRIPTION. The default is 1280. mmToPixel : TYPE, optional DESCRIPTION. The default is 16140. Returns ------- bool DESCRIPTION. ''' if (targetPixel < 0 or targetPixel > maxPixel): # Fix correct boundries print("Target pixel outside of bounds") return False # There should be a minus here, this is due to the setup dx = -(targetPixel - currentPixel) / mmToPixel motor.SetJogStepSize(Decimal(float(dx))) try: motor.MoveJog(1, timeoutVal) # Jog in forward direction except: print("Trying to move motor to NOK position") return False return True
def testDecimalConversion(self): """Test decimal conversion.""" from System import Decimal max_d = Decimal.Parse("79228162514264337593543950335") min_d = Decimal.Parse("-79228162514264337593543950335") self.failUnless(Decimal.ToInt64(Decimal(10)) == 10L) object = ConversionTest() self.failUnless(object.DecimalField == Decimal(0)) object.DecimalField = Decimal(10) self.failUnless(object.DecimalField == Decimal(10)) object.DecimalField = Decimal.One self.failUnless(object.DecimalField == Decimal.One) object.DecimalField = Decimal.Zero self.failUnless(object.DecimalField == Decimal.Zero) object.DecimalField = max_d self.failUnless(object.DecimalField == max_d) object.DecimalField = min_d self.failUnless(object.DecimalField == min_d) def test(): ConversionTest().DecimalField = None self.failUnlessRaises(TypeError, test) def test(): ConversionTest().DecimalField = "spam" self.failUnlessRaises(TypeError, test) def test(): ConversionTest().DecimalField = 1 self.failUnlessRaises(TypeError, test)