Changeset 2026


Ignore:
Timestamp:
Oct 28, 2015 5:32:01 PM (6 years ago)
Author:
toby
Message:

autoint minimal, but ready for testing; fixes to Exports

Location:
trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASII.py

    r2017 r2026  
    775775                first = False
    776776                self.CheckNotebook()
    777             G2IO.LoadImage(rd.readfilename,self,rd.Comments,rd.Data,rd.Npix,rd.Image)
     777            G2IO.LoadImage2Tree(rd.readfilename,self,rd.Comments,rd.Data,rd.Npix,rd.Image)
    778778        self.PatternTree.SelectItem(G2gd.GetPatternTreeItemId(self,self.Image,'Image Controls'))             #show last image to have beeen read
    779779                   
     
    22502250        self.Integrate = 0
    22512251        self.imageDefault = {}
     2252        self.IntgOutList = [] # list of integration tree item Ids created in G2IO.SaveIntegration
     2253        self.autoIntFrame = None
    22522254        self.Sngl = False
    22532255        self.ifGetRing = False
  • trunk/GSASIIIO.py

    r2015 r2026  
    277277    Comments,Data,Npix,Image = GetImageData(G2frame,imagefile)
    278278    if Comments:
    279         LoadImage(imagefile,G2frame,Comments,Data,Npix,Image)
     279        LoadImage2Tree(imagefile,G2frame,Comments,Data,Npix,Image)
    280280   
    281 def LoadImage(imagefile,G2frame,Comments,Data,Npix,Image):
     281def LoadImage2Tree(imagefile,G2frame,Comments,Data,Npix,Image):
    282282    '''Load an image into the tree
    283283    '''
     
    12691269                Azms.append(G2img.meanAzm(azm,azms[i+1]))
    12701270        dazm = np.min(np.abs(np.diff(azms)))/2.
     1271    G2frame.IntgOutList = []
    12711272    for i,azm in enumerate(azms[:-1]):
    12721273        Aname = name+" Azm= %.2f"%((azm+dazm)%360.)
     
    12941295        W = np.where(Y>0.,1./Y,1.e-6)                    #probably not true
    12951296        Id = G2frame.PatternTree.AppendItem(parent=G2frame.root,text=Aname)
     1297        G2frame.IntgOutList.append(Id)
    12961298        G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Comments'),Comments)                   
    12971299        G2frame.PatternTree.SetItemPyData(G2frame.PatternTree.AppendItem(Id,text='Limits'),[tuple(Xminmax),Xminmax])
     
    25812583            fil = os.path.join(self.dirname,self.filename)
    25822584        self.fullpath = os.path.abspath(fil)
    2583         self.fp = open(fil,mode)
     2585        self.fp = open(self.fullpath,mode)
    25842586        return self.fp
    25852587
     
    26992701      match a powder export routine that has a Writer object.
    27002702    '''
    2701     filename = os.path.abspath(os.path.splitext(fileroot)[1]+extension)
     2703    filename = os.path.abspath(os.path.splitext(fileroot)[0]+extension)
    27022704    for obj in G2frame.exporterlist:
    27032705        if obj.extension == extension and 'powder' in obj.exporttype:
     
    27062708            obj.loadTree() # load all histograms in tree into dicts
    27072709            if TreeName not in obj.Histograms:
    2708                 raise Exception('Histogram not found: '+hst)
     2710                raise Exception('Histogram not found: '+str(TreeName))
     2711            try:
     2712                obj.Writer
     2713            except AttributeError:
     2714                continue
    27092715            try:
    27102716                obj.Writer(TreeName,filename)
    27112717                return
    2712             except AttributeError:
    2713                 print('Export Routine for '+extension+' does not have a .Writer method')
     2718            except Exception,err:
     2719                print('Export Routine for '+extension+' failed.')
     2720                print err
    27142721    else:
    27152722        print('No Export routine supports extension '+extension)
  • trunk/GSASIIimgGUI.py

    r2019 r2026  
    8787##### Image Controls
    8888################################################################################                   
    89 def UpdateImageControls(G2frame,data,masks):
     89def UpdateImageControls(G2frame,data,masks,IntegrateOnly=False):
    9090    '''Shows and handles the controls on the "Image Controls"
    9191    data tree entry
     
    110110        data['varyList'] = {'dist':True,'det-X':True,'det-Y':True,'tilt':True,'phi':True,'dep':False,'wave':False}
    111111#end patch
    112    
     112
    113113# Menu items
    114114           
     
    10311031    #end fix
    10321032   
     1033    if IntegrateOnly:
     1034        OnIntegrate(None)
     1035        return
     1036   
    10331037    colorList = sorted([m for m in mpl.cm.datad.keys() if not m.endswith("_r")],key=lambda s: s.lower())
    10341038    calList = sorted([m for m in calFile.Calibrants.keys()],key=lambda s: s.lower())
     
    10551059    if GSASIIpath.GetConfigValue('debug'):
    10561060        import autoint
     1061        def OnDestroy(event):
     1062            G2frame.autoIntFrame = None
    10571063        def OnAutoInt(event):
    1058             frame = autoint.AutoIntFrame(G2frame,PollTime=5.0)
     1064            reload(autoint)
     1065            if G2frame.autoIntFrame: # ensure only one open at a time
     1066                G2frame.autoIntFrame.Raise()
     1067                return
     1068            G2frame.autoIntFrame = autoint.AutoIntFrame(G2frame,PollTime=5.0)
     1069            G2frame.autoIntFrame.Bind(wx.EVT_WINDOW_DESTROY,OnDestroy) # clean up name on window close
    10591070        G2frame.dataFrame.Bind(wx.EVT_MENU, OnAutoInt, id=G2gd.wxID_IMAUTOINTEG)
    10601071    G2frame.dataDisplay = wx.Panel(G2frame.dataFrame)
  • trunk/autoint.py

    r2021 r2026  
    33import copy
    44import glob
     5import re
    56import GSASIIpath
    67import GSASIIIO as G2IO
    78import GSASIIctrls as G2G
    89import GSASIIgrid as G2gd
    9 #('xye','fxye','xy','chi')
     10import GSASIIimgGUI as G2imG
    1011'''
    1112Define a class to be used for Andrey's AutoIntegration process
     
    2930        after the "Start" button is pressed (when its label reads "Pause").
    3031        '''
     32        G2frame = self.G2frame
    3133        try:
    3234            self.currImageList = sorted(
     
    3739
    3840        createdImageIdList = []
     41        # loop over files that are found, reading in new ones
    3942        for newImage in self.currImageList:
    40             if newImage in self.IntegratedList: continue
    41             # need to read in this file
    42             Comments,Data,Npix,Image = G2IO.GetImageData(self.G2frame,newImage)
     43            if newImage in self.IntegratedList: continue # already processed
     44            Comments,Data,Npix,Image = G2IO.GetImageData(G2frame,newImage)
    4345            if not Npix:
    4446                print('problem reading '+newImage)
    4547                continue
    46             G2IO.LoadImage(newImage,self.G2frame,Comments,Data,Npix,Image)
    47             controlsDict = self.G2frame.PatternTree.GetItemPyData(
    48                 G2gd.GetPatternTreeItemId(self.G2frame,self.G2frame.Image, 'Image Controls'))
     48            G2IO.LoadImage2Tree(newImage,G2frame,Comments,Data,Npix,Image)
     49            # update controls from master
     50            controlsDict = G2frame.PatternTree.GetItemPyData(
     51                G2gd.GetPatternTreeItemId(G2frame,G2frame.Image, 'Image Controls'))
    4952            controlsDict.update(self.ImageControls)
    50             ImageMasks = self.G2frame.PatternTree.GetItemPyData(
    51                 G2gd.GetPatternTreeItemId(self.G2frame,self.G2frame.Image, 'Masks'))
    52             createdImageIdList.append(self.G2frame.Image)
    53             self.IntegratedList.append(newImage)
    54             print('debug: read '+newImage)
    55 
     53            # update masks from master
     54            ImageMasks = G2frame.PatternTree.GetItemPyData(
     55                G2gd.GetPatternTreeItemId(G2frame,G2frame.Image, 'Masks'))
     56            createdImageIdList.append(G2frame.Image) # save IMG Id
     57            self.IntegratedList.append(newImage) # save name of image so we don't process it again
     58            #print('debug: read '+newImage)
     59
     60        # now integrate the images we have read
    5661        for newImagId in createdImageIdList:
    57             print('debug: process '+str(newImagId))
    58             pass
    59             # need to integrate in this entry
    60         import datetime
    61         print ("Timer tick at {:%d %b %Y %H:%M:%S}\n".format(datetime.datetime.now()))
    62         #GSASIIpath.IPyBreak_base()
     62            G2frame.Image = newImagId
     63            G2frame.PickId = G2gd.GetPatternTreeItemId(G2frame,G2frame.Image, 'Image Controls')
     64            #  integrate in this entry
     65            size,imagefile = G2frame.PatternTree.GetItemPyData(G2frame.Image)
     66            masks = G2frame.PatternTree.GetItemPyData(
     67                G2gd.GetPatternTreeItemId(G2frame,G2frame.Image, 'Masks'))
     68            data = G2frame.PatternTree.GetItemPyData(G2frame.PickId)
     69            G2frame.ImageZ = G2IO.GetImageData(G2frame,imagefile,True)
     70            self.oldImagefile = '' # mark image as changed; reread as needed
     71            G2imG.UpdateImageControls(G2frame,data,masks,IntegrateOnly=True)
     72            # split name and control number
     73            s = re.split(r'(\d+)\Z',os.path.split(os.path.splitext(imagefile)[0])[1])
     74            namepre = s[0]
     75            if len(s) > 1:
     76                namenum = s[1]
     77            else:
     78                namenum = ''
     79            # write out the images in the selected formats
     80            for Id in G2frame.IntgOutList:
     81                treename = G2frame.PatternTree.GetItemText(Id)
     82                Sdata = G2frame.PatternTree.GetItemPyData(G2gd.GetPatternTreeItemId(G2frame,Id, 'Sample Parameters'))
     83                # determine the name for the current file
     84                fileroot = namepre
     85                if len(G2frame.IntgOutList) > 1:
     86                    fileroot += "_AZM"
     87                    if 'Azimuth' in Sdata:
     88                        fileroot += str(int(10*Sdata['Azimuth']))
     89                    fileroot += "_"
     90                fileroot += namenum
     91                # loop over selected formats
     92                for dfmt in self.fmtlist:
     93                    if not self.params[dfmt[1:]]: continue
     94                    if self.params['SeparateDir']:
     95                        subdir = dfmt[1:]
     96                    else:
     97                        subdir = ''
     98                    fil = os.path.join(self.params['outdir'],subdir,fileroot)
     99                    print('writing file '+fil+dfmt)
     100                    G2IO.ExportPowder(G2frame,treename,fil,dfmt)
     101       
     102        if GSASIIpath.GetConfigValue('debug'):
     103            import datetime
     104            print ("Timer tick at {:%d %b %Y %H:%M:%S}\n".format(datetime.datetime.now()))
    63105
    64106    def StartLoop(self):
     
    91133                    G2gd.GetPatternTreeItemId(self.G2frame,self.G2frame.Image, 'Masks')))
    92134            self.Thresholds = self.ImageMasks['Thresholds'][:]
    93        
    94     def __init__(self,G2frame,PollTime=3.0):
     135        # make sure all output directories exist
     136        if self.params['SeparateDir']:
     137            for dfmt in self.fmtlist:
     138                if not self.params[dfmt[1:]]: continue
     139                dir = os.path.join(self.params['outdir'],dfmt[1:])
     140                if not os.path.exists(dir): os.makedirs(dir)
     141        else:
     142            if not os.path.exists(self.params['outdir']):
     143                os.makedirs(self.params['outdir'])
     144    def __init__(self,G2frame,PollTime=60.0):
    95145        def OnStart(event):
    96146            '''Called when the start button is pressed. Changes button label
     
    99149            is started. When Pause is pressed, the loop is stopped.
    100150            '''
    101             print self.params # for debug
     151            #print self.params # for debug
    102152
    103153            # check inputs before starting
    104154            err = ''
    105             #if not any([self.params[fmt] for fmt in fmtlist]):
     155            #if not any([self.params[fmt] for fmt in self.fmtlist]):
    106156            #    err += '\nPlease select at least one output format\n'
    107157            if (self.params['Mode'] == 'file' and not
     
    148198            in the dict.
    149199            '''
     200            if btn3 == event.GetEventObject():
     201                dlg = wx.DirDialog(
     202                    self, 'Select directory for output files',
     203                    self.params['outdir'],wx.DD_DEFAULT_STYLE)
     204                dlg.CenterOnParent()
     205                try:
     206                    if dlg.ShowModal() == wx.ID_OK:
     207                        self.params['outdir'] = dlg.GetPath()
     208                        fInp3.SetValue(self.params['outdir'])
     209                finally:
     210                    dlg.Destroy()
     211                return
    150212            if btn1 == event.GetEventObject():
    151213                ext = '.imctrl'
    152214                title = 'Image control'
    153                 print 'button 1'
    154215            else:
    155216                ext = '.immask'
     
    207268        self.params['MaskFile'] = ''
    208269        self.params['IgnoreMask'] = True
    209         fmtlist = G2IO.ExportPowderList(G2frame)
     270        self.fmtlist = G2IO.ExportPowderList(G2frame)
    210271        self.timer = wx.Timer()
    211272        self.timer.Bind(wx.EVT_TIMER,self.OnTimerLoop)
     
    215276        self.imagedir,fileroot = os.path.split(imagefile)
    216277        self.params['filter'] = '*'+os.path.splitext(fileroot)[1]
    217         os.chdir(self.imagedir)
     278        self.params['outdir'] = os.path.abspath(self.imagedir)
    218279        # get image names that have already been read
    219280        self.IntegratedList = []
     
    223284                )[1])
    224285           
    225         GSASIIpath.IPyBreak()
    226        
    227         wx.Frame.__init__(self, G2frame)
     286        wx.Frame.__init__(self, G2frame,title='Automatic Integration')
    228287        mnpnl = wx.Panel(self)
    229288        mnsizer = wx.BoxSizer(wx.VERTICAL)
     
    233292        self.ControlBaseLbl.SetLabel(G2frame.PatternTree.GetItemText(G2frame.Image))
    234293        sizer.Add(self.ControlBaseLbl)
    235         mnsizer.Add(sizer,1,wx.ALIGN_LEFT,1)
    236         mnpnl.SetSizer(mnsizer)
    237         #GSASIIpath.IPyBreak()
     294        mnsizer.Add(sizer,0,wx.ALIGN_LEFT,1)
    238295        # file filter stuff
    239296        sizer = wx.BoxSizer(wx.HORIZONTAL)
     
    241298        flterInp = G2G.ValidatedTxtCtrl(mnpnl,self.params,'filter')
    242299        sizer.Add(flterInp)
    243         mnsizer.Add(sizer,1,wx.ALIGN_RIGHT,1)
     300        mnsizer.Add(sizer,0,wx.ALIGN_RIGHT,1)
    244301        # box for integration controls & masks input
    245         lbl = wx.StaticBox(mnpnl, wx.ID_ANY, "Integration Controls/Masks from")
     302        lbl = wx.StaticBox(mnpnl, wx.ID_ANY, "Integration Controls/Masks source")
    246303        lblsizr = wx.StaticBoxSizer(lbl, wx.VERTICAL)
    247304        r1 = wx.RadioButton(mnpnl, wx.ID_ANY, "Use Active Image",
     
    253310        lblsizr.Add(r2)
    254311        r2.Bind(wx.EVT_RADIOBUTTON, OnRadioSelect)
     312        r2.Disable()         # deactivate this until implemented
    255313        # Image controls file
    256314        sizer = wx.BoxSizer(wx.HORIZONTAL)
     
    283341
    284342        # box for output selections
    285         lbl = wx.StaticBox(mnpnl, wx.ID_ANY, "Select output format(s)")
    286         lblsizr = wx.StaticBoxSizer(lbl, wx.HORIZONTAL)
    287         for dfmt in fmtlist:
     343        lbl = wx.StaticBox(mnpnl, wx.ID_ANY, "Output settings")
     344        lblsizr = wx.StaticBoxSizer(lbl, wx.VERTICAL)
     345        sizer = wx.BoxSizer(wx.HORIZONTAL)
     346        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Write to: '))
     347        fInp3 = G2G.ValidatedTxtCtrl(mnpnl,self.params,'outdir',
     348                                       notBlank=False,size=(300,-1))
     349        sizer.Add(fInp3)
     350        btn3 = wx.Button(mnpnl,  wx.ID_ANY, "Browse")
     351        btn3.Bind(wx.EVT_BUTTON, OnBrowse)
     352        sizer.Add(btn3)
     353        lblsizr.Add(sizer)
     354        #lblsizr.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Select format(s): '))
     355        sizer = wx.BoxSizer(wx.HORIZONTAL)
     356        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Select format(s): '))
     357        for dfmt in self.fmtlist:
    288358            fmt = dfmt[1:]
    289359            self.params[fmt] = False
    290360            btn = G2G.G2CheckBox(mnpnl,dfmt,self.params,fmt)
    291             lblsizr.Add(btn)
    292         mnsizer.Add(lblsizr,1,wx.ALIGN_CENTER,1)
     361            sizer.Add(btn)
     362        lblsizr.Add(sizer)
     363        sizer = wx.BoxSizer(wx.HORIZONTAL)
     364        sizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'Separate dir for each format: '))
     365        self.params['SeparateDir'] = False
     366        sizer.Add(G2G.G2CheckBox(mnpnl,'',self.params,'SeparateDir'))
     367        lblsizr.Add(sizer)
     368        mnsizer.Add(lblsizr,0,wx.ALIGN_CENTER,1)
    293369
    294370        # buttons on bottom
    295         mnsizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'AutoIntegration controls'))
     371        mnsizer.Add(wx.StaticText(mnpnl, wx.ID_ANY,'AutoIntegration controls'),0,wx.TOP,5)
    296372        sizer = wx.BoxSizer(wx.HORIZONTAL)
    297373        sizer.Add((20,-1))
     
    307383        sizer.Add(btnquit)
    308384        sizer.Add((20,-1))
    309         mnsizer.Add(sizer,1,wx.EXPAND|wx.BOTTOM,1)
     385        mnsizer.Add(sizer,0,wx.EXPAND|wx.BOTTOM|wx.TOP,5)
    310386       
    311387        # finish up window
     388        mnpnl.SetSizer(mnsizer)
    312389        OnRadioSelect(None) # disable widgets
    313390        mnsizer.Fit(self)
    314         self.Show()
    315    
     391        self.CenterOnParent()
     392        self.Show() 
    316393
    317394if __name__ == '__main__':
  • trunk/exports/G2export_pwdr.py

    r2018 r2026  
    6666        '''
    6767        histblk = self.Histograms[TreeName]
    68         self.OpenFile(filename) # ***rethink
     68        self.OpenFile(filename)
    6969        self.Write(TreeName[5:])
    7070        if prmname: self.Write('Instrument parameter file:'+os.path.split(prmname)[1])
     
    128128       
    129129    def Writer(self,TreeName,filename=None):
    130         GSASIIpath.IPyBreak()
    131 
    132         self.OpenFile()
     130        self.OpenFile(filename)
    133131        histblk = self.Histograms[TreeName]
    134132        self.Write('/*')    #The ugly c comment delimiter used in topas!
Note: See TracChangeset for help on using the changeset viewer.