Пример #1
0
    def _test1(self):
        print('test1')
        ld = LumenDetector()

        def func():
            src = copy(self.manager.video.get_cached_frame())
            # dim = self.stage_map.g_dimension
            ld.pxpermm = 31
            dim = 1.5
            mask_dim = dim * 1.05
            offx, offy = 0, 0
            cropdim = dim * 2.5
            src = ld.crop(src, cropdim, cropdim, offx, offy, verbose=False)

            ld.find_targets(
                self.display_image,
                src,
                dim,
                mask=mask_dim,
                search={
                    'start_offset_scalar': 1,
                    # 'width': 2
                })
            # self.manager.calculate_new_center(0, 0, 0, 0, dim=1.25)

        t = Thread(target=func)
        t.start()
        self.t = t
Пример #2
0
class SM:
    pxpermm = 23

    def __init__(self):
        self.lumen_detector = LumenDetector()

    def update_axes(self):
        pass

    def moving(self, **kw):
        return False

    def find_target(self):
        return self.lumen_detector.find_target(self.frame)

    def find_best_target(self):
        return self.lumen_detector.find_best_target(self.frame)
Пример #3
0
class SM:
    pxpermm = 23

    def __init__(self):
        self.lumen_detector = LumenDetector()

    def update_axes(self):
        pass

    def moving(self, **kw):
        return False

    def find_target(self):
        return self.lumen_detector.find_target(self.frame)

    def find_best_target(self):
        return self.lumen_detector.find_best_target(self.frame)
Пример #4
0
 def __init__(self):
     self.lumen_detector = LumenDetector()
Пример #5
0
    def degas(self, lumens, duration):
        '''
            degas for duration trying to maintain
            lumens
        '''
        if self.laser_manager:

            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm
        #         print cw, ch
        if not cw % 5 == 0:
            cw += cw % 5
        if not ch % 5 == 0:
            ch += ch % 5

        cw, ch = 200, 200
        #         im = self.new_image(
        # #                             frame=zeros((ch, cw)),
        #                             title='Luminosity', view_id='lumens')
        im = TestImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
            #             err = random.random()
            g.add_data(((tt, out), (tt, err), (tt, cl)))
            #             g.redraw()
            #             if i % 5 == 0:
            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False
Пример #6
0
class Degasser(MachineVisionManager, ExecuteMixin):
    _period = 0.05
    crop_width = Int(5)
    crop_height = Int(5)

    _test_lumens = Float(100)
    _test_duration = Int(10)
    _test_graph = Instance(StackedGraph)
    _test_image = Instance(TestImage)
    _testing = False

    pid = Instance(PID, ())

    def degas(self, lumens, duration):
        '''
            degas for duration trying to maintain
            lumens
        '''
        if self.laser_manager:

            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm
        #         print cw, ch
        if not cw % 5 == 0:
            cw += cw % 5
        if not ch % 5 == 0:
            ch += ch % 5

        cw, ch = 200, 200
        #         im = self.new_image(
        # #                             frame=zeros((ch, cw)),
        #                             title='Luminosity', view_id='lumens')
        im = TestImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
            #             err = random.random()
            g.add_data(((tt, out), (tt, err), (tt, cl)))
            #             g.redraw()
            #             if i % 5 == 0:
            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False

    def _set_power(self, pwr, cnt):
        if self.laser_manager:
            self.laser_manager.set_laser_power(pwr, verbose=cnt == 0)

    def _get_current_lumens(self, im, cw, ch):
        src = self.new_image_frame()
        if src:
            src = self._crop_image(src, cw, ch)
        else:
            src = random.random((ch, cw)) * 255
            src = src.astype('uint8')


#         return random.random()
        src, v = self._detector.get_value(src)
        im.set_image(src)
        return v

    def _make_graph(self, lumens, duration):
        g = StackedGraph(container_dict=dict(stack_order='top_to_bottom'))
        g.new_plot(ytitle='Output (W)')
        g.new_series()
        g.new_plot(ytitle='Residual')
        g.new_series(plotid=1)
        g.new_plot(ytitle='Lumens', xtitle='time (s)')
        g.new_series(plotid=2)

        g.add_horizontal_rule(lumens, plotid=2)
        g.set_x_limits(0, duration * 1.1)
        return g

    def _do_execute(self):

        self.debug('starting test degas {} {}'.format(self._test_lumens,
                                                      self._test_duration))
        self._testing = True
        self.degas(self._test_lumens, self._test_duration)

    def traits_view(self):
        v = View(UItem('execute',
                       editor=ButtonEditor(label_value='execute_label')),
                 HGroup(Item('_test_lumens'), Item('_test_duration')),
                 UItem('pid', style='custom'),
                 HGroup(UItem('_test_graph', height=400, style='custom'),
                        UItem('_test_image', style='custom')),
                 resizable=True)
        return v
