Docstrings for the lasio package

Reading LAS files

lasio.read(file_ref, **kwargs)[source]

Read a LAS file.

Note that only versions 1.2 and 2.0 of the LAS file specification are currently supported.

Parameters:file_ref (file-like object, str) – either a filename, an open file object, or a string containing the contents of a file.
Returns:a lasio.LASFile object representing the file – see above

There are a number of optional keyword arguments that can be passed to this function that control how the LAS file is opened and parsed. Any of the keyword arguments from the below functions can be used here:

  • lasio.reader.open_with_codecs() - manage issues relate to character encodings
  • lasio.las.LASFile.read() - control how NULL values and errors are handled during parsing
class lasio.LASFile(file_ref=None, **read_kwargs)[source]

LAS file object.

Keyword Arguments:
 file_ref (file-like object, str) – either a filename, an open file object, or a string containing the contents of a file.

See these routines for additional keyword arguments you can use when reading in a LAS file:

encoding

the character encoding used when reading the file in from disk

Type:str or None
LASFile.read(file_ref, ignore_data=False, read_policy='default', null_policy='strict', ignore_header_errors=False, ignore_comments=('#', ), mnemonic_case='upper', index_unit=None, remove_data_line_filter='#', **kwargs)[source]

Read a LAS file.

Parameters:

file_ref (file-like object, str) – either a filename, an open file object, or a string containing the contents of a file.

Keyword Arguments:
 
  • null_policy (str or list) – see http://lasio.readthedocs.io/en/latest/data-section.html#handling-invalid-data-indicators-automatically
  • ignore_data (bool) – if True, do not read in any of the actual data, just the header metadata. False by default.
  • ignore_header_errors (bool) – ignore LASHeaderErrors (False by default)
  • ignore_comments (tuple/str) – ignore comments beginning with characters e.g. ("#", '"') in header sections
  • mnemonic_case (str) – ‘preserve’: keep the case of HeaderItem mnemonics ‘upper’: convert all HeaderItem mnemonics to uppercase ‘lower’: convert all HeaderItem mnemonics to lowercase
  • index_unit (str) – Optionally force-set the index curve’s unit to “m” or “ft”
  • remove_data_line_filter (str, func) – string or function for removing/ignoring lines in the data section e.g. a function which accepts a string (a line from the data section) and returns either True (do not parse the line) or False (parse the line). If this argument is a string it will instead be converted to a function which rejects all lines starting with that value e.g. "#" will be converted to lambda line: line.strip().startswith("#")

See lasio.reader.open_with_codecs() for additional keyword arguments which help to manage issues relate to character encodings.

lasio.open_file(file_ref, **encoding_kwargs)[source]

Open a file if necessary.

If autodetect_encoding=True then either cchardet or chardet needs to be installed, or else an ImportError will be raised.

Parameters:file_ref (file-like object, str) – either a filename, an open file object, or a string containing the contents of a file.

See lasio.reader.open_with_codecs() for keyword arguments that can be used here.

Returns:tuple of an open file-like object, and the encoding that was used to decode it (if it were read from disk).
lasio.reader.open_with_codecs(filename, encoding=None, encoding_errors='replace', autodetect_encoding=True, autodetect_encoding_chars=4000)[source]

Read Unicode data from file.

Parameters:

filename (str) – path to file

Keyword Arguments:
 
  • encoding (str) – character encoding to open file_ref with, using io.open().
  • encoding_errors (str) – ‘strict’, ‘replace’ (default), ‘ignore’ - how to handle errors with encodings (see this section of the standard library’s codecs module for more information)
  • autodetect_encoding (str or bool) – default True to use chardet/cchardet to detect encoding. Note if set to False several common encodings will be tried but chardet won’t be used.
  • autodetect_encoding_chars (int/None) – number of chars to read from LAS file for auto-detection of encoding.
Returns:

a unicode or string object

This function is called by lasio.reader.open_file().

lasio.reader.get_encoding(auto, raw)[source]

Automatically detect character encoding.

Parameters:
  • auto (str) – auto-detection of character encoding - can be either ‘chardet’, ‘cchardet’, False, or True (the latter will pick the fastest available option)
  • raw (bytes) – array of bytes to detect from
