コード例 #1
0
ファイル: correlationNsplice.py プロジェクト: narunbabu/Loggy
def las_export(spliced_logs, lognames, file_w_path):
    import lasio
    params = np.load(params_file_path)
    las = lasio.LASFile()
    las.add_curve('DEPT', spliced_logs[:, 0], unit='m')
    param_mnems = np.array([params[i]['mnemonic'] for i in range(len(params))])
    for i, lkey in enumerate(lognames):
        if lkey in param_mnems:
            indx = np.where(param_mnems == lkey)[0][0]
            print('*******************************')
            print(indx)
            las.add_curve(lkey,
                          spliced_logs[:, i + 1],
                          unit=params[indx]['unit'])
        else:
            print(
                'The log {} is not there in params, please add a unit to params, \n Until then this log will have unknown units'
                .format(lkey))
            las.add_curve(lkey, spliced_logs[:, i + 1], unit='UNKWN')
    las.other = 'This las is generated by Laggy, the splicing module developed by Ameyem Geosolutions exclusively for Cairn Vedanta...'
    las.well['NULL'] = lasio.HeaderItem('NULL',
                                        value=-999.25,
                                        descr='NULL VALUE')
    las.well['WELL'] = lasio.HeaderItem('WELL', value='W1', descr='WELL')
    print('Writing to ', file_w_path)
    las.write(file_w_path)
コード例 #2
0
def create_las(curve_df, curves_name, origin, las_units, las_longs, null, filepath):
    las = lasio.LASFile()
    # write the pandas data to the las file
    las.set_data(curve_df)
    # write the curve metadata from our three lists.
    counter = 0
    for x in curves_name:
        las.curves[x].unit = las_units[counter]
        las.curves[x].descr = las_longs[counter]
        counter = counter + 1
    las.well.COMP = origin.company
    las.well.WELL = origin.well_name
    las.well.FLD = origin.field_name
    las.well.SRVC = origin.producer_name
    las.well.DATE = origin.creation_time
    las.well.UWI = origin.well_id
    las.well.API = origin.well_id
    las.well.NULL = null
    las.params['PROD'] = lasio.HeaderItem('PROD', value=origin.product)
    las.params['PROG'] = lasio.HeaderItem('PROG', value=origin.programs)
    las.params['RUN'] = lasio.HeaderItem('RUN', value=origin.run_nr)
    las.params['DESCENT'] = lasio.HeaderItem('DESCENT', value=origin.descent_nr)
    las.params['VERSION'] = lasio.HeaderItem('VERSION', value=origin.version)
    las.params['LINEAGE'] = lasio.HeaderItem('LINEAGE', value="Python-converted from DLIS")
    las.params['ORFILE'] = lasio.HeaderItem('ORFILE', value=filepath)
    return las
コード例 #3
0
    def write_las(self, processed_df: pd.core.frame.DataFrame, source: lasio.las.LASFile, filename: str, location=None) -> None:
        r"""Write LAS file

        Arguments:
            processed_df: Dataframe that needs to be written
            source: LAS file from which headers are copied
            filename: Name of the output file
            location (tuple, optional): Latitude and longitude that is written to the header
        """

        if processed_df.empty:
            #TODO: This needs to be a warning through logging
            print('Input dataframe is empty')
            return 
 
        # Create new LAS file here
        processed_las = lasio.LASFile()

        # Copy the headers that haven't been changed
        for entry in _HEADERS_TO_COPY:
            processed_las.header[entry] = source.header[entry]

        # Insert location information to the header
        if location:
            assert(len(location) == 2)

            latitude = location[0]
            longitude = location[1] 

            processed_las.well['SLAT'] = lasio.HeaderItem('SLAT', unit='WGS84', value=latitude, descr='Surface Latitude')
            processed_las.well['SLON'] = lasio.HeaderItem('SLON', unit='WGS84', value=longitude, descr='Surface Longitude')

        # Insert curves now
        for entry in processed_df.columns:
            if entry == 'DEPT':
                processed_las.add_curve('DEPT', processed_df['DEPT'].values, unit='ft')
            else:
                processed_las.add_curve(entry, processed_df[entry].values)

        processed_las.write(os.path.join(self.output_path, filename), version=2)
