write an instruction file for a modflow head observation file

    Parameters
    ----------
    hob_file : str
        modflow hob file

    Returns
    -------
    df : pandas.DataFrame
        pandas DataFrame with control file observation information
184208
def modflow_hob_to_instruction_file(hob_file):
    

    hob_df = pd.read_csv(hob_file,delim_whitespace=True,skiprows=1,
                         header=None,names=["simval","obsval","obsnme"])

    hob_df.loc[:,"obsnme"] = hob_df.obsnme.apply(str.lower)
    hob_df.loc[:,"ins_line"] = hob_df.obsnme.apply(lambda x:"l1 !{0:s}!".format(x))
    hob_df.loc[0,"ins_line"] = hob_df.loc[0,"ins_line"].replace('l1','l2')

    ins_file = hob_file + ".ins"
    f_ins = open(ins_file, 'w')
    f_ins.write("pif ~\n")
    f_ins.write(hob_df.loc[:,["ins_line"]].to_string(col_space=0,
                                                     columns=["ins_line"],
                                                     header=False,
                                                     index=False,
                                                     formatters=[SFMT]) + '\n')
    hob_df.loc[:,"weight"] = 1.0
    hob_df.loc[:,"obgnme"] = "obgnme"
    f_ins.close()
    return hob_df
1363843
def create_extraction_file(bim_filename, out_prefix):
    
    o_file = None
    try:
        o_file = open(out_prefix + ".to_extract", "w")
    except IOError:
        raise ProgramError("{}: cannot write file".format(
            out_prefix + ".to_extract"
        ))

    # Reading the BIM file and extracts only the markers on autosome
    autosomes = set(map(str, range(1, 23)))
    nb_markers = 0
    header = dict(zip(["chrom", "name", "cm", "pos", "a1", "a2"], range(6)))
    with open(bim_filename, "r") as i_file:
        for line in i_file:
            row = line.rstrip("\r\n").split()
            if row[header["chrom"]] in autosomes:
                print >>o_file, row[header["name"]]
                nb_markers += 1

    # Closing the file
    o_file.close()

    logger.info("  - {:,d} markers will be used for contamination "
                "estimation".format(nb_markers))
218214
def setup_observations(self):
        
        obs_methods = [self.setup_water_budget_obs,self.setup_hyd,
                       self.setup_smp,self.setup_hob,self.setup_hds,
                       self.setup_sfr_obs]
        obs_types = ["mflist water budget obs","hyd file",
                     "external obs-sim smp files","hob","hds","sfr"]
        self.obs_dfs = {}
        for obs_method, obs_type in zip(obs_methods,obs_types):
            self.log("processing obs type {0}".format(obs_type))
            obs_method()
            self.log("processing obs type {0}".format(obs_type))
468100
def write_file(fname, info):
    """"""
    with open(fname, 'w') as outfile:
        # File header
        outfile.write('# Copyright (c) 2018 MetPy Developers.\n')
        outfile.write('# Distributed under the terms of the BSD 3-Clause License.\n')
        outfile.write('# SPDX-License-Identifier: BSD-3-Clause\n\n')
        outfile.write('# flake8: noqa\n')
        outfile.write('# Generated file -- do not modify\n')

        # Variable descriptions
        outfile.write('descriptions = {')
        outdata = ',\n                '.join('"{name}": "{desc}"'.format(
            **i) for i in info if need_desc(i))
        outfile.write(outdata)
        outfile.write('}\n\n')

        # Now the struct format
        outfile.write('fields = [')
        outdata = ',\n          '.join('({fname}, "{fmt}")'.format(
            fname=field_name(i), **i) for i in info)
        outfile.write(outdata)
        outfile.write(']\n')
330429
def write_modulators_to_project_file(self, tree=None):
        
        if self.project_file is None or not self.modulators:
            return

        if tree is None:
            tree = ET.parse(self.project_file)

        root = tree.getroot()
        root.append(Modulator.modulators_to_xml_tag(self.modulators))

        tree.write(self.project_file)
724954
def create_map_from_file(self, data_filename):
        
        
        op_filename = data_filename + '.rule'
        
        dataset = mod_datatable.DataTable(data_filename, ',')
        dataset.load_to_array()
        l_map = self.generate_map_from_dataset(dataset)
        with open(op_filename, 'w') as f:
            f.write('# rules file autogenerated by mapper.py v0.1\n')
            f.write('filename:source=' + data_filename + '\n')
            f.write('filename:rule=' + op_filename + '\n\n')
            for row in l_map:
                #print('ROW = ' , row)
                if type(row) is str:
                    f.write(row + '\n')
                else:
                    for v in row:
                        f.write(v)
