Пример #1
0
def pickle(obj, dest=None, protocol=cPickle.HIGHEST_PROTOCOL):
    """
    Pickle an object.

    dest : None | str
        Path to destination where to save the  file. If no destination is
        provided, a file dialog opens. If a destination without extension is
        provided, '.pickled' is appended.
    protocol : int
        Pickle protocol (default is HIGHEST_PROTOCOL).

    """
    if dest is None:
        dest = ui.ask_saveas("Pickle Destination", '',
                             ext=[('pickled', "Pickled Python Object")])
        if dest:
            print 'dest=%r' % dest
        else:
            return
    else:
        dest = os.path.expanduser(dest)
        if not os.path.splitext(dest)[1]:
            dest += '.pickled'

    with open(dest, 'w') as FILE:
        cPickle.dump(obj, FILE, protocol)
Пример #2
0
def save(dataset, destination=None, values=None):
    """
    Saves the dataset with the same name simultaneously in 3 different formats:
    
     - mat: matlab file
     - pickled dataset
     - TSV: tab-separated values
     
    """
    if destination is None:
        msg = ("Pick a name to save the dataset (without extension; '.mat', "
               "'.pickled' and '.tsv' will be appended")
        destination = ui.ask_saveas("Save Dataset", msg, [])
    
    if not destination:
        return
    
    destination = str(destination)
    if ui.test_targetpath(destination):
        msg_temp = "Writing: %r"
        dest = os.path.extsep.join((destination, 'pickled'))
        print msg_temp % dest
        pickle_data = {'design': dataset, 'values': values}
        with open(dest, 'w') as f:
            _pickle.dump(pickle_data, f)
        
        dest = os.path.extsep.join((destination, 'mat'))
        print msg_temp % dest
        export_mat(dataset, values, dest)
        
        dest = os.path.extsep.join((destination, 'tsv'))
        print msg_temp % dest
        dataset.export(dest)
Пример #3
0
    def save_all_pages(self, fname=None):
        if fname is None:
            msg = ("Save all pages. Index is inserted before extension. "
                   "If no extension is provided, pdf is used.")
            fname = ui.ask_saveas("title", msg, None)
            if not fname:
                return

        head, tail = os.path.split(fname)
        if os.path.extsep in tail:
            root, ext = os.path.splitext(tail)
        else:
            root = fname
            ext = '.pdf'
        fntemp = os.path.join(head, root) + '_%i' + ext

        i = self.current_page_i
        self.figure.savefig(fntemp % i)
        pages = range(self.n)
        pages.remove(i)
        prog = ui.progress_monitor(self.n - 1, "Saving Figures", "Saving Figures")
        for i in pages:
            self.show_page(i)
            self.figure.savefig(fntemp % i)
            prog.advance()
        prog.terminate()
Пример #4
0
def save_tex(tex_obj, path=None):
    "saves a textab object as a pdf"
    txt = tex_obj.get_tex()
    if path is None:
        path = ui.ask_saveas(title="Save tex", ext=[('tex','tex source code')])
    if path:
        with open(path, 'w') as f:
            f.write(txt)
Пример #5
0
def save_pdf(tex_obj, path=None):
    "saves a textab object as a pdf"
    pdf = get_pdf(tex_obj)
    if path is None:
        path = ui.ask_saveas(title="Save tex as pdf", ext=[('pdf','pdf')])
    if path:
        with open(path, 'w') as f:
            f.write(pdf)
Пример #6
0
 def export_pickled(self, path=None):
     "Exports the parameter's values as a pickled dictionary file."
     if path is None:
         path = ui.ask_saveas(title="Export Parameter Values", 
                              message="Select a filename to pickle the parameter values:", 
                              ext=[('pickled', "pickled Python object")])
     if path:
         with open(path, 'w') as f:
             pickle.dump(self._value, f)
Пример #7
0
    def OnFileSave(self, event):
        """
        FIXME: maybe start search at wx.py.frame.Frame.OnUpdateMenu()

        """
        path = ui.ask_saveas("Save Figure", "Save the current figure. The format is "
                             "determined from the extension.", None)
        if path:
            self.figure.savefig(path)
Пример #8
0
 def REJECTION_EXPORT(self, fn=None):
     if fn is None:
         msg = "Export rejection dictionary; WARNING: segment id is used as key, so the dictionary can only beused with the same segment sequence (=import procedure)"
         fn = ui.ask_saveas(message=msg,
                            ext = [('pickled', "pickled file")])
     if isinstance(fn, basestring):
         if fn[-8:] != '.pickled':
             fn = fn + '.pickled'
         # create segment-name - id table to assure same segment matching
         with open(fn, 'w') as f:
             out = deepcopy(self.reject_dict)
             out['safety'] = dict((s.id, s.name) for s in self.segments)
             pickle.dump(out, f)