Пример #7
0
    def degas(self, lumens, duration):
        '''
            degas for duration trying to maintain
            lumens
        '''
        if self.laser_manager:

            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm
#         print cw, ch
        if not cw % 5 == 0:
            cw += cw % 5
        if not ch % 5 == 0:
            ch += ch % 5

        cw, ch = 200, 200
#         im = self.new_image(
# #                             frame=zeros((ch, cw)),
#                             title='Luminosity', view_id='lumens')
        im = TestImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
#             err = random.random()
            g.add_data(((tt, out), (tt, err), (tt, cl)))
#             g.redraw()
#             if i % 5 == 0:
            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False
Пример #8
0
class Degasser(MachineVisionManager, ExecuteMixin):
    _period = 0.05
    crop_width = Int(5)
    crop_height = Int(5)

    _test_lumens = Float(100)
    _test_duration = Int(10)
    _test_graph = Instance(StackedGraph)
    _test_image = Instance(TestImage)
    _testing = False

    pid = Instance(PID, ())

    def degas(self, lumens, duration):
        '''
            degas for duration trying to maintain
            lumens
        '''
        if self.laser_manager:

            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm
#         print cw, ch
        if not cw % 5 == 0:
            cw += cw % 5
        if not ch % 5 == 0:
            ch += ch % 5

        cw, ch = 200, 200
#         im = self.new_image(
# #                             frame=zeros((ch, cw)),
#                             title='Luminosity', view_id='lumens')
        im = TestImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
#             err = random.random()
            g.add_data(((tt, out), (tt, err), (tt, cl)))
#             g.redraw()
#             if i % 5 == 0:
            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False

    def _set_power(self, pwr, cnt):
        if self.laser_manager:
            self.laser_manager.set_laser_power(pwr, verbose=cnt == 0)

    def _get_current_lumens(self, im, cw, ch):
        src = self.new_image_frame()
        if src:
            src = self._crop_image(src, cw, ch)
        else:
            src = random.random((ch, cw)) * 255
            src = src.astype('uint8')
#         return random.random()
        src, v = self._detector.get_value(src)
        im.set_image(src)
        return v

    def _make_graph(self, lumens, duration):
        g = StackedGraph(container_dict=dict(stack_order='top_to_bottom'))
        g.new_plot(
                   ytitle='Output (W)'
                   )
        g.new_series()
        g.new_plot(
                   ytitle='Residual'
                   )
        g.new_series(plotid=1)
        g.new_plot(
                   ytitle='Lumens',
                   xtitle='time (s)')
        g.new_series(plotid=2)

        g.add_horizontal_rule(lumens, plotid=2)
        g.set_x_limits(0, duration * 1.1)
        return g

    def _do_execute(self):

        self.debug('starting test degas {} {}'.format(self._test_lumens, self._test_duration))
        self._testing = True
        self.degas(self._test_lumens, self._test_duration)

    def traits_view(self):
        v = View(
                 UItem('execute', editor=ButtonEditor(label_value='execute_label')),
                 HGroup(Item('_test_lumens'), Item('_test_duration')),
                 UItem('pid', style='custom'),
                 HGroup(UItem('_test_graph',
                              height=400,
                              style='custom'),
                        UItem('_test_image', style='custom')
                        ),

                 resizable=True
                 )
        return v
Пример #9
0
    # print v1,v2
    l = (v1**2 + v2**2)**0.5
    try:
        ux, uy = v1 / l, v2 / l
    except ZeroDivisionError:
        ux, uy = 0, 0

    nx = mx + base * scalar * ux
    ny = my + base * scalar * uy
    return nx, ny


