Saves correlation matrix of selected headers

        :param out_file: Output file
540671
def save_to_file(self, out_file):
        
        correlation_matrix = self.get_correlation_matrix_from_columns()
        cr_plot.create_correlation_matrix_plot(
            correlation_matrix, self.title, self.headers_to_test)

        fig = pyplot.gcf()  # get reference to figure
        fig.set_size_inches(23.4, 23.4)
        pyplot.savefig(out_file, dpi=120)
109404
def write_out_config(self, config_file):
        
        with open(config_file, 'w') as f:
            json.dump(self.params, f, indent=2,
                      separators=(',', ': '))
985329
def get_correlation_matrix_from_columns(self):
        
        header_to_column = {}  # create index of headers
        for header in self.headers:
            header_to_column[header] = self.headers.index(header)

        data_to_test = []
        for header in self.headers_to_test:
            header_column = Matrix(self.data) \
                .get_column(header_to_column[header])

            for i, value in enumerate(header_column):
                header_column[i] = float(value)  # get float

            data_to_test.append(header_column)

        return self.get_correlation_matrix(data_to_test)
1044155
def _cnvbed_to_bed(in_file, caller, out_file):
    
    with open(out_file, "w") as out_handle:
        for feat in pybedtools.BedTool(in_file):
            out_handle.write("\t".join([feat.chrom, str(feat.start), str(feat.end),
                                        "cnv%s_%s" % (feat.score, caller)])
                             + "\n")
