Writes src as attribute of gctx out file. 

	Input:
		- hdf5_out (h5py): hdf5 file to write to 
		- gctoo_object (GCToo): GCToo instance to be written to .gctx
		- out_file_name (str): name of hdf5 out file.
552442
def write_src(hdf5_out, gctoo_object, out_file_name):
    
    if gctoo_object.src == None:
        hdf5_out.attrs[src_attr] = out_file_name
    else:
        hdf5_out.attrs[src_attr] = gctoo_object.src
909350
def save(self, out_path):
        

        out = {
            'selectors': [str(x) for x in self.selectors],
            'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
        }

        with open(out_path, "wb") as outfile:
            json.dump(out, outfile, indent=4)
648094
def write(filename, mesh, fmt_version, write_binary=True):
    
    try:
        writer = _writers[fmt_version]
    except KeyError:
        try:
            writer = _writers[fmt_version.split(".")[0]]
        except KeyError:
            raise ValueError(
                "Need mesh format in {} (got {})".format(
                    sorted(_writers.keys()), fmt_version
                )
            )

    writer.write(filename, mesh, write_binary=write_binary)
948389
def gtf_to_bed(gtf, alt_out_dir=None):
    
    out_file = os.path.splitext(gtf)[0] + '.bed'
    if file_exists(out_file):
        return out_file
    if not os.access(os.path.dirname(out_file), os.W_OK | os.X_OK):
        if not alt_out_dir:
            raise IOError('Cannot write transcript BED output file %s' % out_file)
        else:
            out_file = os.path.join(alt_out_dir, os.path.basename(out_file))
    with open(out_file, "w") as out_handle:
        db = get_gtf_db(gtf)
        for feature in db.features_of_type('transcript', order_by=("seqid", "start", "end")):
            chrom = feature.chrom
            start = feature.start
            end = feature.end
            attributes = feature.attributes.keys()
            strand = feature.strand
            name = (feature['gene_name'][0] if 'gene_name' in attributes else
                    feature['gene_id'][0])
            line = "\t".join([str(x) for x in [chrom, start, end, name, ".",
                                               strand]])
            out_handle.write(line + "\n")
    return out_file
911764
def out_to_in(self, out_file):
        
        in_file = os.path.basename(out_file).replace("out", "in", 1)
        dest = os.path.join(self.indir.path, in_file)

        if os.path.exists(dest) and not os.path.islink(dest):
            logger.warning("Will overwrite %s with %s" % (dest, out_file))

        os.rename(out_file, dest)
        return dest
222752
def write_hdf5_series(series, output, path=None, attrs=None, **kwargs):
    
    if attrs is None:
        attrs = format_index_array_attrs(series)
    return write_hdf5_array(series, output, path=path, attrs=attrs, **kwargs)
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()
985296
def write_tf_examples(filename, tf_examples, serialize=True):
    
    with tf.python_io.TFRecordWriter(
            filename, options=TF_RECORD_CONFIG) as writer:
        for ex in tf_examples:
            if serialize:
                writer.write(ex.SerializeToString())
            else:
                writer.write(ex)
957505
def write_outfile(method_name, file)
      schema = @load_schema.call(self)
      context = @load_context.call(self)
      result = schema.public_send(method_name, only: @only, except: @except, context: context)
      dir = File.dirname(file)
      FileUtils.mkdir_p(dir)
      File.write(file, result)
    end