コード例 #4
0
    def to_lasio(self, keys=None, basis=None):
        """
        Makes a lasio object from the current well.

        Args:
            basis (ndarray): Optional. The basis to export the curves in. If
                you don't specify one, it will survey all the curves with
                ``survey_basis()``.
            keys (list): List of strings: the keys of the data items to
                include, if not all of them. You can have nested lists, such
                as you might use for ``tracks`` in ``well.plot()``.

        Returns:
            lasio. The lasio object.
        """

        # Create an empty lasio object.
        l = lasio.LASFile()
        l.well.DATE = str(datetime.datetime.today())

        # Deal with header.
        for obj, dic in LAS_FIELDS.items():
            if obj == 'data':
                continue
            for attr, (sect, item) in dic.items():
                value = getattr(getattr(self, obj), attr, None)
                try:
                    getattr(l, sect)[item].value = value
                except:
                    h = lasio.HeaderItem(item, "", value, "")
                    getattr(l, sect)[item] = h

        # Clear curves from header portion.
        l.header['Curves'] = []

        # Add a depth basis.
        if basis is None:
            basis = self.survey_basis(keys=keys)
        try:
            l.add_curve('DEPT', basis)
        except:
            raise Exception("Please provide a depth basis.")

        # Add meta from basis.
        setattr(l.well, 'STRT', basis[0])
        setattr(l.well, 'STOP', basis[-1])
        setattr(l.well, 'STEP', basis[1] - basis[0])

        # Add data entities.
        other = ''

        if keys is None:
            keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
        else:
            keys = utils.flatten_list(keys)

        for k in keys:
            d = self.data[k]
            if getattr(d, 'null', None) is not None:
                d[np.isnan(d)] = d.null
            try:
                new_data = np.copy(d.to_basis_like(basis))
            except:
                # Basis shift failed; is probably not a curve
                pass
            try:
                descr = getattr(d, 'description', '')
                l.add_curve(k.upper(), new_data, unit=d.units, descr=descr)
            except:
                try:
                    # Treat as OTHER
                    other += "{}\n".format(k.upper()) + d.to_csv()
                except:
                    pass

        # Write OTHER, if any.
        if other:
            l.other = other

        return l
コード例 #5
0
def convert_dlis_to_las(filepath, output_folder_location, null=-999.25):
    filename = os.path.basename(filepath)
    filename = os.path.splitext(filename)[0]
    embedded_files = []
    origins = []
    frame_count = 0

    def df_column_uniquify(df):
        df_columns = df.columns
        new_columns = []
        for item in df_columns:
            counter = 0
            newitem = item
            while newitem in new_columns:
                counter += 1
                newitem = "{}_{}".format(item, counter)
            new_columns.append(newitem)
        df.columns = new_columns
        return df

    with dlisio.load(filepath) as file:
        print(file.describe())
        for d in file:
            embedded_files.append(d)
            frame_count = 0
            for origin in d.origins:
                origins.append(origin)
            for fram in d.frames:
                curves_name = []
                longs = []
                unit = []
                curves_L = []
                frame_count = frame_count + 1
                for channel in fram.channels:
                    curves_name.append(channel.name)
                    longs.append(channel.long_name)
                    unit.append(channel.units)
                    curves = channel.curves()
                    curves_L.append(curves)
                name_index = 0
                las = lasio.LASFile()
                curve_df = pd.DataFrame()
                las_units = []
                las_longs = []
                for c in curves_L:
                    name = curves_name[name_index]
                    print("Processing " + name)
                    units = unit[name_index]
                    long = longs[name_index]
                    c = np.vstack(c)
                    try:
                        num_col = c.shape[1]
                        col_name = [name] * num_col
                        df = pd.DataFrame(data=c, columns=col_name)
                        curve_df = pd.concat([curve_df, df], axis=1)
                        name_index = name_index + 1
                        object_warning = str(
                            name
                        ) + ' had to be expanded in the final .las file, as it has multiple samples per index'
                    except:
                        num_col = 1
                        df = pd.DataFrame(data=c, columns=[name])
                        name_index = name_index + 1
                        curve_df = pd.concat([curve_df, df], axis=1)
                        continue
                    u = [units] * num_col
                    l = [long] * num_col
                    las_units.append(u)
                    las_longs.append(l)
                    print("Completed " + name)
                las_units = [item for sublist in las_units for item in sublist]
                las_longs = [item for sublist in las_longs for item in sublist]

                # Check that the lists are ready for the curve metadata
                print("If these are different lengths, something is wrong:")
                print(len(las_units))
                print(len(las_longs))
                curve_df = df_column_uniquify(curve_df)
                curves_name = list(curve_df.columns.values)
                print(len(curves_name))

                # we will take the first curve in the frame as the index.
                curve_df = curve_df.set_index(curves_name[0])
                # write the pandas data to the las file
                las.set_data(curve_df)
                # write the curve metadata from our three lists.
                counter = 0
                for x in curves_name:
                    las.curves[x].unit = las_units[counter]
                    las.curves[x].descr = las_longs[counter]
                    counter = counter + 1
                las.well.COMP = origin.company
                las.well.WELL = origin.well_name
                las.well.FLD = origin.field_name
                las.well.SRVC = origin.producer_name
                las.well.DATE = origin.creation_time
                las.well.UWI = origin.well_id
                las.well.API = origin.well_id
                las.well.NULL = null
                las.params['PROD'] = lasio.HeaderItem('PROD',
                                                      value=origin.product)
                las.params['PROG'] = lasio.HeaderItem('PROG',
                                                      value=origin.programs)
                las.params['RUN'] = lasio.HeaderItem('RUN',
                                                     value=origin.run_nr)
                las.params['DESCENT'] = lasio.HeaderItem(
                    'DESCENT', value=origin.descent_nr)
                las.params['VERSION'] = lasio.HeaderItem('VERSION',
                                                         value=origin.version)
                las.params['LINEAGE'] = lasio.HeaderItem(
                    'LINEAGE', value="Python-converted from DLIS")
                las.params['ORFILE'] = lasio.HeaderItem('ORFILE',
                                                        value=filepath)

                # -----------------------------------------------------------------------
                # Write file
                # -----------------------------------------------------------------------
                outfile = filename + "_" + "converted_with_python_" + str(
                    frame_count) + ".las"
                outpath = os.path.join(output_folder_location, outfile)

                if not os.path.exists(output_folder_location):
                    print("Making output directory: [{}]\n".format(
                        output_folder_location))
                    os.makedirs(output_folder_location)

                print("Writing: [{}]\n".format(outpath))
                las.write(outpath, version=2)

            print("number of frames: " + str(frame_count) +
                  ": this is the number of .las files created")
            print("embedded_files: " + str(len(embedded_files)))
            print("This file has " + str(len(origins)) +
                  " metadata headers.  This code has used the first.")
            print(object_warning)