1343360
def save_filter(name, filt, full=None, path='filters'):
    """

    # First we'll save the filter using its internal routine.
    # This will create the directory ./filters if it doesn't exist already.
    filt.tofile(path)

    # If full, we store the inversion output
    if full:

        # Get file name
        path = os.path.abspath(path)
        if len(name.split('.')) == 2:
            suffix = '.gz'
        else:
            suffix = ''
        fullfile = os.path.join(path, name.split('.')[0]+'_full.txt' + suffix)

        # Get number of spacing and shift values
        nspace, nshift = full[3].shape

        # Create header
        header = 'Full inversion output from empymod.fdesign.design\n'
        header += 'Line 11: Nr of spacing values\n'
        header += 'Line 12: Nr of shift values\n'
        header += 'Line 13: Best spacing value\n'
        header += 'Line 14: Best shift value\n'
        header += 'Line 15: Min amplitude or max offset\n'

        header += 'Lines 16-{}: Spacing matrix '.format(nspace+15)
        header += '({} x {})\n'.format(nspace, nshift)

        header += 'Lines {}-{}: Spacing matrix '.format(nspace+16, 2*nspace+15)
        header += '({} x {})\n'.format(nspace, nshift)

        header += 'Lines {}-{}: Spacing '.format(2*nspace+16, 3*nspace+15)
        header += 'matrix ({} x {})\n'.format(nspace, nshift)

        header += 'Line {}: Integer: 0: min amp, 1: max r'.format(3*nspace+16)

        # Create arrays; put single values in arrays of nshift values
        nr_spacing = np.r_[nspace, np.zeros(nshift-1)]
        nr_shift = np.r_[nshift, np.zeros(nshift-1)]
        best_spacing = np.r_[full[0][0], np.zeros(nshift-1)]
        best_shift = np.r_[full[0][1], np.zeros(nshift-1)]
        min_value = np.r_[np.atleast_1d(full[1]), np.zeros(nshift-1)]
        min_max = np.r_[full[4], np.zeros(nshift-1)]

        # Collect all in one array
        fullsave = np.vstack((nr_spacing, nr_shift, best_spacing, best_shift,
                              min_value, full[2][0], full[2][1], full[3],
                              min_max))

        # Save array
        np.savetxt(fullfile, fullsave, header=header)
308215
def save_image(self, outname):
        
        hdu = self.global_data.img.hdu
        hdu.data = self.global_data.img._pixels
        hdu.header["ORIGIN"] = "Aegean {0}-({1})".format(__version__, __date__)
        # delete some axes that we aren't going to need
        for c in ['CRPIX3', 'CRPIX4', 'CDELT3', 'CDELT4', 'CRVAL3', 'CRVAL4', 'CTYPE3', 'CTYPE4']:
            if c in hdu.header:
                del hdu.header[c]
        hdu.writeto(outname, overwrite=True)
        self.log.info("Wrote {0}".format(outname))
        return
327823
def _organize_output(output, combine_map, file_key, combine_arg_keys):
    
    out_map = collections.defaultdict(list)
    extra_args = collections.defaultdict(list)
    final_args = collections.OrderedDict()
    extras = []
    for data in output:
        cur_file = data.get(file_key)
        if not cur_file:
            extras.append([data])
        else:
            cur_out = combine_map[cur_file]
            out_map[cur_out].append(cur_file)
            extra_args[cur_out].append([data[x] for x in combine_arg_keys])
            data[file_key] = cur_out
            if cur_out not in final_args:
                final_args[cur_out] = [data]
            else:
                extras.append([data])
    combine_args = [[v, k] + _get_extra_args(extra_args[k], combine_arg_keys)
                    for (k, v) in out_map.items()]
    return combine_args, list(final_args.values()) + extras
960980
def save_yaml(self, outFile):
        """"""
        with open(outFile,'w') as myfile:
            print(yaml.dump(self.params), file=myfile)
1356527
def _save_uploaded_file_list(samples, file_list_work, out_dir):
    
    if not utils.file_exists(file_list_work):
        return None

    if any([cwlutils.is_cwl_run(d) for d in samples]):
        upload_paths = []
        with open(file_list_work) as f:
            for p in (l.strip() for l in f.readlines() if os.path.exists(l.strip())):
                if p.startswith(out_dir):
                    upload_paths.append(p.replace(out_dir + "/", ""))
    else:
        upload_path_mapping = dict()
        for sample in samples:
            upload_path_mapping.update(get_all_upload_paths_from_sample(sample))
        if not upload_path_mapping:
            return None

        with open(file_list_work) as f:
            paths = [l.strip() for l in f.readlines() if os.path.exists(l.strip())]
        upload_paths = [p for p in [
            _work_path_to_rel_final_path(path, upload_path_mapping, samples[0]["upload"]["dir"])
            for path in paths
        ] if p]
        if not upload_paths:
            return None

    file_list_final = os.path.join(out_dir, "list_files_final.txt")
    with open(file_list_final, "w") as f:
        for path in upload_paths:
            f.write(path + '\n')
    return file_list_final
978316
def analyze(self, output_file=None):
        

        fr = None
        for path, code, line, char, desc in self.parser.parse():

            # Create a new FileResult and register it if we have changed to a new file
            if path not in self.files:
                # Update statistics
                if fr:
                    self.update_stats(fr)
                fr = FileResult(path)
                self.files[path] = fr

            # Add line to the FileResult
            fr.add_error(code, line, char, desc)

        # Add final FileResult to statistics, if any were parsed
        if fr:
            self.update_stats(fr)

        # Generate HTML file
        self.generate(output_file=output_file)
1108589
def write(self, output_file):
        
        for message_level, message_text in self:
            output_file.write('%s=%s\r\n' % (message_level, message_text))
        output_file.write('\r\n')
1018216
def write_header(self):
        

        self.output.seek(0)
        self.output.write(struct.pack('!HHHHHH', self.id, self.flags,
                                      self.counts[0], self.counts[1],
                                      self.counts[2], self.counts[3]))
        self.output.seek(0, 2)
555827
def save(self, outpath):
        

        with open(outpath, "w") as outfile:
            outfile.write(self.dump())
1032841
def save_header_data(self):
        
        client = self.aq_parent

        headers = self.get_header_values()
        if not headers:
            return False

        # Plain header fields that can be set into plain schema fields:
        for h, f in [
            ('File name', 'Filename'),
            ('No of Samples', 'NrSamples'),
            ('Client name', 'ClientName'),
            ('Client ID', 'ClientID'),
            ('Client Order Number', 'ClientOrderNumber'),
            ('Client Reference', 'ClientReference')
        ]:
            v = headers.get(h, None)
            if v:
                field = self.schema[f]
                field.set(self, v)
            del (headers[h])

        # Primary Contact
        v = headers.get('Contact', None)
        contacts = [x for x in client.objectValues('Contact')]
        contact = [c for c in contacts if c.Title() == v]
        if contact:
            self.schema['Contact'].set(self, contact)
        else:
            self.error("Specified contact '%s' does not exist; using '%s'"%
                       (v, contacts[0].Title()))
            self.schema['Contact'].set(self, contacts[0])
        del (headers['Contact'])

        # CCContacts
        field_value = {
            'CCNamesReport': '',
            'CCEmailsReport': '',
            'CCNamesInvoice': '',
            'CCEmailsInvoice': ''
        }
        for h, f in [
            # csv header name      DataGrid Column ID
            ('CC Names - Report', 'CCNamesReport'),
            ('CC Emails - Report', 'CCEmailsReport'),
            ('CC Names - Invoice', 'CCNamesInvoice'),
            ('CC Emails - Invoice', 'CCEmailsInvoice'),
        ]:
            if h in headers:
                values = [x.strip() for x in headers.get(h, '').split(",")]
                field_value[f] = values if values else ''
                del (headers[h])
        self.schema['CCContacts'].set(self, [field_value])

        if headers:
            unexpected = ','.join(headers.keys())
            self.error("Unexpected header fields: %s" % unexpected)
627454
def save_disagg_to_csv(metadata, matrices):
    
    skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT')
    base_header = ','.join(
        '%s=%s' % (key, value) for key, value in metadata.items()
        if value is not None and key not in skip_keys)
    for disag_tup, (poe, iml, matrix, fname) in matrices.items():
        header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml)

        if disag_tup == ('Mag', 'Lon', 'Lat'):
            matrix = numpy.swapaxes(matrix, 0, 1)
            matrix = numpy.swapaxes(matrix, 1, 2)
            disag_tup = ('Lon', 'Lat', 'Mag')

        axis = [metadata[v] for v in disag_tup]
        header += ','.join(v for v in disag_tup)
        header += ',poe'

        # compute axis mid points
        axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float
                else ax for ax in axis]

        values = None
        if len(axis) == 1:
            values = numpy.array([axis[0], matrix.flatten()]).T
        else:
            grids = numpy.meshgrid(*axis, indexing='ij')
            values = [g.flatten() for g in grids]
            values.append(matrix.flatten())
            values = numpy.array(values).T

        writers.write_csv(fname, values, comment=header, fmt='%.5E')
1127384
def decomment(bed_file, out_file):
    
    if file_exists(out_file):
        return out_file

    with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
        for line in in_handle:
            if line.startswith("#") or line.startswith("browser") or line.startswith("track"):
                continue
            else:
                out_handle.write(line)
    return out_file
590900
def writeOutput(self, filename, samples, srcFs, targetFs):
        
        import librosa
        inputLength = samples.shape[-1]
        if srcFs != targetFs:
            if inputLength < targetFs:
                logger.info("Input signal is too short (" + str(inputLength) +
                            " samples) for resampling to " + str(targetFs) + "Hz")
                outputSamples = samples
                targetFs = srcFs
            else:
                logger.info("Resampling " + str(inputLength) + " samples from " + str(srcFs) + "Hz to " +
                            str(targetFs) + "Hz")
                outputSamples = librosa.resample(samples, srcFs, targetFs, res_type='kaiser_fast')
        else:
            outputSamples = samples
        logger.info("Writing output to " + filename)
        maxv = np.iinfo(np.int32).max
        librosa.output.write_wav(filename, (outputSamples * maxv).astype(np.int32), targetFs)
        logger.info("Output written to " + filename)