342087
def write(self, output=None):
        
        if not output:
            outfile = self['output']+'_asn.fits'
            output = self['output']
        else:
            outfile = output

        # Delete the file if it exists.
        if os.path.exists(outfile):
            warningmsg =  "\n#########################################\n"
            warningmsg += "#                                       #\n"
            warningmsg += "# WARNING:                              #\n"
            warningmsg += "#  The existing association table,      #\n"
            warningmsg += "           " + str(outfile) + '\n'
            warningmsg += "#  is being replaced.                   #\n"
            warningmsg += "#                                       #\n"
            warningmsg += "#########################################\n\n"
        fasn = fits.HDUList()

        # Compute maximum length of MEMNAME for table column definition
        _maxlen = 0
        for _fname in self['order']:
            if len(_fname) > _maxlen: _maxlen = len(_fname)
        # Enforce a mimimum size of 24
        if _maxlen < 24: _maxlen = 24
        namelen_str = str(_maxlen+2)+'A'
        self.buildPrimary(fasn, output=output)

        mname = self['order'][:]
        mname.append(output)
        mtype = ['EXP-DTH' for l in self['order']]
        mtype.append('PROD-DTH')
        mprsn = [True for l in self['order']]
        mprsn.append(False)
        xoff = [self['members'][l]['xoff'] for l in self['order']]
        xoff.append(0.0)
        yoff = [self['members'][l]['yoff'] for l in self['order']]
        yoff.append(0.0)
        xsh = [self['members'][l]['xshift'] for l in self['order']]
        xsh.append(0.0)
        ysh = [self['members'][l]['yshift'] for l in self['order']]
        ysh.append(0.0)
        rot = [self['members'][l]['rot'] for l in self['order']]
        rot.append(0.0)
        scl = [self['members'][l]['scale'] for l in self['order']]
        scl.append(1.0)

        memname = fits.Column(name='MEMNAME',format=namelen_str,array=N.char.array(mname))
        memtype = fits.Column(name='MEMTYPE',format='14A',array=N.char.array(mtype))
        memprsn = fits.Column(name='MEMPRSNT', format='L', array=N.array(mprsn).astype(N.uint8))
        xoffset = fits.Column(name='XOFFSET', format='E', array=N.array(xoff))
        yoffset = fits.Column(name='YOFFSET', format='E', array=N.array(yoff))
        xdelta = fits.Column(name='XDELTA', format='E', array=N.array(xsh))
        ydelta = fits.Column(name='YDELTA', format='E', array=N.array(ysh))
        rotation = fits.Column(name='ROTATION', format='E', array=N.array(rot))
        scale = fits.Column(name='SCALE', format='E', array=N.array(scl))
        cols = fits.ColDefs([memname,memtype,memprsn,xoffset,yoffset,xdelta,ydelta,rotation,scale])
        hdu = fits.BinTableHDU.from_columns(cols)
        fasn.append(hdu)
        if ASTROPY_VER_GE13:
            fasn.writeto(outfile, overwrite=True)
        else:
            fasn.writeto(outfile, clobber=True)
        fasn.close()
        mem0 = self['order'][0]
        refimg = self['members'][mem0]['refimage']
        if refimg is not None:
            whdu = wcsutil.WCSObject(refimg)
            whdu.createReferenceWCS(outfile,overwrite=False)
            ftab = fits.open(outfile)
            ftab['primary'].header['refimage'] = outfile+"[wcs]"
            ftab.close()
        del whdu
1333945
def _write_crmod_file(filename):
    
    crmod_lines = [
        '***FILES***',
        '../grid/elem.dat',
        '../grid/elec.dat',
        '../rho/rho.dat',
        '../config/config.dat',
        'F                ! potentials ?',
        '../mod/pot/pot.dat',
        'T                ! measurements ?',
        '../mod/volt.dat',
        'F               ! sensitivities ?',
        '../mod/sens/sens.dat',
        'F                ! another dataset ?',
        '1                ! 2D (=0) or 2.5D (=1)',
        'F                ! fictitious sink ?',
        '1660             ! fictitious sink node number',
        'F                ! boundary values ?',
        'boundary.dat',
    ]

    with open(filename, 'w') as fid:
        [fid.write(line + '\n') for line in crmod_lines]
