Esempio n. 1
0
    def addRow(self, evt=None):
        """
        add a row to the list and self.clist.alignParms
        """
        if self.clist.nw >= 5:
            G.openMsg(self, 'The maximum wavelength is 5',
                      'I am sorry for that')
            return

        if wx.version().startswith('3'):
            index = self.InsertStringItem(sys.maxsize, '0')
        else:
            index = self.clist.InsertItem(sys.maxsize, '0')

        self.clist.alignParms = N.insert(self.clist.alignParms,
                                         self.clist.alignParms.shape[1],
                                         0,
                                         axis=1)
        self.clist.alignParms[:, -1, -3:] = 1

        waves = list(self.clist.waves)
        waves.append(0)
        self.clist.waves = N.array(waves)
        self.clist.nw = len(self.clist.waves)

        for i, p in enumerate(self.clist.alignParms[self.clist.t, index]):
            self.clist.SetItem(index, i + 1,
                               str(p))  #SetStringItem(index, i+1, str(p))
Esempio n. 2
0
    def OnChooseInitGuess(self, evt=None):
        """
        set reference files
        """
        wildcard = '*.chromagnon*'

        if os.name == 'posix':
            dlg = G.FileSelectorDialog(self,
                                       direc=self.lastpath,
                                       wildcard=wildcard,
                                       multiple=False)
        else:
            dlg = wx.FileDialog(self,
                                'Choose chromagnon files',
                                defaultDir=self.lastpath,
                                wildcard=wildcard)

        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetPath()
            if chromformat.is_chromagnon(fn, True):
                self._setInitGuess(fn)
            else:
                G.openMsg(parent=self,
                          msg='The file is not a valid chromagnon file',
                          title="Warning")
Esempio n. 3
0
    def OnAutoFocus(self, evt=None):
        """
        please read Chromagnon.alignfuncs.findBestRefZs() for detail of the logic
        """
        if self.doc.nt > 1:
            t = int(self.tSliderBox.GetValue())
        else:
            t = 0
        ws = [
            w for w, hist in enumerate(self.hist_toggleButton)
            if hist.GetValue()
        ]

        ms = N.zeros((len(ws), self.doc.nz), N.float32)

        # FFTW does not work with another program using it
        # here is the workaround for Chromagnon
        try:
            batch = self.GetParent().GetParent().GetParent()
            if hasattr(batch, 'th') and batch.th.isAlive():
                for wi, w in enumerate(ws):
                    arr = self.doc.get3DArr(t=t, w=w)
                    for z in range(self.doc.nz):
                        ms[wi, z] = N.prod(U.mmms(arr[z])[-2:])  # mean * std
                v, _, w, z = U.findMax(ms)
                self.zSliderBox.SetValue(str(z))
                self.OnZSliderBox()
                self.OnAutoScale()

                G.openMsg(
                    parent=self.parent,
                    msg=
                    'A clumsy focusing method was used since another program was using FFTW.\nPlease wait for the better method until the other program is done.',
                    title="Please wait")
                return
        except AttributeError:  # no parent?
            pass

        # Frequency-based caluculation starts
        from Priithon.all import F

        ring = F.ringArr(self.doc.shape[-2:],
                         radius1=self.doc.shape[-1] // 10,
                         radius2=self.doc.shape[-2] // 4,
                         orig=(0, 0),
                         wrap=1)

        for wi, w in enumerate(ws):
            arr = self.doc.get3DArr(t=t, w=w)
            arr = arr / arr.mean()
            for z in range(self.doc.nz):
                af = F.rfft(N.ascontiguousarray(arr[z]))
                ar = af * ring[:, :af.shape[-1]]
                ms[wi, z] = N.sum(N.abs(ar))
        v, _, w, z = U.findMax(ms)

        self.zSliderBox.SetValue(str(z))
        self.OnZSliderBox()
        self.OnAutoScale()