if __name__ == '__main__':
    # crop_width = 2
    # crop_height = 2
    ld = LumenDetector()

    # def get_brightness(src):
    #     # ld = self._lumen_detector
    #     # cw, ch = 2 * crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm
    #     # src = self.video.get_frame()
    #     # src = crop_image(src, 200,200)
    #     # if src:
    #     # else:
    #     #     src = random.random((ch, cw)) * 255
    #     #     src = src.astype('uint8')
    #     #         return random.random()
    #     src, v = ld.get_value(src)
    #     return v

    import matplotlib.pyplot as plt
Пример #10
0
def test1():
    from numpy import zeros, ogrid
    import matplotlib

    matplotlib.use('Qt4Agg')

    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt

    class FrameGenerator:
        def __init__(self):
            self.width = 300
            self.height = 300
            self.ox = 150
            self.oy = 150
            self.radius = 75
            self.laser_x = 0
            self.laser_y = 0
            self.random_walk = False
            self._cnt = 0
            self.time_constant = 0
            self.cradius = 0

        def __iter__(self):
            self._cnt = 0
            return self

        def set_pos(self, x, y):
            self.laser_x = x
            self.laser_y = y
            self.ox = x
            self.oy = y

        def _calculate_radius(self):
            f = ((self.laser_x - self.width / 2.)**2 +
                 (self.laser_y - self.height / 2.)**2)**0.5
            # g = 50*math.sin(0.1*self._cnt)
            # g = 1+math.sin(0.1*self._cnt)
            # print self._cnt, g

            g = min(1, (1 - (50 - self._cnt) / 50.))

            h = 0 + 15 * math.sin(0.1 * self._cnt) if self._cnt > 50 else 0
            self.time_constant = h
            rr = self.radius * g + h
            self._cnt += 1
            r = int(max(1, rr * (150 - f) / 150.))  # +random.randint(0,10)
            self.cradius = r
            return r
            # return self.radius * max(0.001, (1-f/self.radius))
            # try:
            #     ff = 5/float(f)
            # except ZeroDivisionError:
            #     ff = 1
            # print f, 1/f
            # ff = f/self.
            # return int(self.radius*ff)

        def next(self):
            radius = self._calculate_radius()
            offset = 3
            src = zeros((self.width, self.height))

            d = (0, 0)
            if self.random_walk:
                d = random.uniform(-offset, offset, 2)

            cx = self.ox + d[0]
            cy = self.oy + d[1]

            # if ((cx - 100) ** 2 + (cy - 100) ** 2) ** 0.5 > 50:
            #     dx = offset if cx < 0 else -offset
            #     dy = offset if cy < 0 else -offset
            #     cx += dx
            #     cy += dy
            # rain_drops['position'][current_index] += dx,dy

            # self.ox = cx
            # self.oy = cy
            y, x = ogrid[-radius:radius, -radius:radius]
            index = x**2 + y**2 <= radius**2

            # src[cy - radius:cy + radius, cx - radius:cx + radius][index] = 255*random.uniform(size=index.shape)
            src[cy - radius:cy + radius, cx - radius:cx + radius][index] = 255
            # xx, yy = mgrid[:200, :200]
            # circles contains the squared distance to the (100, 100) point
            # we are just using the circle equation learnt at school
            # circle = (xx - 100) ** 2 + (yy - 100) ** 2
            # print circle.shape
            # print circle
            # raise  StopIteration
            return src

    ld = LumenDetector()
    ld.hole_radius = 2
    fig, ((
        ax,
        ax2,
    ), (ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2, figsize=(7, 7))

    f = FrameGenerator()
    pattern = SeekPattern(base=15, perimeter_radius=100)
    o = f.next()

    ax.set_title('Current Frame')
    img = ax.imshow(o)

    gen = pattern.point_generator()

    ax2.set_title('Observed Brightness')
    img2 = ax2.imshow(o)

    ax3.set_title('Position')
    line = ax3.plot([0], [0])[0]

    r = pattern.perimeter_radius
    xs = linspace(-r, r)
    xs2 = xs[::-1]
    ys = (r**2 - xs**2)**0.5
    ys2 = -(r**2 - xs2**2)**0.5
    xxx, yyy = hstack((xs, xs2)) + 150, hstack((ys, ys2)) + 150
    # print xxx,yyy
    # print xs+150, ys+150
    # ax3.plot(xs+150,ys+150)
    ax3.plot(xxx, yyy)

    ax3.set_xlim(50, 250)
    ax3.set_ylim(50, 250)
    scatter = ax3.plot([150], [150], '+')

    xx, yy = 100, 150
    scatter2 = ax3.plot([xx], [yy], 'o')[0]

    cp = ax7.scatter([0], [0], c=[0])
    cp.autoscale()
    ax7.set_xlim(-100, 100)
    ax7.set_ylim(-100, 100)

    ax4.set_title('Intensity')
    tvint = ax4.plot([1], [1])[0]
    # tvint = ax4.semilogy([1],[1])[0]
    ax4.set_xlim(0, 50)
    # ax4.set_ylim(0, 1.1)

    ax5.set_title('Time Constant')
    tc = ax5.plot([0], [0])[0]
    ax5.set_ylim(-20, 20)
    ax5.set_xlim(0, 50)

    ax5.set_title('Radius')
    rs = ax6.plot([0], [0])[0]
    ax6.set_ylim(0, 100)
    ax6.set_xlim(0, 50)

    xs = []
    ys = []
    ts = []
    zs = []
    tcs = []
    rcs = []
    f.set_pos(xx, yy)
    st = time.time()

    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        # z /= 3716625.0
        # z += 0.1 * random.random()
        # print x, y, z
        pattern.set_point(z, x, y)
        zs.append(z)
        # print ts
        # print zs
        tvint.set_data(ts, zs)
        ax4.set_ylim(min(zs) * 0.9, max(zs) * 1.1)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)

        # >>>>>>>>>>>>>>>>>>>>>>>
        # add a plot that is the current points of the triangle
        # >>>>>>>>>>>>>>>>>>>>>>>
        xy = pattern._tri.xys()
        x, y, z = zip(*xy)
        # print x, y
        # cp.set_data(x, y)
        cp.set_offsets(zip(x, y))

        maz, miz = max(z), min(z)
        z = [(zi - miz) / (maz - miz) for zi in z]
        print z
        cp.set_facecolors([cm.hot(zi) for zi in z])
        # cp.set_edgecolors(z)
        if not pattern._tri.is_equilateral():
            print 'not eq'

            # return mplfig_to_npimage(fig)
            # raw_input()

    animation = FuncAnimation(fig, update, interval=1000)
    plt.show()