375117
def write_loom(self, filename: PathLike, write_obsm_varm: bool = False):
        
        from .readwrite.write import write_loom
        write_loom(filename, self, write_obsm_varm = write_obsm_varm)
800139
def write_module_file(name, path, package):
    '''
    '''
    file_path = join(path, '%s.rst' % name)
    mod_file = open(file_path, 'w')

    mod_file.write('%s\n' % AUTOGEN)
    mod_file.write('%s\n' % name.title())
    mod_file.write('=' * len(name))
    mod_file.write('\n\n')
    mod_file.write('.. toctree::\n')
    mod_file.write('   :maxdepth: 1\n\n')
    mod_file.write('.. automodule:: %s.%s\n' % (package, name))
    mod_file.write('   :members:\n')
    mod_file.write('   :undoc-members:\n')
    mod_file.write('   :show-inheritance:\n')
1079488
def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
        
        hdu_prim = fits.PrimaryHDU()
        hdu_hpx = self.make_hdu(data, extname=extname)
        hl = [hdu_prim, hdu_hpx]
        if self.conv.energy_hdu == 'EBOUNDS':
            hdu_energy = self.make_energy_bounds_hdu()
        elif self.conv.energy_hdu == 'ENERGIES':
            hdu_energy = self.make_energies_hdu()
        if hdu_energy is not None:
            hl.append(hdu_energy)
        hdulist = fits.HDUList(hl)
        hdulist.writeto(outfile, overwrite=clobber)
959027
def write_header(self):
        
        self.fileobj.seek(0)
        header = mar_header.build(dict(index_offset=self.last_offset))
        self.fileobj.write(header)
572968
def write_bus_data(self, file):
        
        report = CaseReport(self.case)
        buses = self.case.buses

        col_width = 8
        col_width_2 = col_width * 2 + 1
        col1_width = 6

        sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"

        file.write(sep)
        # Line one of column headers
        file.write("Name".center(col1_width) + " ")
        file.write("Voltage (pu)".center(col_width_2) + " ")
        file.write("Generation".center(col_width_2) + " ")
        file.write("Load".center(col_width_2) + " ")
        file.write("\n")

        file.write("-" * col1_width +" "+ ("-" * col_width_2 + " ") * 3 + "\n")

        # Line two of column header
        file.write("..".ljust(col1_width) + " ")
        file.write("Amp".center(col_width) + " ")
        file.write("Phase".center(col_width) + " ")
        file.write("P (MW)".center(col_width) + " ")
        file.write("Q (MVAr)".center(col_width) + " ")
        file.write("P (MW)".center(col_width) + " ")
        file.write("Q (MVAr)".center(col_width) + " ")
        file.write("\n")

        file.write(sep)

        # Bus rows
        for bus in buses:
            file.write(bus.name[:col1_width].ljust(col1_width))
            file.write(" %8.3f" % bus.v_magnitude)
            file.write(" %8.3f" % bus.v_angle)
            file.write(" %8.2f" % self.case.s_supply(bus).real)
            file.write(" %8.2f" % self.case.s_supply(bus).imag)
            file.write(" %8.2f" % self.case.s_demand(bus).real)
            file.write(" %8.2f" % self.case.s_demand(bus).imag)
            file.write("\n")

        # Totals
#        file.write("..".ljust(col1_width) + " ")
#        file.write(("..".ljust(col_width) + " ")*2)
#        file.write(("_"*col_width + " ")*4 + "\n")
        file.write("..".ljust(col1_width) + " " + "..".ljust(col_width) + " ")
        file.write("*Total:*".rjust(col_width) + " ")
        ptot = report.actual_pgen
        qtot = report.actual_qgen
        file.write("%8.2f " % ptot)
        file.write("%8.2f " % qtot)
        file.write("%8.2f " % report.p_demand)
        file.write("%8.2f " % report.q_demand)
        file.write("\n")
        file.write(sep)
        del report
474580
def write_recording(recording, save_path):
        '''
        
        '''
        assert HAVE_MREX, "To use the MEArec extractors, install MEArec: \n\n pip install MEArec\n\n"
        save_path = Path(save_path)
        if save_path.is_dir():
            print("The file will be saved as recording.h5 in the provided folder")
            save_path = save_path / 'recording.h5'
        if save_path.suffix == '.h5' or save_path.suffix == '.hdf5':
            info = {'recordings': {'fs': recording.get_sampling_frequency()}}
            rec_dict = {'recordings': recording.get_traces()}
            if 'location' in recording.get_channel_property_names():
                positions = np.array([recording.get_channel_property(chan, 'location')
                                      for chan in recording.get_channel_ids()])
                rec_dict['channel_positions'] = positions
            recgen = mr.RecordingGenerator(rec_dict=rec_dict, info=info)
            mr.save_recording_generator(recgen, str(save_path), verbose=False)
        else:
            raise Exception("Provide a folder or an .h5/.hdf5 as 'save_path'")