Esempio n. 4
0
    def OnChooseImgFiles(self, evt, listtype='ref'):
        """
        set reference files
        """
        confdic = C.readConfig()
        if listtype == 'ref':
            ll = self.listRef
            wildcard = confdic.get('lastwildcardref', FILTER)
        else:
            ll = self.listTgt
            wildcard = confdic.get('lastwildcardtgt', FILTER)

        if os.name == 'posix':
            dlg = G.FileSelectorDialog(self, self.lastpath, wildcard=wildcard)
        else:
            dlg = wx.FileDialog(self,
                                'Choose %s files' % listtype,
                                defaultDir=self.lastpath,
                                style=wx.FD_MULTIPLE)

        if dlg.ShowModal() == wx.ID_OK:
            fns = dlg.GetPaths()

            if not fns:
                return
            if os.name == 'posix':
                wildcard = dlg.fnPat
            if isinstance(fns, six.string_types):  #str):
                fns = [fns]

            ll.addFiles(fns)
            if listtype != 'ref':
                if any([nw > 5 for nw in ll.nws
                        ]) and self.outextch.GetStringSelection() == (
                            os.path.extsep + aligner.WRITABLE_FORMATS[1]):
                    self.outextch.SetStringSelection(
                        os.path.extsep + aligner.WRITABLE_FORMATS[0])
                    G.openMsg(
                        parent=self,
                        msg=
                        'Since number of wavelength in some image file is more than 5,\nthe output file format was changed to tiff',
                        title="Output file format change")

            self.lastpath = os.path.dirname(fns[0])
            if listtype == 'ref':
                C.saveConfig(lastwildcardref=wildcard, lastpath=self.lastpath)
            else:
                C.saveConfig(lastwildcardtgt=wildcard, lastpath=self.lastpath)

            self.checkGo()
