Changeset 5322


Ignore:
Timestamp:
Aug 24, 2022 3:39:37 PM (16 months ago)
Author:
vondreele
Message:

improvements to scipy cluster analysis & start on Scikit-learn version

Location:
trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/GSASIIdataGUI.py

    r5319 r5322  
    56975697        '''
    56985698       
     5699        try:
     5700            SKLearn = False
     5701            import sklearn.cluster
     5702            SKLearn = True
     5703        except:
     5704            res = GSASIIpath.condaInstall('scikit-learn')
     5705            if res:
     5706                msg = 'Installation of the sklearn package failed with error:\n' + str(res)
     5707                G2G.G2MessageBox(self,msg,'Install sklearn Error')
    56995708        Id = GetGPXtreeItemId(self,self.root,'Cluster Analysis')
    57005709        if not Id:
     5710               
    57015711            Id = self.GPXtree.AppendItem(self.root,text='Cluster Analysis')
    57025712            ClustDict = {'Files':[],'Method':'correlation','Limits':[0.,100.],'DataMatrix':[],'plots':'All',
     
    57045714            self.GPXtree.SetItemPyData(Id,ClustDict)
    57055715        else:
     5716            ClustDict = self.GPXtree.GetItemPyData(Id)
    57065717            print('Cluster Analysis exists - nothing done')                   
    5707 
     5718        ClustDict['SKLearn'] = SKLearn
    57085719        self.GPXtree.SelectItem(Id)
    57095720   
  • trunk/GSASIIplot.py

    r5319 r5322  
    1154811548    Font = Page.GetFont()
    1154911549    cb = wx.ComboBox(G2frame.G2plotNB.status,style=wx.CB_DROPDOWN|wx.CB_READONLY,choices=choice,
    11550                          size=(G2frame.G2plotNB.status.firstLen,-1))
     11550        size=(G2frame.G2plotNB.status.firstLen,-1))
    1155111551    cb.Bind(wx.EVT_COMBOBOX, OnKeyBox)
    1155211552    text = [str(Layers['Layers'][seq]['Name']) for seq in laySeq]
     
    1156811568#### Plot Cluster Analysis ####################################################
    1156911569
    11570 # def PlotDendogram(G2frame,CLuDict,CLuZ,newPlot=True):
    11571    
    11572 #     import scipy.cluster.hierarchy as SCH
    11573 #     global Plot
    11574 #     def OnMotion(event):
    11575 #         xpos = event.xdata
    11576 #         if xpos:                                        #avoid out of frame mouse position
    11577 #             ypos = event.ydata
    11578 #             SetCursor(Page)
    11579 #             try:
    11580 #                 G2frame.G2plotNB.status.SetStatusText('X =%9.3f %s =%9.3g'%(xpos,Title,ypos),1)                   
    11581 #             except TypeError:
    11582 #                 G2frame.G2plotNB.status.SetStatusText('Select '+Title+' pattern first',1)
    11583 #     xylim = []
    11584 #     Title = 'Cluster dendogram'
    11585 #     new,plotNum,Page,Plot,lim = G2frame.G2plotNB.FindPlotTab(Title,'mpl')
    11586 #     if not new:
    11587 #         if not newPlot:
    11588 #             xylim = copy.copy(lim)
    11589 #     else:
    11590 #         newPlot = True
    11591 #         Page.canvas.mpl_connect('motion_notify_event', OnMotion)
    11592    
    11593 #     Page.Choice = None
    11594 #     G2frame.G2plotNB.status.DestroyChildren() #get rid of special stuff on status bar
    11595 #     Plot.set_title('%s %s'%(CLuDict['LinkMethod'],Title))
    11596 #     Plot.set_xlabel(r''+CLuDict['Method']+' distance',fontsize=14)
    11597 #     Plot.set_ylabel(r''+'data set no.',fontsize=14)
    11598    
    11599 #     CLR = SCH.dendrogram(CLuZ,orientation='right',ax=Plot)
    11600 
    11601 #     if not newPlot:
    11602 #         Page.toolbar.push_current()
    11603 #         Plot.set_xlim(xylim[0])
    11604 #         Plot.set_ylim(xylim[1])
    11605 #         Page.toolbar.push_current()
    11606 #         Page.ToolBarDraw()
    11607 #     else:
    11608 #         Page.canvas.draw()
    11609 
    11610 def PlotClusterXYZ(G2frame,YM,XYZ,CLuDict,Title='',PlotName=None):
    11611     ''' To plot cluster vectors
     11570def PlotClusterXYZ(G2frame,YM,XYZ,CLuDict,Title='',PlotName='cluster'):
     11571    ''' To plot cluster analysis results
    1161211572    :param wx.Frame G2frame: The main GSAS-II tree "window"
    11613     :param array whitMat: whitened data matrix
    11614     :param array codebook: array of cluster centers
    11615    
    11616     :param str labelX,labelY,labelZ: labels for X,Y,Z-axes
     11573    :param array YM: data matrix; plotted as contour
     11574    :param array XYZ: array of 3D PCA coordinates; plotted as 3D scatter plot
     11575    ;param dict CLuDict: Cluster info; may have dendogram & Kmeans results
    1161711576    :param str Title: plot title
    1161811577    :param str PlotName: plot tab name
     
    1162611585           
    1162711586    def OnPick(event):
    11628         ind = event.ind
    11629         print(CLuDict['Files'][ind[0]])
     11587        line = event.artist
     11588        ind = int(line.get_label().split('tion')[1])
     11589        text = 'Data selected: %s'%(CLuDict['Files'][ind])
     11590        G2frame.G2plotNB.status.SetStatusText(text,1)
     11591        print(text)
    1163011592           
    1163111593    Colors = ['xkcd:blue','xkcd:red','xkcd:green','xkcd:cyan',
     
    1164211604        Page.canvas.mpl_connect('motion_notify_event', OnMotion)
    1164311605        Page.canvas.mpl_connect('pick_event', OnPick)
    11644     G2frame.G2plotNB.status.SetStatusText('',1)
    1164511606    Page.Choice = None
    1164611607    np.seterr(all='ignore')
     
    1164811609    Imin = np.min(YM)
    1164911610    Imax = np.max(YM)
     11611    if CLuDict['CLuZ'] is None and CLuDict['plots'] == 'Dendogram':
     11612        CLuDict['plots'] = 'All'
    1165011613    if CLuDict['plots'] == 'Distances':
    1165111614        Page.ImgObj = Plot.imshow(YM,interpolation='nearest',vmin=Imin,vmax=Imax,origin='lower')
     
    1168911652        ax1.set_ylabel('Data set',fontsize=12)
    1169011653        if CLuDict['codes'] is not None:
    11691             ax2.scatter(XYZ[0],XYZ[1],XYZ[2],color=[Colors[code] for code in CLuDict['codes']],picker=True)
     11654            for ixyz,xyz in enumerate(XYZ.T):
     11655                ax2.scatter(xyz[0],xyz[1],xyz[2],color=Colors[CLuDict['codes'][ixyz]],picker=True)
     11656#            ax2.scatter(XYZ[0],XYZ[1],XYZ[2],color=[Colors[code] for code in CLuDict['codes']],picker=True)
    1169211657        else:
    11693             ax2.scatter(XYZ[0],XYZ[1],XYZ[2],color=Colors[0],picker=True)
     11658            for ixyz,xyz in enumerate(XYZ.T):
     11659                ax2.scatter(xyz[0],xyz[1],xyz[2],color=Colors[0],picker=True)
     11660#            ax2.scatter(XYZ[0],XYZ[1],XYZ[2],color=Colors[0],picker=True)
    1169411661        ax2.set_xlabel('PCA axis-1',fontsize=12)
    1169511662        ax2.set_ylabel('PCA axis-2',fontsize=12)
  • trunk/GSASIIseqGUI.py

    r5319 r5322  
    15681568    import scipy.cluster.hierarchy as SCH
    15691569    import scipy.cluster.vq as SCV
    1570     global CLuZ
    1571    
    1572        
     1570    import sklearn.cluster as SKC   
     1571       
     1572    SKLearnCite = '''If you use Scikit-Learn Cluster Analysis, please cite:
     1573    'Scikit-learn: Machine Learning in Python', Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V.,
     1574    Thirion, B., Grisel, O., Blondel, M., Prettenhofer, P., Weiss, R., Dubourg, V., Vanderplas, J.,
     1575    Passos, A., Cournapeau, D., Brucher, M., Perrot, M. and Duchesnay, E.,
     1576    Journal of Machine Learning Research (2011) 12, 2825-2830.
     1577'''
     1578
    15731579    def FileSizer():
    15741580       
     
    18281834                U,s,VT = nl.svd(YM) #s are the Eigenvalues
    18291835                ClusData['PCA'] = s
     1836                s[3:] = 0.
    18301837                S = np.diag(s)
    1831                 XYZ = np.dot(S[:3,:3],VT[:3,:])
    1832                 G2plt.PlotClusterXYZ(G2frame,YM,XYZ,ClusData,PlotName=ClusData['Method'],Title=ClusData['Method'])
     1838                XYZ = np.dot(U,np.dot(S,VT))
     1839                G2plt.PlotClusterXYZ(G2frame,XYZ,XYZ[:3,:],ClusData,PlotName=ClusData['Method'],Title=ClusData['Method'])
    18331840                G2G.HorizontalLine(mainSizer,G2frame.dataWindow)
    18341841                mainSizer.Add(wx.StaticText(G2frame.dataWindow,label='Hierarchical Cluster Analysis:'))
     
    18451852            plotSizer = wx.BoxSizer(wx.HORIZONTAL)
    18461853            plotSizer.Add(wx.StaticText(G2frame.dataWindow,label='Plot selection: '),0,WACV)
    1847             choice = ['All','Distances','Dendogram','3D PCA',]
     1854            if ClusData['CLuZ'] is None:
     1855                choice = ['All','Distances','3D PCA',]
     1856            else:
     1857                choice = ['All','Distances','Dendogram','3D PCA',]
    18481858            plotsel = wx.ComboBox(G2frame.dataWindow,choices=choice,style=wx.CB_READONLY|wx.CB_DROPDOWN)
    18491859            plotsel.SetValue(str(ClusData['plots']))
     
    18511861            plotSizer.Add(plotsel,0,WACV)
    18521862            mainSizer.Add(plotSizer)
     1863           
     1864        if ClusData['SKLearn']:
     1865            G2G.HorizontalLine(mainSizer,G2frame.dataWindow)
     1866            mainSizer.Add(wx.StaticText(G2frame.dataWindow,label=SKLearnCite))
    18531867           
    18541868           
Note: See TracChangeset for help on using the changeset viewer.