コード例 #6
0
ファイル: las_writer.py プロジェクト: dongzexuan/spark_demo
def spliced_las_writer(CORRECTED_LAS_NAME, single_well):

    ##############################################################
    # INSTANTIATE A NEW .LAS FILE OBJECT
    ##############################################################
    las = lasio.LASFile()

    ##############################################################
    # ADD CUSTOM COMMENTS...
    # TODO: The interpolation and printing of custom comments / labels does not quite work yet.
    ##############################################################
    las.sections.update({
        "Comments_1": "",
        "Comments_2": "",
        "Comments_3": "",
        "Comments_4": "",
        "Comments_5": ""
    })
    key_order = ("Comments_1", "Version", "Comments_2", "Well", "Comments_3",
                 "Curves", "Comments_4", "Parameter", "Comments_5", "Other")
    las.sections = dict((k, las.sections[k]) for k in key_order)
    # print(las.sections.keys())

    # Comments_1
    line1 = f"" + "\n"
    line2 = f"# LAS WORX (tm) v17.01.12" + "\n"
    line3 = f"# Original File Owner: ANADARKO" + "\n"
    line4 = f"" + "\n"
    # ~Version ---------------------------------------------------

    # Comments_2
    line5 = f"" + "\n"
    line6 = f"# MNEM UNIT        VALUE/NAME              DESCRIPTION    " + "\n"
    line7 = f"# ---- ---- -------------------------   ------------------" + "\n"
    line8 = f"" + "\n"
    # ~Well ------------------------------------------------------

    # Comments_3
    line9 = f"" + "\n"
    line10 = f"# MNEM UNIT API CODES               DESCRIPTION          " + "\n"
    line11 = f"# ---- ---- ---------   ---------------------------------" + "\n"
    line12 = f"" + "\n"
    # ~Curves ----------------------------------------------------

    # Comments_4
    line13 = f"" + "\n"
    line14 = f"# MNEM UNIT       VALUE/NAME              DESCRIPTION    " + "\n"
    line15 = f"# ---- ---- -----------------------   -------------------" + "\n"
    line16 = f"" + "\n"

    # Comments_5
    # Headers / labels for the curve data should go here.

    ##############################################################
    # SET ALL HEADERS AND DATA
    ##############################################################
    las.sections["Comments_1"] = line1 + line2 + line3 + line4
    # ~Version ---------------------------------------------------
    las.version["VERS"] = lasio.HeaderItem("VERS", value="2.0")
    las.version["WRAP"] = lasio.HeaderItem("WRAP", value="NO")

    las.sections["Comments_2"] = line5 + line6 + line7 + line8
    # ~Well ------------------------------------------------------

    las.well["STRT"] = lasio.HeaderItem(mnemonic="STRT",
                                        value=single_well.top_depth,
                                        descr="START DEPTH")
    las.well["STOP"] = lasio.HeaderItem(mnemonic="STOP",
                                        value=single_well.bottom_depth,
                                        descr="STOP DEPTH")
    las.well["STEP"] = lasio.HeaderItem(mnemonic="STEP",
                                        value=single_well.step,
                                        descr="STEP")

    las.well["CNTY"] = lasio.HeaderItem(mnemonic="CNTY",
                                        value=single_well.county,
                                        descr="COUNTY")
    las.well["SRVC"] = lasio.HeaderItem(mnemonic="SRVC",
                                        value=single_well.logging_contractor,
                                        descr="SERVICE COMPANY")
    las.well["UWI"] = lasio.HeaderItem(mnemonic="UWI",
                                       value=single_well.uwi,
                                       descr="UNIQUE WELL ID")
    las.well["WELL"] = lasio.HeaderItem(mnemonic="WELL",
                                        value=single_well.wellname,
                                        descr="WELL NAME")

    # Adding add'l headers via attribute dot method will not work; must use
    # item-style access...
    las.well["LAT"] = lasio.HeaderItem(mnemonic="LAT",
                                       value=single_well.lat,
                                       descr="LATITUDE")
    las.well["LON"] = lasio.HeaderItem(mnemonic="LON",
                                       value=single_well.lon,
                                       descr="LONGITUDE")

    # Adding header for NULL values
    las.well["NULL"] = lasio.HeaderItem(mnemonic="NULL",
                                        value=ls_config.MISSING,
                                        descr="NULL VALUE")

    las.sections["Comments_3"] = line9 + line10 + line11 + line12
    # ~Curves ----------------------------------------------------
    # Curve description
    single_well.data.columns = single_well.data.columns.map(str.upper)
    col_names = single_well.data.columns.tolist()
    las.curves["DEPT"] = lasio.HeaderItem(mnemonic="DEPT", descr="Depth")
    for col_name in col_names:
        if col_name in ls_config.CURVE_DESC.keys():
            las.curves[col_name] = lasio.HeaderItem(
                mnemonic=col_name, descr=ls_config.CURVE_DESC[col_name])
        else:
            las.curves[col_name] = lasio.HeaderItem(mnemonic=col_name,
                                                    descr="")

    las.sections["Comments_4"] = line13 + line14 + line15 + line16
    # ~Params ----------------------------------------------------

    # las.params['BHT'] = lasio.HeaderItem(
    #     mnemonic='BHT',
    #     value=single_well.bottom_hole_pressure,
    #     descr='BOTTOM HOLE TEMPERATURE')
    # las.params['BS'] = lasio.HeaderItem(
    #     mnemonic='BS',
    #     value=single_well.bit_size,
    #     descr='BIT SIZE')
    las.params["LCNM"] = lasio.HeaderItem(mnemonic="LCNM",
                                          value=single_well.logging_contractor,
                                          descr="LOGGING CONTRACTOR")
    # las.params['RMF'] = lasio.HeaderItem(
    #     mnemonic='RMF',
    #     value= single_well.mud_filtrate_resistivity,
    #     descr='MUD FILTRATE RESISTIVITY')
    las.params["DFD"] = lasio.HeaderItem(mnemonic="DFD",
                                         value=single_well.mud_density,
                                         descr="DRILL FLUID DENSITY")
    las.params["MRT"] = lasio.HeaderItem(mnemonic="MRT",
                                         value=single_well.max_rec_temp,
                                         descr="MAX REC TEMP")
    las.params["RMS"] = lasio.HeaderItem(mnemonic="RMS",
                                         value=single_well.mud_resistivity,
                                         descr="MUD RESISTIVITY")
    las.params["MST"] = lasio.HeaderItem(mnemonic="MST",
                                         value=single_well.mud_temp,
                                         descr="MUD TEMP")
    las.params["MFST"] = lasio.HeaderItem(
        mnemonic="MFST",
        value=single_well.mud_density,
        descr="DRILL FLUID DENSITY")  # mud_density TWICE??

    names = las.curves.keys()

    # ~Other -----------------------------------------------------
    # ~ASCII -----------------------------------------------------
    # single_well.data = single_well.data[names].set_index('DEPT')
    las.set_data(single_well.data, names=names)

    ##############################################################
    # WRITE ALL HEADERS AND DATA
    ##############################################################
    las.write(CORRECTED_LAS_NAME, version=2, fmt="%.3f")