def main():
   
    for i in range(10000):

        print "Acquire " + str(i)
   
        error = False

        caput("BL1A:CS:RunControl:Start", 1, wait=True, timeout=20)
        status = caget("BL1A:CS:RunControl:StateEnum")
        if (status != RC_RUN):
            print "ERROR on Start: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(RC_RUN)
            error = True

        status = caget("BL1A:Det:N1:DetectorState_RBV")
        if (status != AD_ACQUIRE):
            print "ERROR on Start: i= " + str(i) + \
            " BL1A:Det:N1:DetectorState_RBV= " + str(status) + " and it should be " + str(AD_ACQUIRE)
            status_msg = caget("BL1A:Det:N1:StatusMessage_RBV")
            print "ADnED Status message: " + str(status_msg)
            error = True
            
        if error:
            cothread.Sleep(1)
            status = caget("BL1A:Det:N1:DetectorState_RBV")
            print "ADnED delayed status read: " + str(status)
            sys.exit(1)

        sleepTime = randint(1,10)
        print "sleepTime: " + str(sleepTime)
        cothread.Sleep(sleepTime)

        caput("BL1A:CS:RunControl:Stop", 1, wait=True, timeout=20)
        #cothread.Sleep(1) #At the moment callback not supported on a stop.
        status = caget("BL1A:CS:RunControl:StateEnum")
        if (status != RC_IDLE):
            print "ERROR on Stop: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(RC_IDLE)
            error = True

        status = caget("BL1A:Det:N1:DetectorState_RBV")
        if (status != AD_IDLE):
            print "ERROR on Stop: i= " + str(i) + \
            " BL1A:Det:N1:DetectorState_RBV= " + str(status) + " and it should be " + str(AD_IDLE)
            status_msg = caget("BL1A:Det:N1:StatusMessage_RBV")
            print "ADnED Status message: " + str(status_msg)
            error = True

        if error:
            cothread.Sleep(1)
            status = caget("BL1A:Det:N1:DetectorState_RBV")
            print "ADnED delayed status read: " + str(status)
            sys.exit(1)
    def get_mr(self):
        get_command = util.abstract_caget
        beam_current_max_warning = False

        # Only control injection if there are variables that require it.
        if self.measurement_vars_inj:
            # First measure the injection results
            # Begin injecting
            print "Start injection"
            caput('LI-TI-MTGEN-01:START', 1)
            cothread.Sleep(0.1)
            caput('LI-TI-MTGEN-01:START', 0)
            cothread.Sleep(4.0)

            if self.beam_current_bounds[0] is not None:
                beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                while beam_current < self.beam_current_bounds[0]:
                    print 'waiting for beam current to rise above ', \
                        self.beam_current_bounds[0]
                    cothread.Sleep(1)
                    beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                    print '...'

            mrs_inj = util.measure_results(self.measurement_vars_inj,
                                           util.abstract_caget)

            # Now for the non-injection measurements
            if self.beam_current_bounds[1] is not None:
                if get_command(
                        'SR-DI-DCCT-01:SIGNAL') > self.beam_current_bounds[1]:
                    beam_current_max_warning = True

            # Stop injection
            print "Stop injection"
            caput('LI-TI-MTGEN-01:STOP', 1)
            cothread.Sleep(0.1)
            caput('LI-TI-MTGEN-01:STOP', 0)
            cothread.Sleep(1)
        else:
            mrs_inj = []

        mrs_noinj = util.measure_results(self.measurement_vars_noinj,
                                         util.abstract_caget)

        # Now combine the results into a single list
        mrs = mrs_noinj + mrs_inj

        if beam_current_max_warning:
            msg = 'Beam current limit exceeded.\nDump the beam before pressing OK.'
            tkMessageBox.showwarning('DUMP THE BEAM', msg)

        return mrs
示例#3
0
    def test_multi(self):
        l = [1]

        def tick():
            l.append(l[-1] + 2)

        t = cothread.Timer(0.1, tick, retrigger=True)
        self.assertEqual(l, [1])
        cothread.Sleep(0.15)
        self.assertEqual(l, [1, 3])
        cothread.Sleep(0.1)
        self.assertEqual(l, [1, 3, 5])
        t.cancel()
        cothread.Sleep(0.15)
        self.assertEqual(l, [1, 3, 5])
