source: trunk/exports/G2export_map.py @ 1123

Last change on this file since 1123 was 1123, checked in by toby, 8 years ago

add import and export routines to sphinx

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 5.7 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: 2013-10-25 19:24:22 +0000 (Fri, 25 Oct 2013) $
5# $Author: toby $
6# $Revision: 1123 $
7# $URL: trunk/exports/G2export_map.py $
8# $Id: G2export_map.py 1123 2013-10-25 19:24:22Z toby $
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'''
20import os
21import GSASIIpath
22import numpy as np
23GSASIIpath.SetVersionNumber("$Revision: 1123 $")
24import GSASIIIO as G2IO
25#import GSASIIgrid as G2gd
26#import GSASIIstrIO as G2stIO
27#import GSASIImath as G2mth
28#import GSASIIlattice as G2lat
29#import GSASIIspc as G2spc
30#import GSASIIphsGUI as G2pg
31#import GSASIIstrMain as G2stMn
32
33class ExportMapASCII(G2IO.ExportBaseclass):
34    '''Used to create a text file for a phase
35
36    :param wx.Frame G2frame: reference to main GSAS-II frame
37    '''
38    def __init__(self,G2frame):
39        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
40            G2frame=G2frame,
41            formatName = 'FOX/DrawXTL file',
42            extension='.grd',
43            longFormatName = 'Export map as text (.grd) file'
44            )
45        self.exporttype = ['map']
46        self.multiple = False 
47
48    def Exporter(self,event=None):
49        '''Export a map as a text file
50        '''
51        # the export process starts here
52        self.InitExport(event)
53        # load all of the tree into a set of dicts
54        self.loadTree()
55        if self.ExportSelect( # set export parameters
56            AskFile=True          # prompt the user for a file name
57            ): return 
58        for phasenam in self.phasenam:
59            phasedict = self.Phases[phasenam] # pointer to current phase info           
60            rho = phasedict['General']['Map'].get('rho',[])
61            if not len(rho):
62                return
63            print self.filename
64            self.OpenFile(self.filename)
65            self.Write("Map of Phase "+str(phasenam)+" from "+str(self.G2frame.GSASprojectfile))
66            # get cell parameters & print them
67            cellList,cellSig = self.GetCell(phasenam)
68            fmt = 3*" {:9.5f}" + 3*" {:9.3f}"
69            self.Write(fmt.format(*cellList[:6]))
70            nx,ny,nz = rho.shape
71            self.Write(" {:3d} {:3d} {:3d}".format(nx,ny,nz))
72            for i in range(nx):
73                for j in range(ny):
74                    for k in range(nz):
75                        self.Write(str(rho[i,j,k]))
76            print('map from Phase '+str(phasenam)+' written to file '+str(self.filename))
77            self.CloseFile()
78            return
79
80class ExportMapCCP4(G2IO.ExportBaseclass):
81    '''Used to create a text file for a phase
82
83    :param wx.Frame G2frame: reference to main GSAS-II frame
84    '''
85    def __init__(self,G2frame):
86        super(self.__class__,self).__init__( # fancy way to say <parentclass>.__init__
87            G2frame=G2frame,
88            formatName = 'CCP4 map file',
89            extension='.map',
90            longFormatName = 'Export CCP4 .map file'
91            )
92        self.exporttype = ['map']
93        self.multiple = False 
94
95    # Tools for file writing.
96    def OpenFile(self,fil=None):
97        '''Open the output file as binary
98
99        :param str fil: The name of the file to open. If None (default)
100          the name defaults to self.filename.
101        :returns: the file object opened by the routine which is also
102          saved as self.fp
103        '''
104        if not fil:
105            fil = self.filename
106        self.fp = open(fil,'wb')
107        return self.fp
108       
109    def Write(self,data,dtype):
110        import struct
111        '''write a block of output
112
113        :param data: the data to be written.
114        '''
115        self.fp.write(struct.pack(dtype,data))
116       
117    def Exporter(self,event=None):
118        '''Export a map as a text file
119        '''
120        # the export process starts here
121        self.InitExport(event)
122        # load all of the tree into a set of dicts
123        self.loadTree()
124        if self.ExportSelect( # set export parameters
125            AskFile=False     # I'll make the file name
126            ): return 
127        for phasenam in self.phasenam:
128            phasedict = self.Phases[phasenam] # pointer to current phase info
129            mapData = phasedict['General']['Map']
130            rho = mapData.get('rho',[])
131           
132            if not len(rho):
133                return
134            cell = phasedict['General']['Cell'][1:7]
135            nx,ny,nz = rho.shape
136            filename,ext = os.path.splitext(self.filename)
137            self.filename = filename+'_'+phasenam+'_'+mapData['MapType']+ext
138            self.OpenFile(self.filename)
139            for n in rho.shape: self.Write(n,'i')  #nX,nY,nZ
140            self.Write(2,'i')           #mode=2 float map
141            for i in [0,0,0]: self.Write(i,'i')    #1st position on x,y,z
142            for n in rho.shape: self.Write(n,'i')  #nX,nY,nZ
143            for c in cell: self.Write(c,'f')
144            for i in [1,2,3]: self.Write(i,'i')    #axes order = x,y,z
145            self.Write(np.min(rho),'f')
146            self.Write(np.max(rho),'f')
147            self.Write(np.mean(rho),'f')
148            self.Write(0,'i')
149            for i in range(24,53):
150                self.Write(0,'i')
151            for s in ['M','A','P',' ']: self.Write(s,'s')
152            self.Write(0x44410000,'i')
153            self.Write(np.std(rho),'f')
154            for i in range(56,257):
155                self.Write(0,'i')
156            for x in rho.flatten('F'):
157                self.Write(x,'f')
158            print('map from Phase '+str(phasenam)+' written to file '+str(self.filename))
159            self.CloseFile()
160            return
Note: See TracBrowser for help on using the repository browser.