Пример #11
0
 def __init__(self):
     self.lumen_detector = LumenDetector()
Пример #12
0
    def degas(self, lumens, duration):
        """
            degas for duration trying to maintain
            lumens
        """
        if self.laser_manager:
            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm

        # if not cw % 5 == 0:
        #     cw += cw % 5
        # if not ch % 5 == 0:
        #     ch += ch % 5
        #
        # cw, ch = 200, 200

        im = MVImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
            g.add_data(((tt, out), (tt, err), (tt, cl)))

            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False
Пример #13
0
class Degasser(MachineVisionManager, ExecuteMixin):
    _period = 0.05
    crop_width = Int(5)
    crop_height = Int(5)

    _test_lumens = Float(100)
    _test_duration = Int(10)
    _test_graph = Instance(StackedGraph)
    _test_image = Instance(MVImage)
    _testing = False

    pid = Instance(PID, ())
    _detector = Instance(LumenDetector)

    def degas(self, lumens, duration):
        """
            degas for duration trying to maintain
            lumens
        """
        if self.laser_manager:
            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm

        # if not cw % 5 == 0:
        #     cw += cw % 5
        # if not ch % 5 == 0:
        #     ch += ch % 5
        #
        # cw, ch = 200, 200

        im = MVImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
            g.add_data(((tt, out), (tt, err), (tt, cl)))

            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False

    def _set_power(self, pwr, cnt):
        if self.laser_manager:
            self.laser_manager.set_laser_power(pwr, verbose=cnt == 0)

    def _get_current_lumens(self, im, cw, ch):
        src = self.new_image_frame()
        if src:
            src = self._crop_image(src, cw, ch)
        else:
            src = random.random((ch, cw)) * 255
            src = src.astype("uint8")
        src, v = self._detector.get_value(src)
        im.set_image(src)
        return v

    def _make_graph(self, lumens, duration):
        g = StackedGraph(container_dict=dict(stack_order="top_to_bottom"))
        g.new_plot(ytitle="Output (W)")
        g.new_series()
        g.new_plot(ytitle="Residual")
        g.new_series(plotid=1)
        g.new_plot(ytitle="Lumens", xtitle="time (s)")
        g.new_series(plotid=2)

        g.add_horizontal_rule(lumens, plotid=2)
        g.set_x_limits(0, duration * 1.1)
        return g

    def _do_execute(self):

        self.debug("starting test degas {} {}".format(self._test_lumens, self._test_duration))
        self._testing = True
        self.degas(self._test_lumens, self._test_duration)

    def traits_view(self):
        v = View(
            UItem("execute", editor=ButtonEditor(label_value="execute_label")),
            HGroup(Item("_test_lumens"), Item("_test_duration")),
            UItem("pid", style="custom"),
            HGroup(UItem("_test_graph", height=400, style="custom"), UItem("_test_image", style="custom")),
            resizable=True,
        )
        return v