31844
def WriteGoogleTransitFeed(self, file):
    
    # Compression type given when adding each file
    archive = zipfile.ZipFile(file, 'w')

    if 'agency' in self._table_columns:
      agency_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(agency_string)
      columns = self.GetTableColumns('agency')
      writer.writerow(columns)
      for a in self._agencies.values():
        writer.writerow([util.EncodeUnicode(a[c]) for c in columns])
      self._WriteArchiveString(archive, 'agency.txt', agency_string)


    if 'feed_info' in self._table_columns:
      feed_info_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(feed_info_string)
      columns = self.GetTableColumns('feed_info')
      writer.writerow(columns)
      writer.writerow([util.EncodeUnicode(self.feed_info[c]) for c in columns])
      self._WriteArchiveString(archive, 'feed_info.txt', feed_info_string)

    calendar_dates_string = StringIO.StringIO()
    writer = util.CsvUnicodeWriter(calendar_dates_string)
    writer.writerow(
        self._gtfs_factory.ServicePeriod._FIELD_NAMES_CALENDAR_DATES)
    has_data = False
    for period in self.service_periods.values():
      for row in period.GenerateCalendarDatesFieldValuesTuples():
        has_data = True
        writer.writerow(row)
    wrote_calendar_dates = False
    if has_data:
      wrote_calendar_dates = True
      self._WriteArchiveString(archive, 'calendar_dates.txt',
                               calendar_dates_string)

    calendar_string = StringIO.StringIO()
    writer = util.CsvUnicodeWriter(calendar_string)
    writer.writerow(self._gtfs_factory.ServicePeriod._FIELD_NAMES)
    has_data = False
    for s in self.service_periods.values():
      row = s.GetCalendarFieldValuesTuple()
      if row:
        has_data = True
        writer.writerow(row)
    if has_data or not wrote_calendar_dates:
      self._WriteArchiveString(archive, 'calendar.txt', calendar_string)

    if 'stops' in self._table_columns:
      stop_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(stop_string)
      columns = self.GetTableColumns('stops')
      writer.writerow(columns)
      for s in self.stops.values():
        writer.writerow([util.EncodeUnicode(s[c]) for c in columns])
      self._WriteArchiveString(archive, 'stops.txt', stop_string)

    if 'routes' in self._table_columns:
      route_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(route_string)
      columns = self.GetTableColumns('routes')
      writer.writerow(columns)
      for r in self.routes.values():
        writer.writerow([util.EncodeUnicode(r[c]) for c in columns])
      self._WriteArchiveString(archive, 'routes.txt', route_string)

    if 'trips' in self._table_columns:
      trips_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(trips_string)
      columns = self.GetTableColumns('trips')
      writer.writerow(columns)
      for t in self.trips.values():
        writer.writerow([util.EncodeUnicode(t[c]) for c in columns])
      self._WriteArchiveString(archive, 'trips.txt', trips_string)

    # write frequencies.txt (if applicable)
    headway_rows = []
    for trip in self.GetTripList():
      headway_rows += trip.GetFrequencyOutputTuples()
    if headway_rows:
      headway_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(headway_string)
      writer.writerow(self._gtfs_factory.Frequency._FIELD_NAMES)
      writer.writerows(headway_rows)
      self._WriteArchiveString(archive, 'frequencies.txt', headway_string)

    # write fares (if applicable)
    if self.GetFareAttributeList():
      fare_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(fare_string)
      writer.writerow(self._gtfs_factory.FareAttribute._FIELD_NAMES)
      writer.writerows(
          f.GetFieldValuesTuple() for f in self.GetFareAttributeList())
      self._WriteArchiveString(archive, 'fare_attributes.txt', fare_string)

    # write fare rules (if applicable)
    rule_rows = []
    for fare in self.GetFareAttributeList():
      for rule in fare.GetFareRuleList():
        rule_rows.append(rule.GetFieldValuesTuple())
    if rule_rows:
      rule_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(rule_string)
      writer.writerow(self._gtfs_factory.FareRule._FIELD_NAMES)
      writer.writerows(rule_rows)
      self._WriteArchiveString(archive, 'fare_rules.txt', rule_string)
    stop_times_string = StringIO.StringIO()
    writer = util.CsvUnicodeWriter(stop_times_string)
    writer.writerow(self._gtfs_factory.StopTime._FIELD_NAMES)
    for t in self.trips.values():
      writer.writerows(t._GenerateStopTimesTuples())
    self._WriteArchiveString(archive, 'stop_times.txt', stop_times_string)

    # write shapes (if applicable)
    shape_rows = []
    for shape in self.GetShapeList():
      seq = 1
      for (lat, lon, dist) in shape.points:
        shape_rows.append((shape.shape_id, lat, lon, seq, dist))
        seq += 1
    if shape_rows:
      shape_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(shape_string)
      writer.writerow(self._gtfs_factory.Shape._FIELD_NAMES)
      writer.writerows(shape_rows)
      self._WriteArchiveString(archive, 'shapes.txt', shape_string)

    if 'transfers' in self._table_columns:
      transfer_string = StringIO.StringIO()
      writer = util.CsvUnicodeWriter(transfer_string)
      columns = self.GetTableColumns('transfers')
      writer.writerow(columns)
      for t in self.GetTransferIter():
        writer.writerow([util.EncodeUnicode(t[c]) for c in columns])
      self._WriteArchiveString(archive, 'transfers.txt', transfer_string)

    archive.close()
