From 06e6f61e905699c9109c89983df880fa8da84ea7 Mon Sep 17 00:00:00 2001
From: Michael DM Dryden <mdryden@chem.utoronto.ca>
Date: Tue, 28 Mar 2017 15:19:48 -0400
Subject: [PATCH] Fixed saving with separate experiments and gtk3.

---
 .../experiments/experiment_template.py        |   8 ++
 dstat_interface/interface/save.py             | 110 ++++++------------
 2 files changed, 43 insertions(+), 75 deletions(-)

diff --git a/dstat_interface/experiments/experiment_template.py b/dstat_interface/experiments/experiment_template.py
index 72e1e25..a6fc978 100755
--- a/dstat_interface/experiments/experiment_template.py
+++ b/dstat_interface/experiments/experiment_template.py
@@ -290,6 +290,14 @@ class Experiment(object):
             buf += '#{}\n'.format(line)
             
         return buf
+    
+    def get_save_strings(self):
+        """Return dict of strings with experiment parameters and data."""
+        buf = {}
+        buf['params'] = self.get_info_text()
+        buf.update({exp : df.to_string() for exp, df in self.df.items()})
+        
+        return buf
         
 class PlotBox(object):
     """Contains data plot and associated methods."""
diff --git a/dstat_interface/interface/save.py b/dstat_interface/interface/save.py
index 982dcee..515b4d9 100755
--- a/dstat_interface/interface/save.py
+++ b/dstat_interface/interface/save.py
@@ -37,12 +37,12 @@ from errors import InputError, VarError
 from params import save_params, load_params
 
 def manSave(current_exp):