Пример #14
0
def test1():
    from numpy import zeros, ogrid
    import matplotlib

    matplotlib.use('Qt4Agg')

    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt

    class FrameGenerator:
        def __init__(self):
            self.width = 300
            self.height = 300
            self.ox = 150
            self.oy = 150
            self.radius = 75
            self.laser_x = 0
            self.laser_y = 0
            self.random_walk = False
            self._cnt = 0
            self.time_constant = 0
            self.cradius = 0

        def __iter__(self):
            self._cnt = 0
            return self

        def set_pos(self, x, y):
            self.laser_x = x
            self.laser_y = y
            self.ox = x
            self.oy = y

        def _calculate_radius(self):
            f = ((self.laser_x - self.width / 2.) ** 2 + (self.laser_y - self.height / 2.) ** 2) ** 0.5
            # g = 50*math.sin(0.1*self._cnt)
            # g = 1+math.sin(0.1*self._cnt)
            # print self._cnt, g

            g = min(1, (1 - (50 - self._cnt) / 50.))

            h = 0 + 15 * math.sin(0.1 * self._cnt) if self._cnt > 50 else 0
            self.time_constant = h
            rr = self.radius * g + h
            self._cnt += 1
            r = int(max(1, rr * (150 - f) / 150.))  # +random.randint(0,10)
            self.cradius = r
            return r
            # return self.radius * max(0.001, (1-f/self.radius))
            # try:
            #     ff = 5/float(f)
            # except ZeroDivisionError:
            #     ff = 1
            # print f, 1/f
            # ff = f/self.
            # return int(self.radius*ff)

        def next(self):
            radius = self._calculate_radius()
            offset = 3
            src = zeros((self.width, self.height))

            d = (0, 0)
            if self.random_walk:
                d = random.uniform(-offset, offset, 2)

            cx = self.ox + d[0]
            cy = self.oy + d[1]

            # if ((cx - 100) ** 2 + (cy - 100) ** 2) ** 0.5 > 50:
            #     dx = offset if cx < 0 else -offset
            #     dy = offset if cy < 0 else -offset
            #     cx += dx
            #     cy += dy
            # rain_drops['position'][current_index] += dx,dy

            # self.ox = cx
            # self.oy = cy
            y, x = ogrid[-radius:radius, -radius:radius]
            index = x ** 2 + y ** 2 <= radius ** 2

            # src[cy - radius:cy + radius, cx - radius:cx + radius][index] = 255*random.uniform(size=index.shape)
            src[cy - radius:cy + radius, cx - radius:cx + radius][index] = 255
            # xx, yy = mgrid[:200, :200]
            # circles contains the squared distance to the (100, 100) point
            # we are just using the circle equation learnt at school
            # circle = (xx - 100) ** 2 + (yy - 100) ** 2
            # print circle.shape
            # print circle
            # raise  StopIteration
            return src

    ld = LumenDetector()
    ld.hole_radius = 2
    fig, ((ax, ax2,), (ax3, ax4), (ax5, ax6),
          (ax7, ax8)) = plt.subplots(4, 2, figsize=(7, 7))

    f = FrameGenerator()
    pattern = SeekPattern(base=15, perimeter_radius=100)
    o = f.next()

    ax.set_title('Current Frame')
    img = ax.imshow(o)

    gen = pattern.point_generator()

    ax2.set_title('Observed Brightness')
    img2 = ax2.imshow(o)

    ax3.set_title('Position')
    line = ax3.plot([0], [0])[0]

    r = pattern.perimeter_radius
    xs = linspace(-r, r)
    xs2 = xs[::-1]
    ys = (r ** 2 - xs ** 2) ** 0.5
    ys2 = -(r ** 2 - xs2 ** 2) ** 0.5
    xxx, yyy = hstack((xs, xs2)) + 150, hstack((ys, ys2)) + 150
    # print xxx,yyy
    # print xs+150, ys+150
    # ax3.plot(xs+150,ys+150)
    ax3.plot(xxx, yyy)

    ax3.set_xlim(50, 250)
    ax3.set_ylim(50, 250)
    scatter = ax3.plot([150], [150], '+')

    xx, yy = 100, 150
    scatter2 = ax3.plot([xx], [yy], 'o')[0]

    cp = ax7.scatter([0], [0], c=[0])
    cp.autoscale()
    ax7.set_xlim(-100, 100)
    ax7.set_ylim(-100, 100)

    ax4.set_title('Intensity')
    tvint = ax4.plot([1], [1])[0]
    # tvint = ax4.semilogy([1],[1])[0]
    ax4.set_xlim(0, 50)
    # ax4.set_ylim(0, 1.1)

    ax5.set_title('Time Constant')
    tc = ax5.plot([0], [0])[0]
    ax5.set_ylim(-20, 20)
    ax5.set_xlim(0, 50)

    ax5.set_title('Radius')
    rs = ax6.plot([0], [0])[0]
    ax6.set_ylim(0, 100)
    ax6.set_xlim(0, 50)

    xs = []
    ys = []
    ts = []
    zs = []
    tcs = []
    rcs = []
    f.set_pos(xx, yy)
    st = time.time()

    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        # z /= 3716625.0
        # z += 0.1 * random.random()
        # print x, y, z
        pattern.set_point(z, x, y)
        zs.append(z)
        # print ts
        # print zs
        tvint.set_data(ts, zs)
        ax4.set_ylim(min(zs) * 0.9, max(zs) * 1.1)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)

        # >>>>>>>>>>>>>>>>>>>>>>>
        # add a plot that is the current points of the triangle
        # >>>>>>>>>>>>>>>>>>>>>>>
        xy = pattern._tri.xys()
        x, y, z = zip(*xy)
        # print x, y
        # cp.set_data(x, y)
        cp.set_offsets(zip(x, y))

        maz, miz = max(z), min(z)
        z = [(zi - miz) / (maz - miz) for zi in z]
        print z
        cp.set_facecolors([cm.hot(zi) for zi in z])
        # cp.set_edgecolors(z)
        if not pattern._tri.is_equilateral():
            print 'not eq'

            # return mplfig_to_npimage(fig)
            # raw_input()

    animation = FuncAnimation(fig, update, interval=1000)
    plt.show()
