Exemplo n.º 1
0
  def run(self, args):
    def color_change(x):
      """
      Formatting the output for clarity of what the user should be doing.
      """
      if x == '[ON]':
        return log.GREEN(x)
      if x == '[OFF]':
        return log.RED(x)
      if re.match(r'\[[\d\.]+[a-zA-Z]*\]', x):
        return log.GREEN(x)
      if x.isupper():
        return log.YELLOW(x)
      return x

    is_defined = args.string[0] in self.action.shorthands()

    msg = self.action.getmessage(args.string[0]) if is_defined \
          else args.string[0]

    msg = ' '.join([color_change(x) for x in msg.split()])
    log.printmsg(log.GREEN('    THE NEXT STEP REQUIRES USER INTERVENTION'))
    log.printmsg('    > ' + msg)

    input_text = ''
    while input_text != args.string[0]:
      self.check_handle()
      self.printmsg(log.GREEN(f'    TYPE [{args.string[0]}] to continue...'))
      input_text = self.cmd.stdin.readline().strip()

    if is_defined:
      cmd = 'set ' + ' '.join(self.action.getset(args.string[0]))
      self.cmd.onecmd(cmd.strip())
Exemplo n.º 2
0
 def print_printer(self):
   header = log.GREEN('[PRINTER]')
   log.printmsg(header, 'device: ' + str(self.gcoder.dev_path))
   log.printmsg(
       header, 'current coordinates: x{0:.1f} y{1:.1f} z{2:0.1f}'.format(
           self.gcoder.opx, self.gcoder.opy, self.gcoder.opz))
   printset = self.gcoder.getsettings()
   printset = printset.split('\necho:')
   for line in printset:
     log.printmsg(log.GREEN('[PRINTER]'), line)
Exemplo n.º 3
0
 def color_change(x):
   """
   Formatting the output for clarity of what the user should be doing.
   """
   if x == '[ON]':
     return log.GREEN(x)
   if x == '[OFF]':
     return log.RED(x)
   if re.match(r'\[[\d\.]+[a-zA-Z]*\]', x):
     return log.GREEN(x)
   if x.isupper():
     return log.YELLOW(x)
   return x
Exemplo n.º 4
0
class visualshowdet(visualmeta):
    """@brief Display of detector position, until termination signal is obtained."""
    LOG = log.GREEN('[SHOW DETECTOR]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        self.parser.add_argument('--raw',
                                 '-r',
                                 action='store_true',
                                 help="""
                             Show the raw image without image processing
                             lines""")

    def parse(self, args):
        args.monitor = True  # Forcing to be true.
        return args

    def run(self, args):
        self.printmsg("PRESS CTL+C to stop the command")
        self.printmsg("Legend")
        self.printmsg("Failed contor ratio requirement")
        self.printmsg(log.GREEN("Failed area luminosity requirement"))
        self.printmsg(log.YELLOW("Failed rectangular approximation"))
        self.printmsg(log.CYAN("Candidate contour (not largest)"))
        while True:
            try:
                self.check_handle()
            except:
                break

            self.show_img(args, args.raw)
            time.sleep(args.vwait)