Esempio n. 5
0
    def OnAutoFocus(self, evt=None):
        """
        please read Chromagnon.alignfuncs.findBestRefZs() for detail of the logic
        """
        if self.doc.nt > 1:
            t = int(self.tSliderBox.GetValue())
        else:
            t = 0
        ws = [w for w, hist in enumerate(self.hist_toggleButton) if hist.GetValue()]

        ms = N.zeros((len(ws),self.doc.nz), N.float32)

        # FFTW does not work with another program using it
        # here is the workaround for Chromagnon
        try:
            batch = self.GetParent().GetParent().GetParent()
            if hasattr(batch, 'th') and batch.th.isAlive():
                for wi, w in enumerate(ws):
                    arr = self.doc.get3DArr(t=t, w=w)
                    for z in range(self.doc.nz):
                        ms[wi,z] = N.prod(U.mmms(arr[z])[-2:]) # mean * std
                v,_,w,z = U.findMax(ms)
                self.zSliderBox.SetValue(str(z))
                self.OnZSliderBox()
                self.OnAutoScale()
                        
                G.openMsg(parent=self.parent, msg='A clumsy focusing method was used since another program was using FFTW.\nPlease wait for the better method until the other program is done.', title="Please wait")
                return
        except AttributeError: # no parent?
            pass

        # Frequency-based caluculation starts 
        from Priithon.all import F
        
        ring = F.ringArr(self.doc.shape[-2:], radius1=self.doc.shape[-1]//10, radius2=self.doc.shape[-2]//4, orig=(0,0), wrap=1)


        for wi, w in enumerate(ws):
            arr = self.doc.get3DArr(t=t, w=w)
            arr = arr / arr.mean()
            for z in range(self.doc.nz):
                af = F.rfft(N.ascontiguousarray(arr[z]))
                ar = af * ring[:,:af.shape[-1]]
                ms[wi,z] = N.sum(N.abs(ar))
        v,_,w,z = U.findMax(ms)

        self.zSliderBox.SetValue(str(z))
        self.OnZSliderBox()
        self.OnAutoScale()
Esempio n. 6
0
    def view(self, fn):
        """
        opens viewer and hide itself.
        """
        try:
            self.doc = aligner.Chromagnon(fn)
        except:
            G.openMsg(self, 'This file is not a valid image file', 'Error')
            return

        self.loadParm()

        parent = self.GetParent()
        parent._mgr.GetPane('tpanel').Hide()
        parent.addImageXY()
Esempio n. 7
0
    def view(self, fn):
        """
        opens viewer and hide itself.
        """
        try:
            self.doc = aligner.Chromagnon(fn)
            self.doc.zlast = 0
        except:
            G.openMsg(self, 'This file is not a valid image file', 'Error')
            return

        self.loadParm()

        parent = self.GetParent()
        parent._mgr.GetPane('tpanel').Hide()
        parent.addImageXY()
Esempio n. 8
0
    def OnChooseInitGuess(self, evt=None):
        """
        set reference files
        """
        wildcard = '*.chromagnon*'

        if os.name == 'posix':
            dlg = G.FileSelectorDialog(self, direc=self.lastpath, wildcard=wildcard, multiple=False)
        else:
            dlg = wx.FileDialog(self, 'Choose chromagnon files', defaultDir=self.lastpath, wildcard=wildcard)
            
        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetPath()
            if chromformat.is_chromagnon(fn, True):
                self._setInitGuess(fn)
            else:
                G.openMsg(parent=self, msg='The file is not a valid chromagnon file', title="Warning")
Esempio n. 9
0
    def OnChooseImgFiles(self, evt, listtype='ref'):
        """
        set reference files
        """
        confdic = C.readConfig()
        if listtype == 'ref':
            ll = self.listRef
            wildcard = confdic.get('lastwildcardref', FILTER)
        else:
            ll = self.listTgt
            wildcard = confdic.get('lastwildcardtgt', FILTER)

        if os.name == 'posix':
            dlg = G.FileSelectorDialog(self, self.lastpath, wildcard=wildcard)
        else:
            dlg = wx.FileDialog(self, 'Choose %s files' % listtype, defaultDir=self.lastpath, style=wx.FD_MULTIPLE)
            
        if dlg.ShowModal() == wx.ID_OK:
            fns = dlg.GetPaths()

            if not fns:
                return
            if os.name == 'posix':
                wildcard = dlg.fnPat
            if isinstance(fns, six.string_types):
                fns = [fns]

            ll.addFiles(fns)
            if listtype != 'ref':
                if any([nw > 5 for nw in ll.nws]) and self.outextch.GetStringSelection() == (os.path.extsep + aligner.WRITABLE_FORMATS[1]):
                    self.outextch.SetStringSelection(os.path.extsep + aligner.WRITABLE_FORMATS[0])
                    G.openMsg(parent=self, msg='Since number of wavelength in some image file is more than 5,\nthe output file format was changed to tiff', title="Output file format change")
            
            self.lastpath = os.path.dirname(fns[0])
            if listtype == 'ref':
                C.saveConfig(lastwildcardref=wildcard, lastpath=self.lastpath)
            else:
                C.saveConfig(lastwildcardtgt=wildcard, lastpath=self.lastpath)

            self.checkGo()
Esempio n. 10
0
    def addRow(self, evt=None):
        """
        add a row to the list and self.clist.alignParms
        """
        if self.clist.nw >= 5:
            G.openMsg(self, 'The maximum wavelength is 5', 'I am sorry for that')
            return 

        if wx.version().startswith('3'):
            index = self.InsertStringItem(sys.maxsize, '0')
        else:
            index = self.clist.InsertItem(sys.maxsize, '0')

        self.clist.alignParms = N.insert(self.clist.alignParms, self.clist.alignParms.shape[1], 0, axis=1)
        self.clist.alignParms[:,-1,-3:] = 1

        waves = list(self.clist.waves)
        waves.append(0)
        self.clist.waves = N.array(waves)
        self.clist.nw = len(self.clist.waves)
        
        for i, p in enumerate(self.clist.alignParms[self.clist.t,index]):
            self.clist.SetItem(index, i+1, str(p))#SetStringItem(index, i+1, str(p))
Esempio n. 11
0
    def onViewLocal(self, evnt=None, gridStep=60, t=0, w=None, originalFn=None, **kwds):
        """
        save a '.local' file and opens new image viewer
        """
        import wx, tempfile
        import imgio
        from Priithon.all import Y

        if w is None:
            wave = int(self.wavechoice.GetStringSelection())
            w = self.clist.wave.index(wave)
            

        if originalFn is None:
            originalFn = self.originalFileTxt.GetValue()

        factor = int(self.factorchoice.GetStringSelection())
        colstr = self.colorchoice.GetStringSelection()
        colortable = [(0,0,0)] + microscope.COLOR_TABLE
        col = colortable[self.color_name.index(colstr)]
        
        parent = self.GetParent()
        book = parent.GetTopLevelParent()

        mapyx = self.clist.mapyx
        name = self.clist.basename + '.Local'

        if originalFn:
            try:
                img = imgio.Reader(originalFn)#imgfileIO.load(originalFn)
            except:
                G.openMsg(self, 'Is this file really a image file?', title='Error')
                return
            if N.any(N.array(img.shape[-2:]) != N.array(self.clist.mapyx.shape[-2:])):
                G.openMsg(self, 'Please choose original image file BEFORE alignment', title='Error')
                return
            a = N.zeros(self.clist.mapyx.shape[-3:], img.dtype)
            b = img.get3DArr(w=self.clist.refwave, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)
            a[0] = b

            b = img.get3DArr(w=w, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)

            a[1] = af.applyShift(b, self.clist.alignParms[t,w])
            pz, py, px = img.pxlsiz
        else:
            a = N.zeros(self.clist.mapyx.shape[-3:], N.uint8)
            pz = py = px = 1

        out = os.path.join(tempfile.gettempdir(), 'Chromagnon.local.tif')

        wtr = imgio.Writer(out)
        wtr.setPixelSize(pz=pz, py=py, px=px)
        wtr.setDim(nx=a.shape[-1], ny=a.shape[-2], nz=1, nt=1, nw=2, dtype=a.dtype.type, wave=[self.clist.wave[self.clist.refwave], self.clist.wave[w]], imgSequence=1)
        for w, a2d in enumerate(a):
            wtr.writeArr(a2d, w=w)
        wtr.close()
        
        an = aligner.Chromagnon(out)
        newpanel = aui.ImagePanel(book, an.img)
        book.imEditWindows.AddPage(newpanel, name, select=True)
        v = newpanel.viewers[0]
        wx.Yield()

        inds = N.indices(mapyx.shape[-2:], N.float32)
        slcs1 = [slice(gridStep//2, -gridStep//2, gridStep) for d in range(2)]

        #for w in xrange(self.clist.nw):
        vs = []
        for d in range(2):
            slcs = [slice(d,d+1)] + slcs1
            vs.append(inds[slcs].ravel())
        iis = N.array(list(zip(*vs)))

        vs = []
        for d in range(2):
            slcs = [slice(t,t+1), slice(w,w+1), slice(d,d+1)] + slcs1
            vs.append(mapyx[slcs].ravel())
        yxs = N.array(list(zip(*vs)))

        wave = self.clist.wave[w]
        #col = microscope.LUT(wave)
        #col = (1,1,1)
        wx.CallAfter(Y.vgAddArrows, v, iis, iis+yxs, color=col, factor=factor, width=2, **kwds)
Esempio n. 12
0
 def quit(self, message='', title='ERROR'):
     if message:
         G.openMsg(parent=self, msg=message, title=title)
     self.goButton.SetValue(0)
     self.label.SetLabel('')
Esempio n. 13
0
    def OnGo(self, ev=None):
        """
        run or cancel the alignment program

        The actual sequence of processes is written in threads.ThreadWithExc.run()
        """
        if self.goButton.GetValue():
            
            if not self.listRef.columnkeys:
                return

            fns = [os.path.join(*self.listRef.getFile(index)[:2]) for index in self.listRef.columnkeys]
            targets = [os.path.join(*self.listTgt.getFile(index)[:2]) for index in self.listTgt.columnkeys]

            # other parameters
            #initguess = ''
            confdic = C.readConfig()

            form = self.outextch.GetStringSelection()
            if not form:
                self.quit('Please select the output file format next to the Suffix text box', title="The format type is missing")
                return

            # check wavelengths
            waves1 = [list(map(int, self.listRef.getFile(index)[2].split(','))) for index in self.listRef.columnkeys]
            waves2 = [list(map(int, self.listTgt.getFile(index)[2].split(','))) for index in self.listTgt.columnkeys]
            nts = all([t == 1 for t in self.listRef.nts])
            ids = af.checkWaves(waves1, waves2)
            if ids is not None and nts:
                for i, listbox in zip(ids, (self.listRef, self.listTgt)):
                    listbox.SetItemTextColour(i, 'purple')
                    #listbox.SetBackGroundColour(i, 'gray')
                msg = 'Less than two Common wavelengths were found at least in %s and %s\n\nThe program will not run.' % (self.listRef.getFile(ids[0])[1], self.listTgt.getFile(ids[1])[1])
                self.quit(msg, title='Error in input files')
                return
            
            # averaging
            if self.averageCb.GetValue() and len(fns) > 1:
                if any([waves1[0] != ws1 for ws1 in waves1[1:]]):
                    self.quit('There are inconsistency in channel composition in the reference files', title="Reference files are not appropriate for averaging")
                    return
                
                try:
                    self.label.SetLabel('averaging...')
                    self.label.SetForegroundColour('red')
                    wx.Yield()
                    ave_fn = af.averageImage(fns, ext=form)
                except Exception as e:
                    self.quit(e.args[0], title="Reference files are not appropriate for averaging")
                    return         
                self.listRef.clearAll()
                self.listRef.addFile(ave_fn)
                fns = [ave_fn]
            elif self.averageCb.GetValue() and len(fns) == 1:
                self.averageCb.SetValue(0)


            accur = self.extra_parms.get('zacuur', confdic.get('accur', aligner.ACCUR_CHOICE[0]))
            if accur in aligner.ACCUR_CHOICE_DIC:
                accur = aligner.ACCUR_CHOICE_DIC[accur]
            
            # parameters
            parms = [self.cutoutCb.GetValue(),
                     self.extra_parms.get('outdir'),#initguess,
                     self.localListChoice.GetStringSelection(),
                     self.extra_parms.get('refwave'), #None, #self.maxShift.GetValue(),
                     int(accur),#self.extra_parms.get('zacuur', confdic.get('accur', aligner.ACCUR_CHOICE[0]))), #self.accurListChoice.GetStringSelection(),
                    self.parm_suffix_txt.GetValue(),
                        self.img_suffix_txt.GetValue(),
                     self.extra_parms.get('tseries4wave', 'time'),#[nt for nt in self.listRef.nts], # copy
                     form,
                     int(self.min_pxls_choice.GetStringSelection()),
                         self.extra_parms.get('max_shift', af.MAX_SHIFT)] 

            #print(parms[4], confdic.get('accur', aligner.ACCUR_CHOICE[0]), type(parms[4]))
            # check the user-inputs
            old="""
            try:
                parms[3] = float(parms[3])
            except ValueError:
                G.openMsg(parent=self, msg='The default value (%.2f um) will be used' % af.MAX_SHIFT, title="The value for max shift allowed is missing")
                parms[3] = af.MAX_SHIFT
                self.maxShift.SetValue(str(parms[3]))"""
                        
            if not parms[6]:
                G.openMsg(parent=self, msg='The default suffix will be used', title="The file suffix is missing")
                parms[6] = aligner.IMG_SUFFIX
                self.img_suffix_txt.SetValue(parms[6])

            # save current settings
            C.saveConfig(cutout=parms[0], local=parms[2], accur=parms[4], parm_suffix_txt=parms[5], img_suffix_txt=parms[6], format=parms[8], min_pxls_yx=parms[9])
            #C.saveConfig(cutout=parms[0], local=parms[2], maxShift=parms[3], accur=parms[4], parm_suffix_txt=parms[5], img_suffix_txt=parms[6], format=parms[8], min_pxls_yx=parms[9])

            # run program
            gui = threads.GUImanager(self, __name__)
            
            self.th = threads.ThreadWithExc(gui, self.localChoice, fns, targets, parms)
            self.th.start()

        else:
            tid = self.th._get_my_tid()
            threads.async_raise(tid, threads.MyError)
Esempio n. 14
0
    def OnGo(self, ev=None):
        """
        run or cancel the alignment program

        The actual sequence of processes is written in threads.ThreadWithExc.run()
        """
        if self.goButton.GetValue():
            if not self.listRef.columnkeys:
                return

            fns = [
                os.path.join(*self.listRef.getFile(index)[:2])
                for index in self.listRef.columnkeys
            ]
            targets = [
                os.path.join(*self.listTgt.getFile(index)[:2])
                for index in self.listTgt.columnkeys
            ]

            # other parameters
            initguess = ''

            form = self.outextch.GetStringSelection()
            if not form:
                G.openMsg(
                    parent=self,
                    msg=
                    'Please select the output file format next to the Suffix text box',
                    title="The format type is missing")
                self.goButton.SetValue(0)
                return

            parms = [
                self.cutoutCb.GetValue(),
                initguess,
                self.localListChoice.GetStringSelection(),
                self.maxShift.GetValue(),
                self.zmagch.GetStringSelection(),
                self.parm_suffix_txt.GetValue(),
                self.img_suffix_txt.GetValue(),
                [nt for nt in self.listRef.nts],  # copy
                form,
                int(self.min_pxls_choice.GetStringSelection())
            ]

            # check the user-inputs
            try:
                parms[3] = float(parms[3])
            except ValueError:
                G.openMsg(parent=self,
                          msg='The default value (%.2f um) will be used' %
                          af.MAX_SHIFT,
                          title="The value for max shift allowed is missing")
                parms[3] = af.MAX_SHIFT
                self.maxShift.SetValue(str(parms[3]))

            if not parms[6]:
                G.openMsg(parent=self,
                          msg='The default suffix will be used',
                          title="The file suffix is missing")
                parms[6] = alginer.IMG_SUFFIX
                self.img_suffix_txt.SetValue(parms[6])

            # save current settings
            C.saveConfig(cutout=parms[0],
                         local=parms[2],
                         maxShift=parms[3],
                         Zmag=parms[4],
                         parm_suffix_txt=parms[5],
                         img_suffix_txt=parms[6],
                         format=parms[8],
                         min_pxls_yx=parms[9])

            # run program
            gui = threads.GUImanager(self, __name__)

            self.th = threads.ThreadWithExc(gui, self.localChoice, fns,
                                            targets, parms)
            self.th.start()

        else:
            tid = self.th._get_my_tid()
            threads.async_raise(tid, threads.MyError)
Esempio n. 15
0
def ChromagnonReader(fn, rdr=None, holder=None):
    rdr = rdr
    holder = holder

    dratio = N.ones((3, ), N.float32)

    if not is_binary(fn):
        text = True

        fp = open(fn)
        reader = csv.reader(fp)

        # read parameters
        nt = int(reader.next()[1])
        nw = int(reader.next()[1])
        pxlsiz = N.array([eval(p) for p in reader.next()[1:]])
        imgSequence = 2
        refwave = eval(reader.next()[1])
        num_entry = len(reader.next()[2:])
        wave = []
        #self.pos0 = self.tell()

        alignParms = N.empty((nt, nw, num_entry), N.float32)
        for t in xrange(nt):
            for w in xrange(nw):
                row = reader.next()
                wave.append(_eval(row[1]))
                alignParms[t, w] = [eval(v) for v in row[2:]]
    else:
        text = False

        reader = bioformatsIO.BioformatsReader(fn)
        pxlsiz = reader.pxlsiz
        wave = reader.wave
        nw = reader.nw
        nt = reader.nt
        nz = reader.nz
        nz //= 2
        ny = reader.ny
        nx = reader.nx

        # read parameters
        refwave = eval(reader.ome.get_structured_annotation('refwave'))
        num_entry = eval(reader.ome.get_structured_annotation('num_entry'))

        alignParms = N.empty((reader.nt, reader.nw, reader.num_entry),
                             N.float32)
        for t in xrange(reader.nt):
            for w in xrange(reader.nw):
                for i, key in enumerate(DIMSTRS):
                    alignParms[t, w, i] = eval(
                        reader.ome.get_structured_annotation('t%03d_w%i_' %
                                                             (t, w) + key))

    # loading parameters to the parent classes
    if rdr and holder:
        # reading the header
        if hasattr(rdr, 'pxlsiz'):
            dratio = N.asarray(pxlsiz, N.float32) / N.asarray(
                rdr.pxlsiz, N.float32)
        else:  # chromeditor
            dratio = N.ones((3, ), N.float32)
            rdr.pxlsiz = pxlsiz
            rdr.wave = wave
            rdr.nw = nw
            rdr.nt = nt
            rdr.nz = nz

        # wavelength difference
        pwaves = list(wave[:nw])
        twaves = list(rdr.wave[:rdr.nw])
        tids = [twaves.index(wave) for wave in pwaves if wave in twaves]
        pids = [pwaves.index(wave) for wave in twaves if wave in pwaves]

        somewaves = [w for w, wave in enumerate(pwaves) if wave in twaves]

        if refwave in twaves:
            holder.refwave = twaves.index(refwave)
        elif len(
                somewaves
        ) >= 1:  # the reference wavelength was not found but some found
            holder.refwave = somewaves[0]
            from PriCommon import guiFuncs as G
            message = 'The original reference wavelength %i of the initial guess was not found in the target %s' % (
                refwave, holder.file)
            G.openMsg(msg=message, title='WARNING')

        else:
            from PriCommon import guiFuncs as G
            message = 'No common wavelength with initial guess was found in %s and %s' % (
                os.path.basename(file), rdr.file)
            G.openMsg(msg=message, title='WARNING')
            return

        # compensate wavelength difference
        target = N.zeros((nt, rdr.nw, num_entry), N.float32)
        target[:, :, 4:] = 1
        target[:, tids] = alignParms[:, pids]
        for w in [w for w, wave in enumerate(twaves) if wave not in pwaves]:
            target[:, w] = alignParms[:, holder.refwave]
        target[:, :, :3] *= dratio
        alignParms = target

        # set holder
        if hasattr(self.holder, 'setAlignParam'):
            holder.setAlignParam(alignParms)
        else:
            holder.alignParms = alignParms

        # obtain mapping array
        if not text:
            nzyx = N.array((nz, reader.ny, reader.nx), N.float32)
            nzyx *= dratio
            nyzx = nzyx.astype(N.int)

            tmin = min(rdr.nt, reader.nt)
            if nzyx[0] > 1:
                arr = N.zeros((rdr.nt, rdr.nw, nzyx[0], 2, nzyx[1], nzyx[2]),
                              reader.dtype)
            else:
                arr = N.zeros((rdr.nt, rdr.nw, 2, nzyx[1], nzyx[2]),
                              reader.dtype)

            for t in xrange(tmin):
                for wt, wp in enumerate(pids):
                    w = tids[wt]

                    a = N.zeros((nzyx[0], 2, nzyx[1], nzyx[2]), reader.dtype)

                    for z in xrange(nz):
                        warr = reader.get3DArr(t=t, w=w)
                        warr = warr.reshape((nz, 2, reader.ny, reader.nx))
                        for s in xrange(2):
                            zc = z * 2 + s
                            if any(dratio[1:] != 1):
                                a[z, s] = nd.zoom(warr[:, s],
                                                  dratio) * dratio[1 + (s % 2)]
                            else:
                                arr[z, s] = warr[:, s]

                    if nzyx[0] > 1:
                        arr[t, w] = a
                    else:
                        arr[t, w] = a[0]

            for w in [
                    w for w, wave in enumerate(twaves) if wave not in pwaves
            ]:
                arr[:tmin, w] = arr[:tmin, refwave]

            holder.mapyx = arr
    return reader
Esempio n. 16
0
    def onViewLocal(self,
                    evnt=None,
                    gridStep=60,
                    t=0,
                    w=None,
                    originalFn=None,
                    **kwds):
        """
        save a '.local' file and opens new image viewer
        """
        import wx, tempfile
        import imgio
        from Priithon.all import Y

        if w is None:
            wave = int(self.wavechoice.GetStringSelection())
            w = self.clist.wave.index(wave)

        if originalFn is None:
            originalFn = self.originalFileTxt.GetValue()

        factor = int(self.factorchoice.GetStringSelection())
        colstr = self.colorchoice.GetStringSelection()
        colortable = [(0, 0, 0)] + microscope.COLOR_TABLE
        col = colortable[self.color_name.index(colstr)]

        parent = self.GetParent()
        book = parent.GetTopLevelParent()

        mapyx = self.clist.mapyx
        name = self.clist.basename + '.Local'

        if originalFn:
            try:
                img = imgio.Reader(originalFn)  #imgfileIO.load(originalFn)
            except:
                G.openMsg(self,
                          'Is this file really a image file?',
                          title='Error')
                return
            if N.any(
                    N.array(img.shape[-2:]) != N.array(
                        self.clist.mapyx.shape[-2:])):
                G.openMsg(self,
                          'Please choose original image file BEFORE alignment',
                          title='Error')
                return
            a = N.zeros(self.clist.mapyx.shape[-3:], img.dtype)
            b = img.get3DArr(w=self.clist.refwave, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)
            a[0] = b

            b = img.get3DArr(w=w, t=t)
            if self.clist.mapyx.ndim == 5:
                b = N.max(b, 0)

            a[1] = af.applyShift(b, self.clist.alignParms[t, w])
            pz, py, px = img.pxlsiz
        else:
            a = N.zeros(self.clist.mapyx.shape[-3:], N.uint8)
            pz = py = px = 1

        out = os.path.join(tempfile.gettempdir(), 'Chromagnon.local.tif')

        wtr = imgio.Writer(out)
        wtr.setPixelSize(pz=pz, py=py, px=px)
        wtr.setDim(
            nx=a.shape[-1],
            ny=a.shape[-2],
            nz=1,
            nt=1,
            nw=2,
            dtype=a.dtype.type,
            wave=[self.clist.wave[self.clist.refwave], self.clist.wave[w]],
            imgSequence=1)
        for w, a2d in enumerate(a):
            wtr.writeArr(a2d, w=w)
        wtr.close()

        an = aligner.Chromagnon(out)
        newpanel = aui.ImagePanel(book, an.img)
        book.imEditWindows.AddPage(newpanel, name, select=True)
        v = newpanel.viewers[0]
        wx.Yield()

        inds = N.indices(mapyx.shape[-2:], N.float32)
        slcs1 = [
            slice(gridStep // 2, -gridStep // 2, gridStep) for d in range(2)
        ]

        #for w in xrange(self.clist.nw):
        vs = []
        for d in range(2):
            slcs = [slice(d, d + 1)] + slcs1
            vs.append(inds[slcs].ravel())
        iis = N.array(list(zip(*vs)))

        vs = []
        for d in range(2):
            slcs = [slice(t, t + 1), slice(w, w + 1), slice(d, d + 1)] + slcs1
            vs.append(mapyx[slcs].ravel())
        yxs = N.array(list(zip(*vs)))

        wave = self.clist.wave[w]
        #col = microscope.LUT(wave)
        #col = (1,1,1)
        wx.CallAfter(Y.vgAddArrows,
                     v,
                     iis,
                     iis + yxs,
                     color=col,
                     factor=factor,
                     width=2,
                     **kwds)
Esempio n. 17
0
    def loadParm(self):
        """
        load a chromagnon file
        """

        # reading the header
        if hasattr(self.rdr, 'pxlsiz'):
            self.dratio = N.asarray(self.pxlsiz, N.float32) / N.asarray(
                self.rdr.pxlsiz, N.float32)
        else:  # chromeditor
            self.dratio = N.ones((3, ), N.float32)
            self.rdr.pxlsiz = self.pxlsiz
            self.rdr.wave = self.wave
            self.rdr.nw = self.nw
            self.rdr.nt = self.nt
            self.rdr.nz = self.nz

        # wavelength difference
        self.pwaves = [int(round(w)) for w in self.wave[:self.nw]]
        self.twaves = [int(round(w)) for w in self.rdr.wave[:self.rdr.nw]]
        self.tids = [
            self.twaves.index(wave) for wave in self.pwaves
            if wave in self.twaves
        ]
        self.pids = [
            self.pwaves.index(wave) for wave in self.twaves
            if wave in self.pwaves
        ]

        somewaves = [
            w for w, wave in enumerate(self.pwaves) if wave in self.twaves
        ]

        if self.refwave in self.twaves:
            self.holder.refwave = self.twaves.index(self.refwave)
        elif len(
                somewaves
        ) >= 1:  # the reference wavelength was not found but some found
            self.holder.refwave = somewaves[0]
            from PriCommon import guiFuncs as G
            message = 'The original reference wavelength %i of the initial guess was not found in the target %s' % (
                self.refwave, self.holder.fn)
            G.openMsg(msg=message, title='WARNING')

        else:
            #self.holder.parm = N.zeros((self.rdr.nt, self.rdr.nw, self.num_entry), self.dtype)
            from PriCommon import guiFuncs as G
            message = 'No common wavelength with initial guess was found in %s and %s' % (
                os.path.basename(self.file), self.rdr.file)
            G.openMsg(msg=message, title='WARNING')
            return

        # obtain affine parms
        self.readParmWave()

        if hasattr(self.holder, 'setAlignParam'):
            self.holder.setAlignParam(self.alignParms)
        else:
            self.holder.alignParms = self.alignParms

        # obtain mapping array
        if not self.text:
            self.holder.mapyx = self.readMapAll()