Returns:

A string specifying the character encoding.

lasio.reader.read_file_contents(file_obj, regexp_subs, value_null_subs, ignore_data=False, remove_line_filter='#')[source]

Read file contents into memory.

Parameters:

file_obj (open file-like object) –

Keyword Arguments:
 
  • null_subs (bool) – True will substitute numpy.nan for invalid values
  • ignore_data (bool) – if True, do not read in the numerical data in the ~ASCII section
  • remove_line_filter (str, func) – string or function for removing/ignoring lines in the data section e.g. a function which accepts a string (a line from the data section) and returns either True (do not parse the line) or False (parse the line). If this argument is a string it will instead be converted to a function which rejects all lines starting with that value e.g. "#" will be converted to lambda line: line.strip().startswith("#")
Returns:

OrderedDict

I think of the returned dictionary as a “raw section”. The keys are the first line of the LAS section, including the tilde. Each value is a dict with either:

{"section_type": "header",
 "title": str,               # title of section (including the ~)
 "lines": [str, ],           # a list of the lines from the lAS file
 "line_nos": [int, ]         # line nos from the original file
 }

or:

{"section_type": "data",
 "title": str,              # title of section (including the ~)
 "start_line": int,         # location of data section (the title line)
 "ncols": int,              # no. of columns on first line of data,
 "array": ndarray           # 1-D numpy.ndarray,
 }
LASFile.match_raw_section(pattern, re_func='match', flags=<RegexFlag.IGNORECASE: 2>)[source]

Find raw section with a regular expression.

Parameters:

pattern (str) – regular expression (you need to include the tilde)

Keyword Arguments:
 
  • re_func (str) – either “match” or “search”, see python re module.
  • flags (int) – flags for re.compile()
Returns:

dict

Intended for internal use only.

lasio.reader.read_data_section_iterative(file_obj, line_nos, regexp_subs, value_null_subs, remove_line_filter)[source]

Read data section into memory.

Parameters:
  • file_obj – file-like object open for reading at the beginning of the section
  • line_nos (tuple) – the first and last line no of the section to read
  • regexp_subs (list) – each item should be a tuple of the pattern and substitution string for a call to re.sub() on each line of the data section. See defaults.py READ_SUBS and NULL_SUBS for examples.
  • value_null_subs (list) – list of numerical values to be replaced by numpy.nan values.
  • remove_line_filter (str or func) – string or function for removing/ignoring lines in the data section e.g. a function which accepts a string (a line from the data section) and returns either True (do not parse the line) or False (parse the line). If this argument is a string it will instead be converted to a function which rejects all lines starting with that value e.g. "#" will be converted to lambda line: line.strip().startswith("#")
Returns:

A 1-D numpy ndarray.

lasio.reader.get_substitutions(read_policy, null_policy)[source]

Parse read and null policy definitions into a list of regexp and value substitutions.

Parameters:
  • read_policy (str, list, or substitution) – either (1) a string defined in defaults.READ_POLICIES; (2) a list of substitutions as defined by the keys of defaults.READ_SUBS; or (3) a list of actual substitutions similar to the values of defaults.READ_SUBS. You can mix (2) and (3) together if you want.
  • null_policy (str, list, or sub) – as for read_policy but for defaults.NULL_POLICIES and defaults.NULL_SUBS
Returns:

regexp_subs, value_null_subs, version_NULL - two lists and a bool. The first list is pairs of regexp patterns and substrs, and the second list is just a list of floats or integers. The bool is whether or not ‘NULL’ was located as a substitution.

class lasio.reader.SectionParser(title, version=1.2)[source]

Parse lines from header sections.

Parameters:title (str) – title line of section. Used to understand different order formatting across the special sections ~C, ~P, ~W, and ~V, depending on version 1.2 or 2.0.
Keyword Arguments:
 version (float) – version to parse according to. Default is 1.2.
lasio.reader.read_header_line(line, pattern=None, section_name=None)[source]

Read a line from a LAS header section.

The line is parsed with a regular expression – see LAS file specs for more details, but it should basically be in the format:

name.unit       value : descr
Parameters:
  • line (str) – line from a LAS header section
  • section_name (str) – Name of the section the ‘line’ is from. The default
  • is None. (value) –