Пример #9
0
 def save_tsv(self, path=None, delimiter='\t', linesep='\r\n', fmt='%.15e'):
     """
     Saves the table as tab-separated values file. 
     
     :arg str delimiter: string that is placed between cells (default: tab).
     :arg str linesep: string that is placed in between lines.
     :arg str fmt: format string for representing numerical cells. 
         (see 'Python String Formatting Documentation <http://docs.python.org/library/stdtypes.html#string-formatting-operations>'_ )
         http://docs.python.org/library/stdtypes.html#string-formatting-operations
         
     """
     if not path:
         path = ui.ask_saveas(title = "Save Tab Separated Table",
                              message = "Please Pick a File Name",
                              ext = [("txt", "txt (tsv) file")])
     if ui.test_targetpath(path):
         ext = os.path.splitext(path)[1]
         if ext not in ['.tsv', '.txt']:
             path += '.txt'
         with open(path, 'w') as f:
             f.write(self.get_tsv(delimiter=delimiter, linesep=linesep, 
                                  fmt=fmt))
Пример #10
0
def txt(iterator, fmt='%s', delim=os.linesep, dest=None):
    """
    Writes any object that supports iteration to a text file.
    
    iterator : iterator
        Object that iterates over values to be saved
    fmt : fmt-str
        format-string which is used to format the iterator's values
    delim : str
        the delimiter which is inserted between values
    dest : str(path) | None
        The destination; if None, a system save-as dialog is displayed 

    """
    if dest is None:
        name = repr(iterator)[:20]
        msg = "Save %s..." % name
        dest = ui.ask_saveas(msg, msg, None)
    
    if dest:
        with open(dest, 'w') as FILE:
            FILE.write(delim.join(fmt % v for v in iterator))
Пример #11
0
 def OnInsertPath(self, event, t=None):
     if t is None:
         t = event.GetSelection()
     # get
     if t == 0: # File
         filenames = ui.ask_file(mult=True)
     elif t == 1: # Dir
         filenames = ui.ask_dir()
     elif t == 2: # New
         filenames = ui.ask_saveas(title = "Get New File Name",
                                   message = "Please Pick a File Name", 
                                   ext = None)
     # put to terminal
     if filenames:
         if len(filenames) == 1:
             filenames = '"'+filenames[0]+'"'
         else:
             filenames = '"'+str(filenames)+'"'
         
         if 'wxMSW' in wx.PlatformInfo:
             filenames = 'r'+filenames
         
         self.InsertStr(filenames)
Пример #12
0
 def saveas(self, path=None):
     "Save the experiment. if path is None, a system file dialog is used."
     if not path:
         msg = ("Pick a filename to pickle your data. A folder named"+\
                " '<name>.cache' will be created to store data files.")
         path = ui.ask_saveas(title="Save Pickled EEG",
                              message=msg, 
                              ext = [(_extension, "pickled eelbrain experiment")])
     if path:
         if not path.endswith(os.path.extsep + _extension):
             path = os.path.extsep.join((path, _extension))
         
         # if the experiment already has a cache, copy it
         if self.path is not None:
             old_cache = self._cache_path
             new_cache = path + '.cache'
             if os.path.exists(old_cache):
                 shutil.copytree(old_cache, new_cache)
         
         # save the experiment
         self.path = path
         self.save()
     else:
         print "Saving aborted"
Пример #13
0
def export_mat(dataset, values=None, destination=None):
    """
    Usage::
    
        >>> export_mat(dataset, 
        ...            values={varname -> {cellname -> value}},
        ...            destination='/path/to/file.mat')
    
    
    Arguments
    ---------
    
    dataset : dataset
        dataset containing the trial list
    
    values : `None` or `{varname -> {cellname -> value}}`
        additional values that should be stored, where: `varname` is the 
        variable name by which the struct will be available in matlab; 
        `cellname` is the name of the struct's field, and `value` is the value
        of that field.
    
    destination : None or str
        Path where the mat file should be saved. If `None`, the ui will ask 
        for a location.
    
    """
    # Make sure we have a valid destination 
    if destination is None:
        print_path = True
        destination = ui.ask_saveas("Mat destination", 
                                    "Where do you want to save the mat file?", 
                                    ext=[('mat', "Matlab File")])
        if not destination:
            print "aborted"
            return
    else:
        print_path = False
    
    if not isinstance(destination, basestring):
        raise ValueError("destination is not a string")
    
    dirname = os.path.dirname(destination)
    if not os.path.exists(dirname):
        if ui.ask("Create %r?" % dirname, "No folder named %r exists. Should "
                  "it be created?" % dirname):
            os.mkdir(dirname)
        else:
            print "aborted"
            return
    
    if not destination.endswith('mat'):
        os.path.extsep.join(destination, 'mat')
    
    # assemble the mat file contents
    mat = {'trials': list(dataset.itercases())}
    if values:
        mat.update(values)
    
    if print_path:
        print 'Saving: %r' % destination
    scipy.io.savemat(destination, mat, do_compression=True, oned_as='row')