source: trunk/exports/G2export_map.py @ 3136

Last change on this file since 3136 was 3136, checked in by vondreele, 4 years ago

make GSAS-II python 3.6 compliant & preserve python 2.7 use;changes:
do from future import division, print_function for all GSAS-II py sources
all menu items revised to be py 2.7/3.6 compliant
all wx.OPEN --> wx.FD_OPEN in file dialogs
all integer divides (typically for image pixel math) made explicit with ; ambiguous ones made floats as appropriate
all print "stuff" --> print (stuff)
all print >> pFile,'stuff' --> pFile.writeCIFtemplate('stuff')
all read file opens made explicit 'r' or 'rb'
all cPickle imports made for py2.7 or 3.6 as cPickle or _pickle; test for '2' platform.version_tuple[0] for py 2.7
define cPickleload to select load(fp) or load(fp,encoding='latin-1') for loading gpx files; provides cross compatibility between py 2.7/3.6 gpx files
make dict.keys() as explicit list(dict.keys()) as needed (NB: possible source of remaining py3.6 bugs)
make zip(a,b) as explicit list(zip(a,b)) as needed (NB: possible source of remaining py3.6 bugs)
select unichr/chr according test for '2' platform.version_tuple[0] for py 2.7 (G2pwdGUI * G2plot) for special characters
select wg.EVT_GRID_CELL_CHANGE (classic) or wg.EVT_GRID_CELL_CHANGED (phoenix) in grid Bind
maxint --> maxsize; used in random number stuff
raise Exception,"stuff" --> raise Exception("stuff")
wx 'classic' sizer.DeleteWindows?() or 'phoenix' sizer.Clear(True)
wx 'classic' SetToolTipString?(text) or 'phoenix' SetToolTip?(wx.ToolTip?(text)); define SetToolTipString?(self,text) to handle the choice in plots
status.SetFields? --> status.SetStatusText?
'classic' AddSimpleTool? or 'phoenix' self.AddTool? for plot toolbar; Bind different as well
define GetItemPydata? as it doesn't exist in wx 'phoenix'
allow python versions 2.7 & 3.6 to run GSAS-II
Bind override commented out - no logging capability (NB: remove all logging code?)
all import ContentsValidator? open filename & test if valid then close; filepointer removed from Reader
binary importers (mostly images) test for 'byte' type & convert as needed to satisfy py 3.6 str/byte rules

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 5.5 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2017-10-23 16:39:16 +0000 (Mon, 23 Oct 2017) $
5# $Author: vondreele $
6# $Revision: 3136 $
7# $URL: trunk/exports/G2export_map.py $
8# $Id: G2export_map.py 3136 2017-10-23 16:39:16Z vondreele $
9########### SVN repository information ###################
10'''
11*Module G2export_map: Map export*
12-------------------------------------------
13
14Code to write Fourier/Charge-Flip atomic density maps out in formats that
15can be read by external programs. At present a GSAS format
16that is supported by FOX and DrawXTL
17(:class:`ExportMapASCII`) and the CCP4 format that
18is used by COOT (:class:`ExportMapCCP4`) are implemented.
19'''
20from __future__ import division, print_function
21import os
22import GSASIIpath
23import numpy as np
24GSASIIpath.SetVersionNumber("$Revision: 3136 $")
25import GSASIIIO as G2IO
26
27class ExportMapASCII(G2IO.ExportBaseclass):
28    '''Used to create a text file for a phase
29
30    :param wx.Frame G2frame: reference to main GSAS-II frame
31    '''
32    def __init__(self,G2frame):
33        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
34            G2frame=G2frame,
35            formatName = 'FOX/DrawXTL file',
36            extension='.grd',
37            longFormatName = 'Export map as text (.grd) file'
38            )
39        self.exporttype = ['map']
40        self.multiple = False 
41
42    def Exporter(self,event=None):
43        '''Export a map as a text file
44        '''
45        # the export process starts here
46        self.InitExport(event)
47        # load all of the tree into a set of dicts
48        self.loadTree()
49        if self.ExportSelect(): return  # set export parameters, get file name
50        filename = self.filename
51        for phasenam in self.phasenam:
52            phasedict = self.Phases[phasenam] # pointer to current phase info           
53            rho = phasedict['General']['Map'].get('rho',[])
54            if not len(rho):
55                print ("There is no map for phase "+phasenam)
56                continue
57            if len(self.phasenam) > 1: # if more than one filename is written, add a phase # -- not in use yet
58                i = self.Phases[phasenam]['pId']
59                self.filename = os.path.splitext(filename)[1] + "_" + mapData['MapType'] + str(i) + self.extension
60            self.OpenFile()
61            self.Write(u"Map of Phase "+phasenam+u" from "+self.G2frame.GSASprojectfile)
62            # get cell parameters & print them
63            cellList,cellSig = self.GetCell(phasenam)
64            fmt = 3*" {:9.5f}" + 3*" {:9.3f}"
65            self.Write(fmt.format(*cellList[:6]))
66            nx,ny,nz = rho.shape
67            self.Write(" {:3d} {:3d} {:3d}".format(nx,ny,nz))
68            for i in range(nx):
69                for j in range(ny):
70                    for k in range(nz):
71                        self.Write(str(rho[i,j,k]))
72            self.CloseFile()
73            print(u'map from Phase '+phasenam+u' written to file '+self.fullpath)
74
75class ExportMapCCP4(G2IO.ExportBaseclass):
76    '''Used to create a text file for a phase
77
78    :param wx.Frame G2frame: reference to main GSAS-II frame
79    '''
80    def __init__(self,G2frame):
81        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
82            G2frame=G2frame,
83            formatName = 'CCP4 map file',
84            extension='.map',
85            longFormatName = 'Export CCP4 .map file'
86            )
87        self.exporttype = ['map']
88        self.multiple = False 
89
90    # Tools for file writing.
91    def Write(self,data,dtype):
92        import struct
93        '''write a block of output
94
95        :param data: the data to be written.
96        '''
97        self.fp.write(struct.pack(dtype,data))
98       
99    def Exporter(self,event=None):
100        '''Export a map as a text file
101        '''
102        # the export process starts here
103        self.InitExport(event)
104        # load all of the tree into a set of dicts
105        self.loadTree()
106        if self.ExportSelect(): return  # set export parameters, get file name
107        filename = self.filename
108        for phasenam in self.phasenam:
109            phasedict = self.Phases[phasenam] # pointer to current phase info
110            mapData = phasedict['General']['Map']
111            rho = mapData.get('rho',[])
112           
113            if not len(rho):
114                print ("There is no map for phase "+phasenam)
115                continue
116            if len(self.phasenam) > 1: # if more than one filename is written, add a phase # -- not in use yet
117                i = self.Phases[phasenam]['pId']
118                self.filename = os.path.splitext(filename)[1] + "_" + mapData['MapType'] + str(i) + self.extension
119            cell = phasedict['General']['Cell'][1:7]
120            nx,ny,nz = rho.shape
121            self.OpenFile(mode='wb')
122            for n in rho.shape: self.Write(n,'i')  #nX,nY,nZ
123            self.Write(2,'i')           #mode=2 float map
124            for i in [0,0,0]: self.Write(i,'i')    #1st position on x,y,z
125            for n in rho.shape: self.Write(n,'i')  #nX,nY,nZ
126            for c in cell: self.Write(c,'f')
127            for i in [1,2,3]: self.Write(i,'i')    #axes order = x,y,z
128            self.Write(np.min(rho),'f')
129            self.Write(np.max(rho),'f')
130            self.Write(np.mean(rho),'f')
131            self.Write(0,'i')
132            for i in range(24,53):
133                self.Write(0,'i')
134            for s in ['M','A','P',' ']: self.Write(s,'s')
135            self.Write(0x44410000,'i')
136            self.Write(np.std(rho),'f')
137            for i in range(56,257):
138                self.Write(0,'i')
139            for x in rho.flatten('F'):
140                self.Write(x,'f')
141            self.CloseFile()
142            print(u'map from Phase '+phasenam+u' written to file '+self.fullpath)
Note: See TracBrowser for help on using the repository browser.