示例#4
0
    def get_mr(self):
        get_command = util.abstract_caget
        beam_current_max_warning = False

        # First measure the injection results
        # Begin injecting
        print "Start injection"
        caput('LI-TI-MTGEN-01:START', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:START', 0)
        cothread.Sleep(4.0)

        if self.beam_current_bounds is not None:
            beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
            while beam_current < self.beam_current_bounds[0]:
                print 'waiting for beam current to rise above ', \
                    self.beam_current_bounds[0]
                cothread.Sleep(1)
                beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                print '...'

        mrs_inj = util.measure_results(self.measurement_vars_inj,
                                       util.abstract_caget)

        # Now for the non-injection measurements

        if self.beam_current_bounds is not None:
            if get_command(
                    'SR-DI-DCCT-01:SIGNAL') > self.beam_current_bounds[1]:
                beam_current_max_warning = True

        # Stop injection
        print "Stop injection"
        caput('LI-TI-MTGEN-01:STOP', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:STOP', 0)
        cothread.Sleep(1)

        mrs_noinj = util.measure_results(self.measurement_vars_noinj,
                                         util.abstract_caget)

        # Now combine the results into a single list

        results = mrs_noinj + mrs_inj

        mrs = results

        return mrs
示例#5
0
def main():
   
    for i in range(100):

        print "Acquire " + str(i)
   
        det1_counts = caget("BL99:Det:N1:Det1:EventTotal_RBV")
        det2_counts = caget("BL99:Det:N1:Det2:EventTotal_RBV")
        print "det1_counts before: " + str(det1_counts)
        print "det2_counts before: " + str(det2_counts)

        caput("BL99:Det:N1:Start", 1, wait=True, timeout=5)
        status = caget("BL99:Det:N1:DetectorState_RBV")
        if (status != STAT_ACQUIRE):
            print "ERROR on Start: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(STAT_ACQUIRE)
            sys.exit(1)


        det1_counts = caget("BL99:Det:N1:Det1:EventTotal_RBV")
        det2_counts = caget("BL99:Det:N1:Det2:EventTotal_RBV")
        print "det1_counts after: " + str(det1_counts)
        print "det2_counts after: " + str(det2_counts)

        cothread.Sleep(5)

        caput("BL99:Det:N1:Stop", 1, wait=True, timeout=5)
        status = caget("BL99:Det:N1:DetectorState_RBV")
        if (status != STAT_IDLE):
            print "ERROR on Stop: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(STAT_IDLE)
            sys.exit(1)
示例#6
0
    def test_monitor(self):
        self.assertIOCRunning()
        longout = self.testprefix + 'longout'

        values = []

        def callback(value):
            values.append(value)

        m = catools.camonitor(longout, callback, notify_disconnect=True)

        # Wait for connection
        while not values:
            cothread.Sleep(0.1)
        catools.caput(longout, 43, wait=True)
        catools.caput(longout, 44, wait=True)
        self.iocStop()

        # Can't call iocStop twice...
        def iocStop():
            return

        self.iocStop = iocStop
        m.close()

        self.assertEqual(len(values), 4)
        self.assertEqual(values[:3], [42, 43, 44])
        self.assertEqual([v.ok for v in values], [True, True, True, False])
示例#7
0
 def do_go(self):
     if caget(self.prefix + ":MOTOR.RBV") < 0.001:
         self.go_countdown = 0
     if self.go_countdown == 0:
         try:
             val = float(str(self.ui.D.text()))
         except ValueError:
             val = 10
             self.ui.D.setText("10")
         caput(self.prefix + ":GATHER:DEMAND", val)
         tSample = caget(self.prefix + ":GATHER:TSAMPLE.B")
         accl = caget(self.prefix + ":MOTOR.ACCL")
         tMove = max(accl + (val / caget(self.prefix + ":MOTOR.VELO")),
                     2 * accl)
         tMove = 2 * tMove + caget(self.prefix + ":GATHER:DELAY") + 0.5
         sPeriod = int(tMove * 1000.0 / (1024.0 * tSample)) + 1
         caput(self.prefix + ":GATHER:SPERIOD", sPeriod)
         cothread.Sleep(0.2)
         # timer tick in ms
         tick = sPeriod * tSample * 10.24 + 30
         self.timer = QtCore.QTimer()
         self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.tick)
         caput(self.prefix + ":GATHER:STATE", "EXECUTE")
         caput(self.prefix + ":GATHER:EXECUTE", 1)
         self.timer.start(tick)
         self.go_countdown = 50
         self.go_timer.stop()
     else:
         self.go_countdown -= 1
示例#8
0
def worker(n):
    for i in range(25):
        print(f"{n}", end="")
        if i == 6:
            raise Exception(f"cothread {n} crashed!")
        cothread.Sleep(random.random() * 0.5)  # suspend cothread

    print()
示例#9
0
    def get_mr(self):
        global beam_current_bounds
        get_command = abstract_caget
        beam_current_max_warning = False
        ''' First measure the injection results '''
        # Begin injecting
        print "Start injection"
        caput('LI-TI-MTGEN-01:START', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:START', 0)
        cothread.Sleep(4.0)

        beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
        while beam_current < beam_current_bounds[0]:
            print 'waiting for beam current to rise above ', beam_current_bounds[
                0]
            cothread.Sleep(1)
            beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
            print '...'

        run = True
        start_time = time.time()

        mrs_inj = measure_results(self.measurement_vars_inj, abstract_caget)
        ''' Now for the non-injection measurements '''

        if get_command('SR-DI-DCCT-01:SIGNAL') > beam_current_bounds[1]:
            beam_current_max_warning = True

        # Stop injection
        print "Stop injection"
        caput('LI-TI-MTGEN-01:STOP', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:STOP', 0)
        cothread.Sleep(1)

        mrs_noinj = measure_results(self.measurement_vars_noinj,
                                    abstract_caget)
        ''' Now combine the results into a single list '''

        results = mrs_noinj + mrs_inj

        mrs = results

        return mrs, beam_current_max_warning
示例#10
0
    def test_oneshot(self):
        l = []

        def tick():
            l.append(1)

        t = cothread.Timer(0.1, tick, reuse=True)
        self.assertEqual(l, [])
        cothread.Sleep(0.2)
        self.assertEqual(l, [1])
        cothread.Sleep(0.2)
        self.assertEqual(l, [1])
        t.reset(0.05)
        self.assertEqual(l, [1])
        cothread.Sleep(0.1)
        self.assertEqual(l, [1, 1])
        cothread.Sleep(0.1)
        self.assertEqual(l, [1, 1])
示例#11
0
def timer():
    last = time.time()
    last_callbacks = 0
    while True:
        cothread.Sleep(1)
        now = time.time()
        print("%d callbacks" % callbacks, callbacks - last_callbacks)
        last = now
        last_callbacks = callbacks
示例#12
0
 def test_rate_conversion(self):
     channel = MagicMock()
     listener = MagicMock()
     sub = Subscription(channel, listener, 0.01)
     channel.value = 32
     sub.cb_value(channel.value)
     channel.value = 33
     sub.cb_value(channel.value)
     listener.cb_value.assert_called_once_with(sub, 32)
     listener.cb_value.reset_mock()
     channel.value = 34
     cothread.Sleep(0.01)
     sub.cb_value(channel.value)
     listener.cb_value.assert_called_once_with(sub, 34)
     listener.cb_value.reset_mock()
     channel.value = 35
     cothread.Sleep(0.01)
     sub.cb_value(channel.value)
     listener.cb_value.assert_called_once_with(sub, 35)
示例#13
0
def main():

    for i in range(2):

        print "Acquire " + str(i)

        #Set up ROI1 on XY and enable ROI filter
        caput("BL99:Det:N1:Det1:PixelROIFilterEnable",
              1,
              wait=True,
              timeout=20)

        caput("BL99:Det:N1:Start", 1, wait=True, timeout=2000)
        status = caget("BL99:Det:N1:DetectorState_RBV")
        if (status != STAT_ACQUIRE):
            print "ERROR on Start: i= " + str(i) + \
                " status= " + str(status) + " and it should be " + str(STAT_ACQUIRE)
            sys.exit(1)

        for x in range(32):
            for y in range(32):

                print "x: " + str(x)
                print "y: " + str(y)
                caput("BL99:Det:N1:Det1:XY:ROI:1:MinX",
                      x,
                      wait=True,
                      timeout=20)
                caput("BL99:Det:N1:Det1:XY:ROI:1:MinY",
                      y,
                      wait=True,
                      timeout=20)

                for xsize in range(32):
                    for ysize in range(32):

                        print "xsize: " + str(xsize)
                        print "ysize: " + str(ysize)
                        caput("BL99:Det:N1:Det1:XY:ROI:1:SizeX",
                              xsize,
                              wait=True,
                              timeout=20)
                        caput("BL99:Det:N1:Det1:XY:ROI:1:SizeY",
                              ysize,
                              wait=True,
                              timeout=20)

                        cothread.Sleep(0.1)

        caput("BL16B:Det:ADnED:Stop", 1, wait=True, timeout=2000)
        status = caget("BL16B:Det:ADnED:DetectorState_RBV")
        if (status != STAT_IDLE):
            print "ERROR on Stop: i= " + str(i) + \
                " status= " + str(status) + " and it should be " + str(STAT_IDLE)
            sys.exit(1)
示例#14
0
文件: pmaccases.py 项目: jlmuir/tpmac
    def pollDMOVs(self):
        for motor in self.getMotors():
            dmov = 0
            pv_dmov = self.getPVBase() + motor + ".DMOV"
            while (dmov == 0):
                cothread.Sleep(0.1)
                dmov = self.getPv(pv_dmov)
                if dmov:
                    self.diagnostic("Motor " + str(motor) + " has finished.")

        self.diagnostic("All motors finished.")
def main():
   
    for i in range(10000):

        print "Acquire " + str(i)

        error = False
   
        caput("BL1A:Det:ADnED:Start", 1, wait=True, timeout=10)
        status = caget("BL1A:Det:ADnED:State")
        if (status != STAT_OK):
            print "ERROR on ADnED start. High level status: " + str(status) + ". It should be " + str(STAT_OK)
            adned_status = caget("BL1A:Det:N1:DetectorState_RBV")
            adned_status_msg = caget("BL1A:Det:N1:StatusMessage_RBV")
            print "ADnED status: " + str(adned_status) + ". Message: " + str(adned_status_msg)
            error = True

        if error:
            cothread.Sleep(1)
            status = caget("BL1A:Det:N1:DetectorState_RBV")
            print "ADnED delayed status read: " + str(status)
            status = caget("BL1A:Det:N1:DetectorState_RBV")
            sys.exit(1)

        cothread.Sleep(1)

        caput("BL1A:Det:ADnED:Stop", 1, wait=True, timeout=10)
        #cothread.Sleep(1) #At the moment callback not supported on a stop.
        status = caget("BL1A:Det:ADnED:State")
        if (status != STAT_OK):
            print "ERROR on Stop. High level status: " + str(status) + ". It should be " + str(STAT_OK)
            adned_status = caget("BL1A:Det:N1:DetectorState_RBV")
            adned_status_msg = caget("BL1A:Det:N1:StatusMessage_RBV")
            print "ADnED Status: " + str(adned_status) + ". Message: " + str(adned_status_msg)
            error = True

        if error:
            cothread.Sleep(1)
            status = caget("BL1A:Det:N1:DetectorState_RBV")
            print "ADnED delayed status read: " + str(status)
            sys.exit(1)
示例#16
0
文件: pmaccases.py 项目: jlmuir/tpmac
    def runTest(self):

        for motor in self.getMotors():

            self.diagnostic(
                "motorCaseMoveCheckStatus for motor " + str(motor) + "...",
                self.getDiag())

            pv_val = self.getPVBase() + motor + ".VAL"
            pv_dmov = self.getPVBase() + motor + ".DMOV"
            pv_msta = self.getPVBase() + motor + ".MSTA"
            pv_dir = self.getPVBase() + motor + ".DIR"
            pv_stop = self.getPVBase() + motor + ".STOP"

            #First move motor to zero
            self.diagnostic("Move to zero.", self.getDiag())
            self.putPv(pv_val, 0.0, wait=True, timeout=self.getTimeout())

            #Check MSTA Done is set
            self.verify(0x2, (int(self.getPv(pv_msta)) & 0x2))

            #Not do a move, with no callback
            self.diagnostic("Move to 100.", self.getDiag())
            self.putPv(pv_val, 100.0, wait=False)

            #Use cothread sleep instead of time.sleep(), which blocks the cothread library (stopping the previous caput working).
            cothread.Sleep(2.0)

            #Read DIR field
            direction = self.getPv(pv_dir)
            if (direction == 0):
                #Check MSTA Done is not set, and moving flag is on and direction positive is on.
                self.verify(0x401, (int(self.getPv(pv_msta)) & 0x401))
            else:
                #Check MSTA Done is not set, and moving flag is on.
                self.verify(0x400, (int(self.getPv(pv_msta)) & 0x400))

            #Now stop it, check status, and move back to zero
            self.diagnostic("Stopping.", self.getDiag())
            self.putPv(pv_stop, 1, wait=True, timeout=self.getTimeout())

            self.diagnostic("Move completed. Do final MSTA checks.",
                            self.getDiag())
            #Check MSTA Done is set
            self.verify(0x2, (int(self.getPv(pv_msta)) & 0x2))
            #Check MSTA moving is not set
            self.verify(0x0, (int(self.getPv(pv_msta)) & 0x400))

            #Move back to zero
            self.diagnostic("Move back to zero.", self.getDiag())
            self.putPv(pv_val, 0.0, wait=True, timeout=self.getTimeout())
示例#17
0
    def rampingPut(self):
        try:
            step = int(self.stepLineEdit.text())
            delay = float(self.delayLineEdit.text())
        except:
            print("No ramping: wrong settings of Step or Delay time.")
            QMessageBox.warning(
                self, 'Warning',
                'No ramping: wrong settings of Step or Delay time. Please try again'
            )
            return
        #print("Number of steps: %d; Waiting time between steps: %d"%(step, delay))
        if step < 1:
            print("No ramping: number of steps can't be zero")
            QMessageBox.warning(
                self, 'Warning',
                'No ramping: the number of Steps should be >=1. Please try again'
            )
            return

        try:
            curValues = caget(self.rampPVList, timeout=2, throw=False)
        except:
            print(
                "Oops: can't get PV values to ramp the machine, but will try one-step simple restore"
            )
            traceback.print_exc()
            #QMessageBox.warning(self, 'Warning', "No multiple-step gradual put: some PVs seem disconnected")
            return True  #try one-step simple put
        #print(self.rampPVList)
        #print(curValues)
        #print(self.rampRestoreData)
        try:
            stepSize = [(i - j) / step
                        for i, j in zip(self.rampRestoreData, curValues)]
            #print(stepSize)
            for l in range(1, step):
                stepValues = [l * m + n for m, n in zip(stepSize, curValues)]
                #print(stepValues)
                caput(self.rampPVList, stepValues)
                cothread.Sleep(delay)
        except:
            print(
                "Oops: something wrong with ramping machine, but will try one-step simple restore"
            )
            traceback.print_exc()
            #QMessageBox.warning(self, 'Warning', "Oops: something wrong with multiple-step gradual put")

        return True
示例#18
0
def set_params(param_vars, settings, set_command):
    """
    change the parameters using set_command. This will usually be abstract_caput
    """

    # Calculate the maximum delay time
    max_delay = 0
    for i in param_vars:
        if i.delay > max_delay:
            max_delay = i.delay

    # Set the parameters
    for i in range(len(param_vars)):
        set_command(param_vars[i].pv, settings[i])

    # Sleep for the appropriate amount of time
    cothread.Sleep(max_delay)
示例#19
0
    def put(self, pv, op):
        if self.busy:
            op.done(error="Move in progress")
            return
        self.busy = True
        try:
            initial = self.pos
            final = op.value()
            delta = abs(final-initial)
            op.info("Moving %s -> %s"%(initial, final))

            while delta>=1.0:
                op.info("Moving %s"%delta)
                delta -= 1.0
                cothread.Sleep(1.0) # move at 1 step per second

            self.pos = final
            op.done()
        finally:
            self.busy = False
示例#20
0
 def on_configure(
     self,
     context: scanning.hooks.AContext,
     completed_steps: scanning.hooks.ACompletedSteps,
     steps_to_do: scanning.hooks.AStepsToDo,
     part_info: scanning.hooks.APartInfo,
     generator: scanning.hooks.AGenerator,
     fileDir: scanning.hooks.AFileDir,
     **kwargs: Any,
 ) -> None:
     super(TucsenDriverPart, self).on_configure(
         context,
         completed_steps,
         steps_to_do,
         part_info,
         generator,
         fileDir,
         **kwargs,
     )
     cothread.Sleep(1.5)
示例#21
0
def main():

    for i in range(1000):

        print "Acquire " + str(i)

        caput("BL99:Det:N1:Start", 1, wait=True, timeout=5)
        status = caget("BL99:Det:N1:DetectorState_RBV")
        if (status != STAT_ACQUIRE):
            print "ERROR on Start: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(STAT_ACQUIRE)
            sys.exit(1)

        cothread.Sleep(1)

        caput("BL99:Det:N1:Stop", 1, wait=True, timeout=5)
        status = caget("BL99:Det:N1:DetectorState_RBV")
        if (status != STAT_IDLE):
            print "ERROR on Stop: i= " + str(i) + \
            " status= " + str(status) + " and it should be " + str(STAT_IDLE)
            sys.exit(1)
示例#22
0
    def test_spawn_locked(self):
        def set_v1():
            with self.o:
                self.v = 1

        # check our setter works in isolation
        assert self.v is None
        cothread.Spawn(set_v1).Wait()
        assert self.v == 1

        # now do a long running task works
        with self.o:
            self.v = 2
            assert self.v == 2
            # start our thing that will be blocked, then sleep to make sure
            # it can't do its thing
            s = cothread.Spawn(set_v1)
            cothread.Sleep(0.2)
            assert self.v == 2

        # now wait for the other to complete, and check it could
        s.Wait()
        assert self.v == 1
示例#23
0
    def _co_execute(self):
        """Execute the virtual accelerator. This includes the following:

        1. Creating a temporary working directory for execution of FLAME.
        2. Set up the working directory by symlinking from the data directory.
        3. Writing the EPICS DB to the working directory (va.db).
        4. Starting the softIoc and channel initializing monitors.
        5. Add noise to the settings for all input (CSET) channels.
        6. Create or update the FLAME machine configuration.
        7. Propagate the FLAME simulation and read the results.
        8. Update the READ channels of all devives.
        9. Update the REST channels of input devies.
        10. Repeat from step #5.
        """
        _LOGGER.debug("VA: Execute virtual accelerator")
        _LOGGER.info("VA: Running at " + self._ts_now)

        chanprefix = self._chanprefix
        if self._pv_suffix != '':
            suffix_str = "_" + self._pv_suffix
        else:
            suffix_str = ""

        # Add channel for VA rep-rate
        chanrate = f"{chanprefix}:SVR:RATE{suffix_str}"
        self._epicsdb.append(("ao", chanrate, OrderedDict([
            ("DESC", "Rep-rate of Simulation Engine"),
            ("VAL", self._rate),
            ("PREC", 1),
            ])))
        _LOGGER.info("VA: Reprate PV is " + chanrate)


        # Add channel for sample counting
        chansample_cnt = f"{chanprefix}:SVR:CNT{suffix_str}"
        self._epicsdb.append(("ao", chansample_cnt, OrderedDict([
            ("DESC", "Sample counter for scan client"),
            ("VAL", 0)
            ])))

        # Add channel for VA configuration and control
        channoise = f"{chanprefix}:SVR:NOISE{suffix_str}"
        self._epicsdb.append(("ao", channoise, OrderedDict([
                ("DESC", "Noise level of Virtual Accelerator"),
                ("VAL", self._noise),
                ("PREC", 5)
            ])))
        _LOGGER.info("VA: Noise PV is " + channoise)

        chanstat = f"{chanprefix}:SVR:STATUS{suffix_str}"
        self._epicsdb.append(("bi", chanstat, OrderedDict([
                ("DESC", "Status of Virtual Accelerator"),
                ("VAL", 1),
                ("ZNAM", "ERR"),
                ("ONAM", "OK"),
                ("PINI", "1")
            ])))
        _LOGGER.info("VA: Status PV is " + chanstat)

        # MPS status
        chan_mps_stat = f"{chanprefix}:SVR:MpsStatus"
        self._epicsdb.append(("mbbi", chan_mps_stat, OrderedDict([
                ("DESC", "MPS Status of Virtual Accelerator"),
                ("VAL", 3),
                ("ZRST", "Fault"),
                ("ONST", "Disable"),
                ("TWST", "Monitor"),
                ("THST", "Enable"),
                ("PINI", "1")
            ])))
        _LOGGER.info("VA: MPS PV is " + chan_mps_stat)

        #
        chancharge = f"{chanprefix}:SVR:CHARGE{suffix_str}"
        self._epicsdb.append(("ai", chancharge, OrderedDict([
                ("DESC", "Q/M of Virtual Accelerator"),
                ("VAL", 0.0),
                ("PREC", 5)
            ])))

        # initial beam condition
        chanbsrc = f"{chanprefix}:SVR:BEAM{suffix_str}"
        self._epicsdb.append(("waveform", chanbsrc, OrderedDict([
                ("DESC", "Init beam of Virtual Accelerator"),
                ("NELM", 4096),
                ("FTVL", "UCHAR")
            ])))
        _LOGGER.info("VA: Init beam condition PV is " + chanbsrc)

        #
        if self.work_dir is not None:
            os.makedirs(self.work_dir)
            self._rm_work_dir = False
            latticepath = os.path.join(self.work_dir, "test.lat")
        else:
            self.work_dir = tempfile.mkdtemp(_TEMP_DIRECTORY_SUFFIX)
            self._rm_work_dir = True
            latticepath = None

        _LOGGER.info("VA: Working directory: %s", self._work_dir)

        # input file paths
        epicsdbpath = os.path.join(self.work_dir, "va.db")

        #output file paths
        epicslogpath = os.path.join(self.work_dir, "softioc.log")

        if os.path.isabs(self.data_dir):
            abs_data_dir = self.data_dir
            self._latfactory.dataDir = self.data_dir
        else:
            abs_data_dir = os.path.abspath(self.data_dir)
            self._latfactory.dataDir = os.path.abspath(self.data_dir)

        with open(epicsdbpath, "w") as outfile:
            self._write_epicsdb(outfile)
        _LOGGER.info("VA: Write EPICS database to %s", epicsdbpath)
        #_LOGGER.debug("VA: Write EPICS database to %s", epicsdbpath)

        self._ioc_logfile = open(epicslogpath, "w")
        self._ioc_process = Popen(["softIoc", "-d", "va.db"], cwd=self.work_dir,
                                  stdout=self._ioc_logfile, stderr=subprocess.STDOUT)
        _LOGGER.debug("VA: Start EPICS soft IOC with log %s", epicslogpath)

        _LOGGER.debug("VA: Connecting to channels: {}".format(len(self._csetmap.keys())))

        self._subscriptions = []
        self._subscriptions.append(catools.camonitor(chanrate, self._handle_rate_monitor))
        self._subscriptions.append(catools.camonitor(channoise, self._handle_noise_monitor))
        self._subscriptions.append(catools.camonitor(chanbsrc, self._handle_bsrc_monitor))
        self._subscriptions.extend(catools.camonitor(self._csetmap.keys(), self._handle_cset_monitor))
        _LOGGER.debug("VA: Connecting to channels: Done")

        machine = None

        while self._continue:
            # update the RSET channels with new settings
            batch = catools.CABatch()
            for cset in self._csetmap.items():
                name, field = self._fieldmap[cset[0]]
                batch[cset[1][0]] = self._settings[name][field]
            batch.caput()

            settings = self._copy_settings_with_noise()
            self._latfactory.settings = settings
            lattice = self._latfactory.build()

            start = time.time()

            if machine is None:
                _LOGGER.debug("VA: Create FLAME machine from configuration")
                machine = Machine(lattice.conf())
            else:
                _LOGGER.debug("VA: Reconfigure FLAME machine from configuration")
                for idx, elem in enumerate(lattice.elements):
                    machine.reconfigure(idx, elem[2])

                if self._bsrc is not None:
                    _LOGGER.info("VA: Reconfigure FLAME machine with init beam config")
                    machine.reconfigure(self._bsrc['index'], self._bsrc['properties'])

            if latticepath is not None:
                _LOGGER.debug(f"VA: Write FLAME lattice file to {outfile}")
                generate_latfile(machine, latfile=latticepath)

            _LOGGER.debug("VA: Allocate FLAME state from configuration")
            S = machine.allocState({})

            output_map = []
            for elem in lattice.elements:
                if 'name' in elem[3]:
                    output_map.append(elem[3]['name'])
                else:
                    output_map.append(None)

            batch = catools.CABatch()
            for i in range(0, len(machine)):
                machine.propagate(S, i, 1)

                if output_map[i] in self._elemmap:
                    elem = self._elemmap[output_map[i]]

                    if isinstance(elem, BPMElement):
                        x_centroid = S.moment0_env[0]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.x_phy], x_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.x_phy]] = x_centroid
                        y_centroid = S.moment0_env[2]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.y_phy], y_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.y_phy]] = y_centroid
                         # convert rad to deg and adjust for 161MHz sampling frequency
                        phase = _normalize_phase(2.0 * S.ref_phis * (180.0 / math.pi))
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.phase_phy], phase)
                        batch[self._readfieldmap[elem.name][elem.fields.phase_phy]] = phase
                        energy = S.ref_IonEk/1.0e6 # convert eV to MeV
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.energy_phy], energy)
                        batch[self._readfieldmap[elem.name][elem.fields.energy_phy]] = energy

                    elif isinstance(elem, PMElement):
                        x_centroid = S.moment0_env[0]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.x], x_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.x]] = x_centroid
                        y_centroid = S.moment0_env[2]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.y], y_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.y]] = y_centroid
                        x_rms = S.moment0_rms[0]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.xrms], x_rms)
                        batch[self._readfieldmap[elem.name][elem.fields.xrms]] = x_rms
                        y_rms = S.moment0_rms[2]/1.0e3
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.yrms], y_rms)
                        batch[self._readfieldmap[elem.name][elem.fields.yrms]] = y_rms

                        sign = elem.sign
                        xy_centroid = (sign*x_centroid + y_centroid)/math.sqrt(2.0) # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.xy], xy_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.xy]] = xy_centroid

                        xy_rms = 1.0e-3*math.sqrt(
                                (S.moment1_env[0, 0] + S.moment1_env[2, 2])*0.5
                                + sign*S.moment1_env[0, 2]
                        )
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.xyrms], xy_rms)
                        batch[self._readfieldmap[elem.name][elem.fields.xyrms]] = xy_rms

                        cxy = sign * S.moment1_env[0, 2] * 1e-6 / x_rms / y_rms
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.cxy], cxy)
                        batch[self._readfieldmap[elem.name][elem.fields.cxy]] = cxy

                    elif isinstance(elem, (FCElement, VDElement, TargetElement, DumpElement, WedgeElement)):
                        x_centroid = S.moment0_env[0]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.x], x_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.x]] = x_centroid
                        y_centroid = S.moment0_env[2]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.y], y_centroid)
                        batch[self._readfieldmap[elem.name][elem.fields.y]] = y_centroid
                        x_rms = S.moment0_rms[0]/1.0e3 # convert mm to m
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.xrms], x_rms)
                        batch[self._readfieldmap[elem.name][elem.fields.xrms]] = x_rms
                        y_rms = S.moment0_rms[2]/1.0e3
                        _LOGGER.debug("VA: Update read: %s to %s",
                                      self._readfieldmap[elem.name][elem.fields.yrms], y_rms)
                        batch[self._readfieldmap[elem.name][elem.fields.yrms]] = y_rms

            batch.caput()

            _LOGGER.info("VA: FLAME execution time: %f s", time.time()-start)

            # Allow the BPM, PM, etc. readbacks to update
            # before the device setting readbacks PVs.
            cothread.Yield()

            batch = catools.CABatch()
            for name, value in self._csetmap.items():
                name, field = self._fieldmap[name]
                _LOGGER.debug("VA: Update read: %s to %s", value[1], settings[name][field])
                batch[value[1]] = settings[name][field]
            batch.caput()

            # Sleep for a fraction (10%) of the total execution time
            # when one simulation costs more than 0.50 seconds.
            # Otherwise, sleep for the rest of 1 second.
            # If a scan is being done on this virtual accelerator,
            # then the scan server has a period of time to update
            # setpoints before the next run of IMPACT.
            delt = time.time() - start
            if delt > 0.50:
                cothread.Sleep(delt * 0.1)
            else:
                cothread.Sleep(1.0 / self._rate - delt)
