source: trunk/exports/G2export_map.py @ 4119

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

fix map export for python 3

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