103658
def vid2h5(data: np.ndarray, ut1, rawind, ticks, outfn: Path, P: dict, i: int=0,
           Nfile: int=1, det=None, tstart=None, cmdlog: str=None):
    assert outfn, 'must provide a filename to write'

    outfn = Path(outfn).expanduser()
    assert not outfn.is_dir(
    ), 'must provide FILEname, you provided directory {outfn}'
    outfn.parent.mkdir(exist_ok=True)

    txtupd = f'convert file {i} / {Nfile}'
    if 'spoolfn' in P:
        txtupd += f' {P["spoolfn"].name}'
    txtupd += f' => {outfn}'
    
    print(txtupd + '\r', end="")
    # %% saving
    if outfn.suffix == '.h5':
        """
        Reference: https://www.hdfgroup.org/HDF5/doc/ADGuide/ImageSpec.html
        Thanks to Eric Piel of Delmic for pointing out this spec
        * the HDF5 attributess set are necessary to put HDFView into image mode and enables
        other conforming readers to easily play images stacks as video.
        * the string_() calls are necessary to make fixed length strings per HDF5 spec
        """
        # NOTE write mode r+ to not overwrite incremental images
        if outfn.is_file():
            writemode = 'r+'  # append
        else:
            writemode = 'w'

        if data is not None:

            N = data.shape[0] * Nfile
            ind = slice(i * data.shape[0], (i + 1) * data.shape[0])
        else:  # FIXME haven't reevaluated for update only case
            for q in (ut1, rawind, ticks):
                if q is not None:
                    N = len(q)
                    break
            ind = slice(None)

        with h5py.File(outfn, writemode) as f:
            if data is not None:
                if 'rawimg' not in f:  # first run
                    setupimgh5(f, N, data.shape[1], data.shape[2])

                f['/rawimg'][ind, ...] = data

            if ut1 is not None:
                print(f'writing from {datetime.utcfromtimestamp(ut1[0])}'
                      f'to {datetime.utcfromtimestamp(ut1[-1])}')
                if 'ut1_unix' not in f:
                    fut1 = f.create_dataset(
                        '/ut1_unix', shape=(N,), dtype=float, fletcher32=True)
                    fut1.attrs['units'] = 'seconds since Unix epoch Jan 1 1970 midnight'

                f['/ut1_unix'][ind] = ut1

            if tstart is not None and 'tstart' not in f:
                f['/tstart'] = tstart

            if rawind is not None:
                if 'rawind' not in f:
                    fri = f.create_dataset(
                        '/rawind', shape=(N,), dtype=np.int64, fletcher32=True)
                    fri.attrs['units'] = 'one-based index since camera program started this session'

                f['/rawind'][ind] = rawind

            if ticks is not None:
                if 'ticks' not in f:
                    ftk = f.create_dataset(
                        '/ticks', shape=(N,), dtype=np.uint64, fletcher32=True)  # Uint64
                    ftk.attrs['units'] = 'FPGA tick counter for each image frame'

                f['/ticks'][ind] = ticks

            if 'spoolfn' in P:
                # http://docs.h5py.org/en/latest/strings.html
                if 'spoolfn' not in f:
                    fsp = f.create_dataset(
                        '/spoolfn', shape=(N,), dtype=h5py.special_dtype(vlen=bytes))
                    fsp.attrs['description'] = 'input filename data was extracted from'

                f['/spoolfn'][ind] = P['spoolfn'].name

            if det is not None:
                if 'detect' not in f:
                    fdt = f.create_dataset('/detect', shape=(N,), dtype=int)
                    fdt.attrs['description'] = '# of auroral detections this frame'

                f['/detect'][i] = det[i]

            if 'params' not in f:
                cparam = np.array((
                    P['kineticsec'],
                    P['rotccw'],
                    P['transpose'],
                    P['flipud'],
                    P['fliplr'],
                    1),
                    dtype=[('kineticsec', 'f8'),
                           ('rotccw', 'i1'),
                           ('transpose', 'i1'),
                           ('flipud', 'i1'),
                           ('fliplr', 'i1'),
                           ('questionable_ut1', 'i1')]
                )

                # cannot use fletcher32 here, typeerror
                f.create_dataset('/params', data=cparam)

            if 'sensorloc' not in f and 'sensorloc' in P:
                loc = P['sensorloc']
                lparam = np.array((loc[0], loc[1], loc[2]),
                                  dtype=[('lat', 'f8'), ('lon', 'f8'), ('alt_m', 'f8')])

                # cannot use fletcher32 here, typeerror
                Ld = f.create_dataset('/sensorloc', data=lparam)
                Ld.attrs['units'] = 'WGS-84 lat (deg),lon (deg), altitude (meters)'

            if 'cmdlog' not in f:
                if isinstance(cmdlog, (tuple, list)):
                    cmdlog = ' '.join(cmdlog)
                # cannot use fletcher32 here, typeerror
                f['/cmdlog'] = str(cmdlog)

            if 'header' not in f and 'header' in P:
                f['/header'] = str(P['header'])

            if 'hdf5version' not in f:
                f['/hdf5version'] = h5py.version.hdf5_version_tuple

    elif outfn.suffix == '.fits':
        from astropy.io import fits
        # NOTE the with... syntax does NOT yet work with astropy.io.fits
        hdu = fits.PrimaryHDU(data)
        hdu.writeto(outfn, clobber=False, checksum=True)
        # no close
        """
        Note: the orientation of this FITS in NASA FV program and the preview
        image shown in Python should/must have the same orientation and pixel indexing')
        """

    elif outfn.suffix == '.mat':
        from scipy.io import savemat
        # matlab is fortran order
        matdata = {'imgdata': data.transpose(1, 2, 0)}
        savemat(outfn, matdata, oned_as='column')
    else:
        raise ValueError(f'what kind of file is {outfn}')