Returns:

A dictionary with keys ‘name’, ‘unit’, ‘value’, and ‘descr’, each containing a string as value.

class lasio.HeaderItem(mnemonic='', unit='', value='', descr='', data=None)[source]

Dictionary/namedtuple-style object for a LAS header line.

Parameters:
  • mnemonic (str) – the mnemonic
  • unit (str) – the unit (no whitespace!)
  • value (str) – value
  • descr (str) – description

These arguments are available for use as either items or attributes of the object.

HeaderItem.set_session_mnemonic_only(value)[source]

Set the mnemonic for session use.

See source comments for lasio.HeaderItem.__init__ for a more in-depth explanation.

class lasio.CurveItem(mnemonic='', unit='', value='', descr='', data=None)[source]

Dictionary/namedtuple-style object for a LAS curve.

See lasio.HeaderItem` for the (keyword) arguments.

Keyword Arguments:
 data (array-like, 1-D) – the curve’s data.
class lasio.SectionItems(*args, **kwargs)[source]

Variant of a list which is used to represent a LAS section.

Reading data

LASFile.__getitem__(key)[source]

Provide access to curve data.

Parameters:key (str, int) – either a curve mnemonic or the column index.
Returns:1D numpy.ndarray (the data for the curve)
LASFile.__setitem__(key, value)[source]

Append a curve.

Parameters:
  • key (str) – the curve mnemonic
  • value (1D data or CurveItem) – either the curve data, or a CurveItem

See lasio.LASFile.append_curve_item() or lasio.LASFile.append_curve() for more details.

LASFile.get_curve(mnemonic)[source]

Return CurveItem object.

Parameters:mnemonic (str) – the name of the curve
Returns:lasio.CurveItem (not just the data array)
LASFile.keys()[source]

Return curve mnemonics.

LASFile.values()[source]

Return data for each curve.

LASFile.items()[source]

Return mnemonics and data for all curves.

LASFile.df()[source]

Return data as a pandas.DataFrame structure.

The first Curve of the LASFile object is used as the pandas DataFrame’s index.

LASFile.version

Header information from the Version (~V) section.

Returns:lasio.SectionItems object.
LASFile.well

Header information from the Well (~W) section.

Returns:lasio.SectionItems object.
LASFile.curves

Curve information and data from the Curves (~C) and data section..

Returns:lasio.SectionItems object.
LASFile.curvesdict

Curve information and data from the Curves (~C) and data section..

Returns:dict
LASFile.params

Header information from the Parameter (~P) section.

Returns:lasio.SectionItems object.
LASFile.other

Header information from the Other (~O) section.

Returns:str
LASFile.index

Return data from the first column of the LAS file data (depth/time).

LASFile.depth_m

Return the index as metres.

LASFile.depth_ft

Return the index as feet.

LASFile.data
LASFile.stack_curves(mnemonic, sort_curves=True)[source]

Stack multi-channel curve data to a numpy 2D ndarray. Provide a stub name (prefix shared by all curves that will be stacked) or a list of curve mnemonic strings.

Keyword Arguments:
 
  • mnemonic (str or list) – Supply the first several characters of the channel set to be stacked. Alternatively, supply a list of the curve names (mnemonics strings) to be stacked.
  • sort_curves (bool) – Natural sort curves based on mnemonic prior to stacking.
Returns:

2-D numpy array

Modifying data

LASFile.set_data(array_like, names=None, truncate=False)[source]

Set the data for the LAS; actually sets data on individual curves.

Parameters:

array_like (array_like or pandas.DataFrame) – 2-D data array

Keyword Arguments:
 
  • names (list, optional) – used to replace the names of the existing lasio.CurveItem objects.
  • truncate (bool) – remove any columns which are not included in the Curves (~C) section.

Note: you can pass a pandas.DataFrame to this method.

LASFile.set_data_from_df(df, **kwargs)[source]

Set the LAS file data from a pandas.DataFrame.

Parameters:df (pandas.DataFrame) – curve mnemonics are the column names. The depth column for the curves must be the index of the DataFrame.

Keyword arguments are passed to lasio.LASFile.set_data().

LASFile.append_curve(mnemonic, data, unit='', descr='', value='')[source]

Add a curve.

Parameters:
  • mnemonic (str) – the curve mnemonic
  • data (1D ndarray) – the curve data
Keyword Arguments:
 
  • unit (str) – curve unit
  • descr (str) – curve description
  • value (int/float/str) – value e.g. API code.
LASFile.insert_curve(ix, mnemonic, data, unit='', descr='', value='')[source]

Insert a curve.

Parameters:
  • ix (int) – position to insert curve at i.e. 0 for start.
  • mnemonic (str) – the curve mnemonic
  • data (1D ndarray) – the curve data
Keyword Arguments:
 
  • unit (str) – curve unit
  • descr (str) – curve description
  • value (int/float/str) – value e.g. API code.
LASFile.delete_curve(mnemonic=None, ix=None)[source]

Delete a curve.

Keyword Arguments:
 
  • ix (int) – index of curve in LASFile.curves.
  • mnemonic (str) – mnemonic of curve.

The index takes precedence over the mnemonic.

LASFile.append_curve_item(curve_item)[source]

Add a CurveItem.

Parameters:curve_item (lasio.CurveItem) –
LASFile.insert_curve_item(ix, curve_item)[source]

Insert a CurveItem.

Parameters:
  • ix (int) – position to insert CurveItem i.e. 0 for start
  • curve_item (lasio.CurveItem) –

Writing data out

LASFile.write(file_ref, **kwargs)[source]

Write LAS file to disk.

Parameters:file_ref (open file-like object or str) – a file-like object opening for writing, or a filename.

All **kwargs are passed to lasio.writer.write() – please check the docstring of that function for more keyword arguments you can use here!

Examples

>>> import lasio
>>> las = lasio.read("tests/examples/sample.las")
>>> with open('test_output.las', mode='w') as f:
...     las.write(f, version=2.0)   # <-- this method
lasio.writer.write(las, file_object, version=None, wrap=None, STRT=None, STOP=None, STEP=None, fmt='%.5f', column_fmt=None, len_numeric_field=None, data_width=79, header_width=60)[source]

Write a LAS files.

Parameters:
  • las (lasio.LASFile) –
  • file_object (file-like object open for writing) – output
  • version (float or None) – version of written file, either 1.2 or 2. If this is None, las.version.VERS.value will be used.
  • wrap (bool or None) – whether to wrap the output data section. If this is None, las.version.WRAP.value will be used.
  • STRT (float or None) – value to use as STRT (note the data will not be clipped). If this is None, the data value in the first column, first row will be used.
  • STOP (float or None) – value to use as STOP (note the data will not be clipped). If this is None, the data value in the first column, last row will be used.
  • STEP (float or None) – value to use as STEP (note the data will not be resampled and/or interpolated). If this is None, the STEP will be estimated from the first two rows of the first column.
  • fmt (str) – Python string formatting operator for numeric data to be used.
  • column_fmt (dict or None) – use this to set a different format string for specific columns from the data ndarray. E.g. to use '%.3f' for the depth column and '%.2f' for all the other columns, you would use fmt='%.2f', column_fmt={0: '%.3f'}.
  • len_numeric_field (int) – width of each numeric field column (must be greater than than all the formatted numeric values in the file).
  • data_width (79) – width of data field in characters

Creating an output file is not the only side-effect of this function. It will also modify the STRT, STOP and STEP HeaderItems so that they correctly reflect the ~Data section’s units and the actual first, last, and interval values.

However, passing a version to this write() function only changes the version of the object written to. Example: las.write(myfile, version=2). Lasio’s internal-las-object version will remain separate and defined by las.version.VERS.value

You should avoid calling this function directly - instead use the lasio.LASFile.write() method.

lasio.writer.get_formatter_function(order, left_width=None, middle_width=None)[source]

Create function to format a LAS header item for output.

Parameters:

order – format of item, either ‘descr:value’ or ‘value:descr’

Keyword Arguments:
 
  • left_width (int) – number of characters to the left hand side of the first period
  • middle_width (int) – total number of characters minus 1 between the first period from the left and the first colon from the left.
Returns:

A function which takes a header item (e.g. lasio.HeaderItem) as its single argument and which in turn returns a string which is the correctly formatted LAS header line.

lasio.writer.get_section_order_function(section, version, order_definitions={1.2: {'Curves': ['value:descr'], 'Parameter': ['value:descr'], 'Version': ['value:descr'], 'Well': ['descr:value', ('value:descr', ['STRT', 'STOP', 'STEP', 'NULL', 'strt', 'stop', 'step', 'null'])]}, 2.0: {'Curves': ['value:descr'], 'Parameter': ['value:descr'], 'Version': ['value:descr'], 'Well': ['value:descr']}, 3.0: {'Curves': ['value:descr'], 'Parameter': ['value:descr'], 'Version': ['value:descr'], 'Well': ['value:descr']}})[source]

Get a function that returns the order per the mnemonic and section.

Parameters:
  • section (str) – either ‘well’, ‘params’, ‘curves’, ‘version’
  • version (float) – either 1.2 and 2.0
Keyword Arguments:
 

order_definitions (dict) – see source of defaults.py for more information

Returns:

A function which takes a mnemonic (str) as its only argument, and in turn returns the order ‘value:descr’ or ‘descr:value’.

lasio.writer.get_section_widths(section_name, items, version, order_func)[source]

Find minimum section widths fitting the content in items.

Parameters:
LASFile.to_csv(file_ref, mnemonics=True, units=True, units_loc='line', **kwargs)[source]

Export to a CSV file.

Parameters:

file_ref (open file-like object or str) – a file-like object opening for writing, or a filename.

Keyword Arguments:
 
  • mnemonics (list, True, False) – write mnemonics as a header line at the start. If list, use the supplied items as mnemonics. If True, use the curve mnemonics.
  • units (list, True, False) – as for mnemonics.
  • units_loc (str or None) – either ‘line’, ‘[]’ or ‘()’. ‘line’ will put units on the line following the mnemonics (good for WellCAD). ‘[]’ and ‘()’ will put the units in either brackets or parentheses following the mnemonics, on the single header line (better for Excel)
  • **kwargs – passed to csv.writer. Note that if lineterminator is not specified here, then it will be sent to csv.writer as lineterminator='\n'.
LASFile.to_excel(filename)[source]

Export LAS file to a Microsoft Excel workbook.

This function will raise an ImportError if openpyxl is not installed.

Parameters:filename (str) –
LASFile.to_json()[source]

Custom exceptions

class lasio.exceptions.LASDataError[source]

Error during reading of numerical data from LAS file.

class lasio.exceptions.LASHeaderError[source]

Error during reading of header data from LAS file.

class lasio.exceptions.LASUnknownUnitError[source]

Error of unknown unit in LAS file.

Test data

lasio.examples.open(filename, **kwargs)[source]

Open an example LAS file from lasio’s test suite.

Parameters:filename (str) – forward-slash separated filename of a LAS file from lasio’s test suite, starting from the “tests/examples” subfolder e.g. “1001178549.las” or “2.0/sample_2.0.las”

Other keyword arguments are passed to lasio.LASFile. If lasio has been installed locally from source, then the local version of the example file will be opened. If lasio has not been installed from source then the LAS file will be downloaded from GitHub.

Returns: LASFile object

lasio.examples.open_github_example(filename, url_prefix='https://raw.githubusercontent.com/kinverarity1/lasio/master/tests/examples/', **kwargs)[source]

Open an example LAS file from lasio’s test suite on GitHub

Parameters:filename (str) – forward-slash separated filename of a LAS file from lasio’s test suite, starting from the “tests/examples” subfolder e.g. “1001178549.las” or “2.0/sample_2.0.las”

Other keyword arguments are passed to lasio.LASFile.

Returns: LASFile object

lasio.examples.open_local_example(filename, **kwargs)[source]

Open an example LAS file from lasio’s test suite.

Parameters:filename (str) – forward-slash separated filename of a LAS file from lasio’s test suite, starting from the “tests/examples” subfolder e.g. “1001178549.las” or “2.0/sample_2.0.las”

Other keyword arguments are passed to lasio.LASFile. If lasio has not been installed from source then an exception will be raised.

Returns: LASFile object

lasio.examples.get_local_examples_path()[source]

Return the path to the examples from lasio’s test suite, if it is installed locally.

Returns: path as str.