def start(self): """Start video capture.""" def validate(node, value): node.write_once = node.no_write_shot = False try: node.record = node.record.setValidation(value) finally: node.write_once = node.no_write_shot = True def store_temp(node, new): if isinstance(new, (float, )): node.record = MDSplus.Float64([new]) elif isinstance(new, (int, )): node.record = MDSplus.Uint32([new]) try: validate(self.frame_rate, MDSplus.Float32(self.cygnet4k.frame_rate)) validate(self.exposure, MDSplus.Float32(self.cygnet4k.exposure)) validate(self.trig_mode, MDSplus.Uint8(self.cygnet4k.trig_mode)) validate(self.binning, MDSplus.Int8(self.cygnet4k.binning)) validate(self.roi_rect, MDSplus.Int16(self.cygnet4k.roi_rect)) aoi = self._roi_rect cmos, pcb = self.cygnet4k.start_capture_stream( self._num_frames, aoi, self._stream, self.copy()) store_temp(self.temp_cmos, cmos) store_temp(self.temp_pcb, pcb) except CygnetExcConnect: raise MDSplus.DevOFFLINE except CygnetExcValue: raise MDSplus.DevINV_SETUP except CygnetExcComm: raise MDSplus.DevIO_STUCK
def _stream(dim, data, node, nodemax): nodemax.makeSegment(dim, dim, MDSplus.Float32([dim]), MDSplus.Uint16([numpy.max(data)])) if MDSplus.Device.debug: print('storeFrame: %s, %s, %s' % (node.minpath, dim, data.shape)) dims = MDSplus.Float32([dim]).setUnits('s') data = MDSplus.Uint16([data]) node.makeSegment(dim, dim, dims, data)
def _stream(dim, data, dev): dev.tree.open() dev.frames_percentile.makeSegment( dim, dim, MDSplus.Float32([dim]), MDSplus.Uint16([numpy.percentile(data, 99)])) if MDSplus.Device.debug & 1: print('storeFrame: %s, %s, %s' % (dev.minpath, dim, data.shape)) dims = MDSplus.Float32([dim]).setUnits('s') data = MDSplus.Uint16([data]) dev.frames.makeSegment(dim, dim, dims, data)
def sendY_M(self): print('sendY_M') print('sendStream') print('sendStream(shot, name, time, data)', 0, 'Y_M', MDSplus.Float32(self.sim_time), MDSplus.Float64Array(self.y_m[self.sim_index, :])) sendStream(0, 'Y_M', MDSplus.Float32(self.sim_time), MDSplus.Float64Array(self.y_m[self.sim_index, :])) print('send setpoint') MDSplus.Event.stream(0, 'SETPOINT', MDSplus.Float32(self.sim_time), MDSplus.Float64(self.set_point[self.sim_index])) self.sim_index += 1 print('set label') self.ui.Y_Mlabel.setText(str(self.y_m[self.sim_index, 0])) self.sim_time += .01 print('done')
def sendU(self): if self.sim_index >= len(self.u): self.sim_index = 0 self.sim_time = 0.0 MDSplus.Event.stream(0, 'U', MDSplus.Float32(self.sim_time), MDSplus.Float64(self.u[self.sim_index])) self.ui.Ulabel.setText(str(self.u[self.sim_index])) self.sim_index += 1 self.ui.UNextlabel.setText(str(self.u[self.sim_index])) self.sim_time += .01
def decompile(self): self.assertEqual(str(m.Uint8(123)),'123BU') self.assertEqual(str(m.Uint16(123)),'123WU') self.assertEqual(str(m.Uint32(123)),'123LU') self.assertEqual(str(m.Uint64(123)),'123QU') self.assertEqual(str(m.Int8(123)),'123B') self.assertEqual(str(m.Int16(123)),'123W') self.assertEqual(str(m.Int32(123)),'123') self.assertEqual(str(m.Int64(123)),'123Q') self.assertEqual(str(m.Float32(1.2E-3)),'.0012') self.assertEqual(str(m.Float64(1.2E-3)),'.0012D0') self.assertEqual(str(m.Signal(m.ZERO(100000,0.).evaluate(),None,0.)),"Build_Signal(Set_Range(100000,0. /*** etc. ***/), *, 0.)")
def update(node, new): if isinstance(new, (float, )): new = MDSplus.Float32(new) elif isinstance(new, (int, )): new = MDSplus.Uint16(new) else: return rec = node.getRecord(None) if rec is None: rec = MDSplus.Array([new, new]) elif len(rec) != 1: return else: rec = MDSplus.Array([rec[0], new]) node.write_once = node.no_write_shot = False try: node.record = rec finally: node.write_once = node.no_write_shot = True
def stream(self): event_name = self.stream_event.data() seg_length = int(self.seg_length.data()) max_segments = self.max_segments.data() wave_method = self.wave_method.data() data = np.zeros(seg_length) times = np.zeros(seg_length) segment = 0 start_time = time.time() previous_time = 0 while self.running.on and segment < max_segments: sample = 0 while self.running.on and sample < seg_length: previous_time = time.time() times[sample] = previous_time - start_time if wave_method == "sine": data[sample] = MDSplus.Float32(math.sin(times[sample])) elif wave_method == "cosine": data[sample] = MDSplus.Float32(math.cos(times[sample])) elif wave_method == "triangle": data[sample] = MDSplus.Float32(math.fmod(times[sample], 2)) elif wave_method == "square": data[sample] = MDSplus.Float32(round((math.sin(times[sample]) + 1) / 2)) sample += 1 time.sleep(0.5) if sample != seg_length - 1: times = times[0:sample] data = data[0:sample] segment += 1 self.wave_data.makeSegment(times[0], times[-1], times, data) MDSplus.Event.setevent(event_name)
def tdiFunctions(self): m.dTRUE = m.__dict__['$TRUE'] m.dFALSE = m.__dict__['$FALSE'] from MDSplus import mdsExceptions as Exc """Test Exceptions""" self._doExceptionTest('abort()', Exc.TdiABORT) self._doExceptionTest('{,}', Exc.TdiSYNTAX) self._doExceptionTest('\033[[A', Exc.TdiBOMB) self._doExceptionTest('abs()', Exc.TdiMISS_ARG) self._doExceptionTest('abs("")', Exc.TdiINVDTYDSC) self._doExceptionTest('abs(1,2)', Exc.TdiEXTRA_ARG) self._doExceptionTest('"', Exc.TdiUNBALANCE) """Test $Missing/NoData/None""" self._doTdiTest('', None) """Test abs""" self._doThreeTest('abs(cmplx(3.0,4.0))', m.ABS(m.Complex64(3. + 4.j)), m.Float32(5.)) """Test abs1""" self._doThreeTest('abs1(cmplx(3.0,4.0))', m.ABS1(m.Complex64(3. + 4.j)), m.Float32(7.)) """Test abssq""" self._doThreeTest('abssq(cmplx(3.0,4.0))', m.ABSSQ(m.Complex64(3. + 4.j)), m.Float32(25.)) """Test accumulate""" self._doThreeTestArray('accumulate([1,2,3])', m.ACCUMULATE(m.makeArray([1, 2, 3])), m.Int32Array([1, 3, 6])) self._doThreeTestArray( 'accumulate([[1,3,5],[2,4,6]])', m.ACCUMULATE(m.makeArray([[1, 3, 5], [2, 4, 6]])), m.Int32Array([[1, 4, 9], [11, 15, 21]])) self._doThreeTestArray( 'accumulate([[1,3,5],[2,4,6]],0)', m.ACCUMULATE(m.makeArray([[1, 3, 5], [2, 4, 6]]), 0), m.Int32Array([[1, 4, 9], [2, 6, 12]])) #self._doThreeTestArray('accumulate([[1,3,5],[2,4,6]],1)',m.ACCUMULATE([[1,3,5],[2,4,6]],1),m.Int32Array([[1,3,5],[3,7,11]])) # tdi issue self._doUnaryArray( m.Data.execute('accumulate([[1,3,5],[2,4,6]],1)'), m.ACCUMULATE(m.makeArray([[1, 3, 5], [2, 4, 6]]), 1).getData()) """Test achar""" self._doThreeTest('achar(88)', m.ACHAR(88), m.String('X')) """Test ADJUSTL""" self._doThreeTest('adjustl(" WORD")', m.ADJUSTL(" WORD"), m.String("WORD ")) """Test ADJUSTR""" self._doThreeTest('adjustr("WORD ")', m.ADJUSTR("WORD "), m.String(" WORD")) """Test AIMAG""" self._doThreeTest('AIMAG(CMPLX(2.0,3.0))', m.AIMAG(m.CMPLX(2., 3.)), m.Float32(3.0)) """Test AINT""" self._doThreeTest('aint(2.783)', m.AINT(2.783), m.Float32(2.0)) self._doThreeTest('aint(-2.783)', m.AINT(-2.783), m.Float32(-2.0)) """Test NE (operates on flattened array, i.e. first 3 values are compared)""" A, B = m.makeArray([1, 3, 5]), m.makeArray([[0, 3, 5], [0, 0, 0], [0, 4, 8]]) self._doThreeTestArray( '_A=[1,3,5],_B=[[0,3,5],[0,0,0],[0,4,8]],_A ne _B', m.NE(A, B), m.Uint8Array([1, 0, 0])) """Test NE (operates on flattened array, i.e. first 3 values are compared)""" self._doThreeTestArray('_A eq _B', m.EQ(A, B), m.Uint8Array([0, 1, 1])) """Test ALL and ANY""" self._doThreeTest('all([$TRUE,$FALSE,$TRUE])', m.ALL(m.makeArray([1, 0, 1])), m.Uint8(0)) self._doThreeTest('any([$TRUE,$FALSE,$TRUE])', m.ANY(m.makeArray([1, 0, 1])), m.Uint8(1)) A = 0 self._doThreeTest('_A=0,all(_A eq _B)', m.ALL(m.EQ(A, B)), False) self._doThreeTest('any(_A ne _B)', m.ANY(m.NE(A, B)), True) self._doThreeTestArray('all(_A ne _B,0)', m.ALL(m.NE(A, B), 0), m.Uint8Array([0, 0, 0])) self._doThreeTestArray('any(_A ne _B,0)', m.ANY(m.NE(A, B), 0), m.Uint8Array([1, 0, 1])) self._doThreeTestArray('all(_A eq _B,1)', m.ALL(m.EQ(A, B), 1), m.Uint8Array([1, 0, 0])) self._doThreeTestArray('any(_A ne _B,1)', m.ANY(m.NE(A, B), 1), m.Uint8Array([0, 1, 1])) """Test allocated""" self.assertEqual(m.DEALLOCATE('*') >= 2, True) # deallocates _A and _B and more? self.assertEqual(m.ALLOCATED('_xyz'), m.Uint8(0)) self._doTdiTest('_xyz=0,allocated("_xyz")', m.Uint8(1)) self.assertEqual(m.ALLOCATED('_xyz'), m.Uint8(1)) self.assertEqual(m.DEALLOCATE('*'), m.Uint8(1)) self.assertEqual(m.ALLOCATED('_xyz'), m.Uint8(0)) """Test AND""" A, B = m.makeArray([0, 0, 1, 1]), m.makeArray([0, 1, 0, 1]) self._doThreeTestArray('_A=[0,0,1,1],_B=[0,1,0,1],_A && _B', m.AND(A, B), m.Uint8Array([0, 0, 0, 1])) """Test AND_NOT""" self._doThreeTestArray('_A AND_NOT _B', m.AND_NOT(A, B), m.Uint8Array([0, 0, 1, 0])) """Test ANINT""" self._doThreeTest('ANINT(2.783)', m.ANINT(2.783), m.Float32(3.0)) """Test ARG""" self._doTdiTest( 'execute("abs(arg(cmplx(3.0,4.0)) - .9272952) < .000001")', m.Uint8(1)) """Test ARGD""" self._doTdiTest( 'execute("abs(argd(cmplx(3.0,4.0)) - 53.1301) < .000001")', m.Uint8(1)) """Test arg_of""" self._doThreeTest('arg_of(pub->foo(42,43))', m.ARG_OF(m.Call('pub', 'foo', 42, 43)), m.Int32(42)) self._doThreeTest('arg_of(pub->foo(42,43),1)', m.ARG_OF(m.Call('pub', 'foo', 42, 43), 1), m.Int32(43)) self._doThreeTest('arg_of(1+3,1)', m.ARG_OF(m.ADD(1, 3), 1), m.Int32(3)) """Test Array""" self._doThreeTestArray('array(10)', m.ARRAY(10), m.Float32Array([0] * 10)) self._doThreeTestArray('array(10,0)', m.ARRAY(10, 0), m.Int32Array([0] * 10)) self._doThreeTestArray('array(10,0BU)', m.ARRAY(10, m.Uint8(0)), m.Uint8Array([0] * 10)) self._doThreeTestArray('zero(100)', m.ZERO(100), m.Float32Array([0] * 100))
def trend(self): # start it trending self.running.on = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((str(self.node.data()), 5000)) # open the instrument if self.debugging(): print("about to open cryocon device %s" % str(self.node.data())) event_name = self.data_event.data() try: self.status_out.getData() except: if self.debugging(): print( "Status_Out tree node is empty. Lets write the data now.") # read and save the status commands status_out = {} for cmd in self.status_cmds: if self.debugging(): print('about to send %s' % cmd) # status_out[str(cmd)] = instrument.query(str(cmd)) status_out[str(cmd)] = self.queryCommand(s, str(cmd)) if self.debugging(): print(' got back %s' % status_out[str(cmd)]) self.status_out.record = status_out # Control Loop PID values Numeric Entry The Pgain, Igain and Dgain lines correspond to the Proportional, # Integral and Derivative coefficients of the control loop. Pman is the output power that will be applied # to the load if the manual control mode is selected. # Values for the Proportional, or P, gain term range from zero to 1000. This is a unit- less gain term # that is applied to the control loop. Gain is scaled to reflect the actual heater range and the load resistance. # Integrator gain values range from zero to 10,000. The units of this term are Seconds. A value of zero # turns the integration function off. # Derivative gain values have units of inverse Seconds and may have values from zero to 1000. A value of # zero turns the Derivative control function off. for i in self.loops(): # Proportional gain, or P term for PID control. # This is a numeric field that is a percent of full scale. pgain_chan = self.__getattr__('loop_%c_propor_gain' % (str(i + 1))) pgain_query_cmd = 'LOOP %c:PGA?' % (str(i + 1), ) # Integrator gain term, in Seconds, for PID control. # This is a numeric field that is a percent of full scale. igain_chan = self.__getattr__('loop_%c_integr_gain' % (str(i + 1))) igain_query_cmd = 'LOOP %c:IGA?' % (str(i + 1), ) # Derivative gain term, in inverse-Seconds, for PID control. # This is a numeric field that is a percent of full scale. dgain_chan = self.__getattr__('loop_%c_deriva_gain' % (str(i + 1))) dgain_query_cmd = 'LOOP %c:DGA?' % (str(i + 1), ) spoint_chan = self.__getattr__('loop_%c_setpoint' % (str(i + 1))) spoint_query_cmd = 'LOOP %c:SETP?' % (str(i + 1), ) ansQuery = self.queryCommand(s, pgain_query_cmd) try: pgain_chan.getData() igain_chan.getData() dgain_chan.getData() except: try: print("Parsing Proportional Gain /%s/" % ansQuery) pgain = float(ansQuery) except: if self.debugging(): print("Could not parse Proportional Gain /%s/" % ansQuery) pgain = 0.0 pgain_chan.record = MDSplus.Float32(pgain) ansQuery = self.queryCommand(s, igain_query_cmd) try: print("Parsing Integral Gain /%s/" % ansQuery) igain = float(ansQuery) except: if self.debugging(): print("Could not parse Integral Gain /%s/" % ansQuery) igain = 0.0 igain_chan.record = MDSplus.Float32(igain) ansQuery = self.queryCommand(s, dgain_query_cmd) try: print("Parsing Derivative Gain /%s/" % ansQuery) dgain = float(ansQuery) except: if self.debugging(): print("Could not parse Derivative Gain /%s/" % ansQuery) dgain = 0.0 dgain_chan.record = MDSplus.Float32(dgain) ansQuery = self.queryCommand(s, spoint_query_cmd) try: print("Parsing Setpoint /%s/" % ansQuery) spoint = float(ansQuery) except: if self.debugging(): print("Could not parse Setpoint /%s/" % ansQuery) spoint = 0.0 spoint_chan.record = MDSplus.Float32(spoint) for i in self.inputs(): t_chans = self.__getattr__('input_%c' % (chr(i))) r_chans = self.__getattr__('input_%c_resistence' % (chr(i))) if t_chans.on: query_cmd_temp = 'INP %c:TEMP?;SENP?' % (chr(i), ) ansQuery = self.queryCommand(s, query_cmd_temp) t_time = time.time() # Temperature reading try: temps = float(ansQuery.split(';')[0]) is_digit = True except ValueError: is_digit = False if self.debugging(): print("Could not parse temperature /%s/" % ansQuery.split(';')[0]) if not is_digit: temps = -9999.0 t_chans.putRow(1000, MDSplus.Float32(temps), MDSplus.Int64(t_time * 1000.)) # Resistence reading try: resists = float(ansQuery.split(';')[1]) is_digit = True except ValueError: is_digit = False if self.debugging(): print("Could not parse resist /%s/" % ansQuery.split(';')[1]) if not is_digit: resists = -9999.0 r_chans.putRow(1000, MDSplus.Float32(resists), MDSplus.Int64(t_time * 1000.)) for i in self.loops(): p_chans = self.__getattr__('loop_%c' % (str(i + 1))) query_cmd_outp = 'LOOP %c:HTRRead?' % (str(i + 1), ) ansQuery = self.queryCommand(s, query_cmd_outp) answerOutp = ansQuery[: -1] #remove the '%' at the end of the number if p_chans.on: t_time = time.time() # Output Power reading: Queries the output power of the selected control loop. # This is a numeric field that is a percent of full scale. try: print("Parsing output power /%s/" % ansQuery) if 'NAK' not in ansQuery: outpower = float(answerOutp) else: outpower = float(-9999.0) except ValueError: if self.debugging(): print("Could not parse output power /%s/" % ansQuery) p_chans.putRow(1000, MDSplus.Float32(outpower), MDSplus.Int64(t_time * 1000.)) MDSplus.Event.setevent(event_name) s.close()
def trend(self): ''' trend method for cryocon18i record the values of the status commands start the stream STILL NEEDS TO STORE Calibration CURVES !! Store one sample for each of the channels that is on using putRow. The timestamp will be time since the unix EPOCH in msec ''' # start it trending self.running.on = True event_name = self.data_event.data() if self.debugging(): print("About to open cryocon device %s" % str(self.node.data())) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((str(self.node.data()), 5000)) try: self.status_out.getData() except: # read and save the status commands status_out = {} for cmd in self.status_cmds: if self.debugging(): print('about to send %s' % cmd) status_out[str(cmd)] = self.queryCommand(s, str(cmd)) if self.debugging(): print(' got back %s' % status_out[str(cmd)]) self.status_out.record = status_out # for i in range(ord('a'), ord('h')+1+1): # chan = self.__getattr__('input_%c'%(chr(i),)) # if chan.on: # cal = self.__getattr__('input_%c_calibration'%(chr(i),)) # ans = self.queryCommand(s, 'CALCUR %c?'%(chr(i))) # print(ans) # cal.record = ans #print(self.queryCommand(s, 'CALCUR')) query_cmd = '' ansQuery = [] for i in self.inputs: t_chan = self.__getattr__('input_%c' % (i, )) if t_chan.on: query_cmd = 'INP %c?;INP %c:SENP?;' % (i, i) ansQuery = self.queryCommand(s, query_cmd)[:-1].split(';') t_time = time.time() try: temp = float(ansQuery[0]) except: if self.debugging(): print("Could not parse temperature /%s/" % ansQuery[0]) temp = 0.0 t_chan.putRow(1000, MDSplus.Float32(temp), MDSplus.Int64(t_time * 1000.)) r_chan = self.__getattr__('input_%c_resistence' % (i, )) try: resist = float(ansQuery[1]) except: if self.debugging(): print("Could not parse resist /%s/" % ansQuery[1]) resist = 0.0 r_chan.putRow(1000, MDSplus.Float32(resist), MDSplus.Int64(t_time * 1000.)) MDSplus.Event.setevent(event_name) s.close()
def sendSetPoint(self): MDSplus.Event.stream( 0, 'SETPOINT', MDSplus.Float32(self.time), MDSplus.Float64(self.ui.positionSlider.value() / 100.))
def sendUValue(self): u = float(self.ui.uValue.text()) MDSplus.Event.stream(0, 'U', MDSplus.Float32(self.time), MDSplus.Float64(u))
def store(self, start=0, end=0): if not self.on: return try: from influxdb import InfluxDBClient except: raise Exception( "You must install the `influxdb` python package to use the `influxhistorian` device class" ) address = self.address.data() parts = address.split(":", 2) address = parts[0] port = 8086 if len(parts) > 1: port = int(parts[1]) username = '' password = '' try: with open(self.credentials.data()) as cred_file: lines = cred_file.readlines() if len(lines) < 2: print("Failed to read credentials from file %s" % (self.credentials.data(), )) username = lines[0].strip('\n') password = lines[1].strip('\n') except IOError as e: print("Failed to open credentials file %s" % (self.credentials.data(), )) client = InfluxDBClient(address, port, username, password, self.database.data()) startTimeQuery = '' endTimeQuery = '' if start > 0: # Convert to nanosecond UNIX timestamp startTimeQuery = 'time > %d' % (start * 1000000, ) if end > 0: # Convert to nanosecond UNIX timestamp endTimeQuery = 'time < %d' % (end * 1000000, ) for i in range(self.DATA_COUNT): try: node = self.__getattr__("data_d%03d" % (i + 1, )) where = self.__getattr__("data_d%03d_where" % (i + 1, )).data() if not node.on: continue if where == '': continue whereList = [where] if startTimeQuery != '': whereList.append(startTimeQuery) if endTimeQuery != '': whereList.append(endTimeQuery) where = '' if len(whereList) > 0: where = 'WHERE %s'.format(' AND '.join(whereList)) query = 'SELECT %s AS value FROM "%s" %s'.format( node.SELECT.data(), self.series.data(), where) if self.debugging(): print(query) result = client.query(query, params={'epoch': 'ms'}) for row in result.get_points(): node.putRow(1000, MDSplus.Float32(float(row['value'])), MDSplus.Uint64(row['time'])) except MDSplus.TreeNODATA: pass except Exception as e: print(e) MDSplus.Event.setevent(self.data_event.data())