Exemplo n.º 5
0
class pulse(cmdbase.controlcmd):
    """
  Running the trigger for a certain about of pulses with alternative wait
  options.

  @details this is some test
  """

    LOG = log.GREEN('[PULSE]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        self.parser.add_argument('-n',
                                 type=int,
                                 default=100000,
                                 help='number of times to fire the trigger')
        self.parser.add_argument(
            '--wait',
            type=int,
            default=500,
            help='Time (in microseconds) between triggers')

    def run(self, args):
        # Splitting into 1000 chunks
        for i in range(args.n // 100):
            self.check_handle()
            self.gpio.pulse(100, args.wait)
Exemplo n.º 6
0
class zscan(cmdbase.controlcmd):
    """
  Performing z scanning at a certain x-y coordinate
  """

    DEFAULT_SAVEFILE = 'zscan_<CHIPID>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[LUMI ZSCAN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_zscan_options()
        self.add_savefile_options(zscan.DEFAULT_SAVEFILE)

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_readout_options(args)
        self.parse_zscan_options(args)
        self.parse_xychip_options(args)
        self.parse_savefile(args)
        return args

    def run(self, args):
        self.init_handle()
        lumi = []
        unc = []

        for z in args.zlist:
            self.check_handle(args)
            self.move_gantry(args.x, args.y, z, False)

            lumival = 0
            uncval = 0
            while 1:
                lumival, uncval = self.readout.read(channel=args.channel,
                                                    samples=args.samples)
                if self.readout.mode == self.readout.MODE_PICO:
                    wmax = self.pico.waveformmax(args.channel)
                    if wmax < 100 and self.pico.range > self.pico.rangemin():
                        self.pico.setrange(self.pico.range - 1)
                    elif wmax > 200 and self.pico.range < self.pico.rangemax():
                        self.pico.setrange(self.pico.range + 1)
                    else:
                        break
                else:
                    break

            lumi.append(lumival)
            unc.append(uncval)

            # Writing to screen
            self.update('z:{0:5.1f}, L:{1:8.5f}, uL:{2:8.6f}'.format(
                z, lumival, uncval))
            # Writing to file
            args.savefile.write(
                "{0:5.1f} {1:5.1f} {2:5.1f} {3:8.5f} {4:8.6f}\n".format(
                    args.x, args.y, z, lumival, uncval))

        self.close_savefile(args)
Exemplo n.º 7
0
class lowlightcollect(cmdbase.singlexycmd, cmdbase.readoutcmd,
                      cmdbase.savefilecmd):
    """@brief Collection of low light data at a single gantry position, data will
  be collected without averaging."""

    DEFAULT_SAVEFILE = 'lowlight_<BOARDTYPE>_<BOARDID>_<DETID>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[LUMI LOWLIGHT]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        """@brief adding the additional arguments"""
        self.parser.add_argument('-z',
                                 type=float,
                                 default=300,
                                 help="""z height to perform the low light
                             collection result. (units: mm)""")
        self.parser.add_argument(
            '--power',
            '-p',
            type=float,
            help="""PWM duty cycle for data collection, using
                             current value if not specified""")

    def parse(self, args):
        """
    @details As the number of samples passed to the readoutcmd class is typically
    very large for the readout settings. Here we split the samples into segments
    of 1000 data collections as this will help to monitor and segment the
    function in-case of user cutoff.
    """
        if not args.power:
            args.power = self.gpio.pwm_duty(0)
        ## Modifying the sample argument to make monitoring simpler:
        args.nparts = (args.samples // 1000) + 1
        args.samples = 1000
        return args

    def run(self, args):
        """
    @brief Running low light collection.

    @details Operation of this command relatively straight forwards, simply run
    the readout command multiple times with no averaging and write to a file in
    standard format. Progress will be printed for every 1000 data collections.
    """
        self.move_gantry(args.x, args.y, args.z, False)
        self.gpio.pwm(0, args.power, 1e5)
        for i in range(args.nparts):
            self.check_handle()
            readout = self.readout(args, average=False)
            self.write_standard_line(readout, det_id=args.detid)
            self.update_progress(
                progress=(i + 1, args.nparts),
                temperature=True,
                coordinates=True,
                display_data={'Lumi': (readout[-1], readout[-2])})
Exemplo n.º 8
0
 def print_action(self):
   header = log.GREEN('[ACTION]')
   msg_format = log.YELLOW('{0}') + ' | {1}'
   set_format = log.YELLOW('{0}') + ' | RUN CMD | set {1}'
   for key in self.action.shorthands():
     msg = msg_format.format(key, self.action.getmessage(key))
     smsg = set_format.format(key, " ".join(self.action.getset(key)))
     log.printmsg(header, msg)
     log.printmsg(header, smsg)
Exemplo n.º 9
0
 def print_camera(self):
   header = log.GREEN('[CAMERA]')
   log.printmsg(header, str(self.visual.dev_path))
   log.printmsg(header, 'Threshold:{0:3f}'.format(self.visual.threshold))
   log.printmsg(header, 'Blur:     {0:3d} [pix]'.format(self.visual.blur_range))
   log.printmsg(header, 'Max Lumi: {0:3f}'.format(self.visual.lumi_cutoff))
   log.printmsg(header,
                'Min Size: {0:3d} [pix]'.format(self.visual.size_cutoff))
   log.printmsg(header, 'Ratio:    {0:3f}'.format(self.visual.ratio_cutoff))
   log.printmsg(header, 'Poly:     {0:3f}'.format(self.visual.poly_range))
Exemplo n.º 10
0
 def print_board(self):
   header = log.GREEN('[BOARDTYPE]')
   msg_format = 'Det:{0:>4s} | x:{1:5.1f}, y:{2:5.1f}'
   log.printmsg(header, str(self.board.boardtype))
   log.printmsg(header, str(self.board.boarddescription))
   log.printmsg(header, 'Board ID: ' + self.board.boardid)
   for detid in self.board.dets():
     det = self.board.get_det(detid)
     msg = msg_format.format(detid, det.orig_coord[0], det.orig_coord[1])
     log.printmsg(header, msg)
Exemplo n.º 11
0
class getcoord(cmdbase.controlcmd):
    """Printing current gantry coordinates"""
    LOG = log.GREEN('[GANTRY-COORD]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def run(self, args):
        self.printmsg('x:{0:.1f} y:{1:.1f} z:{2:.1f}'.format(
            self.gcoder.cx, self.gcoder.cy, self.gcoder.cz))
Exemplo n.º 12
0
class showreadout(cmdbase.controlcmd):
    """
  Continuously display ADC readout
  """

    LOG = log.GREEN('[READOUT]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_readout_option()
        self.parser.add_argument(
            '--dumpval',
            action='store_true',
            help='Dump the entire sequence of collected data')
        self.parser.add_argument(
            '--nowait',
            action='store_true',
            help=('Whether or not to perform the random wait '
                  'process for ADC data collection'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_readout_options(args)
        return args

    def run(self, args):
        self.init_handle()
        val = []

        for i in range(1000):
            self.check_handle(args)

            val.append(self.readout.read_adc_raw(0))
            self.update('{0} | {1} | {2} | {3}'.format(
                'Latest: {0:10.5f}'.format(val[-1]),
                'Mean: {0:10.5f}'.format(np.mean(val)),
                'STD: {0:11.6f}'.format(np.std(val)),
                'PROGRESS [{0:3d}/1000]'.format(i + 1)))
            if args.nowait:
                continue
            time.sleep(1 / 50 *
                       np.random.random())  ## Sleeping for random time
        meanval = np.mean(val)
        stdval = np.std(val)
        valstrip = [x for x in val if abs(x - meanval) < stdval]
        self.printmsg('RAWVAL | Mean: {0:.5f} | STD: {1:.6f}'.format(
            np.mean(val), np.std(val)))
        self.printmsg('Update | Mean: {0:.5f} | STD: {1:.6f}'.format(
            np.mean(valstrip), np.std(valstrip)))
        if args.dumpval:
            for v in val:
                print(v)
Exemplo n.º 13
0
    def reconnect(self, remotehost):
        # Closing existing section
        if self.get_transport():
            self.sftp.close()
            self.close()

        ## Nothing is saved in memory!
        self.connect(remotehost,
                     username=input(
                         log.GREEN('Username at {0}: ').format(remotehost)),
                     password=getpass.getpass(
                         log.GREEN('Password at {0}: ').format(remotehost)),
                     compress=True)

        ## Magic settings for boosting speed
        self.get_transport().window_size = 2147483647
        self.get_transport().packetizer.REKEY_BYTES = pow(2, 40)
        self.get_transport().packetizer.REKEY_PACKETS = pow(2, 40)

        # Opening sftp stuff.
        self.sftp = self.open_sftp()
        self.host = remotehost
Exemplo n.º 14
0
  def print_alignment(self):
    lumi_header = log.GREEN('[LUMI_ALIGN]')
    matrix_header = log.GREEN('[VIS_MATRIX]')
    vis_header = log.GREEN('[VIS__ALIGN]')
    det_format = log.YELLOW(' DET{0:3d}')

    for detid in self.board.dets():
      det_str = det_format.format(int(detid))
      det = self.board.get_det(detid)
      for z in det.lumi_coord:
        log.printmsg(
            lumi_header + det_str,
            'x:{0:.2f}+-{1:.2f} y:{2:.2f}+-{3:.2f} | at z={4:.1f}'.format(
                det.lumi_coord[z][0], det.lumi_coord[z][2], det.lumi_coord[z][1],
                det.lumi_coord[z][3], z))
      for z in det.vis_M:
        log.printmsg(matrix_header + det_str, '{0} | at z={1:.1f}'.format(
            det.vis_M[z], z))
      for z in det.vis_coord:
        log.printmsg(
            vis_header + det_str, 'x:{0:.2f} y:{1:.2f} | at z={2:.1f}'.format(
                det.vis_coord[z][0], det.vis_coord[z][1], z))
Exemplo n.º 15
0
 def set_printer(self, args):
   """Setting up the gantry system, given the /dev/ USB path"""
   if (not self.is_dummy_dev(args.printerdev, 'Printer')
       and args.printerdev != self.gcoder.dev_path):
     try:
       self.gcoder.init(args.printerdev)
       printset = self.gcoder.getsettings()
       printset = printset.split('\necho:')
       for line in printset:
         log.printmsg(log.GREEN('[PRINTER]'), line)
     except Exception as err:
       self.printerr(str(err))
       self.printwarn('Failed to setup printer, skipping over settings')
Exemplo n.º 16
0
    def run(self, args):
        """
    @brief Running the gcode command

    @details While the wait time is set to 10000 seconds, this is not
    representative of a true wait time, as commmands can return the 'ok' signal
    as soons as the internal state of the printer is modified, rather than when
    the command actually finishes execution.
    """
        retstr = self.gcoder.run_gcode(args.cmd, 0, int(1e5), True)
        retstr = retstr.split('\necho:')
        for line in retstr:
            log.printmsg(log.GREEN('[PRINTER]'), line)
Exemplo n.º 17
0
    def run(self, args):
        self.printmsg("PRESS CTL+C to stop the command")
        self.printmsg("Legend")
        self.printmsg("Failed contor ratio requirement")
        self.printmsg(log.GREEN("Failed area luminosity requirement"))
        self.printmsg(log.YELLOW("Failed rectangular approximation"))
        self.printmsg(log.CYAN("Candidate contour (not largest)"))
        while True:
            try:
                self.check_handle()
            except:
                break

            self.show_img(args, args.raw)
            time.sleep(args.vwait)
Exemplo n.º 18
0
class history(cmdbase.controlcmd):
  """
  Getting the input history. Notice that this will only include the user input
  history. Commands in the runfile will note be expanded.
  """
  LOG = log.GREEN("[SIPMCALIB HISTORY]")

  def __init__(self, cmd):
    cmdbase.controlcmd.__init__(self, cmd)

  def run(self, args):
    import readline
    self.printmsg(
        f'commands since startup: {str(readline.get_current_history_length())}')
    for idx in range(1, readline.get_current_history_length() + 1):
      self.printmsg(readline.get_history_item(idx))
Exemplo n.º 19
0
class visualmaxsharp(cmdbase.controlcmd):
    """
  Moving the gantry so that the image sharpness is maximized
  """
    LOG = log.GREEN('[VISMAXSHARP]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_xychip_options()
        self.parser.add_argument(
            '-z',
            '--startz',
            type=float,
            default=30,
            help=('Initial value to begin finding optimal z '
                  'value [mm]'))
        self.parser.add_argument('-d',
                                 '--stepsize',
                                 type=float,
                                 default=1,
                                 help=('First step size to scan for immediate '
                                       'neighborhood z scan [mm]'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_xychip_options(args, add_visoffset=True)
        return args

    def run(self, args):
        self.move_gantry(args.x, args.y, args.startz, False)
        laplace = self.visual.sharpness(False)
        zval = args.startz
        zstep = args.stepsize

        while abs(zstep) >= 0.1:
            self.gcoder.moveto(args.x, args.y, zval + zstep, False)
            newlap = self.visual.sharpness(False)

            if newlap > laplace:
                laplace = newlap
                zval += zstep
            else:
                zstep *= -0.8
            self.update('z:{0:.1f}, L:{1:.2f}'.format(zval, laplace))
        self.printmsg('Final z:{0:.1f}'.format(self.gcoder.opz))
Exemplo n.º 20
0
class drscalib(cmdbase.controlcmd):
  """@brief Running the DRS calibration process."""
  """This function will confirm with the user where or not the DRS is in the
  correct configuration before continuing.
  """
  LOG = log.GREEN('[DRSCALIB]')

  def __init__(self, cmd):
    cmdbase.controlcmd.__init__(self, cmd)

  def add_args(self):
    self.parser.add_argument('--skipconfirm',
                             action='store_true',
                             help='Skipping the confirmation dialog')

  def run(self, args):
    if not args.skipconfirm:
      self.cmd.onecmd('promptaction DRS_CALIB')
    self.drs.run_calibrations()
Exemplo n.º 21
0
class visualzscan(cmdbase.singlexycmd, cmdbase.zscancmd, cmdbase.savefilecmd,
                  visualmeta):
    """
  @brief Scanning focus to calibrate z distance
  """
    VISUAL_OFFSET = True
    DEFAULT_SAVEFILE = 'vscan_<DETID>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[VISZSCAN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        pass

    def run(self, args):
        for idx, z in enumerate(args.zlist):
            # Checking termination signal
            self.check_handle()
            self.move_gantry(args.x, args.y, z, False)
            time.sleep(args.wait)

            center = self.visual.get_latest()
            self.show_img(args, True)
            laplace.append(center.sharpness)
            reco_x.append(center.x)
            reco_y.append(center.y)
            reco_a.append(center.area)
            reco_d.append(center.maxmeas)

            self.update_progress(progress=(idx, len(args.zlen)),
                                 temperature=True,
                                 coordinates=True,
                                 display_data={
                                     'sharpness': (center.s2, center.s4),
                                     'reco': (center.x, center.y),
                                     'measure': (center.area, center.maxmeas)
                                 })
            self.write_standard_line(
                (laplace[-1], center.x, center.y, center.area, center.maxmeas),
                det_id=args.detid)
Exemplo n.º 22
0
class timescan(cmdbase.controlcmd):
    """
  Generate a log of the readout in terms relative to time.
  """
    DEFAULT_SAVEFILE = 'tscan_<CHIPID>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[TIMESCAN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_readout_option()
        self.add_savefile_options(timescan.DEFAULT_SAVEFILE)
        self.parser.add_argument('--nslice',
                                 type=int,
                                 default=30,
                                 help='total number of sample to tak')
        self.parser.add_argument(
            '--interval',
            type=int,
            default=5,
            help='Time interval between sampling (seconds)')

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_readout_options(args)
        self.parse_savefile(args)
        return args

    def run(self, args):
        self.init_handle()
        for i in range(args.nslice):
            self.check_handle(args)
            lumival, uncval = self.readout.read(channel=args.channel,
                                                sample=args.samples)
            args.savefile.write('{0:d} {1:.3f} {2:.4f}\n'.format(
                i * args.interval, lumival, uncval))
            self.update('{0:5.1f} {1:5.1f} | PROGRESS [{2:3d}/{3:3d}]'.format(
                lumival, uncval, i + 1, args.nslice))
            time.sleep(args.interval)

        self.close_savefile(args)
Exemplo n.º 23
0
class pulse(cmdbase.controlcmd):
    LOG = log.GREEN('[PULSE]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.parser.add_argument('-n',
                                 type=int,
                                 default=100000,
                                 help='number of times to pulse the signal')
        self.parser.add_argument(
            '--wait',
            type=int,
            default=500,
            help='Time (in microseconds) between triggers')

    def run(self, args):
        self.init_handle()

        for i in range(args.n):
            self.check_handle(args)
            self.trigger.pulse(1, args.wait)
            time.sleep(args.wait / 1e6)
Exemplo n.º 24
0
class savecalib(cmdbase.controlcmd):
  """@brief Saving current calibration information into a json file"""
  LOG = log.GREEN('[SAVE_CALIB]')

  def __init__(self, cmd):
    cmdbase.controlcmd.__init__(self, cmd)

  def add_args(self):
    self.parser.add_argument('-f',
                             '--file',
                             type=argparse.FileType('w'),
                             required=True,
                             help='File to save the calibration events to')

  def parse(self, args):
    if not args.file:
      raise Exception('File name must be specified')
    return args

  def run(self, args):
    self.printmsg('Saving calibration results to file [{0}]'.format(
        args.file.name))
    self.board.save_calib_file(args.file.name)
Exemplo n.º 25
0
class showadc(cmdbase.controlcmd):
    """
  Printing the ADC values that are stored in memory
  """

    LOG = log.GREEN("[SHOWADC]")

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        self.parser.add_argument('--time',
                                 '-t',
                                 default=10,
                                 type=float,
                                 help='Time to run command [seconds]')
        self.parser.add_argument(
            '--interval',
            '-i',
            type=float,
            default=1,
            help='Time interval between updates [seconds]')

    def run(self, args):
        start_time = time.time()
        end_time = time.time()
        while (end_time - start_time) < args.time:
            self.check_handle()
            self.update('{0} | {1} | {2} | {3}'.format(
                'LED TEMP:{0:5.2f}C ({1:5.1f}mV)'.format(
                    self.gpio.ntc_read(0), self.gpio.adc_read(0)),
                'SiPM TEMP:{0:5.2f}C ({1:5.1f}mV)'.format(
                    self.gpio.rtd_read(1), self.gpio.adc_read(1)),
                'PWM0: {0:6.4f}V'.format(self.gpio.adc_read(2) / 1000),
                'PWM1: {0:6.4f}V'.format(self.gpio.adc_read(3) / 1000)))
            time.sleep(args.interval)
            end_time = time.time()
Exemplo n.º 26
0
class picorunblock(cmdbase.controlcmd):
    """
  Initiating a single run block instance. This assumes that the program will
  finish without user intervension (no program fired triggering)
  """

    DEFAULT_SAVEFILE = 'picoblock_<TIMESTAMP>.txt'
    LOG = log.GREEN('[PICOBLOCK]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_savefile_options(picorunblock.DEFAULT_SAVEFILE)
        self.parser.add_argument(
            '--numblocks',
            type=int,
            default=1,
            help='Number of rapid block acquisitions to run')
        self.parser.add_argument('--dumpbuffer',
                                 action='store_true',
                                 help='Dumping the buffer onto screen')
        self.parser.add_argument('--channel',
                                 type=int,
                                 default=0,
                                 help='Channel to collect input from')
        self.parser.add_argument('--sum',
                                 action='store_true',
                                 help=('Store the sum of the waveform values '
                                       'instead of waveforms itself'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_savefile(args)
        return args

    def run(self, args):
        self.init_handle()
        ## First line in file contains convertion information
        if args.savefile.tell() == 0:
            args.savefile.write("{0} {1} {2} {3} {4}\n".format(
                self.pico.timeinterval, self.pico.ncaptures,
                self.pico.presamples, self.pico.postsamples,
                self.pico.adc2mv(1)))
            args.savefile.flush()

        for i in range(args.numblocks):
            self.update('Collecting block...[{0:5d}/{1:d}]'.format(
                i,
                args.numblocks,
            ))
            self.pico.startrapidblocks()

            while not self.pico.isready():
                self.check_handle(args)
                self.trigger.pulse(int(self.pico.ncaptures / 10), 500)

            self.pico.flushbuffer()

            for cap in range(self.pico.ncaptures):
                line = self.pico.waveformstr(args.channel, cap)
                args.savefile.write(line + '\n')

        # Closing
        args.savefile.flush()
        args.savefile.close()

        if args.dumpbuffer:
            self.pico.dumpbuffer()
Exemplo n.º 27
0
class visualhscan(cmdbase.controlcmd):
    """
  Performing horizontal scan with camera system
  """

    DEFAULT_SAVEFILE = 'vhscan_<SCANZ>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[VIS HSCAN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        ## Adding common coordinate for x-y scanning
        self.add_hscan_options(hrange=3, distance=0.5)
        self.add_savefile_options(self.DEFAULT_SAVEFILE)
        self.parser.add_argument(
            '-m',
            '--monitor',
            action='store_true',
            help=('Whether or not to open the monitoring window'
                  ' (could be slow!!)'))
        self.parser.add_argument(
            '--overwrite',
            action='store_true',
            help=('Forcing the storage of scan results as '
                  'session information'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_xychip_options(args, add_visoffset=True)
        self.parse_savefile(args)
        return args

    def run(self, args):
        self.init_handle()
        x, y = self.make_hscan_mesh(args)

        ## New container to account for chip not found in FOV
        gantry_x = []
        gantry_y = []
        reco_x = []
        reco_y = []

        ## Running over mesh.
        for idx, (xval, yval) in enumerate(zip(x, y)):
            self.check_handle(args)
            self.move_gantry(xval, yval, args.scanz, False)

            center = self.visual.find_chip(args.monitor)

            if center.x > 0 and center.y > 0:
                gantry_x.append(xval)
                gantry_y.append(yval)
                reco_x.append(center.x)
                reco_y.append(center.y)

            self.update('{0} | {1} | {2}'.format(
                'x:{0:.1f}, y:{1:.1f}, z:{2:.1f}'.format(
                    xval, yval, args.scanz),
                'Reco x:{0:.1f}, y:{1:.1f}'.format(center.x, center.y),
                'Progress [{0}/{1}]'.format(idx, len(x))))
            args.savefile.write(
                '{0:.1f} {1:.1f} {2:.1f} {3:.2f} {4:.3f}\n'.format(
                    xval, yval, args.scanz, center.x, center.y))
        cv2.destroyAllWindows()
        self.close_savefile(args)

        fitx, covar_x = curve_fit(visualhscan.model,
                                  np.vstack((gantry_x, gantry_y)), reco_x)
        fity, covar_y = curve_fit(visualhscan.model,
                                  np.vstack((gantry_x, gantry_y)), reco_y)

        self.printmsg( 'Transformation for CamX ' \
              '= ({0:.2f}+-{1:.3f})x + ({2:.2f}+-{3:.2f})y'.format(
                  fitx[0], np.sqrt(covar_x[0][0]),
                  fitx[1], np.sqrt(covar_x[1][1])  ) )
        self.printmsg( 'Transformation for CamY ' \
              '= ({0:.2f}+-{1:.3f})x + ({2:.2f}+-{3:.2f})y'.format(
                  fity[0], np.sqrt(covar_y[0][0]),
                  fity[1], np.sqrt(covar_y[1][1])  ) )

        ## Generating calibration chip id if using chip coordinates
        if not args.chipid in self.board.visM and int(args.chipid) < 0:
            self.board.add_calib_chip(args.chipid)

        ## Saving rounded coordinates
        if (not self.gcoder.opz in self.board.visM[args.chipid]
                or args.overwrite):
            self.board.add_visM(args.chipid, self.gcoder.opz,
                                [[fitx[0], fitx[1]], [fity[0], fity[1]]])
        elif self.gcoder.opz in self.board.visM[args.chipid]:
            if self.cmd.prompt(
                    'Tranformation equation for z={0:.1f} already exists, overwrite?'
                    .format(args.scanz), 'no'):
                self.board.add_visM(args.chipid, self.gcoder.opz,
                                    [[fitx[0], fitx[1]], [fity[0], fity[1]]])

        ## Moving back to center
        self.gcoder.moveto(args.x, args.y, args.scanz, False)

    @staticmethod
    def model(xydata, a, b, c):
        x, y = xydata
        return a * x + b * y + c
Exemplo n.º 28
0
class visualzscan(cmdbase.controlcmd):
    """
  Scanning focus to calibrate z distance
  """

    DEFAULT_SAVEFILE = 'vscan_<CHIPID>_<TIMESTAMP>.txt'
    LOG = log.GREEN('[VISZSCAN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_savefile_options(visualzscan.DEFAULT_SAVEFILE)
        self.add_zscan_options()
        self.parser.add_argument(
            '-m',
            '--monitor',
            action='store_true',
            help=('Whether or not to open a monitoring window '
                  '(could be slow!!)'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_zscan_options(args)
        self.parse_xychip_options(args, add_visoffset=True)
        self.parse_savefile(args)
        return args

    def run(self, args):
        self.init_handle()
        laplace = []
        reco_x = []
        reco_y = []
        reco_a = []
        reco_d = []

        for z in args.zlist:
            # Checking termination signal
            self.check_handle(args)
            self.move_gantry(args.x, args.y, z, False)

            reco = self.visual.find_chip(args.monitor)
            laplace.append(self.visual.sharpness(args.monitor))
            reco_x.append(reco.x)
            reco_y.append(reco.y)
            reco_a.append(reco.area)
            reco_d.append(reco.maxmeas)

            # Writing to screen
            self.update('{0} | {1} | {2}'.format(
                'x:{0:.1f} y:{1:.1f} z:{2:.1f}'.format(self.gcoder.opx,
                                                       self.gcoder.opy,
                                                       self.gcoder.opz),
                'Sharpness:{0:.2f}'.format(laplace[-1]),
                'Reco x:{0:.1f} Reco y:{1:.1f} Area:{2:.1f} MaxD:{3:.1f}'.
                format(reco.x, reco.y, reco.area, reco.maxmeas)))
            # Writing to file
            args.savefile.write('{0:.1f} {1:.1f} {2:.1f} '\
                        '{3:.2f} '\
                        '{4:.1f} {5:.1f} {6:.1f} {7:.1f}\n'.format(
                self.gcoder.opx, self.gcoder.opy, self.gcoder.opz,
                laplace[-1],
                reco.x, reco.y, reco.area, reco.maxmeas
                ))

        cv2.destroyAllWindows()
Exemplo n.º 29
0
class visualcenterchip(cmdbase.controlcmd):
    """
  Moving the gantry so that the chip is in the center of the field of view
  """

    LOG = log.GREEN('[VIS ALIGN]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)
        self.add_xychip_options()
        self.parser.add_argument(
            '-z',
            '--scanz',
            type=float,
            help=('Position z to perform centering. User must '
                  'make sure the visual transformation '
                  'equation has already been created before'))
        self.parser.add_argument('--overwrite',
                                 action='store_true',
                                 help=('Whether to overwrite the existing '
                                       'information or not'))

    def parse(self, line):
        args = cmdbase.controlcmd.parse(self, line)
        self.parse_xychip_options(args, add_visoffset=True)
        if not args.scanz:
            raise Exception(
                'Specify the height to perform the centering operation')

        args.calibchip = args.chipid if (self.board.visM_hasz(
            args.chipid, args.scanz)) else next(
                (x for x in self.board.calibchips()
                 if self.board.visM_hasz(x, args.scanz)), None)

        if args.calibchip == None:
            self.printerr(('Motion transformation equation was not found for '
                           'position z={0:.1f}mm, please run command '
                           '[visualhscan] first').format(args.scanz))
            print(args.scanz, self.board.visM)
            raise Exception('Transformation equation not found')
        return args

    def run(self, args):
        self.move_gantry(args.x, args.y, args.scanz, False)
        for movetime in range(10):  ## Maximum of 10 movements
            center = None

            ## Try to find center for a maximum of 3 times
            for findtime in range(10):
                center = self.visual.find_chip(False)
                if center.x > 0:
                    break

            ## Early exit if chip is not found.
            if (center.x < 0 or center.y < 0):
                raise Exception(
                    ('Chip lost! Check current camera position with '
                     'command visualchipshow'))

            deltaxy = np.array([
                self.visual.frame_width() / 2 - center.x,
                self.visual.frame_height() / 2 - center.y
            ])

            motionxy = np.linalg.solve(
                np.array(self.board.get_visM(args.calibchip, self.gcoder.opz)),
                deltaxy)

            ## Early exit if difference from center is small
            if np.linalg.norm(motionxy) < 0.1: break

            self.gcoder.moveto(self.gcoder.opx + motionxy[0],
                               self.gcoder.opy + motionxy[1], self.gcoder.opz,
                               False)
            time.sleep(0.1)  ## Waiting for the gantry to stop moving

        center = self.visual.find_chip(False)
        self.printmsg(
          'Gantry position: x={0:.1f} y={1:.1f} | '\
          'Chip FOV position: x={2:.1f} y={3:.1f}'.
            format(self.gcoder.opx, self.gcoder.opy, center.x, center.y))

        if (not self.board.vis_coord_hasz(args.chipid, self.gcoder.opz)
                or args.overwrite):
            self.board.add_vis_coord(args.chipid, self.gcoder.opz,
                                     [self.gcoder.opx, self.gcoder.opy])

        # Luminosity calibrated coordinate doesn't exists. displaying the
        # estimated position from calibration chip position
        if not self.board.lumi_coord_hasz(args.chipid, self.gcoder.opz):
            deltax = None
            deltay = None
            currentz = self.gcoder.opz
            for calibchip in self.board.calibchips():
                if (self.board.vis_coord_hasz(calibchip, currentz)
                        and any(self.board.lumi_coord[calibchip])):
                    closestz = min(self.board.lumi_coord[calibchip].keys(),
                                   key=lambda x: abs(x - currentz))
                    deltax = self.board.get_vis_coord(calibchip, currentz)[0] \
                            - self.board.get_lumi_coord(calibchip,closestz)[0]
                    deltay = self.board.get_vis_coord(calibchip,currentz)[1] \
                            - self.board.get_lumi_coord(calibchip, closestz)[2]
                if deltax != None and deltay != None:
                    self.printmsg('Estimated Lumi center: x={0} y={1}'.format(
                        self.gcoder.opx - deltax, self.gcoder.opy - deltay))
Exemplo n.º 30
0
class picorunblock(cmdbase.savefilecmd):
    """@brief Initiating a single run block instance."""
    """ This assumes that the program will finish without user intervension (no
  program fired triggering)
  """

    DEFAULT_SAVEFILE = 'picoblock_<TIMESTAMP>.txt'
    LOG = log.GREEN('[PICOBLOCK]')

    def __init__(self, cmd):
        cmdbase.controlcmd.__init__(self, cmd)

    def add_args(self):
        self.parser.add_argument(
            '--numblocks',
            type=int,
            default=1,
            help='Number of rapid block acquisitions to run')
        self.parser.add_argument('--dumpbuffer',
                                 action='store_true',
                                 help='Dumping the buffer onto screen')
        self.parser.add_argument('--channel',
                                 type=int,
                                 default=0,
                                 help='Channel to collect input from')
        self.parser.add_argument('--sum',
                                 action='store_true',
                                 help="""
                             Store the sum of the waveform values instead of
                             waveforms itself""")

    def run(self, args):
        ## First line in file contains convertion information
        if self.savefile.tell() == 0:
            self.savefile.write("{time} {bits} {adc}\n".format(
                time=self.pico.timeinterval,
                bits=2,
                adc=self.pico.adc2mv(args.channel, 256)))
            self.savefile.flush()

        for i in range(args.numblocks):
            self.update('Collecting block...[{0:5d}/{1:d}]'.format(
                i,
                args.numblocks,
            ))
            self.pico.startrapidblocks()

            while not self.pico.isready():
                self.check_handle()
                if self.gpio.gpio_status():
                    self.gpio.pulse(int(self.pico.ncaptures / 10), 100)

            self.pico.flushbuffer()

            lines = [
                self.pico.waveformstr(args.channel, cap)
                for cap in range(self.pico.ncaptures)
            ]
            self.savefile.write("\n".join(lines))

        if args.dumpbuffer:
            self.pico.dumpbuffer()