source: trunk/exports/G2export_JSON.py @ 4872

Last change on this file since 4872 was 4872, checked in by toby, 8 months ago

export project to giant ASCII file; add CIF tutorial; set misc svn flags

  • Property svn:eol-style set to native
File size: 4.0 KB
RevLine 
[4872]1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3########### SVN repository information ###################
4# $Date: $
5# $Author: toby $
6# $Revision: $
7# $URL: $
8# $Id: $
9########### SVN repository information ###################
10'''
11*Module G2export_JSON: ASCII .gpx Export*
12------------------------------------------------------
13
14This implements a simple exporter :class:`ExportCIF` that can export the
15contents of an entire project as a sort-of human readable (JSON) ASCII file.
16This provides a way to see the contents of a GSAS-II project file, but
17this format does not provide a mechanism to change the contents of a .gpx file,
18as the likelihood of breaking a data structure is too high, so these
19JSON files cannot be imported back into GSAS-II.
20If you want to change the contents of a .gpx file, use :mod:`GSASIIscriptable`
21where you can access the native Python data structures and change things
22with a good chance of getting things to work.
23
24This code is dedicated to my friend Robert Papoular who wants to see what is
25inside a .gpx file.
26'''
27from __future__ import division, print_function
28import json
29import wx
30import numpy as np
31import GSASIIpath
32GSASIIpath.SetVersionNumber("$Revision: $")
33import GSASIIIO as G2IO
34
35class JsonEncoder(json.JSONEncoder):
36    '''This provides the ability to turn np arrays and masked arrays
37    into something that json can handle.
38    '''
39    def default(self, obj):
40        for t in [list,tuple,dict]:
41            if isinstance(obj, t):
42                return json.JSONEncoder.default(self, obj)
43        if isinstance(obj, np.ma.core.MaskedArray):
44            return {"_npmask":obj.mask.tolist(),'_npvalues':obj.tolist()}
45        elif isinstance(obj, np.ndarray):
46            return {"_nparray":obj.tolist()}
47        else:
48            print('Tell Brian to fix JsonEncoder to handle type=',type(obj),
49                      '. Skipping for now')
50            return "sorry, I don't know how to show a {} object".format(str(type(obj)))
51   
52class ExportJSON(G2IO.ExportBaseclass):
53    '''Implement JSON export of entire projects
54    '''
55    def __init__(self,G2frame):
56        G2IO.ExportBaseclass.__init__(self,
57            G2frame=G2frame,
58            formatName = 'ASCII JSON dump',
59            extension='.json',
60            longFormatName = 'Export project in ASCII a JSON dump'
61            )
62        self.exporttype = ['project']
63       
64    def Exporter(self,event=None):
65        # set up for export
66        self.InitExport(event)
67        if self.ExportSelect(): return # set export parameters; get file name
68        self.OpenFile()
69        wx.BeginBusyCursor()
70        G2frame = self.G2frame
71        # crawl through the tree, dumping as we go
72        try:
73            item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
74            while item:
75                data = []
76                name = G2frame.GPXtree.GetItemText(item)
77                #print('level 0',name)
78                data = {name:G2frame.GPXtree.GetItemPyData(item)}
79                self.Write('\n')
80                self.Write(json.dumps(
81                    "=========== '{}' Tree Item ==============".format(name)))
82                self.Write(json.dumps(data, indent=2, cls=JsonEncoder))
83                item2, cookie2 = G2frame.GPXtree.GetFirstChild(item)
84                while item2:
85                    name2 = G2frame.GPXtree.GetItemText(item2)
86                    #print('  level 1',name2)
87                    self.Write('\n')
88                    self.Write(json.dumps([
89                        "=========== '{}' SubItem of Tree '{}' ==============".format(name2,name)]))
90                    data = {name:{name2:G2frame.GPXtree.GetItemPyData(item)}}
91                    self.Write(json.dumps(data, indent=2, cls=JsonEncoder))
92                    item2, cookie2 = G2frame.GPXtree.GetNextChild(item, cookie2)                           
93                item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)                           
94        finally:
95            wx.EndBusyCursor()
96        self.CloseFile()
Note: See TracBrowser for help on using the repository browser.