1246534
def _write_script(self, script_name, ref, qry, outfile):
        ''''''
        f = pyfastaq.utils.open_file_write(script_name)
        print(self._nucmer_command(ref, qry, 'p'), file=f)
        print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f)
        print(self._show_coords_command('p.delta.filter', outfile), file=f)
        if self.show_snps:
            print(self._show_snps_command('p.delta.filter', outfile + '.snps'), file=f)
        pyfastaq.utils.close(f)
398631
def writeShiftFile(self, filename="shifts.txt"):
        
        lines = ['# frame: ', self['frame'], '\n',
                 '# refimage: ', self['refimage'], '\n',
                 '# form: ', self['form'], '\n',
                 '# units: ', self['units'], '\n']

        for o in self['order']:
            ss = " "
            for shift in self[o]:
                ss += str(shift) + " "
            line = str(o) + ss + "\n"
            lines.append(line)

        fshifts= open(filename, 'w')
        fshifts.writelines(lines)
        fshifts.close()
1072414
def write(tsdict, outfile, start=None, end=None, name='gwpy', run=0,
          compression=257, compression_level=6):
    
    # set frame header metadata
    if not start:
        starts = {LIGOTimeGPS(tsdict[key].x0.value) for key in tsdict}
        if len(starts) != 1:
            raise RuntimeError("Cannot write multiple TimeSeries to a single "
                               "frame with different start times, "
                               "please write into different frames")
        start = list(starts)[0]
    if not end:
        ends = {tsdict[key].span[1] for key in tsdict}
        if len(ends) != 1:
            raise RuntimeError("Cannot write multiple TimeSeries to a single "
                               "frame with different end times, "
                               "please write into different frames")
        end = list(ends)[0]
    duration = end - start
    start = LIGOTimeGPS(start)
    ifos = {ts.channel.ifo for ts in tsdict.values() if
            ts.channel and ts.channel.ifo and
            hasattr(frameCPP, 'DETECTOR_LOCATION_{0}'.format(ts.channel.ifo))}

    # create frame
    frame = io_gwf.create_frame(time=start, duration=duration, name=name,
                                run=run, ifos=ifos)

    # append channels
    for i, key in enumerate(tsdict):
        try:
            # pylint: disable=protected-access
            ctype = tsdict[key].channel._ctype or 'proc'
        except AttributeError:
            ctype = 'proc'
        append_to_frame(frame, tsdict[key].crop(start, end),
                        type=ctype, channelid=i)

    # write frame to file
    io_gwf.write_frames(outfile, [frame], compression=compression,
                        compression_level=compression_level)
699584
def _write_newname_file(in_file, out_file, mappings):
    
    with utils.open_gzipsafe(in_file) as in_handle:
        with open(out_file, "w") as out_handle:
            for line in in_handle:
                if line.startswith("#"):
                    out_handle.write(line)
                else:
                    parts = line.split("\t")
                    new_contig = mappings.get(parts[0])
                    if new_contig:
                        parts[0] = new_contig
                        out_handle.write("\t".join(parts))
