Write the ROI model to a FITS file.
348503
def write_fits(self, fitsfile):
        """"""

        tab = self.create_table()
        hdu_data = fits.table_to_hdu(tab)
        hdus = [fits.PrimaryHDU(), hdu_data]
        fits_utils.write_hdus(hdus, fitsfile)
233010
def fit_track_models(self,
                         model_names,
                         model_objs,
                         input_columns,
                         output_columns,
                         output_ranges,
                         ):
        
        print("Fitting track models")
        groups = self.data["train"]["member"][self.group_col].unique()
        for group in groups:
            group_data = self.data["train"]["combo"].loc[self.data["train"]["combo"][self.group_col] == group]
            group_data = group_data.dropna()
            group_data = group_data.loc[group_data["Duration_Step"] == 1]
            for model_type, model_dict in self.track_models.items():
                model_dict[group] = {}
                output_data = group_data[output_columns[model_type]].values.astype(int)
                output_data[output_data < output_ranges[model_type][0]] = output_ranges[model_type][0]
                output_data[output_data > output_ranges[model_type][1]] = output_ranges[model_type][1]
                discrete_data = (output_data - output_ranges[model_type][0]) // output_ranges[model_type][2] * \
                                output_ranges[model_type][2] + output_ranges[model_type][0]
                model_dict[group]["outputvalues"] = np.arange(output_ranges[model_type][0],
                                                              output_ranges[model_type][1] +
                                                              output_ranges[model_type][2],
                                                              output_ranges[model_type][2])
                for m, model_name in enumerate(model_names):
                    print("{0} {1} {2}".format(group, model_type, model_name))
                    model_dict[group][model_name] = deepcopy(model_objs[m])
                    model_dict[group][model_name].fit(group_data[input_columns], discrete_data)
982679
def write(self):
        """"""
        for entry in self._instream:
            if isinstance(entry, Feature):
                for feature in entry:
                    if feature.num_children > 0 or feature.is_multi:
                        if feature.is_multi and feature != feature.multi_rep:
                            continue
                        self.feature_counts[feature.type] += 1
                        fid = '{}{}'.format(feature.type,
                                            self.feature_counts[feature.type])
                        feature.add_attribute('ID', fid)
                    else:
                        feature.drop_attribute('ID')
            if isinstance(entry, Sequence) and not self._seq_written:
                print('##FASTA', file=self.outfile)
                self._seq_written = True
            print(repr(entry), file=self.outfile)