-    fcd = Gtk.FileChooserDialog("Save...", None, Gtk.FILE_CHOOSER_ACTION_SAVE,
-                                (Gtk.STOCK_CANCEL, Gtk.RESPONSE_CANCEL,
-                                 Gtk.STOCK_SAVE, Gtk.RESPONSE_OK))
-
+    fcd = Gtk.FileChooserDialog("Save…", None, Gtk.FileChooserAction.SAVE,
+                                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+                                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
+    
     filters = [Gtk.FileFilter()]
-    filters[0].set_name("Space separated text (.txt)")
+    filters[0].set_name("Text (.txt)")
     filters[0].add_pattern("*.txt")
 
     fcd.set_do_overwrite_confirmation(True)
@@ -51,7 +51,7 @@ def manSave(current_exp):
 
     response = fcd.run()
 
-    if response == Gtk.RESPONSE_OK:
+    if response == Gtk.ResponseType.OK:
         path = fcd.get_filename()
         logger.info("Selected filepath: %s", path)
         filter_selection = fcd.get_filter().get_name()
@@ -61,14 +61,14 @@ def manSave(current_exp):
             
         fcd.destroy()
 
-    elif response == Gtk.RESPONSE_CANCEL:
+    elif response == Gtk.ResponseType.CANCEL:
         fcd.destroy()
 
 def plot_save_dialog(plots):
     fcd = Gtk.FileChooserDialog("Save Plot…", None,
-                                Gtk.FILE_CHOOSER_ACTION_SAVE,
-                                (Gtk.STOCK_CANCEL, Gtk.RESPONSE_CANCEL,
-                                 Gtk.STOCK_SAVE, Gtk.RESPONSE_OK))
+                                Gtk.FileChooserAction.SAVE,
+                                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+                                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
 
     filters = [Gtk.FileFilter()]
     filters[0].set_name("Portable Document Format (.pdf)")
@@ -83,7 +83,7 @@ def plot_save_dialog(plots):
 
     response = fcd.run()
 
-    if response == Gtk.RESPONSE_OK:
+    if response == Gtk.ResponseType.OK:
         path = fcd.get_filename()
         logger.info("Selected filepath: %s", path)
         filter_selection = fcd.get_filter().get_name()
@@ -100,17 +100,16 @@ def plot_save_dialog(plots):
 
         fcd.destroy()
 
-    elif response == Gtk.RESPONSE_CANCEL:
+    elif response == Gtk.ResponseType.CANCEL:
         fcd.destroy()
 
 
 def man_param_save(window):
     fcd = Gtk.FileChooserDialog("Save Parameters…",
                                 None,
-                                Gtk.FILE_CHOOSER_ACTION_SAVE,
-                                (Gtk.STOCK_CANCEL, Gtk.RESPONSE_CANCEL,
-                                 Gtk.STOCK_SAVE, Gtk.RESPONSE_OK)
-                                )
+                                Gtk.FileChooserAction.SAVE,
+                                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+                                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
 
     filters = [Gtk.FileFilter()]
     filters[0].set_name("Parameter File (.yml)")
@@ -122,7 +121,7 @@ def man_param_save(window):
 
     response = fcd.run()
 
-    if response == Gtk.RESPONSE_OK:
+    if response == Gtk.ResponseType.OK:
         path = fcd.get_filename()
         logger.info("Selected filepath: %s", path)
 
@@ -133,16 +132,15 @@ def man_param_save(window):
 
         fcd.destroy()
 
-    elif response == Gtk.RESPONSE_CANCEL:
+    elif response == Gtk.ResponseType.CANCEL:
         fcd.destroy()
 
 def man_param_load(window):
     fcd = Gtk.FileChooserDialog("Load Parameters…",
                                 None,
-                                Gtk.FILE_CHOOSER_ACTION_OPEN,
-                                (Gtk.STOCK_CANCEL, Gtk.RESPONSE_CANCEL,
-                                 Gtk.STOCK_OPEN, Gtk.RESPONSE_OK)
-                                )
+                                Gtk.FileChooserAction.OPEN,
+                                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
+                                 Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
 
     filters = [Gtk.FileFilter()]
     filters[0].set_name("Parameter File (.yml)")
@@ -153,7 +151,7 @@ def man_param_load(window):
 
     response = fcd.run()
 
-    if response == Gtk.RESPONSE_OK:
+    if response == Gtk.ResponseType.OK:
         path = fcd.get_filename()
         logger.info("Selected filepath: %s", path)
 
@@ -161,7 +159,7 @@ def man_param_load(window):
 
         fcd.destroy()
 
-    elif response == Gtk.RESPONSE_CANCEL:
+    elif response == Gtk.ResponseType.CANCEL:
         fcd.destroy()
 
 def autoSave(exp, path, name):
@@ -186,62 +184,22 @@ def autoPlot(exp, path, name):
     save_plot(exp, path)
 
 def save_text(exp, path):
-    name, _sep, ext = path.rpartition('.') # ('','',string) if no match
-    if _sep == '':
-        name = ext
-        ext = 'txt'
+    savestrings = exp.get_save_strings()
+    path = path.rstrip('.txt')
     
     num = ''
     j = 0
     
-    for dname in exp.data: # Test for any existing files
-        while os.path.exists("%s%s-%s.%s" % (name, num, dname, ext)):
+    for key, text in savestrings.items(): # Test for existing files of any kind
+        while os.path.exists("{}{}-{}.txt".format(path, num, key)):
             j += 1
             num = j
-    
-    for dname in exp.data: # save data
-        file = open("%s%s-%s.%s" % (name, num, dname, ext), 'w')
-
-        time = exp.time
-        header = "".join(['# TIME ', time.isoformat(), "\n"])
-    
-        header += "# DSTAT COMMANDS\n#  "
-        for i in exp.commands:
-            header += i
-
-        file.write("".join([header, '\n']))
-    
-        analysis_buffer = []
-    
-        if exp.analysis != {}:
-            analysis_buffer.append("# ANALYSIS")
-            for key, value in exp.analysis.iteritems():
-                analysis_buffer.append("#  %s:" % key)
-                for scan in value:
-                    number, result = scan
-                    analysis_buffer.append(
-                        "#    Scan %s -- %s" % (number, result)
-                        )
-    
-        for i in analysis_buffer:
-            file.write("%s\n" % i)
-      
-        # Write out actual data  
-        line_buffer = []
-    
-        for scan in zip(*exp.data[dname]):
-            for dimension in scan:
-                for i in range(len(dimension)):
-                    try:
-                        line_buffer[i] += "%s     " % dimension[i]
-                    except IndexError:
-                        line_buffer.append("")
-                        line_buffer[i] += "%s     " % dimension[i]
             
-        for i in line_buffer:
-            file.write("%s\n" % i)
-
-        file.close()
+    save_path = "{}{}".format(path, num)
+    
+    for key, text in savestrings.items():   
+        with open('{}-{}.txt'.format(save_path, key), 'w') as f:
+            f.write(text)
         
 def save_plot(exp, path):
     """Saves everything in exp.plots to path. Appends a number for duplicates.
@@ -256,9 +214,11 @@ def save_plot(exp, path):
     j = 0
     
     for i in exp.plots: # Test for any existing files
-        while os.path.exists("%s%s-%s.%s" % (name, num, i, ext)):
+        plot_type = '_'.join(i.name.lower().split())
+        while os.path.exists("%s%s-%s.%s" % (name, num, plot_type, ext)):
             j += 1
             num = j
     
     for i in exp.plots: # save data
-        exp.plots[i].figure.savefig("%s%s-%s.%s" % (name, num, i, ext))
\ No newline at end of file
+        plot_type = '_'.join(i.name.lower().split())
+        i.figure.savefig("%s%s-%s.%s" % (name, num, plot_type, ext))
\ No newline at end of file
-- 
GitLab