416413
def write(filename, mesh, add_global_ids=True):
    
    import h5py

    f = h5py.File(filename, "w")

    tstt = f.create_group("tstt")

    # The base index for h5m is 1.
    global_id = 1

    # add nodes
    nodes = tstt.create_group("nodes")
    coords = nodes.create_dataset("coordinates", data=mesh.points)
    coords.attrs.create("start_id", global_id)
    global_id += len(mesh.points)

    # Global tags
    tstt_tags = tstt.create_group("tags")

    # The GLOBAL_ID associated with a point is used to identify points if
    # distributed across several processes. mbpart automatically adds them,
    # too.
    # Copy to pd to avoid changing point_data. The items are not deep-copied.
    pd = mesh.point_data.copy()
    if "GLOBAL_ID" not in pd and add_global_ids:
        pd["GLOBAL_ID"] = numpy.arange(1, len(mesh.points) + 1)

    # add point data
    if pd:
        tags = nodes.create_group("tags")
    for key, data in pd.items():
        if len(data.shape) == 1:
            dtype = data.dtype
            tags.create_dataset(key, data=data)
        else:
            # H5M doesn't accept n-x-k arrays as data; it wants an n-x-1
            # array with k-tuples as entries.
            n, k = data.shape
            dtype = numpy.dtype((data.dtype, (k,)))
            dset = tags.create_dataset(key, (n,), dtype=dtype)
            dset[:] = data

        # Create entry in global tags
        g = tstt_tags.create_group(key)
        g["type"] = dtype
        # Add a class tag:
        # From
        # <http://lists.mcs.anl.gov/pipermail/moab-dev/2015/007104.html>:
        # ```
        # /* Was dense tag data in mesh database */
        #  define mhdf_DENSE_TYPE   2
        # /** \brief Was sparse tag data in mesh database */
        # #define mhdf_SPARSE_TYPE  1
        # /** \brief Was bit-field tag data in mesh database */
        # #define mhdf_BIT_TYPE     0
        # /** \brief Unused */
        # #define mhdf_MESH_TYPE    3
        #
        g.attrs["class"] = 2

    # add elements
    elements = tstt.create_group("elements")

    elem_dt = h5py.special_dtype(
        enum=(
            "i",
            {
                "Edge": 1,
                "Tri": 2,
                "Quad": 3,
                "Polygon": 4,
                "Tet": 5,
                "Pyramid": 6,
                "Prism": 7,
                "Knife": 8,
                "Hex": 9,
                "Polyhedron": 10,
            },
        )
    )

    tstt["elemtypes"] = elem_dt

    tstt.create_dataset(
        "history",
        data=[
            __name__.encode("utf-8"),
            __about__.__version__.encode("utf-8"),
            str(datetime.now()).encode("utf-8"),
        ],
    )

    # number of nodes to h5m name, element type
    meshio_to_h5m_type = {
        "line": {"name": "Edge2", "type": 1},
        "triangle": {"name": "Tri3", "type": 2},
        "tetra": {"name": "Tet4", "type": 5},
    }
    for key, data in mesh.cells.items():
        if key not in meshio_to_h5m_type:
            logging.warning("Unsupported H5M element type '%s'. Skipping.", key)
            continue
        this_type = meshio_to_h5m_type[key]
        elem_group = elements.create_group(this_type["name"])
        elem_group.attrs.create("element_type", this_type["type"], dtype=elem_dt)
        # h5m node indices are 1-based
        conn = elem_group.create_dataset("connectivity", data=(data + 1))
        conn.attrs.create("start_id", global_id)
        global_id += len(data)

    # add cell data
    if mesh.cell_data:
        tags = elem_group.create_group("tags")
        for key, value in mesh.cell_data.items():
            tags.create_dataset(key, data=value)

    # add empty set -- MOAB wants this
    sets = tstt.create_group("sets")
    sets.create_group("tags")

    # set max_id
    tstt.attrs.create("max_id", global_id, dtype="u8")
    return
54259
def dict_to_hdf5(dict_like, h5group):
    
    # Write attributes
    for key, value in dict_like.items():
        if value is not None:
            h5group.attrs[str(key)] = value
58427
def writevrt(out_csv,srs='EPSG:4326',x='field_1',y='field_2'):
    
    out_vrt = os.path.splitext(out_csv)[0]+'.vrt'
    out_csv = os.path.split(out_csv)[-1]
    f = open(out_vrt, 'w')
    f.write('<OGRVRTDataSource>\n')
    f.write('   <OGRVRTLayer name="%s">\n' % os.path.splitext(out_csv)[0])
    f.write('        <SrcDataSource>%s</SrcDataSource>\n' % out_csv)
    f.write('        <GeometryType>wkbPoint</GeometryType>\n')
    f.write('        <LayerSRS>%s</LayerSRS>\n' % srs)
    f.write('        <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>\n' % (x, y))
    f.write('    </OGRVRTLayer>\n')
    f.write('</OGRVRTDataSource>\n')
    f.close()