Dump a dictionary with model data into a file using the R dump format that
    Stan supports.

    Parameters
    ----------
    data : dict
    filename : str
765849
def stan_rdump(data, filename):
    
    for name in data:
        if not is_legal_stan_vname(name):
            raise ValueError("Variable name {} is not allowed in Stan".format(name))
    with open(filename, 'w') as f:
        f.write(_dict_to_rdump(data))
660626
def load_model(f, format=None, load_external_data=True):  # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto
    '''
    
    '''
    s = _load_bytes(f)
    model = load_model_from_string(s, format=format)

    if load_external_data:
        model_filepath = _get_file_path(f)
        if model_filepath:
            base_dir = os.path.dirname(model_filepath)
            load_external_data_for_model(model, base_dir)

    return model
694775
def dump_dict_to_file(dictionary, filepath):
    """"""
    create_dirs(
        os.path.dirname(filepath)
    )

    with open(filepath, 'a') as outfile:
        json.dump(dictionary, outfile)
        outfile.write('\n')
462021
def rm(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    data(dataset, **ctx.obj).rm(**kwargs)
1006732
def to_json(self, filename=None):
        
        def json_encoder(obj):
            if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series):
                if isinstance(obj.index, pd.core.index.MultiIndex):
                    obj = obj.reset_index()  # convert MultiIndex to columns

                return json.loads(obj.to_json(date_format='iso'))
            elif isinstance(obj, melodist.cascade.CascadeStatistics):
                return obj.__dict__
            elif isinstance(obj, np.ndarray):
                return obj.tolist()
            else:
                raise TypeError('%s not supported' % type(obj))

        d = dict(
            temp=self.temp,
            wind=self.wind,
            precip=self.precip,
            hum=self.hum,
            glob=self.glob
        )

        j = json.dumps(d, default=json_encoder, indent=4)

        if filename is None:
            return j
        else:
            with open(filename, 'w') as f:
                f.write(j)
501582
def json_to_file(data, filename, pretty=False):
    ''''''
    kwargs = dict(indent=4) if pretty else {}
    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    dump = json.dumps(api.__schema__, **kwargs)
    with open(filename, 'wb') as f:
        f.write(dump.encode('utf-8'))
1034522
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL):
        
        result = self.result()

        with open(dump_filename, 'wb') as f:
            pickle.dump((self.__class__, result), f, pickle_protocol)
571676
def storedata(filename=None):
    """"""
    if filename is None:
        filename = 'credolib_state.pickle'
    ns = get_ipython().user_ns
    with open(filename, 'wb') as f:
        d = {}
        for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
                    'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
                    'saveto_dir',
                    'badfsns_datcmp', 'auximages_dir', 'subtractedsamplenames', 'outputpath', 'saveto_dir_rel',
                    'auximages_dir_rel', 'crd_prefix']:
            try:
                d[var] = ns[var]
            except KeyError:
                warnings.warn('Skipping storage of unavailable variable "%s"' % var)
        pickle.dump(d, f)
1284784
def file_data_to_str(data):
    
    if not data:
        return _('<i>File name not recorded</i>')
    res = data['name']
    try:
        mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S',
                                     time.localtime(data['mtime']))
        res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str)
        res += '<br><i>{}</i>: {} {}'.format(
                _('Size'), data['size'], _('bytes'))
    except KeyError:
        res += '<br>' + _('<i>File no longer exists</i>')
    return res
477250
def save_model(self, file_name='model.cx'):
        
        with open(file_name, 'wt') as fh:
            cx_str = self.print_cx()
            fh.write(cx_str)
134149
def write_data(X, dir='sim/test', append=False, header='',
               varNames={}, Adj=np.array([]), Coupl=np.array([]),
               boolRules={}, model='', modelType='', invTimeStep=1):
    
    # check if output directory exists
    if not os.path.exists(dir):
        os.makedirs(dir)
    # update file with sample ids
    filename = dir+'/id.txt'
    if os.path.exists(filename):
        f = open(filename,'r')
        id = int(f.read()) + (0 if append else 1)
        f.close()
    else:
        id = 0
    f = open(filename,'w')
    id = '{:0>6}'.format(id)
    f.write(str(id))
    f.close()
    # dimension
    dim = X.shape[1]
    # write files with adjacancy and coupling matrices
    if not append:
        if False:
            if Adj.size > 0:
                # due to 'update formulation' of model, there
                # is always a diagonal dependence
                Adj = np.copy(Adj)
                if 'hill' in model:
                    for i in range(Adj.shape[0]):
                        Adj[i,i] = 1
                np.savetxt(dir+'/adj_'+id+'.txt',Adj,
                           header=header,
                           fmt='%d')
            if Coupl.size > 0:
                np.savetxt(dir+'/coupl_'+id+'.txt',Coupl,
                           header=header,
                           fmt='%10.6f')
        # write model file
        if varNames and Coupl.size > 0:
            f = open(dir+'/model_'+id+'.txt','w')
            f.write('# For each "variable = ", there must be a right hand side: \n')
            f.write('# either an empty string or a python-style logical expression \n')
            f.write('# involving variable names, "or", "and", "(", ")". \n')
            f.write('# The order of equations matters! \n')
            f.write('# \n')
            f.write('# modelType = ' + modelType + '\n')
            f.write('# invTimeStep = '+ str(invTimeStep) + '\n')
            f.write('# \n')
            f.write('# boolean update rules: \n')
            for rule in boolRules.items():
                f.write(rule[0] + ' = ' + rule[1] + '\n')
            # write coupling via names
            f.write('# coupling list: \n')
            names = list(varNames.keys())
            for gp in range(dim):
                for g in range(dim):
                    if np.abs(Coupl[gp,g]) > 1e-10:
                        f.write('{:10} '.format(names[gp])
                                + '{:10} '.format(names[g])
                                + '{:10.3} '.format(Coupl[gp,g]) + '\n')
            f.close()
    # write simulated data
    # the binary mode option in the following line is a fix for python 3
    # variable names
    if varNames:
        header += '{:>2} '.format('it')
        for v in varNames.keys():
            header += '{:>7} '.format(v)
    f = open(dir+'/sim_'+id+'.txt','ab' if append else 'wb')
    np.savetxt(f,np.c_[np.arange(0,X.shape[0]),X],header=('' if append else header),
               fmt=['%4.f']+['%7.4f' for i in range(dim)])
    f.close()
1003998
def load_data(self, filename):
        
        with zopen(filename, "rt") as f:
            self._data = json.load(f, cls=MontyDecoder)
528482
def load_data_file_to_net(self, filename):
    '''
    
    '''
    inst_dat = self.load_json_to_dict(filename)
    load_data.load_data_to_net(self, inst_dat)
819971
def json_dumps(self, data):
        
        return json.dumps(
            data, 
            separators=(',', ':'), 
            sort_keys=True, 
            cls=self.json_encoder, 
            ensure_ascii=False
        ).encode('utf8')
729373
def convert_to_dataset_file_metadata(self, file_data, path):
        
        as_metadata = {
            'path': os.path.join(path, file_data['name']),
            'description': file_data['description']
        }

        schema = {}
        fields = []
        for column in file_data['columns']:
            field = {
                'name': column['name'],
                'title': column['description'],
                'type': column['type']
            }
            fields.append(field)
        schema['fields'] = fields
        as_metadata['schema'] = schema

        return as_metadata
51577
def write_json(filename, data):
    
    with open(filename, 'w') as file:
        json.dump(data, file, indent=4, sort_keys=True)
502137
def format_filename(self, data, row):
        
        return self.filename.format(**self.filename_formatters(data, row))