示例#24
0
def worker(n, event):
    event.Wait()
    for i in range(25):
        print(f"{n}", end="")
        cothread.Sleep(random.random() * 0.5)  # suspend cothread
    print()
示例#25
0
import cothread
import random


def worker(n, event):
    event.Wait()
    for i in range(25):
        print(f"{n}", end="")
        cothread.Sleep(random.random() * 0.5)  # suspend cothread
    print()


threads = []
event = cothread.Event(auto_reset=False)
# auto_reset=True:  let only one cothread see the signal
# auto_reset=False: let all cothreads see the signal

for n in range(1, 5):
    t = cothread.Spawn(worker, n, event)
    threads.append(t)

delay = 10
print(f"main cothread waiting for {delay} seconds")
cothread.Sleep(delay)

event.Signal()
for t in threads:
    t.Wait()
示例#26
0
 def test_starts_ioc(self):
     cothread.Sleep(5)
     assert catools.caget(self.prefix + ":PYMALCOLM:VER") in ["work", __version__]
示例#27
0
    def get_mr(self):
        #mrs = measure_results(self.measurement_vars, model.caget)

        average_inj = [0] * len(self.measurement_vars_inj)
        counts_inj = [0] * len(self.measurement_vars_inj)
        dev_inj = [0] * len(self.measurement_vars_inj)

        average_noinj = [0] * len(self.measurement_vars_noinj)
        counts_noinj = [0] * len(self.measurement_vars_noinj)
        dev_noinj = [0] * len(self.measurement_vars_noinj)
        ''' Final ones '''
        #average = [0] * len(measurement_vars)
        #counts = [0] * len(measurement_vars)
        #dev = [0] * len(measurement_vars)

        get_command = model.caget

        run = True
        start_time = time.time()
        ''' First measure the injection results '''
        # Begin injecting
        print "Start injection"
        #caput('LI-TI-MTGEN-01:START', 1)
        cothread.Sleep(0.1)
        #caput('LI-TI-MTGEN-01:START', 0)
        cothread.Sleep(1)

        run = True
        start_time = time.time()

        while run:
            # Check whether to make any measurements
            for i in range(len(self.measurement_vars_inj)):
                # If the time since start is > the measurement delay * number of times its been counted, then
                if (time.time() - start_time) > (
                        self.measurement_vars_inj[i].delay * counts_inj[i]):
                    print "Measuring {0}".format(
                        self.measurement_vars_inj[i].pv)
                    value = get_command(self.measurement_vars_inj[i].pv)
                    average_inj[i] += value
                    counts_inj[i] += 1
                    dev_inj[i] += value**2

            # Check if finished
            run = False
            for i in range(len(self.measurement_vars_inj)):
                # If the number counted is less than that required, then carry on, else you can stop
                if counts_inj[i] < self.measurement_vars_inj[i].min_counts:
                    run = True

        average_inj = [
            average_inj[i] / counts_inj[i] for i in range(len(average_inj))
        ]
        dev_inj = [(dev_inj[i] / counts_inj[i]) - average_inj[i]**2
                   for i in range(len(average_inj))]
        err_inj = [(dev_inj[i]) / (math.sqrt(counts_inj[i]))
                   for i in range(len(average_inj))]

        # Return results back to the optimiser
        #return average We would previously just return the number. Now we will return a measurement object
        results_inj = []
        for i in range(len(average_inj)):
            results_inj.append(
                measurement(mean=average_inj[i],
                            counts=counts_inj[i],
                            dev=dev_inj[i],
                            err=err_inj[i]))
        ''' Now for the non-injection measurements '''
        # Stop injection
        print "Stop injection"
        #caput('LI-TI-MTGEN-01:STOP', 1)
        cothread.Sleep(0.1)
        #caput('LI-TI-MTGEN-01:STOP', 0)
        cothread.Sleep(1)

        run = True
        start_time = time.time()

        while run:
            # Check whether to make any measurements
            for i in range(len(self.measurement_vars_noinj)):
                # If the time since start is > the measurement delay * number of times its been counted, then
                if (time.time() -
                        start_time) > (self.measurement_vars_noinj[i].delay *
                                       counts_noinj[i]):
                    print "Measuring {0}".format(
                        self.measurement_vars_noinj[i].pv)
                    value = get_command(self.measurement_vars_noinj[i].pv)
                    average_noinj[i] += value
                    counts_noinj[i] += 1
                    dev_noinj[i] += value**2

            # Check if finished
            run = False
            for i in range(len(self.measurement_vars_noinj)):
                # If the number counted is less than that required, then carry on, else you can stop
                if counts_noinj[i] < self.measurement_vars_noinj[i].min_counts:
                    run = True

        average_noinj = [
            average_noinj[i] / counts_noinj[i]
            for i in range(len(average_noinj))
        ]
        dev_noinj = [(dev_noinj[i] / counts_noinj[i]) - average_noinj[i]**2
                     for i in range(len(average_noinj))]
        err_noinj = [(dev_noinj[i]) / (math.sqrt(counts_noinj[i]))
                     for i in range(len(average_noinj))]

        # Return results back to the optimiser
        #return average We would previously just return the number. Now we will return a measurement object
        results_noinj = []
        for i in range(len(average_noinj)):
            results_noinj.append(
                measurement(mean=average_noinj[i],
                            counts=counts_noinj[i],
                            dev=dev_noinj[i],
                            err=err_noinj[i]))
        ''' Now combine the results into a single list '''

        results = results_noinj + results_inj

        mrs = results

        return mrs
示例#28
0
 def _sleep(self, delay):
     cothread.Sleep(delay)
示例#29
0
 def test_ioc_ticks(self):
     cothread.Sleep(5)
     uptime = catools.caget(self.prefix + ":UPTIME:RAW")
     assert uptime >= 0
     time.sleep(5)
     assert catools.caget(self.prefix + ":UPTIME:RAW") >= uptime + 5
def worker(n):
    for i in range(25):
        print(f"{n}", end="")
        cothread.Sleep(random.random() * 0.5) # suspend cothread   
    print()