500742
def fromfits(infilename, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "FITS import shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "FITS file BITPIX : %s" % (hdr["BITPIX"])
        print "Internal array type :", pixelarray.dtype.name
    
    return pixelarray, hdr
1341945
def _write_mef(self, key, extlist, outfile):
        """"""
        channel = self.fv.get_channel(self.chname)
        with fits.open(outfile, mode='update') as pf:
            # Process each modified data extension
            for idx in extlist:
                k = '{0}[{1}]'.format(key, self._format_extname(idx))
                image = channel.datasrc[k]

                # Insert data and header into output HDU
                pf[idx].data = image.get_data()
                self._write_header(image, pf[idx])

            # Write history to PRIMARY
            self._write_history(key, pf['PRIMARY'])
1078715
def _write_config_file(batch_id, caller_names, base_dir, data):
    
    config_dir = utils.safe_makedir(os.path.join(base_dir, "config"))
    config_file = os.path.join(config_dir, "{0}-ensemble.yaml".format(batch_id))
    algorithm = data["config"]["algorithm"]
    econfig = {"ensemble": algorithm["ensemble"],
               "names": caller_names,
               "prep-inputs": False}
    intervals = validate.get_analysis_intervals(data, None, base_dir)
    if intervals:
        econfig["intervals"] = os.path.abspath(intervals)
    with open(config_file, "w") as out_handle:
        yaml.safe_dump(econfig, out_handle, allow_unicode=False, default_flow_style=False)
    return config_file
1313289
def _set_roi_mask(self, roi_mask):
        """"""

        if isinstance(roi_mask,
                      np.ndarray):  # not (roi_mask is None or roi_mask=='auto'):
            self._verify_shape_compatibility(roi_mask, 'ROI set')
            self.roi_mask = roi_mask

            self.roi_list = np.unique(roi_mask.flatten())
            np.setdiff1d(self.roi_list, cfg.background_value)
        else:
            self.roi_mask = np.ones(self.carpet.shape[:-1]) # last dim is self.fixed_dim already
            self.roi_list = [1, ]
713204
def writeToFile(self, filename, saveOpts=False):
        '''
        
        '''
        try:
            if not filename.endswith('.%s' % self.ftype):
                filename += '.%s' % self.ftype
            s = {'coeffs': self.coeffs}
            if saveOpts:
                s['opts'] = self.opts
#             else:
#                 s['opts':{}]
            np.savez(filename, **s)
            return filename
        except AttributeError:
            raise Exception(
                'need to calibrate camera before calibration can be saved to file')
659294
def create_from_fitsfile(cls, fitsfile):
        
        from fermipy.skymap import Map
        index_map = Map.create_from_fits(fitsfile)
        mult_map = Map.create_from_fits(fitsfile, hdu=1)
        ff = fits.open(fitsfile)
        hpx = HPX.create_from_hdu(ff[0])
        mapping_data = dict(ipixs=index_map.counts,
                            mult_val=mult_map.counts,
                            npix=mult_map.counts.shape)
        return cls(hpx, index_map.wcs, mapping_data)
163024
def make_hdu(self, data, **kwargs):
        
        shape = data.shape
        extname = kwargs.get('extname', self.conv.extname)

        if shape[-1] != self._npix:
            raise Exception(
                "Size of data array does not match number of pixels")
        cols = []

        if self._ipix is not None:
            cols.append(fits.Column(self.conv.idxstring, "J", array=self._ipix))

        if self.conv.convname == 'FGST_SRCMAP_SPARSE':
            nonzero = data.nonzero()
            nfilled = len(nonzero[0])
            if len(shape) == 1:
                cols.append(fits.Column("PIX", "J", array=nonzero[0].astype(int)))
                cols.append(fits.Column("VALUE", "E", array=data.flat[nonzero].astype(float).reshape(nfilled)))
            elif len(shape) == 2:
                keys = self._npix * nonzero[0] + nonzero[1]
                cols.append(fits.Column("PIX", "J", array=nonzero[1].reshape(nfilled)))
                cols.append(fits.Column("CHANNEL", "I", array=nonzero[0].reshape(nfilled)))
                cols.append(fits.Column("VALUE", "E",
                                        array=data.flat[keys].astype(float).reshape(nfilled)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        else:
            if len(shape) == 1:
                cols.append(fits.Column(self.conv.colname(
                    indx=self.conv.firstcol), "E", array=data.astype(float)))
            elif len(shape) == 2:
                for i in range(shape[0]):
                    cols.append(fits.Column(self.conv.colname(
                        indx=i + self.conv.firstcol), "E", array=data[i].astype(float)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        header = self.make_header()
        hdu = fits.BinTableHDU.from_columns(cols, header=header, name=extname)

        return hdu
1188651
def WriteFile(self, printer):
        """"""
        self.Validate()
        extended_descriptor.WritePythonFile(
            self.__file_descriptor, self.__package, self.__client_info.version,
            printer)
1211076
def writefits(self,fname,clobber=True, trimzero=True, binned=True,
                  hkeys=None):
        
        spectrum.CompositeSourceSpectrum.writefits(self,fname,
                                                   clobber=clobber,
                                                   trimzero=trimzero,
                                                   binned=binned,
                                                   hkeys=hkeys)
1373502
def write_posterior(self, filename, **kwargs):
        
        f = h5py.File(filename, 'w')

        # Preserve top-level metadata
        for key in self.attrs:
            f.attrs[key] = self.attrs[key]

        f.attrs['filetype'] = PosteriorFile.name
        s = f.create_group('samples')
        fields = self[self.samples_group].keys()

        # Copy and squash fields into one dimensional arrays
        for field_name in fields:
            fvalue = self[self.samples_group][field_name][:]
            thin = fvalue[:,self.thin_start:self.thin_end:self.thin_interval]
            s[field_name] = thin.flatten()
1161423
def _to_file_format(self, iamc_index):
        """"""
        df = self.timeseries(iamc_index=iamc_index).reset_index()
        df = df.rename(columns={c: str(c).title() for c in df.columns})
        return df
143579
def _make_fits(self):
        """"""
        a = self.tests[self.active]
        args = self.curargs
        #We need to generate a fit for the data if there are any fits specified.
        if len(args["fits"]) > 0:
            for fit in list(args["fits"].keys()):
                a.fit(args["independent"], fit, args["fits"][fit], args["threshold"], args["functions"])
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()
1028206
def write_tables_to_fits(filepath, tablelist, clobber=False,
                         namelist=None, cardslist=None, hdu_list=None):
    
    outhdulist = [fits.PrimaryHDU()]
    rmlist = []
    for i, table in enumerate(tablelist):
        ft_name = "%s._%i" % (filepath, i)
        rmlist.append(ft_name)
        try:
            os.unlink(ft_name)
        except:
            pass
        table.write(ft_name, format="fits")
        ft_in = fits.open(ft_name)
        if namelist:
            ft_in[1].name = namelist[i]
        if cardslist:
            for k, v in cardslist[i].items():
                ft_in[1].header[k] = v
        ft_in[1].update()
        outhdulist += [ft_in[1]]

    if hdu_list is not None:
        for h in hdu_list:
            outhdulist.append(h)

    fits.HDUList(outhdulist).writeto(filepath, overwrite=clobber)
    for rm in rmlist:
        os.unlink(rm)