def degauss_magnets():

        # CHOOSE MAGNETS + LIST FOR SETPOINTS

        trial_magnets = [ ]
        f = open("field_strength.cal","r")
        h = f.readlines()
        
        for find_magnets in range(0,len(h)):

            if  'DIP'  in h[find_magnets][3:6] :
                trial_magnets.append(h[find_magnets][:8])
            elif 'QUA' in h[find_magnets][3:6] : 
                trial_magnets.append(h[find_magnets][:8])
            elif 'CRV' in h[find_magnets][3:6] :
                trial_magnets.append(h[find_magnets][:8])                

        trial_magnets = trial_magnets[13:] 
        # excludes dump and diagnostic magnets

        # trial_magnets = ["MD2DIP01","MD2QUA02"]
        # test magnets in dump
        
        # CREATE 2D ARRAY OF SETPOINTS AND LIMITS

        trial_magnet_setpoint = [caget_many([x + "_cmd" for x in trial_magnets]) ,caget_many([x + "_cmd.DRVH" for x in trial_magnets]),caget_many([x + "_cmd.DRVL" for x in trial_magnets])]

        # array of setpoint, drive high, drive low current values, caget_many to get each parameter for each magnet, list comprehension used to add needed string to magnet name 
        
        # SET VARIABLES
        No_pts = 25
        pause_time = 2
        swing_current = 1
        
        # SET DEGAUSSING PARAMETERS

        caput_many(["degauss:" + x + "_N_pts" for x in trial_magnets],[No_pts]*len(trial_magnets))
        caput_many(["degauss:" + x + "_pause" for x in trial_magnets],[pause_time]*len(trial_magnets))
        caput_many(["degauss:" + x + "_amplitude" for x in trial_magnets],[swing_current]*len(trial_magnets))
        
        # FOR LOOP TO STOP EXCEEDING POWER SUPPLIES

        for nmag in range(0,len(trial_magnets)):
        
             if (trial_magnet_setpoint[0][nmag] + swing_current) > trial_magnet_setpoint[1][nmag] or (trial_magnet_setpoint[0][nmag] - swing_current) < trial_magnet_setpoint[2][nmag]:

                print("Outside of Power Supply Tolerance in EPICS: ", trial_magnets[nmag])  
                return
                
        # SET THE STANDARDIZATION PROCEDURE TO RUN
        #caput degauss:MAGNETNAME_cmd TargetValue
        #caput_many(["degauss:" + x + "_cmd" for x in trial_magnets],caget_many([x + "_cmd" for x in trial_magnets]))

        # CHECK IF SUCCESSFUL
        vprint("...Magnets Standardizing",True,0,True)
Exemplo n.º 2
0
def test_caget_many():
    write('Simple Test of caget_many() function\n')
    pvs = [pvnames.double_pv, pvnames.enum_pv, pvnames.str_pv]
    vals = caget_many(pvs)
    assert len(vals) == len(pvs)
    assert isinstance(vals[0], float)
    assert isinstance(vals[1], int)
    assert isinstance(vals[2], str)
Exemplo n.º 3
0
 def test_caget_many(self):
     write('Simple Test of caget_many() function\n')
     pvs = [pvnames.double_pv, pvnames.enum_pv, pvnames.str_pv]
     vals = caget_many(pvs)
     self.assertEqual(len(vals), len(pvs))
     self.assertIsInstance(vals[0], float)
     self.assertIsInstance(vals[1], int)
     self.assertIsInstance(vals[2], str)
Exemplo n.º 4
0
 def test_caget_many(self):
     write('Simple Test of caget_many() function\n')
     pvs = [pvnames.double_pv, pvnames.enum_pv, pvnames.str_pv]
     vals = caget_many(pvs)
     self.assertEqual(len(vals), len(pvs))
     self.assertIsInstance(vals[0], float)
     self.assertIsInstance(vals[1], int)
     self.assertIsInstance(vals[2], str)
Exemplo n.º 5
0
def default_measurement(settings, measurements, pause=1.0):

    set_results = caput_many(settings.keys(), settings.values())

    time.sleep(pause)

    measured_values = caget_many(measurements)

    if None in set_results:
        raise ValueError('Could not set machine settings.')

    data = {name: measured_values[ii] for ii, name in enumerate(measurements)}

    return data
    def _get_slot_codes(self, slots=range(1, 257)):
        pvs = [f"{self.pvname}:Evt-{slot}-Code-SP" for slot in slots]
        codes = caget_many(pvs)

        slots_out = []
        codes_out = []
        for s, c in zip(slots, codes):
            if not c == None:
                if c in codes_out:
                    print(f"Code {c} exists multiple times!")
                    continue
                slots_out.append(s)
                codes_out.append(c)

        codes_out, slots_out = zip(*sorted(zip(codes_out, slots_out)))
        return slots_out, codes_out