Пример #15
0
 def _lumen_detector_default(self):
     ld = LumenDetector()
     ld.pixel_depth = self.video.pixel_depth
     return ld
Пример #16
0
    def degas(self, lumens, duration):
        """
            degas for duration trying to maintain
            lumens
        """
        if self.laser_manager:
            self.laser_manager.fiber_light.power_off()

        g = self._make_graph(lumens, duration)
        if self._testing:
            self._test_graph = g
        else:
            self.laser_manager.auxilary_graph = g.plotcontainer

        cw, ch = 2 * self.crop_width * self.pxpermm, 2 * self.crop_height * self.pxpermm

        # if not cw % 5 == 0:
        #     cw += cw % 5
        # if not ch % 5 == 0:
        #     ch += ch % 5
        #
        # cw, ch = 200, 200

        im = MVImage()
        im.setup_images(1, (cw, ch))
        if self._testing:
            self._test_image = im
        else:
            self.view_image(im)

        self._detector = LumenDetector()
        dt = self._period

        pid = self.pid
        st = time.time()
        i = 0
        while 1:
            ct = time.time()
            tt = ct - st
            if not self.isAlive():
                break

            cl = self._get_current_lumens(im, cw, ch)

            err = lumens - cl
            out = pid.get_value(err, dt)
            g.add_data(((tt, out), (tt, err), (tt, cl)))

            self._set_power(out, i)

            if tt > duration:
                break
            et = time.time() - ct
            time.sleep(max(0, dt - et))

            i += 1
            if i > 1e6:
                i = 0

        if self.laser_manager:
            self.laser_manager.fiber_light.power_on()

        self.executing = False