967761
def write_moc_fits_hdu(moc):
    

    # Ensure data are normalized.
    moc.normalize()

    # Determine whether a 32 or 64 bit column is required.
    if moc.order < 14:
        moc_type = np.int32
        col_type = 'J'
    else:
        moc_type = np.int64
        col_type = 'K'

    # Convert to the NUNIQ value which guarantees that one of the
    # top two bits is set so that the order of the value can be
    # determined.
    nuniq = []
    for (order, cells) in moc:
        uniq_prefix = 4 * (4 ** order)
        for npix in cells:
            nuniq.append(npix + uniq_prefix)

    # Prepare the data, and sort into numerical order.
    nuniq = np.array(nuniq, dtype=moc_type)
    nuniq.sort()

    # Create the FITS file.
    col = fits.Column(name='UNIQ', format=col_type, array=nuniq)

    cols = fits.ColDefs([col])
    rec = fits.FITS_rec.from_columns(cols)
    tbhdu = fits.BinTableHDU(rec)

    # Mandatory Keywords.
    tbhdu.header['PIXTYPE'] = 'HEALPIX'
    tbhdu.header['ORDERING'] = 'NUNIQ'
    tbhdu.header['COORDSYS'] = 'C'
    tbhdu.header['MOCORDER'] = moc.order
    tbhdu.header.comments['PIXTYPE'] = 'HEALPix magic code'
    tbhdu.header.comments['ORDERING'] = 'NUNIQ coding method'
    tbhdu.header.comments['COORDSYS'] = 'ICRS reference frame'
    tbhdu.header.comments['MOCORDER'] = 'MOC resolution (best order)'

    # Optional Keywords.
    tbhdu.header['MOCTOOL'] = 'PyMOC ' + version
    tbhdu.header.comments['MOCTOOL'] = 'Name of MOC generator'
    if moc.type is not None:
        tbhdu.header['MOCTYPE'] = moc.type
        tbhdu.header.comments['MOCTYPE'] = 'Source type (IMAGE or CATALOG)'
    if moc.id is not None:
        tbhdu.header['MOCID'] = moc.id
        tbhdu.header.comments['MOCID'] = 'Identifier of the collection'
    if moc.origin is not None:
        tbhdu.header['ORIGIN'] = moc.origin
        tbhdu.header.comments['ORIGIN'] = 'MOC origin'
    tbhdu.header['DATE'] = datetime.utcnow().replace(
        microsecond=0).isoformat()
    tbhdu.header.comments['DATE'] = 'MOC creation date'
    if moc.name is not None:
        tbhdu.header['EXTNAME'] = moc.name
        tbhdu.header.comments['EXTNAME'] = 'MOC name'

    return tbhdu
730038
def write_bus_data(self, file):
        
        writer = self._get_writer(file)
        writer.writerow(BUS_ATTRS)
        for bus in self.case.buses:
            writer.writerow([getattr(bus, attr) for attr in BUS_ATTRS])