Exemplo n.º 7
0
    def scan_motor_img(motor, start, stop, steps, camera, images=10):
        """Method to scan a motor and save images and epics data at each position
        Parameters:
        ----------
        motor: pcdsdevice EpicsMotor like object
            Example is (mr3k4_kbo.x).  The motor you'd like to scan in x

        start: float
            Absolute x motor starting position

        stop: float
            Absolute x motor ending position

        steps: int
            Number of steps for the x scan

        camera: str
            Camera name in lower case format (i.e. 'im2k4')

        images: int
            Number of images to collect at each motor position
        """
        df = pd.DataFrame()
        motor_vals = np.linspace(start, stop, steps)
        c = CamH5()
        c.camera = camera
        c.images = images
        image_files = []
        times = []
        logger.info(f'Scanning {motor.name} over {motor_vals}')
        for val in motor_vals:
            motor.mv(val, wait=True)
            filename = c.collect()
            image_files.append(filename)
            times.append(time.time())
            logger.info(f'Collected camera images and saved to {filename}')
            df = df.append(pd.DataFrame([caget_many(EPICSARCH)],
                                        columns=EPICSARCH),
                           ignore_index=True)
        df = df.assign(times=times)
        df = df.assign(image_files=image_files)
        file_name = f'{motor.name}-{int(time.time())}.h5'
        location = ''.join([SCAN_PATH, file_name])
        df.to_hdf(location, key='metadata')
        logger.info(f'wrote all data to {location}')
Exemplo n.º 8
0
 def scanner(self,
             mov_pv,
             start,
             stop,
             steps,
             tol,
             cam,
             images=10,
             rbck_ext='.RBV'):
     """General scanner for now because we want to take images"""
     steps = np.linspace(start, stop, steps)
     times = []
     image_files = []
     self.cam_tools.camera = cam
     try:
         pv_obj = PV(mov_pv)
         pv_rbck = PV(mov_pv + rbck_ext)
     except:
         logger.warning('Unable to connect to {mov_pv}')
     df = pd.DataFrame()
     for step in steps:
         pv_obj.put(step)
         while abs(pv_rbck.get() - step) > tol:
             time.sleep(0.1)
         logger.info(f'Stepper reached {step}, collecting data')
         times.append(time.time())
         self.cam_tools.num_images = images
         self.cam_tools.collect(images)
         f = self.cam_tools.save()
         image_files.append(f)
         df = df.append(pd.DataFrame([caget_many(EPICSARCH)],
                                     columns=EPICSARCH),
                        ignore_index=True)
     df = df.assign(times=times)
     df = df.assign(image_files=image_files)
     file_name = f'{mov_pv}-{int(time.time())}.h5'
     location = SCAN_PATH + file_name
     df.to_hdf(location, key='metadata')
     logger.info(f'wrote all data to {location}')
Exemplo n.º 9
0
    # title of backup file.
    title = inFile.split('/')[-1].replace('-', ' ')[:inFile.find('-list.opi')]

    bu.append('# Detector: ' + title)
    bu.append('# chid\tcrate\tslot\tchannel\tgroup\tV0Set\tI0Set\tSVMax\t\
RUp\tRDwn')

    # performs caget_many function for every list element of buList
    count = 0
    for pv in buList:
        ch = '\t'.join(map(str, map(int, pv[0])))
        chid = ids[maps.index(ch)]
        line = chid + '\t' + ch + '\t' + group + '\t'
        refLog.append(line.strip())
        res = epics.caget_many(pv[1:], as_string=True)
        line += '\t'.join(res)
        bu.append(line.strip())

    bu.append('#')

#writes data to a text file (file extension .sav can be changed to fit user
# preferences).
outFile = 'HV-backup_' + date.replace(' ', '_') + '.sav'
with open(path + outFile, 'w') as f:
    for line in bu:
        f.write(line)
        f.write('\n')

# prints a reponse that CSS looks for to indicate program is done.
print('BACKUP COMPLETE\n' + outFile + ' created.')
Exemplo n.º 10
0
    epics.caput_many(pvs,vals)
    count = count + size
    if not silence:
        sys.stdout.write(('\r{1} |{0}'+progEnd).format(int(25*count/total)*'=',\
            str(int(100*count/total))+'%'))
        sys.stdout.flush()
if not silence:
    print('\nRestoration complete.')
    print('\nVerifying restore...')

okay = True
failed = []
count = 0
for n,grp in enumerate(pvGroups):
    vals = valGroups[n]
    check = epics.caget_many(grp,as_string=True)
    count = count + size
    if not silence:
        sys.stdout.write(('\r{1} |{0}'+progEnd).format(int(25*count/total)*'=',\
            str(int(100*count/total))+'%'))
        sys.stdout.flush()
    for i,item in enumerate(check):
        if 'SV' in grp[i]:
            if item == '1':
                item = 'MINOR'
            elif item == '2':
                item = 'MAJOR'
            elif item == '0':
                item = 'NO_ALARM'
        if item != vals[i]:
            okay = False